copernicus-rag-core / server /load_all.py
dmpantiu's picture
server kit: in-collection resume + async upserts + batch 512
320004c verified
Raw
History Blame Contribute Delete
8.18 kB
#!/usr/bin/env python3
"""Migrate the prebuilt copernicus-rag-core Qdrant indexes into a Qdrant SERVER.
Downloads indexes/*.tar.gz from the HF dataset (or uses --source-dir if you
already have them), opens each embedded index locally, and streams every
collection into the target server: identical vectors (dense 768 + sparse BM25),
identical payloads (incl. the relinked publication<->dataset fields), identical
payload indexes. No embedding model or API key of any kind is needed.
Usage:
python load_all.py --url http://localhost:6333
python load_all.py --url http://localhost:6333 --collections publications
python load_all.py --url https://<cluster>.cloud.qdrant.io --api-key <key>
python load_all.py --url ... --source-dir ./indexes_untarred # skip download
Resumable: a collection already on the server with the full point count is
skipped; pass --recreate to force a clean re-copy.
"""
import argparse
import os
import sys
import tarfile
import tempfile
import time
from pathlib import Path
from qdrant_client import QdrantClient, models
REPO = "dmpantiu/copernicus-rag-core"
TARBALLS = {
"qdrant_marine_and_cards.tar.gz": ["marine_docs", "copernicus_docs"],
"qdrant_cds_docs.tar.gz": ["cds_docs"],
"qdrant_eqc_qa.tar.gz": ["eqc_qa"],
"qdrant_publications.tar.gz": ["publications"],
}
BATCH = 512
# The embedded (local-mode) indexes cannot persist payload indexes, so they are
# re-created here exactly as the original loaders defined them.
K, I, B = "keyword", "integer", "bool"
PAYLOAD_INDEXES = {
"marine_docs": {"product_id": K, "doc_type": K, "chunk_type": K, "section_path": K},
"copernicus_docs": {"product_id": K, "doc_type": K, "store": K},
"cds_docs": {"dataset_ids": K, "store": K, "doc_type": K, "doc_url": K},
"eqc_qa": {"dataset_id": K, "store": K, "doc_type": K, "aspect": K},
"publications": {"doi": K, "paper_id": K, "journal": K, "year": I,
"domains": K, "orphan": B, "linked_products": K, "chunk_type": K},
}
def log(msg):
print(f"[load_all] {msg}", flush=True)
def fetch_and_untar(work: Path, only: set[str] | None) -> dict[str, Path]:
"""Download needed tarballs from HF and untar. Returns {tarball: qdrant_db dir}."""
from huggingface_hub import hf_hub_download
token = os.environ.get("HF_TOKEN")
if not token:
sys.exit("HF_TOKEN env var required to download the private dataset "
"(or pre-download and use --source-dir).")
out = {}
for tb, colls in TARBALLS.items():
if only and not (set(colls) & only):
continue
dest = work / tb.replace(".tar.gz", "")
if (dest / "qdrant_db").exists():
log(f"{tb}: already untarred, reusing")
else:
log(f"downloading {tb} ...")
p = hf_hub_download(REPO, f"indexes/{tb}", repo_type="dataset",
token=token, local_dir=work / "_dl")
dest.mkdir(parents=True, exist_ok=True)
log(f"untarring {tb} ...")
with tarfile.open(p) as t:
t.extractall(dest)
out[tb] = dest / "qdrant_db"
return out
def source_dirs(src: Path, only: set[str] | None) -> dict[str, Path]:
"""Use pre-untarred dirs: <src>/<tarball-stem>/qdrant_db."""
out = {}
for tb, colls in TARBALLS.items():
if only and not (set(colls) & only):
continue
d = src / tb.replace(".tar.gz", "") / "qdrant_db"
if not d.exists():
sys.exit(f"missing {d} — untar indexes/{tb} there, "
f"or drop --source-dir to auto-download")
out[tb] = d
return out
def migrate_collection(local: QdrantClient, remote: QdrantClient,
coll: str, recreate: bool):
info = local.get_collection(coll)
total = local.count(coll).count
skip_first = 0
if remote.collection_exists(coll):
have = remote.count(coll).count
if have == total and not recreate:
log(f"{coll}: server already has {have}/{total} points — skip "
f"(--recreate to force)")
return
if recreate or have == 0 or have > total:
log(f"{coll}: server has {have}/{total} — recreating")
remote.delete_collection(coll)
else:
# Interrupted copy: local scroll order is deterministic and
# upserts are idempotent, so resume with an overlap margin.
skip_first = max(0, have - 8 * BATCH)
log(f"{coll}: server has {have}/{total} — resuming from "
f"~{skip_first} (with overlap)")
if not remote.collection_exists(coll):
remote.create_collection(
collection_name=coll,
vectors_config=info.config.params.vectors,
sparse_vectors_config=info.config.params.sparse_vectors,
on_disk_payload=True,
)
indexes = {f: s.data_type for f, s in (info.payload_schema or {}).items()}
if not indexes:
indexes = PAYLOAD_INDEXES.get(coll, {})
for field, schema in indexes.items():
remote.create_payload_index(collection_name=coll, field_name=field,
field_schema=schema)
log(f"{coll}: created (vectors={list(info.config.params.vectors)}, "
f"sparse={list(info.config.params.sparse_vectors or {})}, "
f"payload indexes={list(indexes)})")
done, seen, offset, t0 = 0, 0, None, time.time()
while True:
points, offset = local.scroll(coll, limit=BATCH, offset=offset,
with_payload=True, with_vectors=True)
if not points:
break
seen += len(points)
if seen > skip_first:
batch = points if seen - len(points) >= skip_first else \
points[-(seen - skip_first):]
remote.upsert(coll, wait=False, points=[
models.PointStruct(id=p.id, vector=p.vector, payload=p.payload)
for p in batch])
done += len(batch)
if seen % (BATCH * 40) == 0 or offset is None:
rate = done / max(time.time() - t0, 1e-9)
log(f"{coll}: {skip_first + done}/{total} ({rate:.0f} pts/s live)")
if offset is None:
break
time.sleep(2) # let async upserts settle before the count check
got = remote.count(coll).count
status = "OK" if got == total else "MISMATCH"
log(f"{coll}: {status} — server {got} / source {total}")
if got != total:
sys.exit(f"{coll}: point count mismatch, aborting")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--url", required=True, help="Qdrant server URL, e.g. http://localhost:6333")
ap.add_argument("--api-key", default=None)
ap.add_argument("--source-dir", default=None,
help="dir with pre-untarred indexes (skips HF download)")
ap.add_argument("--collections", nargs="*", default=None,
help="subset, e.g. --collections publications eqc_qa")
ap.add_argument("--recreate", action="store_true")
a = ap.parse_args()
only = set(a.collections) if a.collections else None
remote = QdrantClient(url=a.url, api_key=a.api_key, timeout=120)
remote.get_collections() # fail fast if unreachable
if a.source_dir:
dirs = source_dirs(Path(a.source_dir), only)
else:
work = Path(tempfile.gettempdir()) / "copernicus_rag_indexes"
work.mkdir(parents=True, exist_ok=True)
log(f"workdir: {work}")
dirs = fetch_and_untar(work, only)
for tb, db_dir in dirs.items():
log(f"opening embedded index {db_dir}")
local = QdrantClient(path=str(db_dir))
try:
for coll in TARBALLS[tb]:
if only and coll not in only:
continue
migrate_collection(local, remote, coll, a.recreate)
finally:
local.close()
log("ALL DONE. Server collections:")
for c in remote.get_collections().collections:
log(f" {c.name}: {remote.count(c.name).count} points")
if __name__ == "__main__":
main()