"""Export embeddings from the shared Postgres into this repo's data/ files. READ-ONLY against the DB. Writes data/{repos,issues}.f32.npy + .jsonl + manifest.json. Run this to (re)generate the published artifact; then commit + push to the knot. DB_CONNECTION_STRING=... python scripts/export_embeddings.py # or rely on a .env in this repo / the recommendation/ folder Vectors are read as pgvector text literals ('[v1,...]') exactly like the rec engine (recommendation/app/db.py) and the scraper (scraper/seed_user.py), so no pgvector adapter is needed. They are already 1536-d and L2-normalized. """ from __future__ import annotations import datetime as dt import hashlib import json import os from pathlib import Path import numpy as np import psycopg from psycopg.rows import dict_row try: from dotenv import load_dotenv except ImportError: # dotenv optional if the var is already in env def load_dotenv(*_a, **_k): # type: ignore return False REPO_ROOT = Path(__file__).resolve().parent.parent DATA_DIR = REPO_ROOT / "data" DIM = 1536 MODEL = "gemini-embedding-001" # Repos: mirror recommendation/app/db.py joins so description/topics/created_at/handle # resolve the same way the engine sees them. content stays in the DB — we ship only its # length (for the min-chars gate) and md5(first 500 chars) (for fork dedup). _REPOS_SQL = """ select r.repo_did, r.repo_uri, coalesce(r.owner_handle, ti.handle) as owner_handle, r.repo_name, tr.record_raw->>'description' as description, tr.record_raw->'topics' as topics, tr.record_raw->>'createdAt' as created_at, length(trim(coalesce(r.content, ''))) as content_len, md5(substring(coalesce(r.content, '') for 500)) as content_sha500, r.embedding_model, r.embedded_at, r.embedding::text as etext from tangled_readmes r left join tangled_repos tr on coalesce(tr.repo_did, tr.record_raw->>'repoDid') = r.repo_did left join tangled_identities ti on ti.did = split_part(replace(r.repo_uri, 'at://', ''), '/', 1) where r.embedding is not null order by r.repo_did """ # Issues: only those whose identity fully resolves (same inner joins as _KNN_ISSUES_SQL), # i.e. exactly the set the engine can emit. _ISSUES_SQL = """ select i.uri, i.rkey, i.repo_did, i.repo_uri, i.author_did, i.title, i.body, ti.handle as owner_handle, tr.name as repo_name, tr.record_raw->>'description' as repo_description, i.issue_created_at as created_at, i.embedding_model, i.embedding::text as etext from tangled_open_issues i join tangled_identities ti on ti.did = split_part(replace(i.repo_uri, 'at://', ''), '/', 1) join tangled_repos tr on tr.owner_did = split_part(replace(i.repo_uri, 'at://', ''), '/', 1) and tr.rkey = split_part(i.repo_uri, '/', 5) where i.embedding is not null and i.repo_uri is not null and ti.handle is not null and tr.name is not null order by i.uri """ def _dsn() -> str: for candidate in (REPO_ROOT / ".env", REPO_ROOT.parent / "sunsteadhack" / "recommendation" / ".env"): if candidate.exists(): load_dotenv(candidate) break else: load_dotenv() conn = os.environ.get("DB_CONNECTION_STRING", "").strip() if not conn: raise SystemExit("DB_CONNECTION_STRING not set (env or .env)") if "sslmode=" not in conn: # Cloud SQL public IP, self-signed cert conn += ("&" if "?" in conn else "?") + "sslmode=require" return conn def _parse_vec(etext: str) -> np.ndarray: v = np.fromstring(etext.strip()[1:-1], sep=",", dtype=np.float32) if v.shape[0] != DIM: raise ValueError(f"expected dim {DIM}, got {v.shape[0]}") return v def _json_default(o): if isinstance(o, (dt.datetime, dt.date)): return o.isoformat() return str(o) def _export_section(conn, name: str, sql: str, meta_fields: list[str]) -> dict: rows = conn.execute(sql).fetchall() if not rows: raise SystemExit(f"{name}: no embedded rows found") matrix = np.vstack([_parse_vec(r["etext"]) for r in rows]).astype(np.float32) npy_path = DATA_DIR / f"{name}.f32.npy" jsonl_path = DATA_DIR / f"{name}.jsonl" np.save(npy_path, matrix) with open(jsonl_path, "w", encoding="utf-8") as fh: for i, r in enumerate(rows): rec = {"row": i, "subject_uri": r["uri"] if "uri" in r else r["repo_uri"]} rec.update({k: r[k] for k in meta_fields}) fh.write(json.dumps(rec, default=_json_default, ensure_ascii=False) + "\n") sha = hashlib.sha256(npy_path.read_bytes()).hexdigest() print(f" {name}: {matrix.shape[0]} vectors -> {npy_path.name} ({npy_path.stat().st_size // 1024} KiB)") return { "count": int(matrix.shape[0]), "vectors": f"data/{name}.f32.npy", "meta": f"data/{name}.jsonl", "sha256": sha, } def main() -> int: DATA_DIR.mkdir(parents=True, exist_ok=True) with psycopg.connect(_dsn(), row_factory=dict_row) as conn: print("exporting embeddings (read-only)…") repos = _export_section( conn, "repos", _REPOS_SQL, ["repo_did", "repo_name", "owner_handle", "description", "topics", "created_at", "content_len", "content_sha500", "embedding_model", "embedded_at"], ) issues = _export_section( conn, "issues", _ISSUES_SQL, ["repo_did", "rkey", "repo_uri", "author_did", "title", "body", "owner_handle", "repo_name", "repo_description", "created_at", "embedding_model"], ) manifest = { "schema_version": 1, "model": MODEL, "dim": DIM, "metric": "cosine", "normalized": True, "task_type": "RETRIEVAL_DOCUMENT", "generated_at": dt.datetime.now(dt.timezone.utc).isoformat(), "sections": {"repos": repos, "issues": issues}, } (REPO_ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") print(f"wrote manifest.json (repos={repos['count']}, issues={issues['count']})") return 0 if __name__ == "__main__": raise SystemExit(main())