File size: 1,699 Bytes
f672783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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()