"""Load + query the published embeddings — numpy only, no DB, no network. The whole point of this repo: a consumer does `git pull`, loads the two matrices into memory ONCE at boot, and then every query is an in-memory matmul. Vectors are 1536-d, L2-normalized, so cosine similarity == dot product and distance == 1 - score (identical to the pgvector `<=>` cosine distance the rec engine uses today). from load import load_section, knn V, meta, by_did = load_section("..", "repos") # once hits = knn(V, meta, V[by_did[seed_repo_did]], k=40, exclude_dids={seed_repo_did}) """ from __future__ import annotations import json import os import numpy as np def load_section(repo_root: str, name: str) -> tuple[np.ndarray, list[dict], dict[str, int]]: """Load one section ('repos' or 'issues'). Returns (matrix, meta, row_by_did). matrix[i] is the embedding for meta[i]; row_by_did maps repo_did -> row index (last-wins if a repo_did appears twice, which it shouldn't).""" vectors = np.load(os.path.join(repo_root, "data", f"{name}.f32.npy")) meta: list[dict] = [] with open(os.path.join(repo_root, "data", f"{name}.jsonl"), encoding="utf-8") as fh: for line in fh: line = line.strip() if line: meta.append(json.loads(line)) if len(meta) != vectors.shape[0]: raise ValueError(f"{name}: {len(meta)} meta rows != {vectors.shape[0]} vectors") row_by_did = {m["repo_did"]: m["row"] for m in meta} return vectors, meta, row_by_did def knn( matrix: np.ndarray, meta: list[dict], query: np.ndarray, k: int, exclude_dids: set[str] | None = None, ) -> list[tuple[dict, float]]: """Brute-force cosine kNN. Returns up to k (meta_row, distance) pairs, nearest first, where distance = 1 - cosine_similarity (matches pgvector `<=>`).""" exclude = exclude_dids or set() scores = matrix @ query # cosine similarity (unit vectors) order = np.argsort(-scores) # high score == near out: list[tuple[dict, float]] = [] for i in order: row = meta[int(i)] if row["repo_did"] in exclude: continue out.append((row, 1.0 - float(scores[int(i)]))) if len(out) >= k: break return out