Files
yt-recommender/app/embed.py
2026-12-03 02:08:44 +11:00

53 lines
1.6 KiB
Python

"""Text embeddings for video titles/descriptions (local, CPU, no API)."""
import logging
import numpy as np
from . import config, db
log = logging.getLogger(__name__)
_model = None
def _get_model():
global _model
if _model is None:
from fastembed import TextEmbedding
log.info("loading embedding model %s", config.EMBED_MODEL)
_model = TextEmbedding(config.EMBED_MODEL, cache_dir=str(config.MODEL_CACHE))
return _model
def video_text(row) -> str:
desc = (row["description"] or "").replace("\n", " ")[:400]
return f"{row['title'] or ''}. Channel: {row['channel'] or ''}. {desc}"
def embed_texts(texts: list[str]) -> np.ndarray:
vecs = np.array(list(_get_model().embed(texts, batch_size=64)), dtype=np.float32)
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
return vecs / np.clip(norms, 1e-9, None)
def embed_missing(batch: int = 256) -> int:
"""Embed every stored video that doesn't have a vector yet."""
total = 0
with db.connect() as c:
while True:
rows = c.execute(
"SELECT id, title, channel, description FROM videos "
"WHERE embedding IS NULL AND title IS NOT NULL LIMIT ?",
(batch,),
).fetchall()
if not rows:
break
vecs = embed_texts([video_text(r) for r in rows])
c.executemany(
"UPDATE videos SET embedding = ? WHERE id = ?",
[(db.to_blob(v), r["id"]) for v, r in zip(vecs, rows)],
)
c.commit()
total += len(rows)
log.info("embedded %d videos", total)
return total