File size: 6,442 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python3
"""
load_pubs_qdrant.py — stream the ALREADY-EMBEDDED Copernicus publications corpus
(out/chunks_embedded.jsonl, 768-dim gemini-embedding-2-preview, L2-norm)
into a fresh embedded Qdrant at pubs_rag/qdrant_db, collection `publications`.

NO re-embedding: dense vectors are read straight from the archive.
Sparse BM25 (FastEmbed Qdrant/bm25, IDF modifier) is computed from text_raw
during load. Join metadata (canonical DOI, domains, has_local_md, registry
orphan/linked_products) comes from pubs_join.build_paper_index.

Payload: chunk_id, paper_id, doi (CANONICAL), title, journal, year, domains[],
section, chunk_type, text_raw (<=2500), orphan, linked_products[], has_local_md.
Indexes: doi, paper_id, journal, year, domains, orphan, linked_products,
chunk_type.

Single clean run (embedded Qdrant = single-process lock). ~20-60 min.
"""
import argparse
import json
import shutil
import time
import uuid
from pathlib import Path

from qdrant_client import QdrantClient, models
from fastembed import SparseTextEmbedding

import pubs_join

ROOT = Path(__file__).resolve().parent
OUT = ROOT / "out"
LOG = OUT / "load_archive.log"
COLLECTION = "publications"
DENSE_DIM = 768
LOCAL_DB = ROOT / "qdrant_db"
ARCHIVE = pubs_join.ARCHIVE
BATCH = 400

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


def log(msg: str):
    line = f"[{time.strftime('%H:%M:%S')}] {msg}"
    print(line, flush=True)
    if _logf:
        _logf.write(line + "\n")
        _logf.flush()


def create_collection(client: QdrantClient):
    names = [c.name for c in client.get_collections().collections]
    if COLLECTION in names:
        client.delete_collection(COLLECTION)
    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, schema in [
        ("doi", models.PayloadSchemaType.KEYWORD),
        ("paper_id", models.PayloadSchemaType.KEYWORD),
        ("journal", models.PayloadSchemaType.KEYWORD),
        ("year", models.PayloadSchemaType.INTEGER),
        ("domains", models.PayloadSchemaType.KEYWORD),
        ("orphan", models.PayloadSchemaType.BOOL),
        ("linked_products", models.PayloadSchemaType.KEYWORD),
        ("chunk_type", models.PayloadSchemaType.KEYWORD),
    ]:
        client.create_payload_index(collection_name=COLLECTION, field_name=field, field_schema=schema)
    log(f"created '{COLLECTION}' (dense 768 cosine + sparse bm25, 8 payload indexes)")


def sparse_batch(texts):
    return list(_bm25.embed(texts))


def flush(client, buf_pts, buf_txt):
    sparses = sparse_batch(buf_txt)
    for pt, sp in zip(buf_pts, sparses):
        pt.vector["sparse"] = models.SparseVector(
            indices=sp.indices.tolist(), values=sp.values.tolist())
    client.upsert(collection_name=COLLECTION, points=buf_pts)


def load(client, index, limit=None):
    buf_pts, buf_txt = [], []
    total = skipped = 0
    t0 = time.time()
    with open(ARCHIVE, encoding="utf-8") as f:
        for i, line in enumerate(f):
            if limit and i >= limit:
                break
            c = json.loads(line)
            emb = c.get("embedding")
            if not emb:
                skipped += 1
                continue
            pid = c["paper_id"]
            m = index[pid]
            raw = c.get("text_raw") or c.get("text_with_prefix", "")
            year = c.get("year")
            try:
                year = int(year)
            except (TypeError, ValueError):
                year = None
            section = c.get("section") or c.get("section_path") or c.get("section_name") or ""
            pt = models.PointStruct(
                id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])),
                vector={"dense": emb},  # sparse filled in flush()
                payload={
                    "chunk_id": c["chunk_id"],
                    "paper_id": pid,
                    "doi": m["doi"],
                    "title": c.get("title", ""),
                    "journal": c.get("journal", ""),
                    "year": year,
                    "domains": m["domains"],
                    "section": section,
                    "chunk_type": c.get("chunk_type", "text"),
                    "text_raw": raw[:2500],
                    "orphan": m["orphan"],
                    "linked_products": m["linked_products"],
                    "has_local_md": m["has_local_md"],
                },
            )
            buf_pts.append(pt)
            buf_txt.append(raw)
            if len(buf_pts) >= BATCH:
                flush(client, buf_pts, buf_txt)
                total += len(buf_pts)
                buf_pts, buf_txt = [], []
                if total % 5000 < BATCH:
                    rate = total / (time.time() - t0)
                    log(f"  loaded {total:,} chunks  {rate:.0f}/s  "
                        f"eta {(430066 - total) / max(rate, 1) / 60:.1f} min")
    if buf_pts:
        flush(client, buf_pts, buf_txt)
        total += len(buf_pts)
    dur = time.time() - t0
    pc = client.get_collection(COLLECTION).points_count
    log(f"DONE: loaded {total:,} chunks (skipped {skipped}) in {dur/60:.1f} min "
        f"({total/dur:.0f}/s); collection points_count={pc:,}")
    return total, dur


def main():
    global _logf
    ap = argparse.ArgumentParser()
    ap.add_argument("--limit", type=int, default=None)
    ap.add_argument("--fresh", action="store_true", help="rm qdrant_db dir first")
    a = ap.parse_args()

    OUT.mkdir(exist_ok=True)
    _logf = open(LOG, "a", encoding="utf-8")
    log("=== load_pubs_qdrant start ===")

    free_gb = shutil.disk_usage(str(ROOT)).free / 1e9
    log(f"disk free: {free_gb:.1f} GB")
    if free_gb < 4:
        raise SystemExit("need ~4GB free")

    log("building paper join index (one pass over archive headers)...")
    index, stats = pubs_join.build_paper_index(log=log)
    pubs_join.print_report(stats)

    if a.fresh and LOCAL_DB.exists():
        shutil.rmtree(LOCAL_DB)
        log(f"removed {LOCAL_DB}")

    client = QdrantClient(path=str(LOCAL_DB))
    log(f"Qdrant: local {LOCAL_DB}")
    create_collection(client)
    total, dur = load(client, index, a.limit)
    client.close()
    log("client closed")


if __name__ == "__main__":
    main()