File size: 3,728 Bytes
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
"""
verify_pubs.py — sanity-check the `publications` Qdrant collection.
NO Gemini API calls (quota exhausted).

(a) point count + per-domain + orphan/linked/local counts
(b) BM25 (sparse) probes — top-5 (title, year, score)
(c) dense sanity via a STORED vector: fetch a chunk on a distinctive topic,
    query dense neighbours, confirm same-topic chunks rank top.
"""
from pathlib import Path

from qdrant_client import QdrantClient, models
from fastembed import SparseTextEmbedding

ROOT = Path(__file__).resolve().parent
COLLECTION = "publications"
LOCAL_DB = ROOT / "qdrant_db"

PROBES = [
    "ocean heat content trend",
    "sea ice albedo feedback",
    "ERA5 reanalysis evaluation",
    "flood forecasting skill",
]
DOMAINS = ["ocean/marine", "atmosphere", "cryosphere", "land",
           "climate-modeling", "climate-general", "emergency"]

_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")


def sparse_vec(text):
    r = list(_bm25.query_embed(text))[0]
    return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist())


def show(hits, n=5):
    for h in hits[:n]:
        p = h.payload
        dom = ",".join(p.get("domains", []))
        title = (p.get("title") or "")[:70]
        print(f"    [{h.score:.3f}] ({p.get('year')}) {title}  <{p.get('chunk_type')}> [{dom}]")


def main():
    client = QdrantClient(path=str(LOCAL_DB))
    info = client.get_collection(COLLECTION)
    print(f"collection '{COLLECTION}': {info.points_count:,} points\n")

    def count(flt):
        return client.count(collection_name=COLLECTION, exact=True, count_filter=flt).count

    print("per-domain counts:")
    for d in DOMAINS:
        c = count(models.Filter(must=[models.FieldCondition(
            key="domains", match=models.MatchValue(value=d))]))
        print(f"  {d:18s} {c:,}")
    orphan = count(models.Filter(must=[models.FieldCondition(
        key="orphan", match=models.MatchValue(value=True))]))
    linked = count(models.Filter(must=[models.FieldCondition(
        key="orphan", match=models.MatchValue(value=False))]))
    local = count(models.Filter(must=[models.FieldCondition(
        key="has_local_md", match=models.MatchValue(value=True))]))
    print(f"\n  orphan=true   {orphan:,}")
    print(f"  orphan=false  {linked:,}  (registry-linked)")
    print(f"  has_local_md  {local:,}\n")

    print("=== (b) BM25 sparse probes (top-5) ===")
    for q in PROBES:
        print(f"\nQUERY: {q}")
        hits = client.query_points(collection_name=COLLECTION, query=sparse_vec(q),
                                   using="sparse", limit=5, with_payload=True).points
        show(hits, 5)

    print("\n=== (c) dense sanity (stored vector, no API) ===")
    # pick a distinctive-topic chunk via BM25, use its stored dense vector as query
    seed_hits = client.query_points(collection_name=COLLECTION,
                                    query=sparse_vec("sea ice albedo feedback arctic"),
                                    using="sparse", limit=1, with_payload=True).points
    seed = seed_hits[0]
    rec = client.retrieve(collection_name=COLLECTION, ids=[seed.id],
                          with_vectors=True, with_payload=True)[0]
    dvec = rec.vector["dense"]
    print(f"seed chunk: ({rec.payload.get('year')}) "
          f"{(rec.payload.get('title') or '')[:70]} [{','.join(rec.payload.get('domains', []))}]")
    print(f"  seed text: {(rec.payload.get('text_raw') or '')[:110].replace(chr(10),' ')}")
    nn = client.query_points(collection_name=COLLECTION, query=dvec, using="dense",
                             limit=6, with_payload=True).points
    print("  dense nearest neighbours:")
    show(nn, 6)


if __name__ == "__main__":
    main()