Download encode-pubmed.py from sadit/TextEmbeddings: direct link, hf CLI and curl.
- Browser
- Download file 1.7 kB
-
https://huggingface.co/datasets/sadit/TextEmbeddings/resolve/main/encode-pubmed.py
- Command line
-
hf download hf://datasets/sadit/TextEmbeddings/encode-pubmed.py
-
curl -L -o encode-pubmed.py https://huggingface.co/datasets/sadit/TextEmbeddings/resolve/main/encode-pubmed.py
1.7 kB
| import h5py as h5 | |
| import os | |
| import json | |
| import pandas as pd | |
| import torch | |
| import time | |
| import fire | |
| from glob import glob | |
| from sentence_transformers import SentenceTransformer | |
| torch.set_num_threads(48) | |
| modelname = 'sentence-transformers/all-MiniLM-L6-v2' | |
| model = SentenceTransformer(modelname) | |
| def encode(filename, outname): | |
| print(f"encoding {filename} -> {outname}") | |
| content = [] | |
| title = [] | |
| PMID = [] | |
| with open(filename) as f: | |
| for line in f.readlines(): | |
| d = json.loads(line) | |
| content.append(d["content"]) | |
| title.append(d["title"]) | |
| PMID.append(d["PMID"]) | |
| #d["ID"], d["PMID"] | |
| print("encoding 'content' -- {} entries".format(len(content))) | |
| st = time.time() | |
| Xcontent = model.encode(content) | |
| print("finished in {}s".format(time.time() - st)) | |
| print("encoding 'title' -- {} entries".format(len(title))) | |
| st = time.time() | |
| Xtitle = model.encode(title) | |
| print("finished in {}s".format(time.time() - st)) | |
| with h5.File(outname, "w") as f: | |
| f["model"] = modelname | |
| f["content"] = Xcontent | |
| f["title"] = Xtitle | |
| f["PMID"] = PMID | |
| def encode_pubmed(files, outdir="pubmed-embeddings"): | |
| os.makedirs(outdir, exist_ok=True) | |
| with open(files) as f: | |
| for filename in f.readlines(): | |
| filename = filename.rstrip() | |
| outname = "{}/{}.h5".format(outdir, os.path.basename(filename).replace(".jsonl", "")) | |
| if os.path.isfile(outname): | |
| print(f"{outname} already exists") | |
| else: | |
| encode(filename, outname) | |
| def main(): | |
| fire.Fire(encode_pubmed) | |
| if __name__ == "__main__": | |
| main() | |