#!/usr/bin/env python3 """ verify_eqc_qa.py — sanity-check the eqc_qa Qdrant collection. - point count == embedded chunk count - BM25 (sparse-only) probes [always works, no API] - hybrid dense+BM25 RRF probes [needs one query embedding per probe; degrades to BM25-only if the Gemini quota 429s] Probes: SST consistency, satellite soil moisture completeness, multi-origin atlas. Prints top hits with report_id + dataset_id. """ import json import sys import threading from pathlib import Path sys.path.insert(0, "/Users/dmpantiu/copernicus_mcp/marine_rag") import net_ipv4 # noqa: F401,E402 from qdrant_client import QdrantClient, models from fastembed import SparseTextEmbedding ROOT = Path(__file__).resolve().parent COLLECTION = "eqc_qa" DENSE_DIM = 768 LOCAL_DB = ROOT / "qdrant_db" INPUT = ROOT / "chunks_embedded.jsonl" _bm25 = None _lock = threading.Lock() def log(*a): print(*a, file=sys.stderr, flush=True) def resolve_key() -> str: import os for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"): if os.environ.get(var): return os.environ[var] for env in (Path("/Users/dmpantiu/copernicus_mcp/.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 key") def embed_query(q: str): from google import genai from google.genai import types import numpy as np client = genai.Client(api_key=resolve_key()) r = client.models.embed_content( model="gemini-embedding-2-preview", contents=q, config=types.EmbedContentConfig(task_type="RETRIEVAL_QUERY", output_dimensionality=DENSE_DIM)) v = np.array(list(r.embeddings[0].values), dtype=np.float32) n = np.linalg.norm(v) return (v / n).tolist() if n > 0 else v.tolist() def sparse_query(q: str): global _bm25 with _lock: if _bm25 is None: _bm25 = SparseTextEmbedding(model_name="Qdrant/bm25") sp = list(_bm25.query_embed(q))[0] return models.SparseVector(indices=sp.indices.tolist(), values=sp.values.tolist()) def search(client, query, top_k=5): sparse = sparse_query(query) dense = None try: dense = embed_query(query) except Exception as e: log(f" [dense unavailable: {str(e)[:70]}] BM25-only") if dense is not None: res = client.query_points( collection_name=COLLECTION, prefetch=[ models.Prefetch(query=dense, using="dense", limit=50), models.Prefetch(query=sparse, using="sparse", limit=50), ], query=models.FusionQuery(fusion=models.Fusion.RRF), limit=top_k, with_payload=True, ) mode = "hybrid dense+BM25 RRF" else: res = client.query_points(collection_name=COLLECTION, query=sparse, using="sparse", limit=top_k, with_payload=True) mode = "BM25-only" return res.points, mode def main(): client = QdrantClient(path=str(LOCAL_DB)) n_pts = client.get_collection(COLLECTION).points_count n_emb = sum(1 for _ in open(INPUT)) if INPUT.exists() else 0 print(f"points={n_pts} embedded_chunks={n_emb} match={'OK' if n_pts == n_emb else 'MISMATCH'}") probes = [ "sea surface temperature consistency assessment", "completeness of satellite soil moisture", "multi-origin atlas quality", ] for q in probes: pts, mode = search(client, q, top_k=5) print(f"\n=== '{q}' [{mode}] ===") for i, p in enumerate(pts, 1): pl = p.payload print(f" #{i} score={p.score:.4f} report={pl['report_id']}") print(f" dataset={pl['dataset_id']} aspect={pl['aspect']} " f"conf={pl.get('match_confidence','')} sec='{pl.get('section','')[:50]}'") print(f" {pl.get('text_raw','')[:150].strip()}") if __name__ == "__main__": main()