File size: 909 Bytes
874eec2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""Frozen text embeddings of every caption (BAAI/bge-small-en-v1.5 via fastembed, ONNX, CPU), computed once and cached.
The text embedded is exactly the text BM25 indexes: packet.caption_text(caption) (seven fields joined).
Run in an environment with fastembed:  python embed.py <captions.json> <out.npz>"""
import json, re, sys
import numpy as np
from fastembed import TextEmbedding

FIELDS = ("organ", "location", "lesion_shape_margin", "color", "texture", "distribution", "visible_discriminators")
caps = json.load(open(sys.argv[1]))
ids = sorted(caps)
text = ["; ".join(f"{k}: {caps[i].get(k)}" for k in FIELDS if caps[i].get(k)) for i in ids]
m = TextEmbedding("BAAI/bge-small-en-v1.5")
E = np.array(list(m.embed(text, batch_size=64)), dtype=np.float32)
E /= np.linalg.norm(E, axis=1, keepdims=True)
np.savez_compressed(sys.argv[2], ids=np.array(ids), E=E, model="BAAI/bge-small-en-v1.5")
print(E.shape)