copernicus-rag-core / scripts /marine_rag /load_copernicus_docs.py
dmpantiu's picture
Upload folder using huggingface_hub
0ec8fd6 verified
Raw
History Blame Contribute Delete
4.2 kB
#!/usr/bin/env python3
"""
load_copernicus_docs.py — build the unified `copernicus_docs` Qdrant collection:
one metadata card per dataset across ALL four Copernicus stores (~1415).
- 164 CDS/ADS/EWDS cards from out/cds_cards_embedded.jsonl (store=CDS/ADS/EWDS)
- 1251 Marine dataset cards, reusing the already-embedded CARD chunks in
out/chunks_embedded.jsonl (store=CMEMS)
Dense (768-dim Cosine, gemini-embedding-2-preview) + sparse (BM25) hybrid,
same recipe as marine_docs. Adds a `store` payload keyword for per-store filtering.
The deep Marine PUM/QUID/SQO doc-RAG (marine_docs) is left untouched.
"""
import json
import time
import uuid
from pathlib import Path
from qdrant_client import QdrantClient, models
from fastembed import SparseTextEmbedding
ROOT = Path(__file__).resolve().parent
OUT = ROOT / "out"
COLLECTION = "copernicus_docs"
DENSE_DIM = 768
LOCAL_DB = OUT / "qdrant_db"
CDS_EMB = OUT / "cds_cards_embedded.jsonl"
MARINE_EMB = OUT / "chunks_embedded.jsonl"
BATCH = 400
_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
def to_sparse(text: str) -> models.SparseVector:
r = list(_bm25.embed([text]))[0]
return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist())
def iter_cards():
"""Yield (chunk, store) for every dataset card to index."""
# CDS/ADS/EWDS — each row already carries a `store` field
for line in open(CDS_EMB, encoding="utf-8"):
c = json.loads(line)
if c.get("embedding"):
yield c, c.get("store", "CDS")
# Marine — reuse CARD chunks only, tag store=CMEMS
seen = set()
for line in open(MARINE_EMB, encoding="utf-8"):
c = json.loads(line)
if c.get("doc_type") != "CARD" or not c.get("embedding"):
continue
if c["chunk_id"] in seen:
continue
seen.add(c["chunk_id"])
yield c, "CMEMS"
def create_collection(client: QdrantClient) -> None:
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 in ("product_id", "doc_type", "store"):
client.create_payload_index(collection_name=COLLECTION, field_name=field,
field_schema=models.PayloadSchemaType.KEYWORD)
print(f"created '{COLLECTION}' (dense+sparse, 3 payload indexes)")
def load(client: QdrantClient) -> None:
buf, total, t0 = [], 0, time.time()
per_store = {}
for c, store in iter_cards():
per_store[store] = per_store.get(store, 0) + 1
raw = c.get("text_raw", c.get("text_with_prefix", ""))
buf.append(models.PointStruct(
id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])),
vector={"dense": c["embedding"], "sparse": to_sparse(raw)},
payload={
"chunk_id": c["chunk_id"],
"product_id": c["product_id"],
"product_title": c.get("product_title", ""),
"dataset_id": c.get("doc_id", c["product_id"]),
"doc_type": c.get("doc_type", "CARD"),
"chunk_type": c.get("chunk_type", "card"),
"store": store,
"text_raw": raw[:2500],
},
))
if len(buf) >= BATCH:
client.upsert(collection_name=COLLECTION, points=buf)
total += len(buf); buf = []
print(f" [{total:,}] {total/(time.time()-t0):.0f} pts/s")
if buf:
client.upsert(collection_name=COLLECTION, points=buf)
total += len(buf)
print(f"DONE: {total:,} points | per store: {per_store} | "
f"collection now {client.get_collection(COLLECTION).points_count:,}")
def main():
client = QdrantClient(path=str(LOCAL_DB))
print(f"Qdrant local: {LOCAL_DB}")
create_collection(client)
load(client)
if __name__ == "__main__":
main()