Upload encode-pubmed.py with huggingface_hub
Browse files- encode-pubmed.py +61 -0
encode-pubmed.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import h5py as h5
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import torch
|
| 6 |
+
import time
|
| 7 |
+
import fire
|
| 8 |
+
from glob import glob
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
+
torch.set_num_threads(48)
|
| 11 |
+
modelname = 'sentence-transformers/all-MiniLM-L6-v2'
|
| 12 |
+
model = SentenceTransformer(modelname)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def encode(filename, outname):
|
| 16 |
+
print(f"encoding {filename} -> {outname}")
|
| 17 |
+
content = []
|
| 18 |
+
title = []
|
| 19 |
+
PMID = []
|
| 20 |
+
with open(filename) as f:
|
| 21 |
+
for line in f.readlines():
|
| 22 |
+
d = json.loads(line)
|
| 23 |
+
content.append(d["content"])
|
| 24 |
+
title.append(d["title"])
|
| 25 |
+
PMID.append(d["PMID"])
|
| 26 |
+
#d["ID"], d["PMID"]
|
| 27 |
+
|
| 28 |
+
print("encoding 'content' -- {} entries".format(len(content)))
|
| 29 |
+
st = time.time()
|
| 30 |
+
Xcontent = model.encode(content)
|
| 31 |
+
print("finished in {}s".format(time.time() - st))
|
| 32 |
+
print("encoding 'title' -- {} entries".format(len(title)))
|
| 33 |
+
st = time.time()
|
| 34 |
+
Xtitle = model.encode(title)
|
| 35 |
+
print("finished in {}s".format(time.time() - st))
|
| 36 |
+
with h5.File(outname, "w") as f:
|
| 37 |
+
f["model"] = modelname
|
| 38 |
+
f["content"] = Xcontent
|
| 39 |
+
f["title"] = Xtitle
|
| 40 |
+
f["PMID"] = PMID
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def encode_pubmed(files, outdir="pubmed-embeddings"):
|
| 44 |
+
os.makedirs(outdir, exist_ok=True)
|
| 45 |
+
|
| 46 |
+
with open(files) as f:
|
| 47 |
+
for filename in f.readlines():
|
| 48 |
+
filename = filename.rstrip()
|
| 49 |
+
outname = "{}/{}.h5".format(outdir, os.path.basename(filename).replace(".jsonl", ""))
|
| 50 |
+
if os.path.isfile(outname):
|
| 51 |
+
print(f"{outname} already exists")
|
| 52 |
+
else:
|
| 53 |
+
encode(filename, outname)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
fire.Fire(encode_pubmed)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
main()
|