File size: 6,782 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 | #!/usr/bin/env python3
"""
build_bundle.py — gather EVERYTHING the RAG is made of into one place: rag_bundle/
- all_chunks.jsonl : every text chunk from every collection, unified schema,
deduped by chunk_id, tagged with `collection` (embeddings stripped -> portable).
- embedded/ : symlinks to the real *_embedded.jsonl (vectors, no copy).
- source_chunks/ : symlinks to each collection's source chunks.jsonl.
- raw/ : symlinks to the parsed-markdown dirs (marine_parsed, etc.).
- sidecars/ : notebook code sidecar + catalog + unified metadata (copied, small).
- MANIFEST.json + INDEX.md : full inventory (counts, sizes, sources, qdrant points).
Disk-safe: big files are symlinked, only the merged text + small sidecars are written.
"""
import json
import os
import shutil
from pathlib import Path
ROOT = Path("/Users/dmpantiu/copernicus_mcp")
OUT = ROOT / "rag_bundle"
# (collection, source chunks.jsonl [text], embedded.jsonl, id_field)
SOURCES = [
("marine_docs", "marine_rag/out/chunks.jsonl", "marine_rag/out/chunks_embedded.jsonl"),
("cds_docs", "deep_docs/chunks.jsonl", "deep_docs/chunks_embedded.jsonl"),
("eqc_qa", "eqc_qa/chunks.jsonl", "eqc_qa/chunks_embedded.jsonl"),
("copernicus_docs", "marine_rag/out/cds_cards_chunks.jsonl", "marine_rag/out/cds_cards_embedded.jsonl"),
("publications", "pubs_rag/out/chunks.jsonl", "pubs_rag/out/chunks_embedded.jsonl"),
]
RAW_DIRS = ["marine_parsed", "deep_docs/parsed", "eqc_qa/parsed", "eqc_qa/notebooks_code"]
SIDECARS = ["eqc_qa/notebooks_by_dataset.json", "marine_rag/out/catalog.json"]
def norm_row(collection, o):
"""Unified minimal schema (drop embeddings; keep text + key metadata)."""
return {
"collection": collection,
"chunk_id": o.get("chunk_id"),
"doc_type": o.get("doc_type") or o.get("chunk_type"),
"store": o.get("store"),
"product_id": o.get("product_id"),
"dataset_ids": o.get("dataset_ids") or ([o["dataset_id"]] if o.get("dataset_id") else None),
"doc_id": o.get("doc_id"),
"doc_url": o.get("doc_url"),
"title": o.get("title") or o.get("product_title") or o.get("doc_title"),
"section": o.get("section") or o.get("section_path"),
"token_count": o.get("token_count"),
"text_raw": o.get("text_raw") or o.get("text_with_prefix") or "",
}
def link(src: Path, dst: Path):
if dst.exists() or dst.is_symlink():
dst.unlink()
if src.exists():
dst.symlink_to(src)
return True
return False
def main():
for sub in ("embedded", "source_chunks", "raw", "sidecars"):
(OUT / sub).mkdir(parents=True, exist_ok=True)
manifest = {"collections": [], "raw_dirs": [], "sidecars": [], "totals": {}}
all_path = OUT / "all_chunks.jsonl"
seen = set()
total_chunks = 0
with open(all_path, "w", encoding="utf-8") as out:
for coll, chunks_rel, emb_rel in SOURCES:
src = ROOT / chunks_rel
entry = {"collection": coll, "source_chunks": chunks_rel,
"embedded": emb_rel, "chunks_written": 0, "duplicates_skipped": 0,
"source_exists": src.exists()}
if src.exists():
for line in open(src, encoding="utf-8"):
line = line.strip()
if not line:
continue
o = json.loads(line)
cid = o.get("chunk_id")
key = (coll, cid)
if cid and key in seen:
entry["duplicates_skipped"] += 1
continue
seen.add(key)
out.write(json.dumps(norm_row(coll, o), ensure_ascii=False) + "\n")
entry["chunks_written"] += 1
total_chunks += 1
# symlinks
link(src, OUT / "source_chunks" / f"{coll}__{src.name}")
emb = ROOT / emb_rel
entry["embedded_exists"] = emb.exists()
if emb.exists():
entry["embedded_bytes"] = emb.stat().st_size
link(emb, OUT / "embedded" / f"{coll}__{emb.name}")
manifest["collections"].append(entry)
# raw dirs (symlink)
for rd in RAW_DIRS:
src = ROOT / rd
if src.is_dir():
n_md = sum(1 for _ in src.rglob("*.md"))
link(src, OUT / "raw" / rd.replace("/", "__"))
manifest["raw_dirs"].append({"dir": rd, "md_files": n_md})
# sidecars (copy — small)
for sc in SIDECARS:
src = ROOT / sc
if src.exists():
dst = OUT / "sidecars" / src.name
shutil.copy2(src, dst)
manifest["sidecars"].append({"file": sc, "bytes": src.stat().st_size})
manifest["totals"] = {
"unified_text_chunks": total_chunks,
"all_chunks_jsonl_bytes": all_path.stat().st_size,
"collections": len(SOURCES),
}
(OUT / "MANIFEST.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2))
# human-readable index
lines = ["# RAG bundle — consolidated corpus\n",
f"Unified text chunks: **{total_chunks:,}** in `all_chunks.jsonl` "
f"({all_path.stat().st_size/1e6:.0f} MB, embeddings stripped)\n",
"## Collections\n",
"| collection | text chunks | source | embedded |",
"|---|--:|---|---|"]
for e in manifest["collections"]:
eb = f"{e.get('embedded_bytes',0)/1e6:.0f}MB" if e.get("embedded_exists") else "—"
lines.append(f"| {e['collection']} | {e['chunks_written']:,} | "
f"`{e['source_chunks']}` | {eb} |")
lines += ["\n## Raw markdown (symlinked in raw/)\n",
"| dir | md files |", "|---|--:|"]
for r in manifest["raw_dirs"]:
lines.append(f"| {r['dir']} | {r['md_files']:,} |")
lines += ["\n## Sidecars (copied)\n"] + [f"- `{s['file']}`" for s in manifest["sidecars"]]
lines += ["\n## Layout",
"- `all_chunks.jsonl` — every chunk, unified schema, `collection` field",
"- `embedded/` — symlinks to vector files (768-d gemini)",
"- `source_chunks/` — symlinks to per-collection source jsonl",
"- `raw/` — symlinks to parsed-markdown trees",
"- `sidecars/` — notebook code map + catalog"]
(OUT / "INDEX.md").write_text("\n".join(lines) + "\n")
print(json.dumps(manifest["totals"], indent=2))
for e in manifest["collections"]:
print(f" {e['collection']:16s} {e['chunks_written']:>7,} chunks "
f"(dupes {e['duplicates_skipped']})")
if __name__ == "__main__":
main()
|