#!/usr/bin/env python3 """ embed_load.py — embed the CDS/ADS/EWDS deep-doc chunks (gemini-embedding-2-preview, 768-dim, RETRIEVAL_DOCUMENT, L2-norm) and load them into Qdrant `cds_docs` (dense + BM25 sparse), in a SEPARATE db (deep_docs/qdrant_db) so it never contends the marine_docs lock. Phases (resumable): --phase embed chunks.jsonl -> chunks_embedded.jsonl (checkpointed, skips done) --phase load chunks_embedded.jsonl -> Qdrant cds_docs --phase all embed then load (default) Env: BATCH= embed batch size (default 32); SAMPLE_N= smoke test. """ import argparse import json import os import sys import time import uuid from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parent.parent CHUNKS = ROOT / "deep_docs" / "chunks.jsonl" EMB = ROOT / "deep_docs" / "chunks_embedded.jsonl" LOCAL_DB = ROOT / "deep_docs" / "qdrant_db" COLLECTION = "cds_docs" DENSE_DIM = 768 def log(*a): print(*a, file=sys.stderr, flush=True) def resolve_key() -> str: for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"): if os.environ.get(var): return os.environ[var] for env in (ROOT / ".env", Path("/Users/dmpantiu/cmip6/cmip6_gpt/.env")): if env.exists(): for line in env.read_text().splitlines(): line = line.strip() if "api_key" in line.lower() and "=" in line and not line.startswith("#"): return line.split("=", 1)[1].strip().strip('"').strip("'") raise SystemExit("No Gemini API key.") def _norm(vals): v = np.array(list(vals), dtype=np.float32) n = np.linalg.norm(v) return (v / n).tolist() if n > 0 else v.tolist() def embed_phase(workers: int, sample: int): """One embedding per chunk (the API returns a single vector per call), parallelised with a thread pool for throughput.""" import threading from concurrent.futures import ThreadPoolExecutor, as_completed from google import genai from google.genai import types client = genai.Client(api_key=resolve_key()) cfg = types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT", output_dimensionality=DENSE_DIM) done = set() if EMB.exists(): for line in EMB.read_text().splitlines(): if line.strip(): done.add(json.loads(line)["chunk_id"]) rows = [json.loads(l) for l in CHUNKS.read_text().splitlines() if l.strip()] todo = [r for r in rows if r["chunk_id"] not in done] if sample: todo = todo[:sample] log(f"embed: total={len(rows)} done={len(done)} todo={len(todo)} workers={workers}") lock = threading.Lock() out = open(EMB, "a", encoding="utf-8") state = {"n": 0, "fail": 0} def work(rec): for attempt in range(5): try: r = client.models.embed_content( model="gemini-embedding-2-preview", contents=rec["text_with_prefix"], config=cfg) rec["embedding"] = _norm(r.embeddings[0].values) with lock: out.write(json.dumps(rec, ensure_ascii=False) + "\n") out.flush() state["n"] += 1 if state["n"] % 500 == 0: log(f" embedded {state['n']}/{len(todo)}") return except Exception as e: if attempt == 4: with lock: state["fail"] += 1 log(f" chunk {rec['chunk_id']} PERMA-FAIL ({repr(e)[:80]})") else: time.sleep(1.5 * (attempt + 1)) with ThreadPoolExecutor(max_workers=workers) as ex: list(as_completed(ex.submit(work, r) for r in todo)) out.close() log(f"EMBED DONE: +{state['n']} (fail {state['fail']}, total file now {len(done)+state['n']})") def load_phase(recreate: bool): from qdrant_client import QdrantClient, models from fastembed import SparseTextEmbedding bm25 = SparseTextEmbedding(model_name="Qdrant/bm25") def to_sparse(text): r = list(bm25.embed([text]))[0] return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist()) client = QdrantClient(path=str(LOCAL_DB)) names = [c.name for c in client.get_collections().collections] if COLLECTION in names and recreate: client.delete_collection(COLLECTION); names.remove(COLLECTION) if COLLECTION not in names: client.create_collection( collection_name=COLLECTION, vectors_config={"dense": models.VectorParams(size=DENSE_DIM, distance=models.Distance.COSINE)}, sparse_vectors_config={"sparse": models.SparseVectorParams(modifier=models.Modifier.IDF)}, ) for field in ("dataset_ids", "store", "doc_type", "doc_url"): client.create_payload_index(collection_name=COLLECTION, field_name=field, field_schema=models.PayloadSchemaType.KEYWORD) log(f"created '{COLLECTION}' (dense+sparse, 4 indexes)") buf, total, t0 = [], 0, time.time() for line in EMB.read_text().splitlines(): if not line.strip(): continue c = json.loads(line) emb = c.get("embedding") if not emb: continue raw = c.get("text_raw", "") buf.append(models.PointStruct( id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])), vector={"dense": emb, "sparse": to_sparse(raw)}, payload={ "chunk_id": c["chunk_id"], "dataset_ids": c.get("dataset_ids", []), "store": c.get("store", ""), "stores": c.get("stores", []), "doc_url": c.get("doc_url", ""), "doc_title": c.get("doc_title", ""), "doc_kind": c.get("doc_kind", ""), "doc_type": "DEEP_DOC", "section": c.get("section", ""), "text_raw": raw[:2500], })) if len(buf) >= 400: client.upsert(collection_name=COLLECTION, points=buf) total += len(buf); buf = [] log(f" loaded {total} ({total/(time.time()-t0):.0f}/s)") if buf: client.upsert(collection_name=COLLECTION, points=buf); total += len(buf) log(f"LOAD DONE: {total} points; collection now {client.get_collection(COLLECTION).points_count}") client.close() def main(): ap = argparse.ArgumentParser() ap.add_argument("--phase", choices=("embed", "load", "all"), default="all") ap.add_argument("--recreate", action="store_true") a = ap.parse_args() workers = int(os.environ.get("WORKERS", "10")) sample = int(os.environ.get("SAMPLE_N", "0")) if a.phase in ("embed", "all"): embed_phase(workers, sample) if a.phase in ("load", "all") and not sample: load_phase(a.recreate) if __name__ == "__main__": main()