x-virality-model / embed.py
brainfish's picture
Upload X virality model v2.1 (default) + v2.2: bundles, inference code, model card
853e005 verified
Raw History Blame Contribute Delete
3.9 kB
"""v2 cached embeddings (CPU, ONNX via fastembed; no torch).
Text : sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 (384-d, multilingual)
Image: Qdrant/clip-ViT-B-32-vision (512-d CLIP image tower) on X media thumbnails (?name=small)
Caches live in emb_cache/ (gitignored). Re-running only embeds ids/urls not already cached.
At Brev scale swap in MobileCLIP2 / SigLIP2 towers on GPU (see research/rlcd-tiny-multimodal.md §5)."""
import os, sys, hashlib, io, urllib.request
import numpy as np, pandas as pd
HERE=os.path.dirname(os.path.abspath(__file__))
CACHE=os.path.join(HERE,'emb_cache'); IMG_DIR=os.path.join(CACHE,'img')
MODEL_CACHE=os.environ.get('XVM_EMB_CACHE') or os.path.join(CACHE,'models') # XVM_EMB_CACHE: e.g. the HF hub cache on a Space
TEXT_MODEL='sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2'
IMAGE_MODEL='Qdrant/clip-ViT-B-32-vision'
_tm=_im=None
def text_model():
global _tm
if _tm is None:
from fastembed import TextEmbedding
_tm=TextEmbedding(TEXT_MODEL, cache_dir=MODEL_CACHE, threads=4)
return _tm
def image_model():
global _im
if _im is None:
from fastembed import ImageEmbedding
_im=ImageEmbedding(IMAGE_MODEL, cache_dir=MODEL_CACHE, threads=4)
return _im
def embed_texts(texts):
from features import clean_text
return np.array(list(text_model().embed([clean_text(t or '') or ' ' for t in texts], batch_size=64)),dtype=np.float32)
def thumb_url(u):
if 'pbs.twimg.com/media/' in u and '?' not in u:
base,ext=os.path.splitext(u); return f'{base}?format={ext.lstrip(".") or "jpg"}&name=small'
return u
def fetch_image(url, timeout=10):
"""Download once into emb_cache/img; returns local path or None (skips gracefully)."""
os.makedirs(IMG_DIR,exist_ok=True)
p=os.path.join(IMG_DIR,hashlib.sha1(url.encode()).hexdigest()+'.jpg')
if os.path.exists(p): return p if os.path.getsize(p)>0 else None
try:
req=urllib.request.Request(thumb_url(url),headers={'User-Agent':'Mozilla/5.0'})
data=urllib.request.urlopen(req,timeout=timeout).read()
from PIL import Image; Image.open(io.BytesIO(data)).verify()
open(p,'wb').write(data); return p
except Exception:
open(p,'wb').close(); return None
def embed_image_urls(urls):
"""Mean CLIP embedding over a post's images; None if no image could be fetched."""
paths=[q for q in (fetch_image(u) for u in urls if u) if q]
if not paths: return None
v=np.array(list(image_model().embed(paths)),dtype=np.float32)
return v.mean(0)
def build_cache(posts_csv=os.path.join(HERE,'data','posts.csv')):
d=pd.read_csv(posts_csv,dtype={'id':str},usecols=['id','text','media_urls'])
tp=os.path.join(CACHE,'text_emb.npz')
ids,E=([],np.zeros((0,384),np.float32))
if os.path.exists(tp):
z=np.load(tp,allow_pickle=True); ids,E=list(z['ids']),z['emb']
have=set(ids); new=d[~d.id.isin(have)]
if len(new):
print('embedding text',len(new),flush=True)
E=np.vstack([E,embed_texts(new.text.tolist())]); ids=ids+new.id.tolist()
np.savez(tp,ids=np.array(ids),emb=E)
ip=os.path.join(CACHE,'image_emb.npz')
iids,IE=([],np.zeros((0,512),np.float32))
if os.path.exists(ip):
z=np.load(ip,allow_pickle=True); iids,IE=list(z['ids']),z['emb']
have=set(iids); todo=d[d.media_urls.notna()&~d.id.isin(have)]
print('images to try',len(todo),flush=True); got=[];vecs=[]
for i,(pid,mu) in enumerate(zip(todo.id,todo.media_urls)):
v=embed_image_urls(str(mu).split())
if v is not None: got.append(pid); vecs.append(v)
if i%100==0: print(' img',i,len(got),flush=True)
if got:
IE=np.vstack([IE,np.array(vecs)]); iids=iids+got
np.savez(ip,ids=np.array(iids),emb=IE)
print('text cached',len(ids),'image cached',len(iids))
if __name__=='__main__': build_cache()