Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- scripts/build_bundle.py +155 -0
- scripts/build_rag_tree.sh +77 -0
- scripts/deep_docs/chunk_docs.py +175 -0
- scripts/deep_docs/embed_load.py +177 -0
- scripts/deep_docs/fetch_parse.py +141 -0
- scripts/eqc_qa/chunk_reports.py +220 -0
- scripts/eqc_qa/embed_reports.py +266 -0
- scripts/eqc_qa/eqc_finish.py +69 -0
- scripts/eqc_qa/eqc_orchestrator.py +78 -0
- scripts/eqc_qa/extract_code.py +209 -0
- scripts/eqc_qa/fetch_reports.py +53 -0
- scripts/eqc_qa/load_eqc_qa.py +114 -0
- scripts/eqc_qa/merge_notebooks.py +126 -0
- scripts/eqc_qa/parse_reports.py +203 -0
- scripts/eqc_qa/verify_eqc_qa.py +122 -0
- scripts/marine_rag/MCP_INTEGRATION.md +39 -0
- scripts/marine_rag/PLAN.md +177 -0
- scripts/marine_rag/RAG_SERVER.md +69 -0
- scripts/marine_rag/batch_loop.sh +30 -0
- scripts/marine_rag/batch_orchestrator.py +203 -0
- scripts/marine_rag/build_catalog.py +132 -0
- scripts/marine_rag/build_cds_cards.py +145 -0
- scripts/marine_rag/build_meta_chunks.py +123 -0
- scripts/marine_rag/build_missing_cds_cards.py +126 -0
- scripts/marine_rag/build_tree.py +116 -0
- scripts/marine_rag/chunk_docs.py +225 -0
- scripts/marine_rag/clean_md.py +150 -0
- scripts/marine_rag/embed.py +265 -0
- scripts/marine_rag/embed_cds_batch.py +108 -0
- scripts/marine_rag/embed_cds_cards.py +81 -0
- scripts/marine_rag/load_copernicus_docs.py +112 -0
- scripts/marine_rag/load_qdrant.py +114 -0
- scripts/marine_rag/net_ipv4.py +18 -0
- scripts/marine_rag/rag_api.py +110 -0
- scripts/marine_rag/rag_server.py +1026 -0
- scripts/marine_rag/run_overnight.sh +62 -0
- scripts/marine_rag/search.py +144 -0
- scripts/marine_rag/verify_copernicus_docs.py +77 -0
- scripts/meta_harvest/01_dump_cmems.py +30 -0
- scripts/meta_harvest/02_harvest_stac.py +89 -0
- scripts/meta_harvest/03_enrich_cmems.py +201 -0
- scripts/meta_harvest/04_harvest_pages.py +167 -0
- scripts/meta_harvest/05_enrich_stac.py +72 -0
- scripts/meta_harvest/06_unify.py +149 -0
- scripts/meta_harvest/07_stats.py +106 -0
- scripts/meta_harvest/08_harvest_forms.py +145 -0
- scripts/meta_harvest/GAPS.md +74 -0
- scripts/meta_harvest/STATS.md +119 -0
- scripts/notebook_harvest/parse_gallery.py +126 -0
- scripts/notebook_harvest/parse_instac.py +192 -0
scripts/build_bundle.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
build_bundle.py — gather EVERYTHING the RAG is made of into one place: rag_bundle/
|
| 4 |
+
|
| 5 |
+
- all_chunks.jsonl : every text chunk from every collection, unified schema,
|
| 6 |
+
deduped by chunk_id, tagged with `collection` (embeddings stripped -> portable).
|
| 7 |
+
- embedded/ : symlinks to the real *_embedded.jsonl (vectors, no copy).
|
| 8 |
+
- source_chunks/ : symlinks to each collection's source chunks.jsonl.
|
| 9 |
+
- raw/ : symlinks to the parsed-markdown dirs (marine_parsed, etc.).
|
| 10 |
+
- sidecars/ : notebook code sidecar + catalog + unified metadata (copied, small).
|
| 11 |
+
- MANIFEST.json + INDEX.md : full inventory (counts, sizes, sources, qdrant points).
|
| 12 |
+
|
| 13 |
+
Disk-safe: big files are symlinked, only the merged text + small sidecars are written.
|
| 14 |
+
"""
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
ROOT = Path("/Users/dmpantiu/copernicus_mcp")
|
| 21 |
+
OUT = ROOT / "rag_bundle"
|
| 22 |
+
|
| 23 |
+
# (collection, source chunks.jsonl [text], embedded.jsonl, id_field)
|
| 24 |
+
SOURCES = [
|
| 25 |
+
("marine_docs", "marine_rag/out/chunks.jsonl", "marine_rag/out/chunks_embedded.jsonl"),
|
| 26 |
+
("cds_docs", "deep_docs/chunks.jsonl", "deep_docs/chunks_embedded.jsonl"),
|
| 27 |
+
("eqc_qa", "eqc_qa/chunks.jsonl", "eqc_qa/chunks_embedded.jsonl"),
|
| 28 |
+
("copernicus_docs", "marine_rag/out/cds_cards_chunks.jsonl", "marine_rag/out/cds_cards_embedded.jsonl"),
|
| 29 |
+
("publications", "pubs_rag/out/chunks.jsonl", "pubs_rag/out/chunks_embedded.jsonl"),
|
| 30 |
+
]
|
| 31 |
+
RAW_DIRS = ["marine_parsed", "deep_docs/parsed", "eqc_qa/parsed", "eqc_qa/notebooks_code"]
|
| 32 |
+
SIDECARS = ["eqc_qa/notebooks_by_dataset.json", "marine_rag/out/catalog.json"]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def norm_row(collection, o):
|
| 36 |
+
"""Unified minimal schema (drop embeddings; keep text + key metadata)."""
|
| 37 |
+
return {
|
| 38 |
+
"collection": collection,
|
| 39 |
+
"chunk_id": o.get("chunk_id"),
|
| 40 |
+
"doc_type": o.get("doc_type") or o.get("chunk_type"),
|
| 41 |
+
"store": o.get("store"),
|
| 42 |
+
"product_id": o.get("product_id"),
|
| 43 |
+
"dataset_ids": o.get("dataset_ids") or ([o["dataset_id"]] if o.get("dataset_id") else None),
|
| 44 |
+
"doc_id": o.get("doc_id"),
|
| 45 |
+
"doc_url": o.get("doc_url"),
|
| 46 |
+
"title": o.get("title") or o.get("product_title") or o.get("doc_title"),
|
| 47 |
+
"section": o.get("section") or o.get("section_path"),
|
| 48 |
+
"token_count": o.get("token_count"),
|
| 49 |
+
"text_raw": o.get("text_raw") or o.get("text_with_prefix") or "",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def link(src: Path, dst: Path):
|
| 54 |
+
if dst.exists() or dst.is_symlink():
|
| 55 |
+
dst.unlink()
|
| 56 |
+
if src.exists():
|
| 57 |
+
dst.symlink_to(src)
|
| 58 |
+
return True
|
| 59 |
+
return False
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main():
|
| 63 |
+
for sub in ("embedded", "source_chunks", "raw", "sidecars"):
|
| 64 |
+
(OUT / sub).mkdir(parents=True, exist_ok=True)
|
| 65 |
+
|
| 66 |
+
manifest = {"collections": [], "raw_dirs": [], "sidecars": [], "totals": {}}
|
| 67 |
+
all_path = OUT / "all_chunks.jsonl"
|
| 68 |
+
seen = set()
|
| 69 |
+
total_chunks = 0
|
| 70 |
+
|
| 71 |
+
with open(all_path, "w", encoding="utf-8") as out:
|
| 72 |
+
for coll, chunks_rel, emb_rel in SOURCES:
|
| 73 |
+
src = ROOT / chunks_rel
|
| 74 |
+
entry = {"collection": coll, "source_chunks": chunks_rel,
|
| 75 |
+
"embedded": emb_rel, "chunks_written": 0, "duplicates_skipped": 0,
|
| 76 |
+
"source_exists": src.exists()}
|
| 77 |
+
if src.exists():
|
| 78 |
+
for line in open(src, encoding="utf-8"):
|
| 79 |
+
line = line.strip()
|
| 80 |
+
if not line:
|
| 81 |
+
continue
|
| 82 |
+
o = json.loads(line)
|
| 83 |
+
cid = o.get("chunk_id")
|
| 84 |
+
key = (coll, cid)
|
| 85 |
+
if cid and key in seen:
|
| 86 |
+
entry["duplicates_skipped"] += 1
|
| 87 |
+
continue
|
| 88 |
+
seen.add(key)
|
| 89 |
+
out.write(json.dumps(norm_row(coll, o), ensure_ascii=False) + "\n")
|
| 90 |
+
entry["chunks_written"] += 1
|
| 91 |
+
total_chunks += 1
|
| 92 |
+
# symlinks
|
| 93 |
+
link(src, OUT / "source_chunks" / f"{coll}__{src.name}")
|
| 94 |
+
emb = ROOT / emb_rel
|
| 95 |
+
entry["embedded_exists"] = emb.exists()
|
| 96 |
+
if emb.exists():
|
| 97 |
+
entry["embedded_bytes"] = emb.stat().st_size
|
| 98 |
+
link(emb, OUT / "embedded" / f"{coll}__{emb.name}")
|
| 99 |
+
manifest["collections"].append(entry)
|
| 100 |
+
|
| 101 |
+
# raw dirs (symlink)
|
| 102 |
+
for rd in RAW_DIRS:
|
| 103 |
+
src = ROOT / rd
|
| 104 |
+
if src.is_dir():
|
| 105 |
+
n_md = sum(1 for _ in src.rglob("*.md"))
|
| 106 |
+
link(src, OUT / "raw" / rd.replace("/", "__"))
|
| 107 |
+
manifest["raw_dirs"].append({"dir": rd, "md_files": n_md})
|
| 108 |
+
|
| 109 |
+
# sidecars (copy — small)
|
| 110 |
+
for sc in SIDECARS:
|
| 111 |
+
src = ROOT / sc
|
| 112 |
+
if src.exists():
|
| 113 |
+
dst = OUT / "sidecars" / src.name
|
| 114 |
+
shutil.copy2(src, dst)
|
| 115 |
+
manifest["sidecars"].append({"file": sc, "bytes": src.stat().st_size})
|
| 116 |
+
|
| 117 |
+
manifest["totals"] = {
|
| 118 |
+
"unified_text_chunks": total_chunks,
|
| 119 |
+
"all_chunks_jsonl_bytes": all_path.stat().st_size,
|
| 120 |
+
"collections": len(SOURCES),
|
| 121 |
+
}
|
| 122 |
+
(OUT / "MANIFEST.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2))
|
| 123 |
+
|
| 124 |
+
# human-readable index
|
| 125 |
+
lines = ["# RAG bundle — consolidated corpus\n",
|
| 126 |
+
f"Unified text chunks: **{total_chunks:,}** in `all_chunks.jsonl` "
|
| 127 |
+
f"({all_path.stat().st_size/1e6:.0f} MB, embeddings stripped)\n",
|
| 128 |
+
"## Collections\n",
|
| 129 |
+
"| collection | text chunks | source | embedded |",
|
| 130 |
+
"|---|--:|---|---|"]
|
| 131 |
+
for e in manifest["collections"]:
|
| 132 |
+
eb = f"{e.get('embedded_bytes',0)/1e6:.0f}MB" if e.get("embedded_exists") else "—"
|
| 133 |
+
lines.append(f"| {e['collection']} | {e['chunks_written']:,} | "
|
| 134 |
+
f"`{e['source_chunks']}` | {eb} |")
|
| 135 |
+
lines += ["\n## Raw markdown (symlinked in raw/)\n",
|
| 136 |
+
"| dir | md files |", "|---|--:|"]
|
| 137 |
+
for r in manifest["raw_dirs"]:
|
| 138 |
+
lines.append(f"| {r['dir']} | {r['md_files']:,} |")
|
| 139 |
+
lines += ["\n## Sidecars (copied)\n"] + [f"- `{s['file']}`" for s in manifest["sidecars"]]
|
| 140 |
+
lines += ["\n## Layout",
|
| 141 |
+
"- `all_chunks.jsonl` — every chunk, unified schema, `collection` field",
|
| 142 |
+
"- `embedded/` — symlinks to vector files (768-d gemini)",
|
| 143 |
+
"- `source_chunks/` — symlinks to per-collection source jsonl",
|
| 144 |
+
"- `raw/` — symlinks to parsed-markdown trees",
|
| 145 |
+
"- `sidecars/` — notebook code map + catalog"]
|
| 146 |
+
(OUT / "INDEX.md").write_text("\n".join(lines) + "\n")
|
| 147 |
+
|
| 148 |
+
print(json.dumps(manifest["totals"], indent=2))
|
| 149 |
+
for e in manifest["collections"]:
|
| 150 |
+
print(f" {e['collection']:16s} {e['chunks_written']:>7,} chunks "
|
| 151 |
+
f"(dupes {e['duplicates_skipped']})")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
main()
|
scripts/build_rag_tree.sh
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# build_rag_tree.sh — assemble the curated RAG/ view as SYMLINKS only.
|
| 3 |
+
# Physically moves NOTHING: originals stay put, live Qdrant indexes keep working.
|
| 4 |
+
# Re-runnable (idempotent): clears only the symlinks it manages, then relinks.
|
| 5 |
+
set -uo pipefail
|
| 6 |
+
ROOT=/Users/dmpantiu/copernicus_mcp
|
| 7 |
+
RAG=$ROOT/RAG
|
| 8 |
+
cd "$ROOT"
|
| 9 |
+
|
| 10 |
+
ln_safe() { # ln_safe <abs-target> <link-path>
|
| 11 |
+
local tgt="$1" lnk="$2"
|
| 12 |
+
if [ ! -e "$tgt" ]; then echo " MISS $tgt (skip $lnk)"; return; fi
|
| 13 |
+
rm -f "$lnk"
|
| 14 |
+
ln -s "$tgt" "$lnk"
|
| 15 |
+
echo " link ${lnk#$RAG/} -> ${tgt#$ROOT/}"
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
mkdir -p "$RAG"/{originals,chunks,indexes,pipeline,metadata,publications}
|
| 19 |
+
|
| 20 |
+
echo "== 00 originals (raw parsed / harvested source docs) =="
|
| 21 |
+
mkdir -p "$RAG"/originals
|
| 22 |
+
ln_safe "$ROOT/marine_parsed" "$RAG/originals/cmems_marine_parsed"
|
| 23 |
+
ln_safe "$ROOT/deep_docs/parsed" "$RAG/originals/cds_ads_ewds_parsed"
|
| 24 |
+
ln_safe "$ROOT/eqc_qa/parsed" "$RAG/originals/eqc_reports"
|
| 25 |
+
ln_safe "$ROOT/eqc_qa/notebooks_code" "$RAG/originals/notebooks_code"
|
| 26 |
+
ln_safe "$ROOT/notebook_harvest" "$RAG/originals/notebook_harvest"
|
| 27 |
+
|
| 28 |
+
echo "== 01 chunks (ready text chunks + embedded vectors) =="
|
| 29 |
+
mkdir -p "$RAG"/chunks/{marine_docs,cds_docs,cards,eqc_qa,publications}
|
| 30 |
+
ln_safe "$ROOT/marine_rag/out/chunks.jsonl" "$RAG/chunks/marine_docs/chunks.jsonl"
|
| 31 |
+
ln_safe "$ROOT/marine_rag/out/chunks_embedded.jsonl" "$RAG/chunks/marine_docs/chunks_embedded.jsonl"
|
| 32 |
+
ln_safe "$ROOT/deep_docs/chunks.jsonl" "$RAG/chunks/cds_docs/chunks.jsonl"
|
| 33 |
+
ln_safe "$ROOT/deep_docs/chunks_embedded.jsonl" "$RAG/chunks/cds_docs/chunks_embedded.jsonl"
|
| 34 |
+
ln_safe "$ROOT/marine_rag/out/cds_cards_chunks.jsonl" "$RAG/chunks/cards/cds_cards_chunks.jsonl"
|
| 35 |
+
ln_safe "$ROOT/marine_rag/out/cds_cards_embedded.jsonl" "$RAG/chunks/cards/cds_cards_embedded.jsonl"
|
| 36 |
+
ln_safe "$ROOT/eqc_qa/chunks.jsonl" "$RAG/chunks/eqc_qa/chunks.jsonl"
|
| 37 |
+
ln_safe "$ROOT/eqc_qa/chunks_embedded.jsonl" "$RAG/chunks/eqc_qa/chunks_embedded.jsonl"
|
| 38 |
+
# publications/chunks -> filled after L3 parse (slot lives under publications/)
|
| 39 |
+
|
| 40 |
+
echo "== 02 indexes (LIVE Qdrant collections — symlinked, do not move) =="
|
| 41 |
+
mkdir -p "$RAG"/indexes
|
| 42 |
+
ln_safe "$ROOT/marine_rag/out/qdrant_db" "$RAG/indexes/marine_docs__copernicus_docs"
|
| 43 |
+
ln_safe "$ROOT/deep_docs/qdrant_db" "$RAG/indexes/cds_docs"
|
| 44 |
+
ln_safe "$ROOT/eqc_qa/qdrant_db" "$RAG/indexes/eqc_qa"
|
| 45 |
+
ln_safe "$ROOT/pubs_rag/qdrant_db" "$RAG/indexes/publications"
|
| 46 |
+
|
| 47 |
+
echo "== 03 pipeline (build/embed/load scripts, by store) =="
|
| 48 |
+
mkdir -p "$RAG"/pipeline/{marine_cmems,cds_ads_ewds,eqc_notebooks,cards,server}
|
| 49 |
+
for f in "$ROOT"/marine_rag/*.py; do ln_safe "$f" "$RAG/pipeline/marine_cmems/$(basename "$f")"; done
|
| 50 |
+
for f in "$ROOT"/deep_docs/*.py; do ln_safe "$f" "$RAG/pipeline/cds_ads_ewds/$(basename "$f")"; done
|
| 51 |
+
for f in "$ROOT"/eqc_qa/*.py; do ln_safe "$f" "$RAG/pipeline/eqc_notebooks/$(basename "$f")"; done
|
| 52 |
+
ln_safe "$ROOT/marine_rag/build_cds_cards.py" "$RAG/pipeline/cards/build_cds_cards.py"
|
| 53 |
+
ln_safe "$ROOT/marine_rag/build_missing_cds_cards.py" "$RAG/pipeline/cards/build_missing_cds_cards.py"
|
| 54 |
+
ln_safe "$ROOT/marine_rag/embed_cds_cards.py" "$RAG/pipeline/cards/embed_cds_cards.py"
|
| 55 |
+
ln_safe "$ROOT/marine_rag/load_copernicus_docs.py" "$RAG/pipeline/cards/load_copernicus_docs.py"
|
| 56 |
+
ln_safe "$ROOT/marine_rag/rag_server.py" "$RAG/pipeline/server/rag_server.py"
|
| 57 |
+
ln_safe "$ROOT/marine_rag/RAG_SERVER.md" "$RAG/pipeline/server/RAG_SERVER.md"
|
| 58 |
+
|
| 59 |
+
echo "== 04 metadata (catalogs, universe, sidecars, manifests) =="
|
| 60 |
+
mkdir -p "$RAG"/metadata
|
| 61 |
+
ln_safe "$ROOT/meta_harvest/unified_metadata.json" "$RAG/metadata/unified_metadata.json"
|
| 62 |
+
ln_safe "$ROOT/meta_harvest/deep_doc_plan.json" "$RAG/metadata/deep_doc_plan.json"
|
| 63 |
+
ln_safe "$ROOT/marine_rag/out/catalog.json" "$RAG/metadata/cmems_catalog.json"
|
| 64 |
+
ln_safe "$ROOT/marine_rag/out/catalog_summary.json" "$RAG/metadata/cmems_catalog_summary.json"
|
| 65 |
+
ln_safe "$ROOT/eqc_qa/notebooks_by_dataset.json" "$RAG/metadata/notebooks_by_dataset.json"
|
| 66 |
+
ln_safe "$ROOT/deep_docs/manifest.jsonl" "$RAG/metadata/deep_docs_manifest.jsonl"
|
| 67 |
+
|
| 68 |
+
echo "== 05 publications (L3 track — the slot articles plug into) =="
|
| 69 |
+
mkdir -p "$RAG"/publications/{originals_pdfs,parsed,chunks,pipeline}
|
| 70 |
+
ln_safe "$ROOT/publications/pdfs" "$RAG/publications/originals_pdfs/registry"
|
| 71 |
+
ln_safe "$ROOT/publications/pdfs_openalex" "$RAG/publications/originals_pdfs/openalex"
|
| 72 |
+
ln_safe "$ROOT/publications/pdfs_extended" "$RAG/publications/originals_pdfs/extended_oa"
|
| 73 |
+
ln_safe "$ROOT/publications/extended" "$RAG/publications/corpus"
|
| 74 |
+
ln_safe "$ROOT/pubs_rag/qdrant_db" "$RAG/publications/index"
|
| 75 |
+
for f in "$ROOT"/publications/*.py; do ln_safe "$f" "$RAG/publications/pipeline/$(basename "$f")"; done
|
| 76 |
+
|
| 77 |
+
echo "DONE. Tree at $RAG (symlinks only; nothing moved)."
|
scripts/deep_docs/chunk_docs.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
chunk_docs.py — section-aware chunking of the fetched CDS/ADS/EWDS deep docs.
|
| 4 |
+
|
| 5 |
+
Mirrors eqc_qa/chunk_reports.py. One chunk-set per UNIQUE doc (a doc shared by
|
| 6 |
+
several datasets is chunked once; its chunks carry dataset_ids[] = all datasets
|
| 7 |
+
that reference it, so the server can filter per dataset).
|
| 8 |
+
|
| 9 |
+
Input : deep_docs/manifest.jsonl (status==ok rows) + their parsed/*.md
|
| 10 |
+
Output: deep_docs/chunks.jsonl — payload:
|
| 11 |
+
chunk_id, doc_url, doc_title, doc_kind, dataset_ids[], store, stores[],
|
| 12 |
+
section, chunk_index, token_count, text_raw, text_with_prefix
|
| 13 |
+
"""
|
| 14 |
+
import hashlib
|
| 15 |
+
import json
|
| 16 |
+
import re
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import tiktoken
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 23 |
+
MANIFEST = ROOT / "deep_docs" / "manifest.jsonl"
|
| 24 |
+
OUT = ROOT / "deep_docs" / "chunks.jsonl"
|
| 25 |
+
META = ROOT / "meta_harvest" / "unified_metadata.json"
|
| 26 |
+
|
| 27 |
+
MAX_TOKENS = 1000
|
| 28 |
+
MIN_QUALITY_TOKENS = 30
|
| 29 |
+
MIN_TOKENS = 80
|
| 30 |
+
OVERLAP_RATIO = 0.05
|
| 31 |
+
_enc = tiktoken.get_encoding("cl100k_base")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def log(*a):
|
| 35 |
+
print(*a, file=sys.stderr, flush=True)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def count_tokens(t): return len(_enc.encode(t))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
HEADING = re.compile(r"^(#{1,4})\s+(.*)$")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def parse_sections(md):
|
| 45 |
+
lines = md.splitlines()
|
| 46 |
+
stack, cur_path, buf, sections, in_fence = [], "[intro]", [], [], False
|
| 47 |
+
|
| 48 |
+
def flush():
|
| 49 |
+
body = "\n".join(buf).strip()
|
| 50 |
+
if body:
|
| 51 |
+
sections.append((cur_path, body))
|
| 52 |
+
for ln in lines:
|
| 53 |
+
if ln.lstrip().startswith("```"):
|
| 54 |
+
in_fence = not in_fence; buf.append(ln); continue
|
| 55 |
+
m = None if in_fence else HEADING.match(ln)
|
| 56 |
+
if m:
|
| 57 |
+
flush(); buf = []
|
| 58 |
+
level = len(m.group(1))
|
| 59 |
+
title = re.sub(r"[#*`]", "", m.group(2)).strip()
|
| 60 |
+
while stack and stack[-1][0] >= level:
|
| 61 |
+
stack.pop()
|
| 62 |
+
stack.append((level, title))
|
| 63 |
+
cur_path = " > ".join(t for _, t in stack) or "[section]"
|
| 64 |
+
else:
|
| 65 |
+
buf.append(ln)
|
| 66 |
+
flush()
|
| 67 |
+
return sections
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def split_by_tokens(text, max_tokens):
|
| 71 |
+
paras = re.split(r"\n\s*\n", text)
|
| 72 |
+
chunks, cur, cur_tok = [], [], 0
|
| 73 |
+
for p in paras:
|
| 74 |
+
p = p.strip()
|
| 75 |
+
if not p:
|
| 76 |
+
continue
|
| 77 |
+
pt = count_tokens(p)
|
| 78 |
+
if pt > max_tokens:
|
| 79 |
+
if cur:
|
| 80 |
+
chunks.append("\n\n".join(cur)); cur, cur_tok = [], 0
|
| 81 |
+
ids = _enc.encode(p)
|
| 82 |
+
for i in range(0, len(ids), max_tokens):
|
| 83 |
+
chunks.append(_enc.decode(ids[i:i + max_tokens]))
|
| 84 |
+
continue
|
| 85 |
+
if cur_tok + pt > max_tokens and cur:
|
| 86 |
+
chunks.append("\n\n".join(cur)); cur, cur_tok = [], 0
|
| 87 |
+
cur.append(p); cur_tok += pt
|
| 88 |
+
if cur:
|
| 89 |
+
chunks.append("\n\n".join(cur))
|
| 90 |
+
return chunks
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def add_overlap(chunks, ratio):
|
| 94 |
+
if len(chunks) < 2 or ratio <= 0:
|
| 95 |
+
return chunks
|
| 96 |
+
out = [chunks[0]]
|
| 97 |
+
for i in range(1, len(chunks)):
|
| 98 |
+
ptoks = _enc.encode(chunks[i - 1])
|
| 99 |
+
n = max(1, int(len(ptoks) * ratio))
|
| 100 |
+
out.append(_enc.decode(ptoks[-n:]) + "\n\n" + chunks[i])
|
| 101 |
+
return out
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def main():
|
| 105 |
+
meta = json.loads(META.read_text()) if META.exists() else {}
|
| 106 |
+
store_of = {}
|
| 107 |
+
for k, v in meta.items():
|
| 108 |
+
pid = v.get("product_id") or k
|
| 109 |
+
store_of[pid] = (v.get("store") or "").upper()
|
| 110 |
+
|
| 111 |
+
recs = [json.loads(l) for l in MANIFEST.read_text().splitlines() if l.strip()]
|
| 112 |
+
ok = [r for r in recs if r["status"] == "ok" and r.get("md_path")]
|
| 113 |
+
# dedup by url
|
| 114 |
+
seen_url = {}
|
| 115 |
+
for r in ok:
|
| 116 |
+
seen_url[r["url"]] = r
|
| 117 |
+
log(f"chunking {len(seen_url)} unique docs")
|
| 118 |
+
|
| 119 |
+
n_docs = n_chunks = 0
|
| 120 |
+
with open(OUT, "w", encoding="utf-8") as f:
|
| 121 |
+
for url, r in seen_url.items():
|
| 122 |
+
p = ROOT / r["md_path"]
|
| 123 |
+
if not p.exists():
|
| 124 |
+
continue
|
| 125 |
+
md = p.read_text(encoding="utf-8", errors="replace")
|
| 126 |
+
dsids = sorted(set(r["datasets"]))
|
| 127 |
+
stores = sorted({store_of.get(d, "") for d in dsids} - {""})
|
| 128 |
+
store = stores[0] if stores else "CDS"
|
| 129 |
+
title = r.get("title") or ""
|
| 130 |
+
counter = 0
|
| 131 |
+
seen_h = set()
|
| 132 |
+
for section, body in parse_sections(md):
|
| 133 |
+
body = re.sub(r"\n{3,}", "\n\n", body).strip()
|
| 134 |
+
if not body:
|
| 135 |
+
continue
|
| 136 |
+
raw = split_by_tokens(body, MAX_TOKENS)
|
| 137 |
+
if len(raw) > 1:
|
| 138 |
+
raw = add_overlap(raw, OVERLAP_RATIO)
|
| 139 |
+
for ct in raw:
|
| 140 |
+
ct = ct.strip()
|
| 141 |
+
if count_tokens(ct) < MIN_QUALITY_TOKENS:
|
| 142 |
+
continue
|
| 143 |
+
h = hashlib.md5(ct.encode()).hexdigest()
|
| 144 |
+
if h in seen_h:
|
| 145 |
+
continue
|
| 146 |
+
seen_h.add(h)
|
| 147 |
+
prefix = (f'Copernicus documentation: "{title}"\n'
|
| 148 |
+
f'Dataset(s): {", ".join(dsids[:6])} [{store}]\n'
|
| 149 |
+
f'Section: {section}\n---\n')
|
| 150 |
+
twp = prefix + ct
|
| 151 |
+
f.write(json.dumps({
|
| 152 |
+
"chunk_id": f"{hashlib.md5(url.encode()).hexdigest()[:12]}__{h[:12]}",
|
| 153 |
+
"doc_url": url,
|
| 154 |
+
"doc_title": title,
|
| 155 |
+
"doc_kind": r.get("kind"),
|
| 156 |
+
"dataset_ids": dsids,
|
| 157 |
+
"store": store,
|
| 158 |
+
"stores": stores,
|
| 159 |
+
"doc_type": "DEEP_DOC",
|
| 160 |
+
"section": section,
|
| 161 |
+
"chunk_index": counter,
|
| 162 |
+
"token_count": count_tokens(twp),
|
| 163 |
+
"text_raw": ct,
|
| 164 |
+
"text_with_prefix": twp,
|
| 165 |
+
}, ensure_ascii=False) + "\n")
|
| 166 |
+
counter += 1
|
| 167 |
+
n_docs += 1
|
| 168 |
+
n_chunks += counter
|
| 169 |
+
toks = sum(json.loads(l)["token_count"] for l in open(OUT))
|
| 170 |
+
log(f"DONE: {n_docs} docs -> {n_chunks} chunks ({toks:,} tokens) -> {OUT}")
|
| 171 |
+
log(f"est batch embed ${toks/1e6*0.125:.2f} (realtime ${toks/1e6*0.25:.2f})")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
main()
|
scripts/deep_docs/embed_load.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
embed_load.py — embed the CDS/ADS/EWDS deep-doc chunks (gemini-embedding-2-preview,
|
| 4 |
+
768-dim, RETRIEVAL_DOCUMENT, L2-norm) and load them into Qdrant `cds_docs`
|
| 5 |
+
(dense + BM25 sparse), in a SEPARATE db (deep_docs/qdrant_db) so it never
|
| 6 |
+
contends the marine_docs lock.
|
| 7 |
+
|
| 8 |
+
Phases (resumable):
|
| 9 |
+
--phase embed chunks.jsonl -> chunks_embedded.jsonl (checkpointed, skips done)
|
| 10 |
+
--phase load chunks_embedded.jsonl -> Qdrant cds_docs
|
| 11 |
+
--phase all embed then load (default)
|
| 12 |
+
|
| 13 |
+
Env: BATCH=<n> embed batch size (default 32); SAMPLE_N=<n> smoke test.
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
import uuid
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 26 |
+
CHUNKS = ROOT / "deep_docs" / "chunks.jsonl"
|
| 27 |
+
EMB = ROOT / "deep_docs" / "chunks_embedded.jsonl"
|
| 28 |
+
LOCAL_DB = ROOT / "deep_docs" / "qdrant_db"
|
| 29 |
+
COLLECTION = "cds_docs"
|
| 30 |
+
DENSE_DIM = 768
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def log(*a):
|
| 34 |
+
print(*a, file=sys.stderr, flush=True)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def resolve_key() -> str:
|
| 38 |
+
for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
|
| 39 |
+
if os.environ.get(var):
|
| 40 |
+
return os.environ[var]
|
| 41 |
+
for env in (ROOT / ".env", Path("/Users/dmpantiu/cmip6/cmip6_gpt/.env")):
|
| 42 |
+
if env.exists():
|
| 43 |
+
for line in env.read_text().splitlines():
|
| 44 |
+
line = line.strip()
|
| 45 |
+
if "api_key" in line.lower() and "=" in line and not line.startswith("#"):
|
| 46 |
+
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
| 47 |
+
raise SystemExit("No Gemini API key.")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _norm(vals):
|
| 51 |
+
v = np.array(list(vals), dtype=np.float32)
|
| 52 |
+
n = np.linalg.norm(v)
|
| 53 |
+
return (v / n).tolist() if n > 0 else v.tolist()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def embed_phase(workers: int, sample: int):
|
| 57 |
+
"""One embedding per chunk (the API returns a single vector per call),
|
| 58 |
+
parallelised with a thread pool for throughput."""
|
| 59 |
+
import threading
|
| 60 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 61 |
+
from google import genai
|
| 62 |
+
from google.genai import types
|
| 63 |
+
client = genai.Client(api_key=resolve_key())
|
| 64 |
+
cfg = types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT",
|
| 65 |
+
output_dimensionality=DENSE_DIM)
|
| 66 |
+
|
| 67 |
+
done = set()
|
| 68 |
+
if EMB.exists():
|
| 69 |
+
for line in EMB.read_text().splitlines():
|
| 70 |
+
if line.strip():
|
| 71 |
+
done.add(json.loads(line)["chunk_id"])
|
| 72 |
+
rows = [json.loads(l) for l in CHUNKS.read_text().splitlines() if l.strip()]
|
| 73 |
+
todo = [r for r in rows if r["chunk_id"] not in done]
|
| 74 |
+
if sample:
|
| 75 |
+
todo = todo[:sample]
|
| 76 |
+
log(f"embed: total={len(rows)} done={len(done)} todo={len(todo)} workers={workers}")
|
| 77 |
+
|
| 78 |
+
lock = threading.Lock()
|
| 79 |
+
out = open(EMB, "a", encoding="utf-8")
|
| 80 |
+
state = {"n": 0, "fail": 0}
|
| 81 |
+
|
| 82 |
+
def work(rec):
|
| 83 |
+
for attempt in range(5):
|
| 84 |
+
try:
|
| 85 |
+
r = client.models.embed_content(
|
| 86 |
+
model="gemini-embedding-2-preview",
|
| 87 |
+
contents=rec["text_with_prefix"], config=cfg)
|
| 88 |
+
rec["embedding"] = _norm(r.embeddings[0].values)
|
| 89 |
+
with lock:
|
| 90 |
+
out.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
| 91 |
+
out.flush()
|
| 92 |
+
state["n"] += 1
|
| 93 |
+
if state["n"] % 500 == 0:
|
| 94 |
+
log(f" embedded {state['n']}/{len(todo)}")
|
| 95 |
+
return
|
| 96 |
+
except Exception as e:
|
| 97 |
+
if attempt == 4:
|
| 98 |
+
with lock:
|
| 99 |
+
state["fail"] += 1
|
| 100 |
+
log(f" chunk {rec['chunk_id']} PERMA-FAIL ({repr(e)[:80]})")
|
| 101 |
+
else:
|
| 102 |
+
time.sleep(1.5 * (attempt + 1))
|
| 103 |
+
|
| 104 |
+
with ThreadPoolExecutor(max_workers=workers) as ex:
|
| 105 |
+
list(as_completed(ex.submit(work, r) for r in todo))
|
| 106 |
+
out.close()
|
| 107 |
+
log(f"EMBED DONE: +{state['n']} (fail {state['fail']}, total file now {len(done)+state['n']})")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def load_phase(recreate: bool):
|
| 111 |
+
from qdrant_client import QdrantClient, models
|
| 112 |
+
from fastembed import SparseTextEmbedding
|
| 113 |
+
bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
|
| 114 |
+
|
| 115 |
+
def to_sparse(text):
|
| 116 |
+
r = list(bm25.embed([text]))[0]
|
| 117 |
+
return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist())
|
| 118 |
+
|
| 119 |
+
client = QdrantClient(path=str(LOCAL_DB))
|
| 120 |
+
names = [c.name for c in client.get_collections().collections]
|
| 121 |
+
if COLLECTION in names and recreate:
|
| 122 |
+
client.delete_collection(COLLECTION); names.remove(COLLECTION)
|
| 123 |
+
if COLLECTION not in names:
|
| 124 |
+
client.create_collection(
|
| 125 |
+
collection_name=COLLECTION,
|
| 126 |
+
vectors_config={"dense": models.VectorParams(size=DENSE_DIM, distance=models.Distance.COSINE)},
|
| 127 |
+
sparse_vectors_config={"sparse": models.SparseVectorParams(modifier=models.Modifier.IDF)},
|
| 128 |
+
)
|
| 129 |
+
for field in ("dataset_ids", "store", "doc_type", "doc_url"):
|
| 130 |
+
client.create_payload_index(collection_name=COLLECTION, field_name=field,
|
| 131 |
+
field_schema=models.PayloadSchemaType.KEYWORD)
|
| 132 |
+
log(f"created '{COLLECTION}' (dense+sparse, 4 indexes)")
|
| 133 |
+
|
| 134 |
+
buf, total, t0 = [], 0, time.time()
|
| 135 |
+
for line in EMB.read_text().splitlines():
|
| 136 |
+
if not line.strip():
|
| 137 |
+
continue
|
| 138 |
+
c = json.loads(line)
|
| 139 |
+
emb = c.get("embedding")
|
| 140 |
+
if not emb:
|
| 141 |
+
continue
|
| 142 |
+
raw = c.get("text_raw", "")
|
| 143 |
+
buf.append(models.PointStruct(
|
| 144 |
+
id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])),
|
| 145 |
+
vector={"dense": emb, "sparse": to_sparse(raw)},
|
| 146 |
+
payload={
|
| 147 |
+
"chunk_id": c["chunk_id"], "dataset_ids": c.get("dataset_ids", []),
|
| 148 |
+
"store": c.get("store", ""), "stores": c.get("stores", []),
|
| 149 |
+
"doc_url": c.get("doc_url", ""), "doc_title": c.get("doc_title", ""),
|
| 150 |
+
"doc_kind": c.get("doc_kind", ""), "doc_type": "DEEP_DOC",
|
| 151 |
+
"section": c.get("section", ""), "text_raw": raw[:2500],
|
| 152 |
+
}))
|
| 153 |
+
if len(buf) >= 400:
|
| 154 |
+
client.upsert(collection_name=COLLECTION, points=buf)
|
| 155 |
+
total += len(buf); buf = []
|
| 156 |
+
log(f" loaded {total} ({total/(time.time()-t0):.0f}/s)")
|
| 157 |
+
if buf:
|
| 158 |
+
client.upsert(collection_name=COLLECTION, points=buf); total += len(buf)
|
| 159 |
+
log(f"LOAD DONE: {total} points; collection now {client.get_collection(COLLECTION).points_count}")
|
| 160 |
+
client.close()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main():
|
| 164 |
+
ap = argparse.ArgumentParser()
|
| 165 |
+
ap.add_argument("--phase", choices=("embed", "load", "all"), default="all")
|
| 166 |
+
ap.add_argument("--recreate", action="store_true")
|
| 167 |
+
a = ap.parse_args()
|
| 168 |
+
workers = int(os.environ.get("WORKERS", "10"))
|
| 169 |
+
sample = int(os.environ.get("SAMPLE_N", "0"))
|
| 170 |
+
if a.phase in ("embed", "all"):
|
| 171 |
+
embed_phase(workers, sample)
|
| 172 |
+
if a.phase in ("load", "all") and not sample:
|
| 173 |
+
load_phase(a.recreate)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if __name__ == "__main__":
|
| 177 |
+
main()
|
scripts/deep_docs/fetch_parse.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
fetch_parse.py — fetch & text-extract the CDS/ADS/EWDS deep documentation
|
| 4 |
+
(Confluence wiki pages + PDFs + service webpages) so the non-marine stores get
|
| 5 |
+
the same deep-doc RAG depth as CMEMS marine.
|
| 6 |
+
|
| 7 |
+
Input : meta_harvest/deep_doc_plan.json dataset_id -> [{title,url,kind}]
|
| 8 |
+
Output: deep_docs/parsed/<urlhash>.md cleaned text per unique URL
|
| 9 |
+
deep_docs/manifest.jsonl one line per URL (checkpoint: resumable)
|
| 10 |
+
|
| 11 |
+
No VLM needed: Confluence/webpages via requests+bs4+markdownify, PDFs via PyMuPDF.
|
| 12 |
+
Env: SAMPLE_N=<n> to only process the first n URLs (smoke test).
|
| 13 |
+
"""
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import re
|
| 17 |
+
import sys
|
| 18 |
+
import hashlib
|
| 19 |
+
import threading
|
| 20 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import requests
|
| 24 |
+
from bs4 import BeautifulSoup
|
| 25 |
+
from markdownify import markdownify as mdify
|
| 26 |
+
import fitz # PyMuPDF
|
| 27 |
+
|
| 28 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 29 |
+
PLAN = ROOT / "meta_harvest" / "deep_doc_plan.json"
|
| 30 |
+
OUTDIR = ROOT / "deep_docs" / "parsed"
|
| 31 |
+
MANIFEST = ROOT / "deep_docs" / "manifest.jsonl"
|
| 32 |
+
UA = {"User-Agent": "Mozilla/5.0 (copernicus-rag deep-doc harvester; research use)"}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def log(*a):
|
| 36 |
+
print(*a, file=sys.stderr, flush=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def uhash(url):
|
| 40 |
+
return hashlib.md5(url.encode()).hexdigest()[:16]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def clean_md(md: str) -> str:
|
| 44 |
+
md = re.sub(r"\n{3,}", "\n\n", md)
|
| 45 |
+
md = re.sub(r"[ \t]+\n", "\n", md)
|
| 46 |
+
# drop obvious confluence chrome lines
|
| 47 |
+
drop = ("Skip to", "Configure Space tools", "Space shortcuts", "Copyright ©",
|
| 48 |
+
"Powered by Atlassian", "Evaluate Confluence", "You are viewing")
|
| 49 |
+
lines = [ln for ln in md.splitlines() if not any(d in ln for d in drop)]
|
| 50 |
+
return "\n".join(lines).strip()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def parse_html(html: str) -> str:
|
| 54 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 55 |
+
for t in soup(["script", "style", "nav", "header", "footer", "noscript", "form"]):
|
| 56 |
+
t.decompose()
|
| 57 |
+
node = (soup.select_one("#main-content") or soup.select_one(".wiki-content")
|
| 58 |
+
or soup.select_one("div[role=main]") or soup.select_one("main")
|
| 59 |
+
or soup.select_one("article") or soup.body or soup)
|
| 60 |
+
md = mdify(str(node), heading_style="ATX", strip=["img"])
|
| 61 |
+
return clean_md(md)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def parse_pdf(content: bytes) -> str:
|
| 65 |
+
doc = fitz.open(stream=content, filetype="pdf")
|
| 66 |
+
parts = [page.get_text("text") for page in doc]
|
| 67 |
+
doc.close()
|
| 68 |
+
return clean_md("\n\n".join(parts))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def fetch_one(url: str, kind: str) -> tuple[str, str]:
|
| 72 |
+
"""Return (markdown, status). status in {ok, empty, http_<code>, error}."""
|
| 73 |
+
try:
|
| 74 |
+
r = requests.get(url, headers=UA, timeout=40, allow_redirects=True)
|
| 75 |
+
if r.status_code != 200:
|
| 76 |
+
return "", f"http_{r.status_code}"
|
| 77 |
+
ct = r.headers.get("content-type", "").lower()
|
| 78 |
+
if kind == "pdf" or "application/pdf" in ct or url.lower().split("?")[0].endswith(".pdf"):
|
| 79 |
+
md = parse_pdf(r.content)
|
| 80 |
+
else:
|
| 81 |
+
md = parse_html(r.text)
|
| 82 |
+
return md, ("ok" if len(md) >= 200 else "empty")
|
| 83 |
+
except Exception as e:
|
| 84 |
+
return "", f"error:{type(e).__name__}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main():
|
| 88 |
+
OUTDIR.mkdir(parents=True, exist_ok=True)
|
| 89 |
+
plan = json.loads(PLAN.read_text())
|
| 90 |
+
# unique url -> {title, kind, datasets:[]}
|
| 91 |
+
urls: dict[str, dict] = {}
|
| 92 |
+
for dsid, docs in plan.items():
|
| 93 |
+
for d in docs:
|
| 94 |
+
u = d["url"]
|
| 95 |
+
e = urls.setdefault(u, {"title": d.get("title", ""), "kind": d.get("kind"), "datasets": []})
|
| 96 |
+
e["datasets"].append(dsid)
|
| 97 |
+
|
| 98 |
+
done = set()
|
| 99 |
+
if MANIFEST.exists():
|
| 100 |
+
for line in MANIFEST.read_text().splitlines():
|
| 101 |
+
if line.strip():
|
| 102 |
+
done.add(json.loads(line)["url"])
|
| 103 |
+
todo = [u for u in urls if u not in done]
|
| 104 |
+
sample = int(os.environ.get("SAMPLE_N", "0"))
|
| 105 |
+
if sample:
|
| 106 |
+
todo = todo[:sample]
|
| 107 |
+
log(f"unique urls={len(urls)} done={len(done)} todo={len(todo)}"
|
| 108 |
+
+ (f" (SAMPLE {sample})" if sample else ""))
|
| 109 |
+
|
| 110 |
+
workers = int(os.environ.get("WORKERS", "10"))
|
| 111 |
+
lock = threading.Lock()
|
| 112 |
+
counts = {"ok": 0, "done": 0}
|
| 113 |
+
mf = open(MANIFEST, "a", encoding="utf-8")
|
| 114 |
+
|
| 115 |
+
def work(url):
|
| 116 |
+
meta = urls[url]
|
| 117 |
+
md, status = fetch_one(url, meta["kind"])
|
| 118 |
+
rec = {"url": url, "kind": meta["kind"], "title": meta["title"],
|
| 119 |
+
"datasets": meta["datasets"], "status": status,
|
| 120 |
+
"n_chars": len(md), "md_path": ""}
|
| 121 |
+
if status == "ok":
|
| 122 |
+
p = OUTDIR / f"{uhash(url)}.md"
|
| 123 |
+
header = f"# {meta['title']}\n\n<!-- source: {url} -->\n\n"
|
| 124 |
+
p.write_text(header + md, encoding="utf-8")
|
| 125 |
+
rec["md_path"] = str(p.relative_to(ROOT))
|
| 126 |
+
with lock:
|
| 127 |
+
mf.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
| 128 |
+
mf.flush()
|
| 129 |
+
counts["done"] += 1
|
| 130 |
+
counts["ok"] += status == "ok"
|
| 131 |
+
if counts["done"] % 40 == 0:
|
| 132 |
+
log(f" {counts['done']}/{len(todo)} ok={counts['ok']}")
|
| 133 |
+
|
| 134 |
+
with ThreadPoolExecutor(max_workers=workers) as ex:
|
| 135 |
+
list(as_completed(ex.submit(work, u) for u in todo))
|
| 136 |
+
mf.close()
|
| 137 |
+
log(f"DONE todo={len(todo)} ok={counts['ok']}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
scripts/eqc_qa/chunk_reports.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
chunk_reports.py — section-aware chunking of parsed EQC QA markdown.
|
| 4 |
+
|
| 5 |
+
Mirrors marine_rag/chunk_docs.py: ~1000-token section-aware chunks, small
|
| 6 |
+
overlap, tiktoken (cl100k_base ≈ Gemini) budget, a metadata prefix per chunk
|
| 7 |
+
(dataset + report + aspect + section path). Self-contained (no cmip6 import).
|
| 8 |
+
|
| 9 |
+
Output: eqc_qa/chunks.jsonl — payload fields:
|
| 10 |
+
chunk_id, report_id, dataset_id, store, doc_type="EQC_QA",
|
| 11 |
+
aspect, aspect_base, category, section, title, text_raw, text_with_prefix, token_count
|
| 12 |
+
"""
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import tiktoken
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).resolve().parent
|
| 22 |
+
PARSED = ROOT / "parsed"
|
| 23 |
+
MANIFEST = ROOT / "reports.jsonl"
|
| 24 |
+
OUT = ROOT / "chunks.jsonl"
|
| 25 |
+
|
| 26 |
+
MAX_TOKENS = 1000
|
| 27 |
+
MIN_QUALITY_TOKENS = 30
|
| 28 |
+
MIN_TOKENS = 80
|
| 29 |
+
OVERLAP_RATIO = 0.05
|
| 30 |
+
|
| 31 |
+
_enc = tiktoken.get_encoding("cl100k_base")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def log(*a):
|
| 35 |
+
print(*a, file=sys.stderr, flush=True)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def count_tokens(t: str) -> int:
|
| 39 |
+
return len(_enc.encode(t))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ── section parsing (markdown heading aware) ─────────────────────────────────
|
| 43 |
+
HEADING = re.compile(r"^(#{1,4})\s+(.*)$")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def parse_sections(md: str) -> list[tuple[str, str]]:
|
| 47 |
+
"""Return [(section_path, body_text)] splitting on ATX headings, tracking
|
| 48 |
+
the heading breadcrumb. Fenced code blocks are left intact (skip heading
|
| 49 |
+
detection inside ``` fences)."""
|
| 50 |
+
lines = md.splitlines()
|
| 51 |
+
stack: list[tuple[int, str]] = [] # (level, title)
|
| 52 |
+
cur_path = "[intro]"
|
| 53 |
+
buf: list[str] = []
|
| 54 |
+
sections: list[tuple[str, str]] = []
|
| 55 |
+
in_fence = False
|
| 56 |
+
|
| 57 |
+
def flush():
|
| 58 |
+
body = "\n".join(buf).strip()
|
| 59 |
+
if body:
|
| 60 |
+
sections.append((cur_path, body))
|
| 61 |
+
|
| 62 |
+
for ln in lines:
|
| 63 |
+
if ln.lstrip().startswith("```"):
|
| 64 |
+
in_fence = not in_fence
|
| 65 |
+
buf.append(ln)
|
| 66 |
+
continue
|
| 67 |
+
m = None if in_fence else HEADING.match(ln)
|
| 68 |
+
if m:
|
| 69 |
+
flush()
|
| 70 |
+
buf = []
|
| 71 |
+
level = len(m.group(1))
|
| 72 |
+
title = re.sub(r"[#*`]", "", m.group(2)).strip()
|
| 73 |
+
title = re.sub(r"[\U0001F000-\U0001FAFF☀-➿]", "", title).strip()
|
| 74 |
+
while stack and stack[-1][0] >= level:
|
| 75 |
+
stack.pop()
|
| 76 |
+
stack.append((level, title))
|
| 77 |
+
cur_path = " > ".join(t for _, t in stack) or "[section]"
|
| 78 |
+
else:
|
| 79 |
+
buf.append(ln)
|
| 80 |
+
flush()
|
| 81 |
+
return sections
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def strip_noise(t: str) -> str:
|
| 85 |
+
# collapse admonition fences markers but keep content
|
| 86 |
+
t = re.sub(r"```\{[^}]*\}", "", t)
|
| 87 |
+
t = re.sub(r"^:class:.*$", "", t, flags=re.MULTILINE)
|
| 88 |
+
t = re.sub(r"\n{3,}", "\n\n", t)
|
| 89 |
+
return t.strip()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def split_by_tokens(text: str, max_tokens: int) -> list[str]:
|
| 93 |
+
"""Greedy paragraph-packing; hard-split any oversized paragraph on tokens."""
|
| 94 |
+
paras = re.split(r"\n\s*\n", text)
|
| 95 |
+
chunks: list[str] = []
|
| 96 |
+
cur: list[str] = []
|
| 97 |
+
cur_tok = 0
|
| 98 |
+
for p in paras:
|
| 99 |
+
p = p.strip()
|
| 100 |
+
if not p:
|
| 101 |
+
continue
|
| 102 |
+
pt = count_tokens(p)
|
| 103 |
+
if pt > max_tokens:
|
| 104 |
+
if cur:
|
| 105 |
+
chunks.append("\n\n".join(cur)); cur, cur_tok = [], 0
|
| 106 |
+
ids = _enc.encode(p)
|
| 107 |
+
for i in range(0, len(ids), max_tokens):
|
| 108 |
+
chunks.append(_enc.decode(ids[i:i + max_tokens]))
|
| 109 |
+
continue
|
| 110 |
+
if cur_tok + pt > max_tokens and cur:
|
| 111 |
+
chunks.append("\n\n".join(cur)); cur, cur_tok = [], 0
|
| 112 |
+
cur.append(p); cur_tok += pt
|
| 113 |
+
if cur:
|
| 114 |
+
chunks.append("\n\n".join(cur))
|
| 115 |
+
return chunks
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def add_overlap(chunks: list[str], ratio: float) -> list[str]:
|
| 119 |
+
if len(chunks) < 2 or ratio <= 0:
|
| 120 |
+
return chunks
|
| 121 |
+
out = [chunks[0]]
|
| 122 |
+
for i in range(1, len(chunks)):
|
| 123 |
+
prev = chunks[i - 1]
|
| 124 |
+
ptoks = _enc.encode(prev)
|
| 125 |
+
n = max(1, int(len(ptoks) * ratio))
|
| 126 |
+
tail = _enc.decode(ptoks[-n:])
|
| 127 |
+
out.append(tail + "\n\n" + chunks[i])
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def make_prefix(rec: dict, section: str) -> str:
|
| 132 |
+
ds = rec["matched_dataset_id"] or rec["dataset_id"] or "(unmapped)"
|
| 133 |
+
return (f'EQC Quality Assessment: "{rec["title"]}"\n'
|
| 134 |
+
f'Dataset: {ds} [{rec["store"] or "CDS"}]\n'
|
| 135 |
+
f'Aspect: {rec["aspect"]} | Category: {rec["category"]}\n'
|
| 136 |
+
f'Section: {section}\n---\n')
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def chunk_report(rec: dict) -> list[dict]:
|
| 140 |
+
md = (PARSED / Path(rec["md_path"]).name).read_text(encoding="utf-8", errors="replace")
|
| 141 |
+
sections = parse_sections(md)
|
| 142 |
+
out: list[dict] = []
|
| 143 |
+
seen: set[str] = set()
|
| 144 |
+
counter = 0
|
| 145 |
+
for section, body in sections:
|
| 146 |
+
body = strip_noise(body)
|
| 147 |
+
if not body:
|
| 148 |
+
continue
|
| 149 |
+
raw = split_by_tokens(body, MAX_TOKENS)
|
| 150 |
+
if len(raw) > 1:
|
| 151 |
+
raw = add_overlap(raw, OVERLAP_RATIO)
|
| 152 |
+
for ct in raw:
|
| 153 |
+
ct = ct.strip()
|
| 154 |
+
if count_tokens(ct) < MIN_QUALITY_TOKENS:
|
| 155 |
+
continue
|
| 156 |
+
h = hashlib.md5(ct.encode()).hexdigest()
|
| 157 |
+
if h in seen:
|
| 158 |
+
continue
|
| 159 |
+
seen.add(h)
|
| 160 |
+
twp = make_prefix(rec, section) + ct
|
| 161 |
+
out.append({
|
| 162 |
+
"chunk_id": f"{rec['report_id']}__{h[:12]}",
|
| 163 |
+
"report_id": rec["report_id"],
|
| 164 |
+
"dataset_id": rec["matched_dataset_id"] or rec["dataset_id"],
|
| 165 |
+
"store": rec["store"] or "CDS",
|
| 166 |
+
"doc_type": "EQC_QA",
|
| 167 |
+
"aspect": rec["aspect"],
|
| 168 |
+
"aspect_base": rec["aspect_base"],
|
| 169 |
+
"category": rec["category"],
|
| 170 |
+
"match_confidence": rec["match_confidence"],
|
| 171 |
+
"section": section,
|
| 172 |
+
"title": rec["title"],
|
| 173 |
+
"chunk_index": counter,
|
| 174 |
+
"token_count": count_tokens(twp),
|
| 175 |
+
"text_raw": ct,
|
| 176 |
+
"text_with_prefix": twp,
|
| 177 |
+
})
|
| 178 |
+
counter += 1
|
| 179 |
+
|
| 180 |
+
# merge tiny adjacent chunks within a section
|
| 181 |
+
merged: list[dict] = []
|
| 182 |
+
i = 0
|
| 183 |
+
while i < len(out):
|
| 184 |
+
c = out[i]
|
| 185 |
+
if (c["token_count"] < MIN_TOKENS and i + 1 < len(out)
|
| 186 |
+
and out[i + 1]["section"] == c["section"]):
|
| 187 |
+
nxt = out[i + 1]
|
| 188 |
+
mt = c["text_raw"] + "\n\n" + nxt["text_raw"]
|
| 189 |
+
nxt["text_raw"] = mt
|
| 190 |
+
nxt["text_with_prefix"] = nxt["text_with_prefix"].split("---\n", 1)[0] + "---\n" + mt
|
| 191 |
+
nxt["token_count"] = count_tokens(nxt["text_with_prefix"])
|
| 192 |
+
i += 1
|
| 193 |
+
else:
|
| 194 |
+
merged.append(c); i += 1
|
| 195 |
+
for j, c in enumerate(merged):
|
| 196 |
+
c["chunk_index"] = j
|
| 197 |
+
return merged
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def main() -> None:
|
| 201 |
+
recs = [json.loads(l) for l in open(MANIFEST)]
|
| 202 |
+
recs = [r for r in recs if not r["is_template"]] # skip scaffold
|
| 203 |
+
log(f"chunking {len(recs)} reports")
|
| 204 |
+
n_docs = n_chunks = 0
|
| 205 |
+
with open(OUT, "w", encoding="utf-8") as f:
|
| 206 |
+
for r in recs:
|
| 207 |
+
chunks = chunk_report(r)
|
| 208 |
+
for c in chunks:
|
| 209 |
+
f.write(json.dumps(c, ensure_ascii=False) + "\n")
|
| 210 |
+
n_docs += 1
|
| 211 |
+
n_chunks += len(chunks)
|
| 212 |
+
toks = 0
|
| 213 |
+
for l in open(OUT):
|
| 214 |
+
toks += json.loads(l)["token_count"]
|
| 215 |
+
log(f"DONE: {n_docs} reports -> {n_chunks} chunks ({toks:,} tokens) -> {OUT}")
|
| 216 |
+
log(f"avg {n_chunks/n_docs:.1f} chunks/report; est realtime ${toks/1e6*0.25:.2f}")
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
if __name__ == "__main__":
|
| 220 |
+
main()
|
scripts/eqc_qa/embed_reports.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
embed_reports.py — embed EQC QA chunks with gemini-embedding-2-preview.
|
| 4 |
+
|
| 5 |
+
LOCKED: gemini-embedding-2-preview, RETRIEVAL_DOCUMENT, 768-dim, L2-normalized.
|
| 6 |
+
IPv4 egress forced (net_ipv4). Key = veretex_api_key in ../.env.
|
| 7 |
+
|
| 8 |
+
Modes:
|
| 9 |
+
realtime (default) — resumable streaming; on sustained 429 print how to fall
|
| 10 |
+
back to batch and exit non-zero.
|
| 11 |
+
batch — submit Gemini Batch API job (schema mirrors marine_rag/embed.py),
|
| 12 |
+
resumable via --mode poll. Sentinel EMBED_DONE written when >=99%.
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
embed_reports.py # realtime
|
| 16 |
+
embed_reports.py --mode batch # submit batch job
|
| 17 |
+
embed_reports.py --mode poll # download completed batch job
|
| 18 |
+
"""
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
# force IPv4 (reuse marine_rag net_ipv4)
|
| 29 |
+
sys.path.insert(0, "/Users/dmpantiu/copernicus_mcp/marine_rag")
|
| 30 |
+
import net_ipv4 # noqa: F401,E402
|
| 31 |
+
|
| 32 |
+
ROOT = Path(__file__).resolve().parent
|
| 33 |
+
IN = ROOT / "chunks.jsonl"
|
| 34 |
+
OUT = ROOT / "chunks_embedded.jsonl"
|
| 35 |
+
BATCH_INPUT = ROOT / "batch_embed_input.jsonl"
|
| 36 |
+
JOB_FILE = ROOT / "batch_job.txt"
|
| 37 |
+
SENTINEL = ROOT / "EMBED_DONE"
|
| 38 |
+
|
| 39 |
+
MODEL = "gemini-embedding-2-preview"
|
| 40 |
+
TASK = "RETRIEVAL_DOCUMENT"
|
| 41 |
+
DIM = 768
|
| 42 |
+
# Free-tier gemini-embedding-2 quota is tiny/fluctuating and counts per content.
|
| 43 |
+
# Keep requests small and well-spaced; the finisher loops passes until complete.
|
| 44 |
+
RT_BATCH = 5
|
| 45 |
+
RT_SLEEP = 20.0
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def log(*a):
|
| 49 |
+
print(*a, file=sys.stderr, flush=True)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def resolve_key() -> str:
|
| 53 |
+
for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
|
| 54 |
+
if os.environ.get(var):
|
| 55 |
+
return os.environ[var]
|
| 56 |
+
for env in (Path("/Users/dmpantiu/copernicus_mcp/.env"),
|
| 57 |
+
Path("/Users/dmpantiu/cmip6/cmip6_gpt/.env")):
|
| 58 |
+
if env.exists():
|
| 59 |
+
for line in env.read_text().splitlines():
|
| 60 |
+
line = line.strip()
|
| 61 |
+
if "api_key" in line.lower() and "=" in line and not line.startswith("#"):
|
| 62 |
+
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
| 63 |
+
raise SystemExit("No Gemini API key found.")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_client():
|
| 67 |
+
from google import genai
|
| 68 |
+
return genai.Client(api_key=resolve_key())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def l2(vec):
|
| 72 |
+
a = np.array(vec, dtype=np.float32)
|
| 73 |
+
n = np.linalg.norm(a)
|
| 74 |
+
return (a / n).tolist() if n > 0 else a.tolist()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def load_chunks():
|
| 78 |
+
return [json.loads(l) for l in open(IN)]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def embedded_keys() -> set:
|
| 82 |
+
keys = set()
|
| 83 |
+
if OUT.exists():
|
| 84 |
+
for line in open(OUT):
|
| 85 |
+
try:
|
| 86 |
+
keys.add(json.loads(line)["chunk_id"])
|
| 87 |
+
except Exception:
|
| 88 |
+
pass
|
| 89 |
+
return keys
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def embed_realtime(chunks):
|
| 93 |
+
from google.genai import types
|
| 94 |
+
client = get_client()
|
| 95 |
+
done = embedded_keys()
|
| 96 |
+
if done:
|
| 97 |
+
log(f"resume: {len(done)} already embedded")
|
| 98 |
+
todo = [c for c in chunks if c["chunk_id"] not in done]
|
| 99 |
+
log(f"to embed: {len(todo)} / {len(chunks)}")
|
| 100 |
+
n = 0
|
| 101 |
+
consecutive_429 = 0
|
| 102 |
+
with open(OUT, "a", encoding="utf-8") as fout:
|
| 103 |
+
for b in range(0, len(todo), RT_BATCH):
|
| 104 |
+
batch = todo[b:b + RT_BATCH]
|
| 105 |
+
# genai 2.10: a list[str] is treated as ONE content -> 1 embedding.
|
| 106 |
+
# Wrap each text in a Content object to get one embedding per input.
|
| 107 |
+
contents = [types.Content(parts=[types.Part(text=c["text_with_prefix"])])
|
| 108 |
+
for c in batch]
|
| 109 |
+
ok = False
|
| 110 |
+
for attempt in range(6):
|
| 111 |
+
try:
|
| 112 |
+
if attempt > 0:
|
| 113 |
+
client = get_client()
|
| 114 |
+
r = client.models.embed_content(
|
| 115 |
+
model=MODEL, contents=contents,
|
| 116 |
+
config=types.EmbedContentConfig(
|
| 117 |
+
task_type=TASK, output_dimensionality=DIM))
|
| 118 |
+
if len(r.embeddings) != len(batch):
|
| 119 |
+
raise RuntimeError(
|
| 120 |
+
f"embedding count mismatch {len(r.embeddings)}!={len(batch)}")
|
| 121 |
+
for c, e in zip(batch, r.embeddings):
|
| 122 |
+
c["embedding"] = l2(e.values)
|
| 123 |
+
fout.write(json.dumps(c, ensure_ascii=False) + "\n")
|
| 124 |
+
n += 1
|
| 125 |
+
fout.flush()
|
| 126 |
+
ok = True
|
| 127 |
+
consecutive_429 = 0
|
| 128 |
+
break
|
| 129 |
+
except Exception as e:
|
| 130 |
+
es = str(e)
|
| 131 |
+
if "IP address restriction" in es:
|
| 132 |
+
raise SystemExit(
|
| 133 |
+
"BLOCKED: Gemini key IP restriction. Whitelist this host's IP.")
|
| 134 |
+
if any(k in es for k in ("429", "RESOURCE_EXHAUSTED", "Quota exceeded")):
|
| 135 |
+
wait = 35
|
| 136 |
+
elif "client has been closed" in es:
|
| 137 |
+
wait = 2
|
| 138 |
+
else:
|
| 139 |
+
wait = min(8 * (2 ** attempt), 60)
|
| 140 |
+
log(f" retry {attempt+1}/6 in {wait}s: {repr(e)[:120]}")
|
| 141 |
+
time.sleep(wait)
|
| 142 |
+
if not ok:
|
| 143 |
+
consecutive_429 += 1
|
| 144 |
+
log(f" FATAL skip batch of {len(batch)}")
|
| 145 |
+
if consecutive_429 >= 3:
|
| 146 |
+
log("SUSTAINED 429 — realtime quota exhausted.")
|
| 147 |
+
log("Fall back to batch: python embed_reports.py --mode batch ; "
|
| 148 |
+
"then: python embed_reports.py --mode poll")
|
| 149 |
+
sys.exit(2)
|
| 150 |
+
if n and n % 400 == 0:
|
| 151 |
+
log(f" [{n}/{len(todo)}]")
|
| 152 |
+
time.sleep(RT_SLEEP)
|
| 153 |
+
finalize(chunks)
|
| 154 |
+
log(f"DONE realtime: {n} newly embedded -> {OUT}")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# ── batch fallback (mirrors marine_rag/embed.py) ─────────────────────────────
|
| 158 |
+
def prepare_batch(chunks):
|
| 159 |
+
done = embedded_keys()
|
| 160 |
+
todo = [c for c in chunks if c["chunk_id"] not in done]
|
| 161 |
+
with open(BATCH_INPUT, "w", encoding="utf-8") as f:
|
| 162 |
+
for c in todo:
|
| 163 |
+
f.write(json.dumps({
|
| 164 |
+
"key": c["chunk_id"],
|
| 165 |
+
"request": {
|
| 166 |
+
"content": {"parts": [{"text": c["text_with_prefix"]}]},
|
| 167 |
+
"task_type": TASK,
|
| 168 |
+
"output_dimensionality": DIM,
|
| 169 |
+
}}, ensure_ascii=False) + "\n")
|
| 170 |
+
log(f"batch input: {BATCH_INPUT} ({len(todo)} reqs)")
|
| 171 |
+
return todo
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def submit_batch(chunks):
|
| 175 |
+
prepare_batch(chunks)
|
| 176 |
+
client = get_client()
|
| 177 |
+
up = client.files.upload(file=str(BATCH_INPUT),
|
| 178 |
+
config={"display_name": "eqc_qa_embed", "mime_type": "jsonl"})
|
| 179 |
+
job = client.batches.create_embeddings(
|
| 180 |
+
model=MODEL, src={"file_name": up.name},
|
| 181 |
+
config={"display_name": "eqc_qa_embeddings"})
|
| 182 |
+
JOB_FILE.write_text(job.name)
|
| 183 |
+
log(f"job: {job.name} state: {job.state} (saved {JOB_FILE})")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _extract_values(resp: dict):
|
| 187 |
+
for path in (("response", "embeddings"), ("response", "embedding"),
|
| 188 |
+
("embeddings",), ("embedding",)):
|
| 189 |
+
node = resp; ok = True
|
| 190 |
+
for k in path:
|
| 191 |
+
if isinstance(node, dict) and k in node:
|
| 192 |
+
node = node[k]
|
| 193 |
+
else:
|
| 194 |
+
ok = False; break
|
| 195 |
+
if not ok:
|
| 196 |
+
continue
|
| 197 |
+
if isinstance(node, list) and node and isinstance(node[0], dict) and "values" in node[0]:
|
| 198 |
+
return node[0]["values"]
|
| 199 |
+
if isinstance(node, dict) and "values" in node:
|
| 200 |
+
return node["values"]
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def poll_batch(chunks, wait=True):
|
| 205 |
+
client = get_client()
|
| 206 |
+
name = JOB_FILE.read_text().strip()
|
| 207 |
+
while True:
|
| 208 |
+
job = client.batches.get(name=name)
|
| 209 |
+
state = str(job.state)
|
| 210 |
+
log(f" job {name}: {state}")
|
| 211 |
+
if any(s in state for s in ("SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED")):
|
| 212 |
+
break
|
| 213 |
+
if not wait:
|
| 214 |
+
return
|
| 215 |
+
time.sleep(30)
|
| 216 |
+
if "SUCCEEDED" not in state:
|
| 217 |
+
log(f"job not successful: {state}"); return
|
| 218 |
+
by_key = {c["chunk_id"]: c for c in chunks}
|
| 219 |
+
dest = getattr(job, "dest", None)
|
| 220 |
+
fn = getattr(dest, "file_name", None) if dest else None
|
| 221 |
+
lines = []
|
| 222 |
+
if fn:
|
| 223 |
+
lines = client.files.download(file=fn).decode("utf-8").strip().split("\n")
|
| 224 |
+
elif dest and getattr(dest, "inlined_responses", None):
|
| 225 |
+
lines = [json.dumps(r) for r in dest.inlined_responses]
|
| 226 |
+
n = 0
|
| 227 |
+
with open(OUT, "a", encoding="utf-8") as fout:
|
| 228 |
+
for line in lines:
|
| 229 |
+
if not line.strip():
|
| 230 |
+
continue
|
| 231 |
+
r = json.loads(line)
|
| 232 |
+
k = r.get("key") or r.get("custom_id")
|
| 233 |
+
vals = _extract_values(r)
|
| 234 |
+
if k in by_key and vals:
|
| 235 |
+
c = dict(by_key[k]); c["embedding"] = l2(vals)
|
| 236 |
+
fout.write(json.dumps(c, ensure_ascii=False) + "\n"); n += 1
|
| 237 |
+
log(f"downloaded {n} embeddings -> {OUT}")
|
| 238 |
+
finalize(chunks)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def finalize(chunks):
|
| 242 |
+
got = embedded_keys()
|
| 243 |
+
frac = len(got) / max(1, len(chunks))
|
| 244 |
+
log(f"coverage: {len(got)}/{len(chunks)} = {frac:.1%}")
|
| 245 |
+
if frac >= 0.99:
|
| 246 |
+
SENTINEL.write_text(f"{len(got)}/{len(chunks)}\n")
|
| 247 |
+
log(f"SENTINEL {SENTINEL} written")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def main():
|
| 251 |
+
ap = argparse.ArgumentParser()
|
| 252 |
+
ap.add_argument("--mode", choices=["realtime", "batch", "poll"], default="realtime")
|
| 253 |
+
a = ap.parse_args()
|
| 254 |
+
chunks = load_chunks()
|
| 255 |
+
toks = sum(c["token_count"] for c in chunks)
|
| 256 |
+
log(f"chunks={len(chunks):,} tokens={toks:,} est ${toks/1e6*0.25:.2f}")
|
| 257 |
+
if a.mode == "realtime":
|
| 258 |
+
embed_realtime(chunks)
|
| 259 |
+
elif a.mode == "batch":
|
| 260 |
+
submit_batch(chunks)
|
| 261 |
+
elif a.mode == "poll":
|
| 262 |
+
poll_batch(chunks, wait=True)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
if __name__ == "__main__":
|
| 266 |
+
main()
|
scripts/eqc_qa/eqc_finish.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
eqc_finish.py — autonomous, resumable finisher.
|
| 4 |
+
|
| 5 |
+
Loops embedding passes (realtime, gentle) until >=99% of chunks are embedded,
|
| 6 |
+
surviving the fluctuating free-tier quota (sleeps between passes). Then:
|
| 7 |
+
- load into eqc_qa Qdrant (recreate)
|
| 8 |
+
- run verification probes
|
| 9 |
+
Everything is resumable; safe to kill and re-launch. Progress -> /tmp/eqc_finish.log
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
PY = "/Users/dmpantiu/copernicus_mcp/marine_rag/.venv/bin/python"
|
| 19 |
+
CHUNKS = ROOT / "chunks.jsonl"
|
| 20 |
+
EMB = ROOT / "chunks_embedded.jsonl"
|
| 21 |
+
SENTINEL = ROOT / "EMBED_DONE"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def log(*a):
|
| 25 |
+
print(*a, file=sys.stderr, flush=True)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def coverage():
|
| 29 |
+
total = sum(1 for _ in open(CHUNKS))
|
| 30 |
+
got = 0
|
| 31 |
+
if EMB.exists():
|
| 32 |
+
got = sum(1 for _ in open(EMB))
|
| 33 |
+
return got, total
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
max_passes = 400
|
| 38 |
+
for p in range(max_passes):
|
| 39 |
+
got, total = coverage()
|
| 40 |
+
log(f"[pass {p}] coverage {got}/{total} = {got/total:.1%}")
|
| 41 |
+
if got >= total * 0.99:
|
| 42 |
+
SENTINEL.write_text(f"{got}/{total}\n")
|
| 43 |
+
log("embeddings complete.")
|
| 44 |
+
break
|
| 45 |
+
subprocess.run([PY, str(ROOT / "embed_reports.py")], cwd=str(ROOT))
|
| 46 |
+
got2, _ = coverage()
|
| 47 |
+
if got2 <= got:
|
| 48 |
+
# no progress this pass -> quota drought; back off longer
|
| 49 |
+
log("no progress; sleeping 180s for quota window")
|
| 50 |
+
time.sleep(180)
|
| 51 |
+
else:
|
| 52 |
+
time.sleep(20)
|
| 53 |
+
else:
|
| 54 |
+
log("max passes reached without completion")
|
| 55 |
+
|
| 56 |
+
got, total = coverage()
|
| 57 |
+
if got < total * 0.99:
|
| 58 |
+
log(f"STOPPING: only {got}/{total} embedded; re-run this script to resume.")
|
| 59 |
+
return
|
| 60 |
+
|
| 61 |
+
log("=== loading Qdrant ===")
|
| 62 |
+
subprocess.run([PY, str(ROOT / "load_eqc_qa.py"), "--recreate"], cwd=str(ROOT))
|
| 63 |
+
log("=== verifying ===")
|
| 64 |
+
subprocess.run([PY, str(ROOT / "verify_eqc_qa.py")], cwd=str(ROOT))
|
| 65 |
+
log("=== eqc_finish DONE ===")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
main()
|
scripts/eqc_qa/eqc_orchestrator.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Resumable batch orchestrator for EQC QA embeddings.
|
| 3 |
+
Retries batch submit through quota 429s (long backoff), then polls the job to
|
| 4 |
+
completion, downloads embeddings -> chunks_embedded.jsonl, writes EMBED_DONE.
|
| 5 |
+
Resumable: reuses batch_job.txt if a job was already submitted.
|
| 6 |
+
"""
|
| 7 |
+
import json, sys, time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
sys.path.insert(0, "/Users/dmpantiu/copernicus_mcp/marine_rag")
|
| 10 |
+
sys.path.insert(0, "/Users/dmpantiu/copernicus_mcp/eqc_qa")
|
| 11 |
+
import net_ipv4 # noqa
|
| 12 |
+
from embed_reports import (get_client, MODEL, BATCH_INPUT, JOB_FILE, OUT, SENTINEL,
|
| 13 |
+
load_chunks, embedded_keys, _extract_values, l2, finalize)
|
| 14 |
+
|
| 15 |
+
def log(*a): print(*a, file=sys.stderr, flush=True)
|
| 16 |
+
|
| 17 |
+
def submit():
|
| 18 |
+
delay = 30
|
| 19 |
+
for attempt in range(240): # ~ up to a few hours
|
| 20 |
+
try:
|
| 21 |
+
c = get_client()
|
| 22 |
+
up = c.files.upload(file=str(BATCH_INPUT),
|
| 23 |
+
config={"display_name": "eqc_qa_embed", "mime_type": "jsonl"})
|
| 24 |
+
job = c.batches.create_embeddings(model=MODEL, src={"file_name": up.name},
|
| 25 |
+
config={"display_name": "eqc_qa_embeddings"})
|
| 26 |
+
JOB_FILE.write_text(job.name)
|
| 27 |
+
log(f"SUBMITTED {job.name} {job.state}")
|
| 28 |
+
return job.name
|
| 29 |
+
except Exception as e:
|
| 30 |
+
es = str(e)[:90]
|
| 31 |
+
log(f"submit attempt {attempt}: {es}")
|
| 32 |
+
time.sleep(delay)
|
| 33 |
+
delay = min(delay * 1.3, 120)
|
| 34 |
+
raise SystemExit("submit failed after many attempts")
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
chunks = load_chunks()
|
| 38 |
+
if JOB_FILE.exists() and JOB_FILE.read_text().strip():
|
| 39 |
+
name = JOB_FILE.read_text().strip()
|
| 40 |
+
log(f"resuming existing job {name}")
|
| 41 |
+
else:
|
| 42 |
+
name = submit()
|
| 43 |
+
c = get_client()
|
| 44 |
+
while True:
|
| 45 |
+
try:
|
| 46 |
+
job = c.batches.get(name=name)
|
| 47 |
+
except Exception as e:
|
| 48 |
+
log(f"poll err {str(e)[:80]}"); time.sleep(30); c = get_client(); continue
|
| 49 |
+
state = str(job.state)
|
| 50 |
+
log(f"job {name}: {state}")
|
| 51 |
+
if any(s in state for s in ("SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED")):
|
| 52 |
+
break
|
| 53 |
+
time.sleep(30)
|
| 54 |
+
if "SUCCEEDED" not in state:
|
| 55 |
+
log(f"job ended {state} — not successful"); sys.exit(1)
|
| 56 |
+
by_key = {x["chunk_id"]: x for x in chunks}
|
| 57 |
+
dest = getattr(job, "dest", None)
|
| 58 |
+
fn = getattr(dest, "file_name", None) if dest else None
|
| 59 |
+
lines = []
|
| 60 |
+
if fn:
|
| 61 |
+
lines = c.files.download(file=fn).decode("utf-8").strip().split("\n")
|
| 62 |
+
elif dest and getattr(dest, "inlined_responses", None):
|
| 63 |
+
lines = [json.dumps(r) for r in dest.inlined_responses]
|
| 64 |
+
n = 0
|
| 65 |
+
with open(OUT, "a", encoding="utf-8") as fout:
|
| 66 |
+
for line in lines:
|
| 67 |
+
if not line.strip(): continue
|
| 68 |
+
r = json.loads(line)
|
| 69 |
+
k = r.get("key") or r.get("custom_id")
|
| 70 |
+
vals = _extract_values(r)
|
| 71 |
+
if k in by_key and vals:
|
| 72 |
+
x = dict(by_key[k]); x["embedding"] = l2(vals)
|
| 73 |
+
fout.write(json.dumps(x, ensure_ascii=False) + "\n"); n += 1
|
| 74 |
+
log(f"downloaded {n} embeddings -> {OUT}")
|
| 75 |
+
finalize(chunks)
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
main()
|
scripts/eqc_qa/extract_code.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
extract_code.py — CODE-PRESERVING re-extraction of the EQC notebooks.
|
| 4 |
+
|
| 5 |
+
Companion to parse_reports.py (which is text-only and DROPS runnable code).
|
| 6 |
+
This one keeps every code cell verbatim so the notebooks can be ATTACHED to
|
| 7 |
+
RAG chunks (payload riders keyed by dataset_id) — the agent then sees the real
|
| 8 |
+
cdsapi / copernicusmarine / xarray / plot code, not just prose.
|
| 9 |
+
|
| 10 |
+
Does NOT mutate any Qdrant index and does NOT touch existing parsed/*.md.
|
| 11 |
+
Outputs (all new):
|
| 12 |
+
eqc_qa/notebooks_code/<report_id>.md full reconstruction (```python fences)
|
| 13 |
+
eqc_qa/notebooks_by_dataset.json dataset_id -> [notebook attach records]
|
| 14 |
+
eqc_qa/extract_code_stats.json summary
|
| 15 |
+
|
| 16 |
+
Mapping reuses eqc_qa/reports.jsonl (matched_dataset_id / store / confidence).
|
| 17 |
+
"""
|
| 18 |
+
import json
|
| 19 |
+
import re
|
| 20 |
+
import sys
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
ROOT = Path(__file__).resolve().parent
|
| 24 |
+
REPO = ROOT / "repo"
|
| 25 |
+
MANIFEST = ROOT / "reports.jsonl"
|
| 26 |
+
OUT_MD = ROOT / "notebooks_code"
|
| 27 |
+
OUT_SIDECAR = ROOT / "notebooks_by_dataset.json"
|
| 28 |
+
OUT_STATS = ROOT / "extract_code_stats.json"
|
| 29 |
+
|
| 30 |
+
SOURCE_REPO = "ecmwf-projects/c3s2-eqc-quality-assessment"
|
| 31 |
+
LICENSE = "Apache-2.0"
|
| 32 |
+
|
| 33 |
+
DOWNLOAD_RE = re.compile(
|
| 34 |
+
r"cdsapi|\.retrieve\(|copernicusmarine|\bcm\.(subset|get|open_dataset)|"
|
| 35 |
+
r"c3s_eqc_automatic_quality_control|\bdownload\.|from .*import .*download|"
|
| 36 |
+
r"!?\bwget\b|urlretrieve|requests\.get|\.hda\b|EO:",
|
| 37 |
+
re.I,
|
| 38 |
+
)
|
| 39 |
+
ANALYZE_RE = re.compile(
|
| 40 |
+
r"\bimport xarray|\bxr\.|\.open_dataset|\.open_mfdataset|\bimport pandas|\bpd\.|"
|
| 41 |
+
r"\bimport numpy|\bnp\.|\bscipy|\bxskillscore|\bruptures|\.groupby\(|\.resample\(|"
|
| 42 |
+
r"\.mean\(|\.sel\(|\.isel\(",
|
| 43 |
+
re.I,
|
| 44 |
+
)
|
| 45 |
+
PLOT_RE = re.compile(
|
| 46 |
+
r"\bmatplotlib|\bplt\.|\bcartopy|\bccrs\b|\bcmocean|\.plot\(|\.plot\.|seaborn|\bsns\.",
|
| 47 |
+
re.I,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def log(*a):
|
| 52 |
+
print(*a, file=sys.stderr, flush=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _src(cell) -> str:
|
| 56 |
+
s = cell.get("source", "")
|
| 57 |
+
return "".join(s) if isinstance(s, list) else s
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def code_line_count(code: str) -> int:
|
| 61 |
+
n = 0
|
| 62 |
+
for ln in code.splitlines():
|
| 63 |
+
st = ln.strip()
|
| 64 |
+
if st and not st.startswith("#"):
|
| 65 |
+
n += 1
|
| 66 |
+
return n
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def text_outputs(cell) -> list[str]:
|
| 70 |
+
"""Trimmed text outputs (stdout/stderr/text-plain), dropping progress-bar / warning noise."""
|
| 71 |
+
out = []
|
| 72 |
+
for o in cell.get("outputs", []):
|
| 73 |
+
ot = o.get("output_type")
|
| 74 |
+
s = None
|
| 75 |
+
if ot == "stream":
|
| 76 |
+
t = o.get("text", "")
|
| 77 |
+
s = "".join(t) if isinstance(t, list) else t
|
| 78 |
+
elif ot in ("execute_result", "display_data"):
|
| 79 |
+
tp = (o.get("data") or {}).get("text/plain")
|
| 80 |
+
if tp is not None:
|
| 81 |
+
s = "".join(tp) if isinstance(tp, list) else tp
|
| 82 |
+
if not s:
|
| 83 |
+
continue
|
| 84 |
+
s = s.strip()
|
| 85 |
+
if not s or re.fullmatch(r"<[^>]+>", s) or s.startswith("<Figure"):
|
| 86 |
+
continue
|
| 87 |
+
# drop tqdm-style progress bars and pure warning spew
|
| 88 |
+
lines = [ln for ln in s.splitlines()
|
| 89 |
+
if "%|" not in ln and "it/s]" not in ln and "B/s]" not in ln]
|
| 90 |
+
s = "\n".join(lines).strip()
|
| 91 |
+
if len(s) >= 8:
|
| 92 |
+
out.append(s[:1500]) # cap giant dumps
|
| 93 |
+
return out
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def classify(code: str) -> list[str]:
|
| 97 |
+
kinds = []
|
| 98 |
+
if DOWNLOAD_RE.search(code):
|
| 99 |
+
kinds.append("download")
|
| 100 |
+
if ANALYZE_RE.search(code):
|
| 101 |
+
kinds.append("analyze")
|
| 102 |
+
if PLOT_RE.search(code):
|
| 103 |
+
kinds.append("plot")
|
| 104 |
+
return kinds or ["other"]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def extract_notebook(path: Path) -> dict:
|
| 108 |
+
nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
|
| 109 |
+
parts = [] # reconstructed md
|
| 110 |
+
n_code_cells = 0
|
| 111 |
+
n_code_lines = 0
|
| 112 |
+
kinds = set()
|
| 113 |
+
title = ""
|
| 114 |
+
for cell in nb.get("cells", []):
|
| 115 |
+
ct = cell.get("cell_type")
|
| 116 |
+
if ct == "markdown":
|
| 117 |
+
txt = _src(cell).strip()
|
| 118 |
+
if txt:
|
| 119 |
+
parts.append(txt)
|
| 120 |
+
if not title:
|
| 121 |
+
for ln in txt.splitlines():
|
| 122 |
+
if ln.startswith("# "):
|
| 123 |
+
title = ln[2:].strip()
|
| 124 |
+
break
|
| 125 |
+
elif ct == "code":
|
| 126 |
+
src = _src(cell).rstrip()
|
| 127 |
+
if not src.strip():
|
| 128 |
+
continue
|
| 129 |
+
n_code_cells += 1
|
| 130 |
+
n_code_lines += code_line_count(src)
|
| 131 |
+
kinds.update(classify(src))
|
| 132 |
+
parts.append("```python\n" + src + "\n```")
|
| 133 |
+
for to in text_outputs(cell):
|
| 134 |
+
parts.append("```text\n" + to + "\n```")
|
| 135 |
+
return {
|
| 136 |
+
"content_md": "\n\n".join(parts).strip(),
|
| 137 |
+
"title": title or path.stem,
|
| 138 |
+
"n_code_cells": n_code_cells,
|
| 139 |
+
"n_code_lines": n_code_lines,
|
| 140 |
+
"recipe_kinds": sorted(kinds),
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def main():
|
| 145 |
+
OUT_MD.mkdir(exist_ok=True)
|
| 146 |
+
manifest = {r["report_id"]: r for r in
|
| 147 |
+
(json.loads(l) for l in MANIFEST.read_text().splitlines() if l.strip())}
|
| 148 |
+
log(f"manifest: {len(manifest)} reports")
|
| 149 |
+
|
| 150 |
+
sidecar: dict[str, list] = {}
|
| 151 |
+
unmatched: list = []
|
| 152 |
+
stats = {"notebooks": 0, "code_cells": 0, "code_lines": 0,
|
| 153 |
+
"with_download": 0, "with_analyze": 0, "with_plot": 0,
|
| 154 |
+
"attached_datasets": 0, "unmatched_notebooks": 0}
|
| 155 |
+
|
| 156 |
+
for nb in sorted(REPO.rglob("*.ipynb")):
|
| 157 |
+
report_id = nb.stem
|
| 158 |
+
rec = manifest.get(report_id, {})
|
| 159 |
+
ex = extract_notebook(nb)
|
| 160 |
+
if ex["n_code_cells"] == 0:
|
| 161 |
+
continue # prose-only (e.g. Applications write-ups) — nothing to attach
|
| 162 |
+
# write full reconstruction
|
| 163 |
+
(OUT_MD / f"{report_id}.md").write_text(ex["content_md"], encoding="utf-8")
|
| 164 |
+
|
| 165 |
+
attach = {
|
| 166 |
+
"notebook_id": report_id,
|
| 167 |
+
"title": ex["title"],
|
| 168 |
+
"store": rec.get("store") or "CDS",
|
| 169 |
+
"matched_dataset_id": rec.get("matched_dataset_id") or "",
|
| 170 |
+
"raw_dataset_id": rec.get("dataset_id") or "",
|
| 171 |
+
"category": rec.get("category") or "",
|
| 172 |
+
"aspect": rec.get("aspect") or "",
|
| 173 |
+
"match_confidence": rec.get("match_confidence") or "unmatched",
|
| 174 |
+
"source_repo": SOURCE_REPO,
|
| 175 |
+
"license": LICENSE,
|
| 176 |
+
"src_path": rec.get("src_path") or str(nb.relative_to(REPO)),
|
| 177 |
+
"md_path": str((OUT_MD / f"{report_id}.md").relative_to(ROOT.parent)),
|
| 178 |
+
"n_code_cells": ex["n_code_cells"],
|
| 179 |
+
"n_code_lines": ex["n_code_lines"],
|
| 180 |
+
"recipe_kinds": ex["recipe_kinds"],
|
| 181 |
+
}
|
| 182 |
+
stats["notebooks"] += 1
|
| 183 |
+
stats["code_cells"] += ex["n_code_cells"]
|
| 184 |
+
stats["code_lines"] += ex["n_code_lines"]
|
| 185 |
+
stats["with_download"] += "download" in ex["recipe_kinds"]
|
| 186 |
+
stats["with_analyze"] += "analyze" in ex["recipe_kinds"]
|
| 187 |
+
stats["with_plot"] += "plot" in ex["recipe_kinds"]
|
| 188 |
+
|
| 189 |
+
key = attach["matched_dataset_id"]
|
| 190 |
+
if key:
|
| 191 |
+
sidecar.setdefault(key, []).append(attach)
|
| 192 |
+
else:
|
| 193 |
+
unmatched.append(attach)
|
| 194 |
+
stats["unmatched_notebooks"] += 1
|
| 195 |
+
|
| 196 |
+
stats["attached_datasets"] = len(sidecar)
|
| 197 |
+
OUT_SIDECAR.write_text(json.dumps(
|
| 198 |
+
{"by_dataset": sidecar, "unmatched": unmatched}, ensure_ascii=False, indent=2))
|
| 199 |
+
OUT_STATS.write_text(json.dumps(stats, indent=2))
|
| 200 |
+
|
| 201 |
+
log(f"notebooks with code : {stats['notebooks']}")
|
| 202 |
+
log(f"code cells / lines : {stats['code_cells']} / {stats['code_lines']:,}")
|
| 203 |
+
log(f"download/analyze/plot: {stats['with_download']}/{stats['with_analyze']}/{stats['with_plot']}")
|
| 204 |
+
log(f"attached to datasets : {stats['attached_datasets']} (unmatched notebooks: {stats['unmatched_notebooks']})")
|
| 205 |
+
log(f"-> {OUT_SIDECAR.relative_to(ROOT.parent)}, {OUT_MD.relative_to(ROOT.parent)}/*.md")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
if __name__ == "__main__":
|
| 209 |
+
main()
|
scripts/eqc_qa/fetch_reports.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
fetch_reports.py — obtain the C3S EQC Quality Assessment notebooks.
|
| 4 |
+
|
| 5 |
+
Source: public GitHub repo ecmwf-projects/c3s2-eqc-quality-assessment (74 .ipynb).
|
| 6 |
+
Strategy: shallow git clone into eqc_qa/repo (idempotent — re-fetches if missing).
|
| 7 |
+
Then list every notebook with its top-level category dir + filename.
|
| 8 |
+
|
| 9 |
+
Text only; no rendering. stderr logging.
|
| 10 |
+
"""
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parent
|
| 16 |
+
REPO = ROOT / "repo"
|
| 17 |
+
URL = "https://github.com/ecmwf-projects/c3s2-eqc-quality-assessment"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def log(*a):
|
| 21 |
+
print(*a, file=sys.stderr, flush=True)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def ensure_repo() -> None:
|
| 25 |
+
if (REPO / ".git").exists():
|
| 26 |
+
log(f"repo already present: {REPO}")
|
| 27 |
+
return
|
| 28 |
+
log(f"cloning {URL} --depth 1 -> {REPO}")
|
| 29 |
+
subprocess.run(
|
| 30 |
+
["git", "clone", "--depth", "1", URL, str(REPO)],
|
| 31 |
+
check=True,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def list_notebooks() -> list[Path]:
|
| 36 |
+
return sorted(REPO.rglob("*.ipynb"))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main() -> None:
|
| 40 |
+
ensure_repo()
|
| 41 |
+
nbs = list_notebooks()
|
| 42 |
+
log(f"found {len(nbs)} notebooks")
|
| 43 |
+
from collections import Counter
|
| 44 |
+
cats = Counter(nb.relative_to(REPO).parts[0] for nb in nbs)
|
| 45 |
+
for nb in nbs:
|
| 46 |
+
rel = nb.relative_to(REPO)
|
| 47 |
+
print(f"{rel.parts[0]}\t{nb.name}")
|
| 48 |
+
log("category counts: " + ", ".join(f"{k}={v}" for k, v in sorted(cats.items())))
|
| 49 |
+
log(f"TOTAL {len(nbs)} notebooks")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
main()
|
scripts/eqc_qa/load_eqc_qa.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
load_eqc_qa.py — load embedded EQC QA chunks into a SEPARATE embedded Qdrant.
|
| 4 |
+
|
| 5 |
+
Mirrors marine_rag/load_qdrant.py. Collection `eqc_qa`:
|
| 6 |
+
- dense (768-dim, Cosine) gemini-embedding-2-preview
|
| 7 |
+
- sparse (BM25 via FastEmbed, IDF modifier)
|
| 8 |
+
- payload indexes: dataset_id, store, doc_type, aspect
|
| 9 |
+
|
| 10 |
+
Storage: eqc_qa/qdrant_db (its OWN db — does NOT touch marine_rag/out/qdrant_db
|
| 11 |
+
or pubs_rag/qdrant_db, to avoid single-process lock contention).
|
| 12 |
+
|
| 13 |
+
Usage: python load_eqc_qa.py --recreate
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
import uuid
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
from qdrant_client import QdrantClient, models
|
| 23 |
+
from fastembed import SparseTextEmbedding
|
| 24 |
+
|
| 25 |
+
ROOT = Path(__file__).resolve().parent
|
| 26 |
+
COLLECTION = "eqc_qa"
|
| 27 |
+
DENSE_DIM = 768
|
| 28 |
+
INPUT = ROOT / "chunks_embedded.jsonl"
|
| 29 |
+
LOCAL_DB = ROOT / "qdrant_db"
|
| 30 |
+
BATCH = 256
|
| 31 |
+
|
| 32 |
+
_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def log(*a):
|
| 36 |
+
print(*a, file=sys.stderr, flush=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def to_sparse(text: str) -> models.SparseVector:
|
| 40 |
+
r = list(_bm25.embed([text]))[0]
|
| 41 |
+
return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist())
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def create_collection(client: QdrantClient, recreate: bool) -> None:
|
| 45 |
+
names = [c.name for c in client.get_collections().collections]
|
| 46 |
+
if COLLECTION in names:
|
| 47 |
+
if recreate:
|
| 48 |
+
client.delete_collection(COLLECTION)
|
| 49 |
+
else:
|
| 50 |
+
log(f"'{COLLECTION}' exists: {client.get_collection(COLLECTION).points_count} pts")
|
| 51 |
+
return
|
| 52 |
+
client.create_collection(
|
| 53 |
+
collection_name=COLLECTION,
|
| 54 |
+
vectors_config={"dense": models.VectorParams(size=DENSE_DIM, distance=models.Distance.COSINE)},
|
| 55 |
+
sparse_vectors_config={"sparse": models.SparseVectorParams(modifier=models.Modifier.IDF)},
|
| 56 |
+
)
|
| 57 |
+
for field in ("dataset_id", "store", "doc_type", "aspect"):
|
| 58 |
+
client.create_payload_index(collection_name=COLLECTION, field_name=field,
|
| 59 |
+
field_schema=models.PayloadSchemaType.KEYWORD)
|
| 60 |
+
log(f"created '{COLLECTION}' (dense+sparse, 4 payload indexes)")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def load(client: QdrantClient) -> None:
|
| 64 |
+
buf, total, skipped, t0 = [], 0, 0, time.time()
|
| 65 |
+
with open(INPUT, encoding="utf-8") as f:
|
| 66 |
+
for line in f:
|
| 67 |
+
c = json.loads(line)
|
| 68 |
+
emb = c.get("embedding")
|
| 69 |
+
if not emb:
|
| 70 |
+
skipped += 1
|
| 71 |
+
continue
|
| 72 |
+
raw = c.get("text_raw", "")
|
| 73 |
+
buf.append(models.PointStruct(
|
| 74 |
+
id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])),
|
| 75 |
+
vector={"dense": emb, "sparse": to_sparse(raw)},
|
| 76 |
+
payload={
|
| 77 |
+
"chunk_id": c["chunk_id"],
|
| 78 |
+
"report_id": c["report_id"],
|
| 79 |
+
"dataset_id": c["dataset_id"],
|
| 80 |
+
"store": c["store"],
|
| 81 |
+
"doc_type": c["doc_type"],
|
| 82 |
+
"aspect": c["aspect"],
|
| 83 |
+
"aspect_base": c.get("aspect_base", ""),
|
| 84 |
+
"category": c.get("category", ""),
|
| 85 |
+
"match_confidence": c.get("match_confidence", ""),
|
| 86 |
+
"section": c.get("section", ""),
|
| 87 |
+
"title": c.get("title", ""),
|
| 88 |
+
"text_raw": raw[:2500],
|
| 89 |
+
},
|
| 90 |
+
))
|
| 91 |
+
if len(buf) >= BATCH:
|
| 92 |
+
client.upsert(collection_name=COLLECTION, points=buf)
|
| 93 |
+
total += len(buf)
|
| 94 |
+
log(f" [{total}] {total/(time.time()-t0):.0f} pts/s")
|
| 95 |
+
buf = []
|
| 96 |
+
if buf:
|
| 97 |
+
client.upsert(collection_name=COLLECTION, points=buf)
|
| 98 |
+
total += len(buf)
|
| 99 |
+
log(f"DONE: {total} points, skipped {skipped}, total now "
|
| 100 |
+
f"{client.get_collection(COLLECTION).points_count}")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main():
|
| 104 |
+
ap = argparse.ArgumentParser()
|
| 105 |
+
ap.add_argument("--recreate", action="store_true")
|
| 106 |
+
a = ap.parse_args()
|
| 107 |
+
client = QdrantClient(path=str(LOCAL_DB))
|
| 108 |
+
log(f"Qdrant local: {LOCAL_DB}")
|
| 109 |
+
create_collection(client, a.recreate)
|
| 110 |
+
load(client)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
main()
|
scripts/eqc_qa/merge_notebooks.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
merge_notebooks.py — unify the notebook code layer into ONE sidecar the server reads.
|
| 4 |
+
|
| 5 |
+
Inputs (both read-only, never mutated):
|
| 6 |
+
eqc_qa/eqc_notebooks_by_dataset.json EQC-only base (from extract_code.py)
|
| 7 |
+
notebook_harvest/harvest_records.json list of per-repo results from the harvest
|
| 8 |
+
workflow (each: {repo, license, records:[...]})
|
| 9 |
+
|
| 10 |
+
Output:
|
| 11 |
+
eqc_qa/notebooks_by_dataset.json unified: by_dataset + generic_by_store + sources
|
| 12 |
+
|
| 13 |
+
Record shape stored per notebook:
|
| 14 |
+
notebook_id, title, store, matched_dataset_id, source_repo, license,
|
| 15 |
+
src_path, md_path, n_code_cells, n_code_lines, recipe_kinds, scope
|
| 16 |
+
"""
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 21 |
+
EQC_BASE = ROOT / "eqc_qa" / "eqc_notebooks_by_dataset.json"
|
| 22 |
+
HARVEST = ROOT / "notebook_harvest" / "harvest_records.json"
|
| 23 |
+
OUT = ROOT / "eqc_qa" / "notebooks_by_dataset.json"
|
| 24 |
+
|
| 25 |
+
STORE_SPLIT = {"CDS/ADS/EWDS": ["CDS", "ADS", "EWDS"], "CADS": ["CDS", "ADS", "EWDS"]}
|
| 26 |
+
# normalise the free-text store labels agents produced to the 4 canonical stores
|
| 27 |
+
STORE_NORM = {
|
| 28 |
+
"CMEMS IN-SITU": "CMEMS", "CMEMS INSITU": "CMEMS", "MARINE": "CMEMS",
|
| 29 |
+
"EWDS/CEMS": "EWDS", "CEMS": "EWDS", "CEMS/EWDS": "EWDS",
|
| 30 |
+
"C3S": "CDS", "CAMS": "ADS", "ADS/CAMS": "ADS",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _store(raw: str) -> str:
|
| 35 |
+
s = (raw or "").strip()
|
| 36 |
+
return STORE_NORM.get(s.upper(), s)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _norm(rec: dict, dataset_id: str, scope: str) -> dict:
|
| 40 |
+
return {
|
| 41 |
+
"notebook_id": rec.get("notebook_id"),
|
| 42 |
+
"title": rec.get("title"),
|
| 43 |
+
"store": _store(rec.get("store")),
|
| 44 |
+
"matched_dataset_id": dataset_id,
|
| 45 |
+
"source_repo": rec.get("source_repo") or rec.get("repo") or "",
|
| 46 |
+
"license": rec.get("license") or "",
|
| 47 |
+
"src_path": rec.get("src_path") or "",
|
| 48 |
+
"md_path": rec.get("md_path") or "",
|
| 49 |
+
"n_code_cells": rec.get("n_code_cells") or 0,
|
| 50 |
+
"n_code_lines": rec.get("n_code_lines") or 0,
|
| 51 |
+
"recipe_kinds": rec.get("recipe_kinds") or [],
|
| 52 |
+
"scope": scope,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
by_dataset: dict[str, list] = {}
|
| 58 |
+
generic: dict[str, list] = {}
|
| 59 |
+
sources: dict[str, dict] = {}
|
| 60 |
+
seen: set = set() # (notebook_id, dataset_id) dedup
|
| 61 |
+
|
| 62 |
+
def add_dataset(dsid, rec):
|
| 63 |
+
key = (rec["notebook_id"], dsid)
|
| 64 |
+
if not dsid or key in seen:
|
| 65 |
+
return
|
| 66 |
+
seen.add(key)
|
| 67 |
+
by_dataset.setdefault(dsid, []).append(rec)
|
| 68 |
+
|
| 69 |
+
def add_generic(store, rec):
|
| 70 |
+
key = (rec["notebook_id"], f"__generic__{store}")
|
| 71 |
+
if key in seen:
|
| 72 |
+
return
|
| 73 |
+
seen.add(key)
|
| 74 |
+
generic.setdefault(store, []).append(rec)
|
| 75 |
+
|
| 76 |
+
# 1) EQC base (all dataset-scoped, store=CDS)
|
| 77 |
+
base = json.loads(EQC_BASE.read_text())
|
| 78 |
+
for dsid, recs in base.get("by_dataset", {}).items():
|
| 79 |
+
for r in recs:
|
| 80 |
+
add_dataset(dsid, _norm(r, dsid, "dataset"))
|
| 81 |
+
sources["ecmwf-projects/c3s2-eqc-quality-assessment"] = {
|
| 82 |
+
"license": "Apache-2.0",
|
| 83 |
+
"n_notebooks": sum(len(v) for v in base.get("by_dataset", {}).values()),
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
# 2) harvested repos
|
| 87 |
+
if HARVEST.exists():
|
| 88 |
+
harvest = json.loads(HARVEST.read_text())
|
| 89 |
+
for repo in harvest:
|
| 90 |
+
if not repo:
|
| 91 |
+
continue
|
| 92 |
+
sources[repo.get("repo", "?")] = {
|
| 93 |
+
"license": repo.get("license"),
|
| 94 |
+
"status": repo.get("status"),
|
| 95 |
+
"n_notebooks": repo.get("n_notebooks"),
|
| 96 |
+
"n_code_lines": repo.get("n_code_lines"),
|
| 97 |
+
}
|
| 98 |
+
for r in repo.get("records", []):
|
| 99 |
+
scope = r.get("scope", "dataset")
|
| 100 |
+
if scope == "dataset" and r.get("matched_dataset_ids"):
|
| 101 |
+
for dsid in r["matched_dataset_ids"]:
|
| 102 |
+
add_dataset(dsid, _norm(r, dsid, "dataset"))
|
| 103 |
+
else:
|
| 104 |
+
raw = (r.get("store") or "").strip()
|
| 105 |
+
stores = STORE_SPLIT.get(raw) or STORE_SPLIT.get(raw.upper()) \
|
| 106 |
+
or [_store(raw)] if raw else ["UNKNOWN"]
|
| 107 |
+
for s in stores:
|
| 108 |
+
add_generic(s, _norm(r, "", "generic"))
|
| 109 |
+
|
| 110 |
+
out = {"by_dataset": by_dataset, "generic_by_store": generic, "sources": sources}
|
| 111 |
+
OUT.write_text(json.dumps(out, ensure_ascii=False, indent=1))
|
| 112 |
+
|
| 113 |
+
n_ds_nb = sum(len(v) for v in by_dataset.values())
|
| 114 |
+
n_gen = sum(len(v) for v in generic.values())
|
| 115 |
+
print(json.dumps({
|
| 116 |
+
"datasets_with_notebooks": len(by_dataset),
|
| 117 |
+
"dataset_notebook_records": n_ds_nb,
|
| 118 |
+
"generic_stores": {k: len(v) for k, v in generic.items()},
|
| 119 |
+
"generic_records": n_gen,
|
| 120 |
+
"sources": len(sources),
|
| 121 |
+
"out": str(OUT.relative_to(ROOT)),
|
| 122 |
+
}, indent=1))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|
scripts/eqc_qa/parse_reports.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
parse_reports.py — extract TEXT only from each EQC QA notebook.
|
| 4 |
+
|
| 5 |
+
For every repo/**/*.ipynb (parsed as JSON, no nbformat dependency):
|
| 6 |
+
- markdown cells -> kept verbatim (prose: methodology, findings, verdicts;
|
| 7 |
+
headings preserved for section-aware chunking)
|
| 8 |
+
- code cells -> comment lines from source (prose intent) + TEXT outputs
|
| 9 |
+
(stream stdout/stderr, execute_result/display_data
|
| 10 |
+
'text/plain'). SKIP image/png/jpeg/svg/base64/raw data.
|
| 11 |
+
|
| 12 |
+
Filename encodes dataset + report type:
|
| 13 |
+
<prefix>_<dataset_id>_<aspect>_q<NN>.ipynb
|
| 14 |
+
e.g. satellite_satellite-sea-surface-temperature_consistency_q01
|
| 15 |
+
-> dataset=satellite-sea-surface-temperature aspect=consistency q=q01
|
| 16 |
+
|
| 17 |
+
Dataset mapping: cross-reference dataset_id against the CDS/ADS/EWDS catalogue
|
| 18 |
+
(meta_harvest/{cds,ads,ewds}_enriched.json); exact -> fuzzy substring -> unmatched.
|
| 19 |
+
|
| 20 |
+
Outputs:
|
| 21 |
+
eqc_qa/parsed/<report_id>.md
|
| 22 |
+
eqc_qa/reports.jsonl (manifest, one line per report)
|
| 23 |
+
|
| 24 |
+
templates/template.ipynb is a scaffold (not a dataset report): parsed for text
|
| 25 |
+
but flagged is_template and left dataset-unmatched.
|
| 26 |
+
"""
|
| 27 |
+
import json
|
| 28 |
+
import sys
|
| 29 |
+
import re
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
ROOT = Path(__file__).resolve().parent
|
| 33 |
+
REPO = ROOT / "repo"
|
| 34 |
+
PARSED = ROOT / "parsed"
|
| 35 |
+
MANIFEST = ROOT / "reports.jsonl"
|
| 36 |
+
META = ROOT.parent / "meta_harvest"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def log(*a):
|
| 40 |
+
print(*a, file=sys.stderr, flush=True)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ── catalogue for dataset mapping ────────────────────────────────────────────
|
| 44 |
+
def load_catalogue() -> dict[str, str]:
|
| 45 |
+
ids: dict[str, str] = {}
|
| 46 |
+
for name, store in (("cds", "CDS"), ("ads", "ADS"), ("ewds", "EWDS")):
|
| 47 |
+
p = META / f"{name}_enriched.json"
|
| 48 |
+
if p.exists():
|
| 49 |
+
for k in json.loads(p.read_text()):
|
| 50 |
+
ids[k] = store
|
| 51 |
+
return ids
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def map_dataset(dataset_id: str, catalogue: dict[str, str]) -> tuple[str, str, str]:
|
| 55 |
+
"""Return (matched_id, store, confidence:{exact,fuzzy,unmatched})."""
|
| 56 |
+
if not dataset_id:
|
| 57 |
+
return "", "", "unmatched"
|
| 58 |
+
if dataset_id in catalogue:
|
| 59 |
+
return dataset_id, catalogue[dataset_id], "exact"
|
| 60 |
+
# fuzzy: substring either direction (guard against trivially short ids)
|
| 61 |
+
if len(dataset_id) >= 5:
|
| 62 |
+
cands = [k for k in catalogue if dataset_id in k or k in dataset_id]
|
| 63 |
+
if cands:
|
| 64 |
+
best = min(cands, key=len)
|
| 65 |
+
return best, catalogue[best], "fuzzy"
|
| 66 |
+
return "", "", "unmatched"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ── text extraction ──────────────────────────────────────────────────────────
|
| 70 |
+
def _src(cell) -> str:
|
| 71 |
+
s = cell.get("source", "")
|
| 72 |
+
return "".join(s) if isinstance(s, list) else s
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def comment_lines(code: str) -> list[str]:
|
| 76 |
+
out = []
|
| 77 |
+
for ln in code.splitlines():
|
| 78 |
+
st = ln.strip()
|
| 79 |
+
if st.startswith("#") and not st.startswith("#!"):
|
| 80 |
+
txt = st.lstrip("#").strip()
|
| 81 |
+
if len(txt) >= 12 and not txt.startswith("%"): # skip trivial / magics
|
| 82 |
+
out.append(txt)
|
| 83 |
+
return out
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def text_outputs(cell) -> list[str]:
|
| 87 |
+
out = []
|
| 88 |
+
for o in cell.get("outputs", []):
|
| 89 |
+
ot = o.get("output_type")
|
| 90 |
+
if ot == "stream":
|
| 91 |
+
t = o.get("text", "")
|
| 92 |
+
out.append("".join(t) if isinstance(t, list) else t)
|
| 93 |
+
elif ot in ("execute_result", "display_data"):
|
| 94 |
+
data = o.get("data", {})
|
| 95 |
+
tp = data.get("text/plain")
|
| 96 |
+
if tp is not None:
|
| 97 |
+
# skip pure object reprs like "<Figure ...>" / matplotlib handles
|
| 98 |
+
s = "".join(tp) if isinstance(tp, list) else tp
|
| 99 |
+
s = s.strip()
|
| 100 |
+
if s and not re.fullmatch(r"<[^>]+>", s) and not s.startswith("<Figure"):
|
| 101 |
+
out.append(s)
|
| 102 |
+
# image/png, image/jpeg, image/svg+xml, application/* -> skipped entirely
|
| 103 |
+
return out
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def parse_notebook(path: Path) -> tuple[str, str]:
|
| 107 |
+
"""Return (markdown_text, title)."""
|
| 108 |
+
nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
|
| 109 |
+
parts: list[str] = []
|
| 110 |
+
for cell in nb.get("cells", []):
|
| 111 |
+
ct = cell.get("cell_type")
|
| 112 |
+
if ct == "markdown":
|
| 113 |
+
txt = _src(cell).strip()
|
| 114 |
+
if txt:
|
| 115 |
+
parts.append(txt)
|
| 116 |
+
elif ct == "code":
|
| 117 |
+
src = _src(cell)
|
| 118 |
+
cmts = comment_lines(src)
|
| 119 |
+
if cmts:
|
| 120 |
+
parts.append("\n".join(cmts))
|
| 121 |
+
for to in text_outputs(cell):
|
| 122 |
+
to = to.strip()
|
| 123 |
+
if to and len(to) >= 8:
|
| 124 |
+
parts.append("```text\n" + to + "\n```")
|
| 125 |
+
md = "\n\n".join(parts).strip()
|
| 126 |
+
# title = first H1
|
| 127 |
+
title = ""
|
| 128 |
+
for ln in md.splitlines():
|
| 129 |
+
if ln.startswith("# "):
|
| 130 |
+
title = ln[2:].strip()
|
| 131 |
+
break
|
| 132 |
+
if not title:
|
| 133 |
+
title = path.stem
|
| 134 |
+
return md, title
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# ── manifest build ───────────────────────────────────────────────────────────
|
| 138 |
+
def main() -> None:
|
| 139 |
+
PARSED.mkdir(exist_ok=True)
|
| 140 |
+
catalogue = load_catalogue()
|
| 141 |
+
log(f"catalogue: {len(catalogue)} collection ids")
|
| 142 |
+
|
| 143 |
+
nbs = sorted(REPO.rglob("*.ipynb"))
|
| 144 |
+
log(f"parsing {len(nbs)} notebooks")
|
| 145 |
+
|
| 146 |
+
records = []
|
| 147 |
+
stats = {"exact": 0, "fuzzy": 0, "unmatched": 0}
|
| 148 |
+
for nb in nbs:
|
| 149 |
+
rel = nb.relative_to(REPO)
|
| 150 |
+
category = rel.parts[0]
|
| 151 |
+
report_id = nb.stem
|
| 152 |
+
toks = report_id.split("_")
|
| 153 |
+
is_template = len(toks) != 4
|
| 154 |
+
if is_template:
|
| 155 |
+
dataset_id, aspect_base, qnum = "", "", ""
|
| 156 |
+
else:
|
| 157 |
+
_prefix, dataset_id, aspect_base, qnum = toks
|
| 158 |
+
aspect = f"{aspect_base}_{qnum}" if aspect_base else ""
|
| 159 |
+
|
| 160 |
+
matched_id, store, conf = map_dataset(dataset_id, catalogue)
|
| 161 |
+
if is_template:
|
| 162 |
+
conf = "unmatched"
|
| 163 |
+
stats[conf] += 1
|
| 164 |
+
|
| 165 |
+
md, title = parse_notebook(nb)
|
| 166 |
+
md_path = PARSED / f"{report_id}.md"
|
| 167 |
+
md_path.write_text(md, encoding="utf-8")
|
| 168 |
+
|
| 169 |
+
rec = {
|
| 170 |
+
"report_id": report_id,
|
| 171 |
+
"dataset_id": dataset_id,
|
| 172 |
+
"matched_dataset_id": matched_id,
|
| 173 |
+
"store": store,
|
| 174 |
+
"match_confidence": conf,
|
| 175 |
+
"category": category,
|
| 176 |
+
"aspect": aspect,
|
| 177 |
+
"aspect_base": aspect_base,
|
| 178 |
+
"qnum": qnum,
|
| 179 |
+
"title": title,
|
| 180 |
+
"md_path": str(md_path.relative_to(ROOT)),
|
| 181 |
+
"n_chars": len(md),
|
| 182 |
+
"is_template": is_template,
|
| 183 |
+
"src_path": str(rel),
|
| 184 |
+
}
|
| 185 |
+
records.append(rec)
|
| 186 |
+
|
| 187 |
+
with open(MANIFEST, "w", encoding="utf-8") as f:
|
| 188 |
+
for r in records:
|
| 189 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 190 |
+
|
| 191 |
+
reports = [r for r in records if not r["is_template"]]
|
| 192 |
+
log(f"wrote {len(records)} manifest rows ({len(reports)} reports + "
|
| 193 |
+
f"{len(records)-len(reports)} template) -> {MANIFEST}")
|
| 194 |
+
log(f"mapping: exact={stats['exact']} fuzzy={stats['fuzzy']} unmatched={stats['unmatched']}")
|
| 195 |
+
ndatasets = len({r['matched_dataset_id'] for r in reports if r['match_confidence'] != 'unmatched'})
|
| 196 |
+
log(f"reports mapped to a known collection: "
|
| 197 |
+
f"{sum(1 for r in reports if r['match_confidence']!='unmatched')}/{len(reports)} "
|
| 198 |
+
f"across {ndatasets} unique collections")
|
| 199 |
+
log(f"total chars: {sum(r['n_chars'] for r in records):,}")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
if __name__ == "__main__":
|
| 203 |
+
main()
|
scripts/eqc_qa/verify_eqc_qa.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
verify_eqc_qa.py — sanity-check the eqc_qa Qdrant collection.
|
| 4 |
+
|
| 5 |
+
- point count == embedded chunk count
|
| 6 |
+
- BM25 (sparse-only) probes [always works, no API]
|
| 7 |
+
- hybrid dense+BM25 RRF probes [needs one query embedding per probe; degrades
|
| 8 |
+
to BM25-only if the Gemini quota 429s]
|
| 9 |
+
|
| 10 |
+
Probes: SST consistency, satellite soil moisture completeness, multi-origin atlas.
|
| 11 |
+
Prints top hits with report_id + dataset_id.
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
import sys
|
| 15 |
+
import threading
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, "/Users/dmpantiu/copernicus_mcp/marine_rag")
|
| 19 |
+
import net_ipv4 # noqa: F401,E402
|
| 20 |
+
|
| 21 |
+
from qdrant_client import QdrantClient, models
|
| 22 |
+
from fastembed import SparseTextEmbedding
|
| 23 |
+
|
| 24 |
+
ROOT = Path(__file__).resolve().parent
|
| 25 |
+
COLLECTION = "eqc_qa"
|
| 26 |
+
DENSE_DIM = 768
|
| 27 |
+
LOCAL_DB = ROOT / "qdrant_db"
|
| 28 |
+
INPUT = ROOT / "chunks_embedded.jsonl"
|
| 29 |
+
|
| 30 |
+
_bm25 = None
|
| 31 |
+
_lock = threading.Lock()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def log(*a):
|
| 35 |
+
print(*a, file=sys.stderr, flush=True)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def resolve_key() -> str:
|
| 39 |
+
import os
|
| 40 |
+
for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
|
| 41 |
+
if os.environ.get(var):
|
| 42 |
+
return os.environ[var]
|
| 43 |
+
for env in (Path("/Users/dmpantiu/copernicus_mcp/.env"),):
|
| 44 |
+
if env.exists():
|
| 45 |
+
for line in env.read_text().splitlines():
|
| 46 |
+
line = line.strip()
|
| 47 |
+
if "api_key" in line.lower() and "=" in line and not line.startswith("#"):
|
| 48 |
+
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
| 49 |
+
raise SystemExit("no key")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def embed_query(q: str):
|
| 53 |
+
from google import genai
|
| 54 |
+
from google.genai import types
|
| 55 |
+
import numpy as np
|
| 56 |
+
client = genai.Client(api_key=resolve_key())
|
| 57 |
+
r = client.models.embed_content(
|
| 58 |
+
model="gemini-embedding-2-preview", contents=q,
|
| 59 |
+
config=types.EmbedContentConfig(task_type="RETRIEVAL_QUERY", output_dimensionality=DENSE_DIM))
|
| 60 |
+
v = np.array(list(r.embeddings[0].values), dtype=np.float32)
|
| 61 |
+
n = np.linalg.norm(v)
|
| 62 |
+
return (v / n).tolist() if n > 0 else v.tolist()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def sparse_query(q: str):
|
| 66 |
+
global _bm25
|
| 67 |
+
with _lock:
|
| 68 |
+
if _bm25 is None:
|
| 69 |
+
_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
|
| 70 |
+
sp = list(_bm25.query_embed(q))[0]
|
| 71 |
+
return models.SparseVector(indices=sp.indices.tolist(), values=sp.values.tolist())
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def search(client, query, top_k=5):
|
| 75 |
+
sparse = sparse_query(query)
|
| 76 |
+
dense = None
|
| 77 |
+
try:
|
| 78 |
+
dense = embed_query(query)
|
| 79 |
+
except Exception as e:
|
| 80 |
+
log(f" [dense unavailable: {str(e)[:70]}] BM25-only")
|
| 81 |
+
if dense is not None:
|
| 82 |
+
res = client.query_points(
|
| 83 |
+
collection_name=COLLECTION,
|
| 84 |
+
prefetch=[
|
| 85 |
+
models.Prefetch(query=dense, using="dense", limit=50),
|
| 86 |
+
models.Prefetch(query=sparse, using="sparse", limit=50),
|
| 87 |
+
],
|
| 88 |
+
query=models.FusionQuery(fusion=models.Fusion.RRF),
|
| 89 |
+
limit=top_k, with_payload=True,
|
| 90 |
+
)
|
| 91 |
+
mode = "hybrid dense+BM25 RRF"
|
| 92 |
+
else:
|
| 93 |
+
res = client.query_points(collection_name=COLLECTION, query=sparse,
|
| 94 |
+
using="sparse", limit=top_k, with_payload=True)
|
| 95 |
+
mode = "BM25-only"
|
| 96 |
+
return res.points, mode
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main():
|
| 100 |
+
client = QdrantClient(path=str(LOCAL_DB))
|
| 101 |
+
n_pts = client.get_collection(COLLECTION).points_count
|
| 102 |
+
n_emb = sum(1 for _ in open(INPUT)) if INPUT.exists() else 0
|
| 103 |
+
print(f"points={n_pts} embedded_chunks={n_emb} match={'OK' if n_pts == n_emb else 'MISMATCH'}")
|
| 104 |
+
|
| 105 |
+
probes = [
|
| 106 |
+
"sea surface temperature consistency assessment",
|
| 107 |
+
"completeness of satellite soil moisture",
|
| 108 |
+
"multi-origin atlas quality",
|
| 109 |
+
]
|
| 110 |
+
for q in probes:
|
| 111 |
+
pts, mode = search(client, q, top_k=5)
|
| 112 |
+
print(f"\n=== '{q}' [{mode}] ===")
|
| 113 |
+
for i, p in enumerate(pts, 1):
|
| 114 |
+
pl = p.payload
|
| 115 |
+
print(f" #{i} score={p.score:.4f} report={pl['report_id']}")
|
| 116 |
+
print(f" dataset={pl['dataset_id']} aspect={pl['aspect']} "
|
| 117 |
+
f"conf={pl.get('match_confidence','')} sec='{pl.get('section','')[:50]}'")
|
| 118 |
+
print(f" {pl.get('text_raw','')[:150].strip()}")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
main()
|
scripts/marine_rag/MCP_INTEGRATION.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Phase E — wiring the docs RAG into the MCP server
|
| 2 |
+
|
| 3 |
+
Goal: a tool the agent calls **through MCP** that, given a dataset/product, returns its
|
| 4 |
+
documentation so the agent knows how to analyze it (find dataset → read docs → work).
|
| 5 |
+
|
| 6 |
+
## New tool: `marine_dataset_docs`
|
| 7 |
+
|
| 8 |
+
```
|
| 9 |
+
marine_dataset_docs(dataset_or_product_id: str, question: str | None = None, top_k: int = 8)
|
| 10 |
+
-> { product_id, product_title, doc_types_available, results: [{doc_type, section, text, score}] }
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
- Resolves a dataset_id OR product_id → product (via the bundled catalogue), then semantic-searches
|
| 14 |
+
that product's PUM/QUID/SQO chunks in Qdrant. `question=None` returns the "how to analyze"
|
| 15 |
+
essentials (variables, coverage, accuracy, validation, interpretation).
|
| 16 |
+
- Backed by `rag_api.get_dataset_docs()` (this folder). Embeddings: `gemini-embedding-2-preview`;
|
| 17 |
+
retrieval: Qdrant dense+BM25; optional rerank: Google `semantic-ranker-default@latest`.
|
| 18 |
+
|
| 19 |
+
## Drop-in flow (respect copernicus-mcp conventions: Pydantic I/O, error classes, stderr logging,
|
| 20 |
+
## **no raw bytes** — this returns text/descriptors only, which complies)
|
| 21 |
+
|
| 22 |
+
1. Package the RAG assets into the server:
|
| 23 |
+
- ship `out/catalog.json` and the Qdrant store (or point the server at a Qdrant URL).
|
| 24 |
+
- add deps: `qdrant-client`, `fastembed`, `google-genai`, `numpy`.
|
| 25 |
+
2. Add `src/copernicus_mcp/backends/cmems/docs_rag.py` ≈ a cleaned port of `rag_api.py` + `search.py`
|
| 26 |
+
(lazy singletons for the Qdrant client, BM25, genai client; key from config/env not a sibling repo).
|
| 27 |
+
3. Register `marine_dataset_docs` in the CMEMS tool module next to `marine_describe_dataset`, with a
|
| 28 |
+
Pydantic request/response model and one of the canonical error classes for unknown ids /
|
| 29 |
+
index-unavailable.
|
| 30 |
+
4. TDD + dual adversarial review per the repo's review protocol before merge.
|
| 31 |
+
|
| 32 |
+
## Intended agent UX
|
| 33 |
+
`marine_search_datasets` → pick dataset → **`marine_dataset_docs(dataset_id)`** → read returned
|
| 34 |
+
sections → run `marine_subset_dataset` with correct, well-understood parameters.
|
| 35 |
+
|
| 36 |
+
## Status
|
| 37 |
+
- `rag_api.py` works once `out/qdrant_db` is built (after embedding completes). Verify:
|
| 38 |
+
`python rag_api.py MEDSEA_ANALYSISFORECAST_PHY_006_013 --query "salinity validation accuracy"`
|
| 39 |
+
- Reranker needs GCP ADC + `GCP_PROJECT`; without it, dense+BM25 RRF is used (still good).
|
scripts/marine_rag/PLAN.md
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Marine Docs RAG — Work Plan
|
| 2 |
+
|
| 3 |
+
## ✅✅ READY (2026-06-25 13:36) — RAG COMPLETE at ~100%
|
| 4 |
+
- Embedded **29,249 / 29,353 unique chunks (99.6%)**; Qdrant `marine_docs` index = **29,249 points**.
|
| 5 |
+
- Verified retrieval across all levels: product docs (QUID/PUM/SQO) AND dataset CARDs + product DESCs.
|
| 6 |
+
- The last shards finished after cancel+resubmit; ~104 chunks (0.4%) dropped — negligible.
|
| 7 |
+
- Background loop stopped; supervision cron ended.
|
| 8 |
+
- NEXT (design done, see out/design.html): code-aware re-chunk of the 344 code docs (attach
|
| 9 |
+
code_blocks[] to text chunks) + two-stage/parallel search (L0 cards → L1 docs ‖ global, RRF+rerank)
|
| 10 |
+
+ wire marine_dataset_docs into the MCP server.
|
| 11 |
+
|
| 12 |
+
### (historical) READY at 90% (2026-06-25 02:56)
|
| 13 |
+
- Embedded **26,496 / 29,353 unique chunks (90%)**; Qdrant `marine_docs` index = **26,496 points**.
|
| 14 |
+
- Retrieval VERIFIED: product-doc query (salinity validation → QUID accuracy/Salinity + SQO) and
|
| 15 |
+
dataset CARD (antarctic_omi_si_extent → PUM/QUID) both return correct sections.
|
| 16 |
+
- Why 90% not 100%: Google free/paid batch queue wedged on the final ~2,857 chunks (jobs sat 3h+
|
| 17 |
+
with no progress, twice — cancelled & resubmitted, still slow). Not a code issue.
|
| 18 |
+
- **To top up to ~100% later** (no babysitting): `python batch_orchestrator.py` (downloads any
|
| 19 |
+
shards that finished, resubmits the rest), repeat until `wc -l out/chunks_embedded.jsonl` unique
|
| 20 |
+
≈29353, then `python load_qdrant.py --recreate`. Or enable a higher Vertex per-model quota.
|
| 21 |
+
- Background loop stopped; out/EMBEDDING_DONE written.
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
## Vision / spec (from user, 2026-06-22 night — verbatim intent)
|
| 27 |
+
|
| 28 |
+
Build a **RAG for the copernicus-mcp MCP server**, embeddings on **Gemini Embedding 2**
|
| 29 |
+
(`gemini-embedding-2-preview`) + **Google reranker** — no other models. Mirror exactly how it
|
| 30 |
+
was done in `/Users/dmpantiu/cmip6/cmip6_gpt/` (study that folder + its article/PLAN: how the
|
| 31 |
+
Qdrant collection was created, how chunks were cleaned/grouped, BM25, etc.) and do the **same**
|
| 32 |
+
for this MCP server, but **per dataset**.
|
| 33 |
+
|
| 34 |
+
- Dataset search already exists in the server. **Now each dataset must also carry documentation**
|
| 35 |
+
(the marine_parsed descriptions, quality-assurance docs, etc.) so the agent can: find a dataset →
|
| 36 |
+
read its docs → know how to analyze it.
|
| 37 |
+
- The RAG lives **inside the MCP server** and is reachable **through MCP**: add a tool (a kind of
|
| 38 |
+
"clarification" tool) the agent/MCP calls; it queries this RAG and returns the documentation
|
| 39 |
+
info for a dataset. "RAG pulls through MCP."
|
| 40 |
+
- Chunks must be properly split (BM25 + dense), same approach as the cmip6 article/pipeline.
|
| 41 |
+
- Catalog + a clean descending **tree of all Copernicus products/datasets**; doc tree too.
|
| 42 |
+
- Marine docs already provide `.md`; **images are NOT embedded — md text only**.
|
| 43 |
+
- More docs arrive tomorrow (resumable re-run picks them up).
|
| 44 |
+
- **BUDGET CAP: spend ≤ €50 on the embedding API.** (Current estimate ~$2 for all 22,556 chunks —
|
| 45 |
+
far under cap; embedding is cheap, no risk.)
|
| 46 |
+
- Work autonomously overnight via a 10-min self-check loop; do not wake the user.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
**Goal.** Give every Copernicus Marine dataset/product attached, searchable documentation
|
| 51 |
+
(PUM / QUID / SQO) so the agent can: find a dataset → read its docs → know how to analyze it.
|
| 52 |
+
Plus a clean top-down tree of the whole Copernicus Marine catalogue.
|
| 53 |
+
|
| 54 |
+
**Models (locked by user — no substitutes):**
|
| 55 |
+
- Embeddings: **`gemini-embedding-2-preview`** (Vertex / Google GenAI), 768-dim, L2-normalized, task `RETRIEVAL_DOCUMENT`.
|
| 56 |
+
- Reranker: **Google Vertex AI Rank API** `semantic-ranker-default@latest` (NOT an LLM).
|
| 57 |
+
- Vector store: Qdrant (dense Gemini + sparse BM25 hybrid), mirrors `cmip6_gpt/rag`.
|
| 58 |
+
|
| 59 |
+
**Reused pipeline:** `/Users/dmpantiu/cmip6/cmip6_gpt/rag/` — `chunk_papers.py` (`chunk_markdown_document`),
|
| 60 |
+
`embed_and_index.py`, `load_qdrant.py`, `search.py`. Deps already in `cmip6_gpt/.venv`.
|
| 61 |
+
|
| 62 |
+
---
|
| 63 |
+
|
| 64 |
+
## Source data
|
| 65 |
+
|
| 66 |
+
- `marine_parsed/<PRODUCT_ID>/<DOC_ID>/<DOC_ID>/vlm/<DOC_ID>.md` — VLM-parsed docs.
|
| 67 |
+
- 309 product folders; **306 match `products.json` product_ids 1:1 (100% catalogue coverage)**, 3 extra.
|
| 68 |
+
- Doc types: **QUID** (308), **PUM** (283), **SQO** (196), + OC-PUM. Total **813 `.md`** files.
|
| 69 |
+
- ~37k images present but **NOT used** (embeddings are text-only, per user).
|
| 70 |
+
- Catalogue manifests: `copernicus-mcp-dev/src/copernicus_mcp/backends/cmems/_data/`
|
| 71 |
+
(`products.json` 306, `dataset_cards.json` 1251, `groups.json` 47 routing groups, `marine.json`, `variables_lookup.json`).
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
## Phases
|
| 76 |
+
|
| 77 |
+
### Phase A — Catalog + Tree (NO API) ✅ doable now
|
| 78 |
+
- A1. `build_catalog.py` → `out/catalog.json`: map every product_id → {title, group, datasets, doc files (PUM/QUID/SQO) with md paths, sizes}. Flag products missing docs and docs missing products.
|
| 79 |
+
- A2. `build_tree.py` → `out/tree.txt` + `out/tree.md`: descending tree
|
| 80 |
+
Catalogue → routing group → product → datasets, with doc-coverage badges.
|
| 81 |
+
|
| 82 |
+
### Phase B — Chunking (NO API) ✅ doable now
|
| 83 |
+
- B1. `chunk_docs.py`: adapt `chunk_markdown_document` for marine docs. Prefix carries
|
| 84 |
+
product_id, product_title, doc_type (PUM/QUID/SQO), section path. Images stripped.
|
| 85 |
+
Reuse all noise/OCR/dedup filters. Resumable.
|
| 86 |
+
- B2. Run on all 813 md → `out/chunks.jsonl`. Record per-doc chunk counts + token totals.
|
| 87 |
+
|
| 88 |
+
### Phase C — Embedding (NEEDS API) ⛔ BLOCKED: Gemini key IP-restricted
|
| 89 |
+
- BLOCKER: key `AQ.Ab8…` rejects IP `134.1.1.80` (403). Fix: whitelist this IP in Google
|
| 90 |
+
Cloud Console, or remove the IP restriction on the key.
|
| 91 |
+
- C1. `embed.py` (adapted from `embed_and_index.py`): `gemini-embedding-2-preview`, 768-dim,
|
| 92 |
+
realtime + batch modes, resumable → `out/chunks_embedded.jsonl`.
|
| 93 |
+
- C2. Cost estimate emitted before run.
|
| 94 |
+
|
| 95 |
+
### Phase D — Index + Search (NEEDS API + Qdrant) ⛔ after C
|
| 96 |
+
- D1. `load_qdrant.py`: local Qdrant (embedded path mode) collection `marine_docs`,
|
| 97 |
+
dense Gemini + BM25 sparse.
|
| 98 |
+
- D2. `search.py`: hybrid retrieve → `semantic-ranker-default@latest` rerank → top-k.
|
| 99 |
+
|
| 100 |
+
### Phase E — MCP integration ⛔ after D
|
| 101 |
+
- E1. New tool `marine_read_docs(dataset_or_product_id)` → returns relevant doc chunks
|
| 102 |
+
(filepath + cited sections), so the agent reads docs before analyzing.
|
| 103 |
+
- E2. Optional `marine_search_docs(query)` semantic search across all docs.
|
| 104 |
+
- Follow copernicus-mcp invariants (no raw bytes, descriptor returns, stderr logging).
|
| 105 |
+
|
| 106 |
+
---
|
| 107 |
+
|
| 108 |
+
## Status log
|
| 109 |
+
- 2026-06-22: workspace created; key validated (auth OK) but IP-restricted; deps confirmed in cmip6 venv.
|
| 110 |
+
- 2026-06-22: Phase A DONE — `out/catalog.json` (306 products, 100% doc coverage), `out/tree.txt`,
|
| 111 |
+
`out/tree_by_region.txt`, `out/tree.md`.
|
| 112 |
+
- 2026-06-22: Phase B DONE — `out/chunks.jsonl`: 813 docs → 22,556 chunks, 8.46M tokens
|
| 113 |
+
(embed cost ~$2 realtime / ~$1 batch).
|
| 114 |
+
- 2026-06-22: Phase C/D scripts written (`embed.py`, `load_qdrant.py`, `search.py`). BLOCKED on key IP whitelist.
|
| 115 |
+
- 2026-06-22: `run_overnight.sh` launched in background (retry every 10 min) — auto-finishes C+D when IP unblocks.
|
| 116 |
+
- 2026-06-23 00:30: Gemini key IP restriction RESOLVED (user removed it). Key works (dims=768).
|
| 117 |
+
- 2026-06-23 00:40: discovered real constraint = **~5 RPM quota** on the AQ express key
|
| 118 |
+
(429 RESOURCE_EXHAUSTED). embed.py tuned: batch=100, ~13s spacing, 35s backoff on 429.
|
| 119 |
+
- 2026-06-23 01:00: **Phase B.5 CLEANING added (user: "чистка вначале!")** — mirrors cmip6 preprocess:
|
| 120 |
+
`clean_md.py` strips CMEMS boilerplate (CHANGE RECORD, TOC, ACRONYM TABLE, running headers,
|
| 121 |
+
REFERENCES), converts HTML→markdown tables, fixes OCR. 813 docs cleaned → `out/cleaned/`, −30% chars.
|
| 122 |
+
Re-chunked from CLEANED md + noise-table filter (drop change-record/acronym/approval tables):
|
| 123 |
+
**27,796 clean chunks, 9.64M tokens, ~$2.41 to embed**. 0 tiny chunks.
|
| 124 |
+
- Pipeline order is now: clean_md.py → chunk_docs.py → embed.py → load_qdrant.py → search.py.
|
| 125 |
+
- 2026-06-23 01:20: **QUOTA REALITY on the AQ express key (free tier):**
|
| 126 |
+
- realtime embed: `online_prediction_requests_per_base_model` for `gemini-embedding-2` is ~0 RPM
|
| 127 |
+
on preview → realtime is NOT viable for 27k chunks.
|
| 128 |
+
- Batch API works but free-tier caps: a single big job (9.6M tok / 38MB) is rejected with
|
| 129 |
+
"exceeded your current quota / check plan & billing"; ~1000-chunk jobs are accepted;
|
| 130 |
+
only ~1800 chunks can be *enqueued concurrently* before 429. As jobs finish, quota frees.
|
| 131 |
+
- **Solution = `batch_orchestrator.py` + `batch_loop.sh`**: shard into 800-chunk batch jobs,
|
| 132 |
+
poll/download/merge, submit more each pass until quota, repeat every 10 min. Resumable via
|
| 133 |
+
`out/batch_state.json`. Writes `out/EMBEDDING_DONE` then auto-builds Qdrant index + verifies.
|
| 134 |
+
- **THE CLEAN FIX (morning, ~$2, within €50 cap): enable billing on the Google Cloud project /
|
| 135 |
+
use a paid-tier key.** Then a single full batch (or realtime) finishes in minutes. Free tier
|
| 136 |
+
may otherwise span >1 day due to a daily batch-token cap.
|
| 137 |
+
- Reranker caveat: Google `semantic-ranker-default@latest` needs GCP ADC + `GCP_PROJECT`
|
| 138 |
+
(`gcloud auth application-default login`). The AQ API key alone is NOT enough for the ranker;
|
| 139 |
+
search falls back to dense+BM25 RRF until ADC is configured.
|
| 140 |
+
|
| 141 |
+
## 2026-06-23 08:40 — PIPELINE VALIDATED END-TO-END ✅
|
| 142 |
+
- Free-tier batch DID complete (~6-9h): first 4 shards SUCCEEDED.
|
| 143 |
+
- Fixed a download bug (`files.download(file=...)` not `name=...`) in batch_orchestrator.py + embed.py.
|
| 144 |
+
- Downloaded + merged **3,398 real embeddings** (38 products) → built partial Qdrant index.
|
| 145 |
+
- **Verified retrieval**: `rag_api.py GLOBAL_ANALYSISFORECAST_PHY_001_024 --query "how is salinity
|
| 146 |
+
accuracy validated"` returned the exact right docs (QUID "I.3 Estimated Accuracy Numbers",
|
| 147 |
+
"IV.2 Salinity" table, SQO "Executive summary"). The find-dataset→read-docs flow works.
|
| 148 |
+
- Remaining: finish embedding 3,398/27,796 → 27,796. Grinding via free-tier batch (slow); a few
|
| 149 |
+
shards complete per ~6-9h cycle. **Enable GCP billing → one full batch finishes in minutes (~$2).**
|
| 150 |
+
- batch_loop.sh keeps polling/downloading/submitting with the fixed code; index auto-rebuilds at ≥99%.
|
| 151 |
+
|
| 152 |
+
## 2026-06-23 ~14:00 — added catalogue text (all textual products)
|
| 153 |
+
- Harvested ALL textual catalogue content (what the MCP server serves via
|
| 154 |
+
marine_describe_dataset / marine_search_*) into the RAG via `build_meta_chunks.py`:
|
| 155 |
+
- **1251 dataset CARDs** (description, best_for, not_good_for, quality_flags, variables, coverage)
|
| 156 |
+
- **306 product DESCs** (description + summary)
|
| 157 |
+
- Appended to chunks.jsonl (existing order untouched → running embedder unaffected).
|
| 158 |
+
Total now **29,353 chunks**. RAG now covers datasets at 2 levels: deep PDF docs + structured cards.
|
| 159 |
+
- TODO (optional, user to confirm): also harvest CDS/ADS/EWDS descriptions (cds/_data, 164 datasets).
|
| 160 |
+
|
| 161 |
+
## Overnight background jobs
|
| 162 |
+
- `batch_loop.sh` (PID logged in out/batch_loop.log) — embedding orchestrator, every 10 min.
|
| 163 |
+
- Monitor: `tail out/batch_loop.log`, `wc -l out/chunks_embedded.jsonl`, `cat out/batch_state.json`.
|
| 164 |
+
|
| 165 |
+
## How to unblock (one action needed)
|
| 166 |
+
Whitelist IP **134.1.1.80** for the Gemini API key `AQ.Ab8…` in Google Cloud Console
|
| 167 |
+
(API key → Application/IP restrictions), OR remove the IP restriction. The overnight
|
| 168 |
+
runner then completes embedding + indexing automatically. To run manually instead:
|
| 169 |
+
`/Users/dmpantiu/cmip6/cmip6_gpt/.venv/bin/python embed.py --mode realtime && … load_qdrant.py --recreate`
|
| 170 |
+
|
| 171 |
+
## Reranker note
|
| 172 |
+
`semantic-ranker-default@latest` (search.py `--rerank`) needs GCP ADC + `GCP_PROJECT` env
|
| 173 |
+
(`gcloud auth application-default login`). Without it, search falls back to dense+BM25 RRF fusion.
|
| 174 |
+
|
| 175 |
+
## Daytime (reviewed) follow-ups
|
| 176 |
+
- Phase E: MCP tools `marine_read_docs` / `marine_search_docs` in copernicus-mcp-dev (TDD + review per CLAUDE.md).
|
| 177 |
+
- Re-run `build_catalog.py` + `chunk_docs.py` (both resumable) when the rest of the docs land tomorrow.
|
scripts/marine_rag/RAG_SERVER.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# copernicus-rag — MCP server (RAG discovery + EQC docs layer)
|
| 2 |
+
|
| 3 |
+
Standalone MCP server exposing the marine_rag retrieval stack. Companion to the
|
| 4 |
+
`copernicus` MCP server (which does the actual subsetting/downloading).
|
| 5 |
+
|
| 6 |
+
- Entry point: `rag_server.py` (stdio). Venv: `marine_rag/.venv` (Python 3.12:
|
| 7 |
+
mcp, qdrant-client, fastembed, google-genai, numpy).
|
| 8 |
+
- Registered: `claude mcp add copernicus-rag -- .../marine_rag/.venv/bin/python .../marine_rag/rag_server.py`
|
| 9 |
+
(local scope, project `/Users/dmpantiu/copernicus_mcp`).
|
| 10 |
+
- Index: embedded Qdrant `out/qdrant_db` (~300 MB) —
|
| 11 |
+
`copernicus_docs` (1415 dataset cards: CMEMS 1251 / CDS 136 / ADS 16 / EWDS 12)
|
| 12 |
+
and `marine_docs` (29,249 PUM/QUID/SQO chunks for 306 CMEMS products).
|
| 13 |
+
Plus separate DBs: `deep_docs/qdrant_db` (`cds_docs`, 23,341 CDS/ADS/EWDS deep-doc
|
| 14 |
+
chunks — Confluence PUGs/ATBDs/PDFs over 165 datasets), `pubs_rag/qdrant_db`
|
| 15 |
+
(`publications`) and `eqc_qa/qdrant_db` (`eqc_qa`, 1,274 CDS EQC quality-report chunks).
|
| 16 |
+
- Retrieval: hybrid dense+BM25 RRF. Dense query = `gemini-embedding-2-preview`
|
| 17 |
+
(768-dim, key = `veretex_api_key` in `../.env`, IPv4 forced via `net_ipv4.py`);
|
| 18 |
+
on embed failure degrades to BM25-only and reports it in `retrieval`.
|
| 19 |
+
Optional rerank: Google `semantic-ranker-default@latest` (needs `GCP_PROJECT` + ADC).
|
| 20 |
+
|
| 21 |
+
## Tools (12)
|
| 22 |
+
|
| 23 |
+
| tool | level | what |
|
| 24 |
+
|---|---|---|
|
| 25 |
+
| `search_datasets(query, store?, top_k?, rerank?)` | L1 discover | RAG search for datasets by description across all 4 stores; hits carry `notebooks[]` (attached code) where available |
|
| 26 |
+
| `get_dataset_docs(id, question?, doc_type?, top_k?, rerank?)` | L2 analyze | deep docs for one dataset — **CMEMS** → PUM/QUID/SQO (`marine_docs`); **CDS/ADS/EWDS** → PUG/ATBD/Confluence (`cds_docs`). Routes by id automatically |
|
| 27 |
+
| `search_docs(query, doc_type?, top_k?, rerank?)` | L2 analyze | global search across the 29k CMEMS doc chunks (cross-product) |
|
| 28 |
+
| `search_deep_docs(query, store?, top_k?, rerank?)` | L2 analyze | global search across the 23k CDS/ADS/EWDS deep-doc chunks (non-marine counterpart of search_docs) |
|
| 29 |
+
| `list_dataset_documents(id)` | L2 analyze | list the product's full documents (doc_id, type, size) |
|
| 30 |
+
| `read_document(doc_id, offset?, max_chars?)` | L2 analyze | pull full doc markdown, paginated; page 0 includes heading outline |
|
| 31 |
+
| `dataset_metadata(id)` | L2 analyze | FULL harvested metadata (variables/units/bounds, services, doc links, references, licence) — backed by `meta_harvest/unified_metadata.json` (1,436 entries) |
|
| 32 |
+
| `search_publications(query, domain?, dataset_or_product_id?, orphan_only?, top_k?, rerank?)` | L3 method | semantic search over the publications RAG (`pubs_rag/qdrant_db`, collection `publications`) |
|
| 33 |
+
| `get_dataset_publications(id, top_k?)` | L3 method | papers cited in the dataset's docs/references (registry: 1,199 DOIs), most-cited first |
|
| 34 |
+
| `read_publication(doi_or_paper_id, offset?, max_chars?)` | L3 method | full parsed paper text (paginated + outline); registry metadata/abstract fallback for unparsed PDFs |
|
| 35 |
+
| `get_eqc_quality_report(query, dataset_id?, aspect?, top_k?, rerank?)` | L4 quality | CDS/C3S EQC quality-assessment reports (27 datasets); results carry `code_notebooks[]` |
|
| 36 |
+
| `get_dataset_code(dataset_id, notebook_id?, kind?, offset?, max_chars?)` | code | runnable example-notebook CODE attached to a dataset (list recipes / full notebook, paginated) |
|
| 37 |
+
|
| 38 |
+
Intended agent flow:
|
| 39 |
+
`search_datasets` → `dataset_metadata` + `get_dataset_docs` (variables, accuracy, caveats)
|
| 40 |
+
→ `get_dataset_publications`/`search_publications` (methodology) → subset data via the `copernicus` server.
|
| 41 |
+
|
| 42 |
+
## Publications layer data
|
| 43 |
+
- Registry: `publications/registry/publications.jsonl` — 1,199 DOIs extracted from 813 EQC docs
|
| 44 |
+
+ CDS/ADS/EWDS references; 918 Crossref-resolved; linked coverage CMEMS 303/306.
|
| 45 |
+
- Orphan corpus: 725 parsed CMIP6 papers (`pubs_rag/out/papers.jsonl`, domain-tagged)
|
| 46 |
+
→ 16,683 chunks → Qdrant `pubs_rag/qdrant_db` (separate embedded DB to dodge the marine lock).
|
| 47 |
+
- OA PDFs of registry papers download into `publications/pdfs/` (raw, VLM-parsed later);
|
| 48 |
+
after parsing, extend the corpus and run `pubs_rag/relink_pubs.py`.
|
| 49 |
+
|
| 50 |
+
## Notebook code layer (attach, not embed)
|
| 51 |
+
|
| 52 |
+
Runnable example-notebook code is **attached to datasets** as a serve-time join —
|
| 53 |
+
NOT a separate searchable collection, NOT embedded. Sidecar
|
| 54 |
+
`eqc_qa/notebooks_by_dataset.json` maps `dataset_id -> [notebook records]`;
|
| 55 |
+
`_notebooks()` loads it (cached, restart to refresh). Full code lives as
|
| 56 |
+
`*.md` with verbatim python cells under `eqc_qa/notebooks_code/` and
|
| 57 |
+
`notebook_harvest/parsed/`. `search_datasets` / `get_eqc_quality_report` hits
|
| 58 |
+
carry compact `notebooks[]`; `get_dataset_code` returns the list or one
|
| 59 |
+
notebook's full code. Source: C3S EQC notebooks (Apache-2.0) + harvested
|
| 60 |
+
toolbox/training notebooks (see `eqc_qa/extract_code.py`).
|
| 61 |
+
|
| 62 |
+
## Operational notes
|
| 63 |
+
|
| 64 |
+
- Embedded Qdrant is **single-process**: while a Claude session holds the server
|
| 65 |
+
open, `load_qdrant.py` / `load_copernicus_docs.py` will fail on the lock.
|
| 66 |
+
Stop sessions (or `claude mcp remove copernicus-rag` temporarily) before rebuilding.
|
| 67 |
+
- First tool call is slow (~5–10 s): opens the 300 MB index + loads the BM25 model.
|
| 68 |
+
- stdout is the JSON-RPC channel — all logging is pinned to stderr at import time.
|
| 69 |
+
- Smoke test: `.venv/bin/python -c "import rag_server as R; print(R.search_datasets('arctic sea ice', top_k=3)['results'][0])"`
|
scripts/marine_rag/batch_loop.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# batch_loop.sh — run the batch orchestrator every 10 min until embedding done.
|
| 3 |
+
# Each pass: poll in-flight shard jobs, download completed, submit more shards
|
| 4 |
+
# until the daily quota 429s. Stops when out/EMBEDDING_DONE appears.
|
| 5 |
+
set -uo pipefail
|
| 6 |
+
cd /Users/dmpantiu/copernicus_mcp/marine_rag
|
| 7 |
+
PY=/Users/dmpantiu/cmip6/cmip6_gpt/.venv/bin/python
|
| 8 |
+
LOG=out/batch_loop.log
|
| 9 |
+
INTERVAL=180 # poll often so the freed 500k active-token budget refills fast
|
| 10 |
+
MAX=400 # ~20h at 180s
|
| 11 |
+
|
| 12 |
+
ts(){ date '+%Y-%m-%d %H:%M:%S'; }
|
| 13 |
+
log(){ echo "[$(ts)] $*" | tee -a "$LOG"; }
|
| 14 |
+
|
| 15 |
+
log "=== batch loop started ==="
|
| 16 |
+
i=0
|
| 17 |
+
while [ "$i" -lt "$MAX" ]; do
|
| 18 |
+
i=$((i+1))
|
| 19 |
+
if [ -f out/EMBEDDING_DONE ]; then
|
| 20 |
+
log "EMBEDDING_DONE present — stopping loop."
|
| 21 |
+
break
|
| 22 |
+
fi
|
| 23 |
+
log "pass $i"
|
| 24 |
+
$PY batch_orchestrator.py >> "$LOG" 2>&1
|
| 25 |
+
emb=$([ -f out/chunks_embedded.jsonl ] && wc -l < out/chunks_embedded.jsonl | tr -d ' ' || echo 0)
|
| 26 |
+
log "pass $i done — embedded $emb/27796"
|
| 27 |
+
[ -f out/EMBEDDING_DONE ] && { log "complete."; break; }
|
| 28 |
+
sleep "$INTERVAL"
|
| 29 |
+
done
|
| 30 |
+
log "=== batch loop exiting (pass $i) ==="
|
scripts/marine_rag/batch_orchestrator.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
batch_orchestrator.py — embed all marine chunks via the Gemini Batch API in
|
| 4 |
+
free-tier-sized shards. One pass per invocation; call repeatedly (cron/loop):
|
| 5 |
+
|
| 6 |
+
- poll in-flight shard jobs; download + merge completed ones → chunks_embedded.jsonl
|
| 7 |
+
- submit new shards from where we left off until the daily quota 429s
|
| 8 |
+
- when ≥99% embedded, build Qdrant index + run a verification search, then exit 0
|
| 9 |
+
|
| 10 |
+
State: out/batch_state.json (shards, job names, statuses, next_start)
|
| 11 |
+
Idempotent + resumable. Free-tier batch jobs are slow (minutes–hours).
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import net_ipv4 # noqa: F401 force IPv4
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).resolve().parent
|
| 22 |
+
OUT = ROOT / "out"
|
| 23 |
+
CHUNKS = OUT / "chunks.jsonl"
|
| 24 |
+
EMB = OUT / "chunks_embedded.jsonl"
|
| 25 |
+
STATE = OUT / "batch_state.json"
|
| 26 |
+
SHARD_DIR = OUT / "_shards"
|
| 27 |
+
PY = "/Users/dmpantiu/cmip6/cmip6_gpt/.venv/bin/python"
|
| 28 |
+
|
| 29 |
+
MODEL = "gemini-embedding-2-preview"
|
| 30 |
+
SHARD_SIZE = 800
|
| 31 |
+
TASK_TYPE = "RETRIEVAL_DOCUMENT"
|
| 32 |
+
DIM = 768
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def resolve_key():
|
| 36 |
+
for env in (Path("/Users/dmpantiu/copernicus_mcp/.env"),
|
| 37 |
+
Path("/Users/dmpantiu/cmip6/cmip6_gpt/.env")):
|
| 38 |
+
if env.exists():
|
| 39 |
+
for line in env.read_text().splitlines():
|
| 40 |
+
line = line.strip()
|
| 41 |
+
if "api_key" in line.lower() and "=" in line and not line.startswith("#"):
|
| 42 |
+
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
| 43 |
+
raise SystemExit("no key")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def client():
|
| 47 |
+
from google import genai
|
| 48 |
+
return genai.Client(api_key=resolve_key())
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def l2(v):
|
| 52 |
+
import numpy as np
|
| 53 |
+
a = np.array(v, dtype=np.float32)
|
| 54 |
+
n = np.linalg.norm(a)
|
| 55 |
+
return (a / n).tolist() if n > 0 else a.tolist()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def load_state():
|
| 59 |
+
if STATE.exists():
|
| 60 |
+
return json.loads(STATE.read_text())
|
| 61 |
+
return {"shards": [], "next_start": 0}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def save_state(s):
|
| 65 |
+
STATE.write_text(json.dumps(s, indent=1))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def embedded_keys():
|
| 69 |
+
keys = set()
|
| 70 |
+
if EMB.exists():
|
| 71 |
+
for line in open(EMB):
|
| 72 |
+
try:
|
| 73 |
+
keys.add(json.loads(line)["chunk_id"])
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
return keys
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def extract_values(resp):
|
| 80 |
+
for path in (("response", "embeddings"), ("response", "embedding"), ("embeddings",), ("embedding",)):
|
| 81 |
+
node = resp
|
| 82 |
+
ok = True
|
| 83 |
+
for k in path:
|
| 84 |
+
if isinstance(node, dict) and k in node:
|
| 85 |
+
node = node[k]
|
| 86 |
+
else:
|
| 87 |
+
ok = False
|
| 88 |
+
break
|
| 89 |
+
if not ok:
|
| 90 |
+
continue
|
| 91 |
+
if isinstance(node, list) and node and isinstance(node[0], dict) and "values" in node[0]:
|
| 92 |
+
return node[0]["values"]
|
| 93 |
+
if isinstance(node, dict) and "values" in node:
|
| 94 |
+
return node["values"]
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
SHARD_DIR.mkdir(exist_ok=True)
|
| 100 |
+
chunks = [json.loads(l) for l in open(CHUNKS)]
|
| 101 |
+
by_key = {c["chunk_id"]: c for c in chunks}
|
| 102 |
+
total = len(chunks)
|
| 103 |
+
state = load_state()
|
| 104 |
+
c = client()
|
| 105 |
+
from google import genai # noqa
|
| 106 |
+
|
| 107 |
+
# 1) poll in-flight jobs; download completed
|
| 108 |
+
done_keys = embedded_keys()
|
| 109 |
+
with open(EMB, "a", encoding="utf-8") as fout:
|
| 110 |
+
for sh in state["shards"]:
|
| 111 |
+
if sh["status"] == "done":
|
| 112 |
+
continue
|
| 113 |
+
try:
|
| 114 |
+
job = c.batches.get(name=sh["job"])
|
| 115 |
+
except Exception as e:
|
| 116 |
+
print(f"shard {sh['idx']}: poll err {str(e)[:80]}")
|
| 117 |
+
continue
|
| 118 |
+
st = str(job.state).split(".")[-1]
|
| 119 |
+
sh["state"] = st
|
| 120 |
+
if "SUCCEEDED" not in st:
|
| 121 |
+
if any(x in st for x in ("FAILED", "CANCELLED", "EXPIRED")):
|
| 122 |
+
sh["status"] = "failed" # will be resubmitted (range reopened)
|
| 123 |
+
state["next_start"] = min(state["next_start"], sh["start"])
|
| 124 |
+
print(f"shard {sh['idx']} [{sh['start']}:{sh['end']}]: {st}")
|
| 125 |
+
continue
|
| 126 |
+
dest = getattr(job, "dest", None)
|
| 127 |
+
fn = getattr(dest, "file_name", None) if dest else None
|
| 128 |
+
lines = []
|
| 129 |
+
if fn:
|
| 130 |
+
lines = c.files.download(file=fn).decode("utf-8").strip().split("\n")
|
| 131 |
+
elif dest and getattr(dest, "inlined_responses", None):
|
| 132 |
+
lines = [json.dumps(r) for r in dest.inlined_responses]
|
| 133 |
+
got = 0
|
| 134 |
+
for line in lines:
|
| 135 |
+
if not line.strip():
|
| 136 |
+
continue
|
| 137 |
+
r = json.loads(line)
|
| 138 |
+
k = r.get("key") or r.get("custom_metadata") or r.get("custom_id")
|
| 139 |
+
if k in done_keys or k not in by_key:
|
| 140 |
+
continue
|
| 141 |
+
vals = extract_values(r)
|
| 142 |
+
if vals:
|
| 143 |
+
rec = dict(by_key[k])
|
| 144 |
+
rec["embedding"] = l2(vals)
|
| 145 |
+
fout.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
| 146 |
+
done_keys.add(k)
|
| 147 |
+
got += 1
|
| 148 |
+
sh["status"] = "done"
|
| 149 |
+
sh["downloaded"] = got
|
| 150 |
+
print(f"shard {sh['idx']} [{sh['start']}:{sh['end']}]: DONE +{got}")
|
| 151 |
+
save_state(state)
|
| 152 |
+
|
| 153 |
+
n_emb = len(done_keys)
|
| 154 |
+
print(f"embedded {n_emb}/{total}")
|
| 155 |
+
|
| 156 |
+
# 2) submit new shards until quota stops us
|
| 157 |
+
submitted_now = 0
|
| 158 |
+
covered = {(sh["start"], sh["end"]) for sh in state["shards"] if sh["status"] != "failed"}
|
| 159 |
+
start = state["next_start"]
|
| 160 |
+
while start < total:
|
| 161 |
+
end = min(start + SHARD_SIZE, total)
|
| 162 |
+
if (start, end) in covered:
|
| 163 |
+
start = end
|
| 164 |
+
continue
|
| 165 |
+
shard_path = SHARD_DIR / f"shard_{start}_{end}.jsonl"
|
| 166 |
+
with open(shard_path, "w", encoding="utf-8") as f:
|
| 167 |
+
for ch in chunks[start:end]:
|
| 168 |
+
f.write(json.dumps({"key": ch["chunk_id"], "request": {
|
| 169 |
+
"content": {"parts": [{"text": ch["text_with_prefix"]}]},
|
| 170 |
+
"task_type": TASK_TYPE, "output_dimensionality": DIM}}) + "\n")
|
| 171 |
+
try:
|
| 172 |
+
up = c.files.upload(file=str(shard_path),
|
| 173 |
+
config={"display_name": f"sh_{start}", "mime_type": "jsonl"})
|
| 174 |
+
job = c.batches.create_embeddings(model=MODEL, src={"file_name": up.name},
|
| 175 |
+
config={"display_name": f"sh_{start}_{end}"})
|
| 176 |
+
state["shards"].append({"idx": len(state["shards"]), "start": start, "end": end,
|
| 177 |
+
"job": job.name, "status": "running",
|
| 178 |
+
"state": str(job.state).split(".")[-1]})
|
| 179 |
+
state["next_start"] = end
|
| 180 |
+
submitted_now += 1
|
| 181 |
+
print(f"submitted shard [{start}:{end}] -> {job.name.split('/')[-1]}")
|
| 182 |
+
save_state(state)
|
| 183 |
+
start = end
|
| 184 |
+
time.sleep(3)
|
| 185 |
+
except Exception as e:
|
| 186 |
+
es = str(e)
|
| 187 |
+
print(f"submit stop at [{start}:{end}]: {es[:120]}")
|
| 188 |
+
break
|
| 189 |
+
save_state(state)
|
| 190 |
+
print(f"submitted {submitted_now} new shards this pass")
|
| 191 |
+
|
| 192 |
+
# 3) finish when essentially complete
|
| 193 |
+
if n_emb >= total * 0.99:
|
| 194 |
+
print("EMBEDDING COMPLETE — building index + verifying")
|
| 195 |
+
subprocess.run([PY, "load_qdrant.py", "--recreate"], cwd=ROOT)
|
| 196 |
+
subprocess.run([PY, "search.py", "how is sea surface salinity validated", "--top-k", "3"], cwd=ROOT)
|
| 197 |
+
Path(OUT / "EMBEDDING_DONE").write_text(f"{n_emb}/{total}\n")
|
| 198 |
+
return 0
|
| 199 |
+
return 1
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
if __name__ == "__main__":
|
| 203 |
+
sys.exit(main())
|
scripts/marine_rag/build_catalog.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
build_catalog.py — Join marine_parsed docs to the copernicus-mcp catalogue.
|
| 4 |
+
|
| 5 |
+
Output: out/catalog.json — one entry per product:
|
| 6 |
+
product_id, product_title, group(s), domains/regions, dataset_ids,
|
| 7 |
+
docs: [{doc_id, doc_type, md_path, md_bytes, has_md}], coverage flags.
|
| 8 |
+
|
| 9 |
+
Pure local. No API.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parent
|
| 16 |
+
WS = ROOT.parent
|
| 17 |
+
PARSED = WS / "marine_parsed"
|
| 18 |
+
DATA = WS / "copernicus-mcp-dev" / "src" / "copernicus_mcp" / "backends" / "cmems" / "_data"
|
| 19 |
+
OUT = ROOT / "out"
|
| 20 |
+
OUT.mkdir(exist_ok=True)
|
| 21 |
+
|
| 22 |
+
DOC_TYPES = ("PUM", "QUID", "SQO")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def doc_type_of(doc_id: str) -> str:
|
| 26 |
+
"""Classify a CMEMS document id by its type token (PUM/QUID/SQO/OTHER)."""
|
| 27 |
+
u = doc_id.upper()
|
| 28 |
+
for t in DOC_TYPES:
|
| 29 |
+
if re.search(rf"(^|[-_]){t}([-_]|$)", u):
|
| 30 |
+
return t
|
| 31 |
+
if "PUM" in u:
|
| 32 |
+
return "PUM"
|
| 33 |
+
if "QUID" in u:
|
| 34 |
+
return "QUID"
|
| 35 |
+
return "OTHER"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def find_md_files(product_dir: Path) -> list[Path]:
|
| 39 |
+
"""All vlm markdown files under a product folder."""
|
| 40 |
+
return sorted(product_dir.rglob("vlm/*.md"))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main() -> None:
|
| 44 |
+
products = json.loads((DATA / "products.json").read_text())
|
| 45 |
+
by_pid = {p["product_id"]: p for p in products}
|
| 46 |
+
|
| 47 |
+
# group membership: groups.json maps group -> product ids (shape-tolerant)
|
| 48 |
+
groups_raw = json.loads((DATA / "groups.json").read_text())
|
| 49 |
+
pid_to_groups: dict[str, list[str]] = {}
|
| 50 |
+
|
| 51 |
+
def _index_group(gid: str, obj) -> None:
|
| 52 |
+
pids: list[str] = []
|
| 53 |
+
if isinstance(obj, dict):
|
| 54 |
+
for key in ("product_ids", "products", "member_product_ids", "members"):
|
| 55 |
+
v = obj.get(key)
|
| 56 |
+
if isinstance(v, list):
|
| 57 |
+
pids.extend(str(x) for x in v)
|
| 58 |
+
elif isinstance(obj, list):
|
| 59 |
+
pids.extend(str(x) for x in obj)
|
| 60 |
+
for pid in pids:
|
| 61 |
+
pid_to_groups.setdefault(pid, [])
|
| 62 |
+
if gid not in pid_to_groups[pid]:
|
| 63 |
+
pid_to_groups[pid].append(gid)
|
| 64 |
+
|
| 65 |
+
if isinstance(groups_raw, dict):
|
| 66 |
+
for gid, obj in groups_raw.items():
|
| 67 |
+
_index_group(gid, obj)
|
| 68 |
+
elif isinstance(groups_raw, list):
|
| 69 |
+
for obj in groups_raw:
|
| 70 |
+
gid = obj.get("group_id") or obj.get("id") or obj.get("name") if isinstance(obj, dict) else None
|
| 71 |
+
if gid:
|
| 72 |
+
_index_group(gid, obj)
|
| 73 |
+
|
| 74 |
+
parsed_folders = {p.name for p in PARSED.iterdir() if p.is_dir()}
|
| 75 |
+
|
| 76 |
+
catalog = []
|
| 77 |
+
n_with_docs = 0
|
| 78 |
+
docs_total = 0
|
| 79 |
+
for pid, p in sorted(by_pid.items()):
|
| 80 |
+
pdir = PARSED / pid
|
| 81 |
+
docs = []
|
| 82 |
+
if pdir.is_dir():
|
| 83 |
+
for md in find_md_files(pdir):
|
| 84 |
+
doc_id = md.stem
|
| 85 |
+
docs.append({
|
| 86 |
+
"doc_id": doc_id,
|
| 87 |
+
"doc_type": doc_type_of(doc_id),
|
| 88 |
+
"md_path": str(md.relative_to(WS)),
|
| 89 |
+
"md_bytes": md.stat().st_size,
|
| 90 |
+
"has_md": md.stat().st_size > 0,
|
| 91 |
+
# 230-byte blank SQO template shells (upstream published an
|
| 92 |
+
# unfilled form) -> flagged so RAG can skip empty stubs.
|
| 93 |
+
"has_content": md.stat().st_size > 300,
|
| 94 |
+
})
|
| 95 |
+
docs_total += len(docs)
|
| 96 |
+
if docs:
|
| 97 |
+
n_with_docs += 1
|
| 98 |
+
catalog.append({
|
| 99 |
+
"product_id": pid,
|
| 100 |
+
"product_title": p.get("product_title", ""),
|
| 101 |
+
"groups": pid_to_groups.get(pid, []),
|
| 102 |
+
"domains": p.get("domains", []),
|
| 103 |
+
"regions": p.get("regions", []),
|
| 104 |
+
"data_types": p.get("data_types", []),
|
| 105 |
+
"dataset_ids": p.get("dataset_ids", []),
|
| 106 |
+
"dataset_count": p.get("dataset_count", len(p.get("dataset_ids", []))),
|
| 107 |
+
"doi": p.get("doi", ""),
|
| 108 |
+
"doc_count": len(docs),
|
| 109 |
+
"doc_types": sorted({d["doc_type"] for d in docs}),
|
| 110 |
+
"has_docs": bool(docs),
|
| 111 |
+
"docs": docs,
|
| 112 |
+
})
|
| 113 |
+
|
| 114 |
+
extra_folders = sorted(parsed_folders - set(by_pid))
|
| 115 |
+
missing_docs = sorted(pid for pid in by_pid if not (PARSED / pid).is_dir() or not find_md_files(PARSED / pid))
|
| 116 |
+
|
| 117 |
+
(OUT / "catalog.json").write_text(json.dumps(catalog, ensure_ascii=False, indent=1))
|
| 118 |
+
summary = {
|
| 119 |
+
"products_total": len(by_pid),
|
| 120 |
+
"products_with_docs": n_with_docs,
|
| 121 |
+
"products_missing_docs": len(missing_docs),
|
| 122 |
+
"docs_total": docs_total,
|
| 123 |
+
"parsed_folders": len(parsed_folders),
|
| 124 |
+
"extra_folders_not_in_catalogue": extra_folders,
|
| 125 |
+
"missing_docs_product_ids": missing_docs,
|
| 126 |
+
}
|
| 127 |
+
(OUT / "catalog_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1))
|
| 128 |
+
print(json.dumps(summary, ensure_ascii=False, indent=1))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
scripts/marine_rag/build_cds_cards.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
build_cds_cards.py — harvest CDS/ADS/EWDS STAC catalogue metadata into RAG
|
| 4 |
+
"card" chunks (one dataset = one card), mirroring the Marine CARD format so a
|
| 5 |
+
single `copernicus_docs` index can be queried across all four stores.
|
| 6 |
+
|
| 7 |
+
Sources (already snapshotted locally, fetched 2026-05-16):
|
| 8 |
+
backends/cds/_data/{cds,ads,ewds}.json — STAC collections
|
| 9 |
+
backends/cds/_data/{cds,ads,ewds}_constraints.json — downloadable variables/options
|
| 10 |
+
|
| 11 |
+
Output: out/cds_cards_chunks.jsonl (schema-compatible with chunks.jsonl)
|
| 12 |
+
"""
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).resolve().parent
|
| 19 |
+
OUT = ROOT / "out"
|
| 20 |
+
DATA = ROOT.parent / "copernicus-mcp-dev" / "src" / "copernicus_mcp" / "backends" / "cds" / "_data"
|
| 21 |
+
OUT_JSONL = OUT / "cds_cards_chunks.jsonl"
|
| 22 |
+
sys.path.insert(0, "/Users/dmpantiu/cmip6/cmip6_gpt/rag")
|
| 23 |
+
from chunk_papers import count_tokens # noqa: E402
|
| 24 |
+
|
| 25 |
+
STORE_LABEL = {"cds": "CDS (Climate Data Store)",
|
| 26 |
+
"ads": "ADS (Atmosphere Data Store)",
|
| 27 |
+
"ewds": "EWDS (Early Warning Data Store)"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def j(v):
|
| 31 |
+
if isinstance(v, list):
|
| 32 |
+
return "; ".join(str(x) for x in v if x is not None)
|
| 33 |
+
return str(v) if v is not None else ""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def coverage(extent: dict) -> str:
|
| 37 |
+
if not extent:
|
| 38 |
+
return ""
|
| 39 |
+
parts = []
|
| 40 |
+
sp = (extent.get("spatial") or {}).get("bbox") or []
|
| 41 |
+
if sp and sp[0]:
|
| 42 |
+
b = sp[0]
|
| 43 |
+
parts.append(f"bbox {b[0]},{b[1]} → {b[2]},{b[3]}")
|
| 44 |
+
tp = (extent.get("temporal") or {}).get("interval") or []
|
| 45 |
+
if tp and tp[0]:
|
| 46 |
+
s = (tp[0][0] or "")[:10]
|
| 47 |
+
e = (tp[0][1] or "")[:10]
|
| 48 |
+
parts.append(f"time {s} → {e}")
|
| 49 |
+
return " | ".join(parts)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def variables(constraint: dict) -> list:
|
| 53 |
+
"""Union of variable-like option lists across all constraint blocks."""
|
| 54 |
+
if not constraint:
|
| 55 |
+
return []
|
| 56 |
+
vs = []
|
| 57 |
+
blocks = constraint if isinstance(constraint, list) else [constraint]
|
| 58 |
+
seen = set()
|
| 59 |
+
for blk in blocks:
|
| 60 |
+
if not isinstance(blk, dict):
|
| 61 |
+
continue
|
| 62 |
+
for key in ("variable", "variables", "product_type", "parameter"):
|
| 63 |
+
for v in blk.get(key) or []:
|
| 64 |
+
if v not in seen:
|
| 65 |
+
seen.add(v)
|
| 66 |
+
vs.append(v)
|
| 67 |
+
return vs
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def card_text(store: str, c: dict, cons: dict) -> str:
|
| 71 |
+
did = c.get("id", "")
|
| 72 |
+
lines = [
|
| 73 |
+
f'Dataset: "{c.get("title","")}" [{did}]',
|
| 74 |
+
f'Store: {STORE_LABEL[store]}',
|
| 75 |
+
]
|
| 76 |
+
kw = c.get("keywords") or []
|
| 77 |
+
if kw:
|
| 78 |
+
lines.append(f'Keywords: {j(kw)}')
|
| 79 |
+
cov = coverage(c.get("extent") or {})
|
| 80 |
+
if cov:
|
| 81 |
+
lines.append(f'Coverage: {cov}')
|
| 82 |
+
vs = variables(cons.get(did))
|
| 83 |
+
if vs:
|
| 84 |
+
shown = vs[:40]
|
| 85 |
+
more = f" (+{len(vs)-40} more)" if len(vs) > 40 else ""
|
| 86 |
+
lines.append(f'Variables/options: {j(shown)}{more}')
|
| 87 |
+
prov = "; ".join(p.get("name", "") for p in (c.get("providers") or []))
|
| 88 |
+
if prov:
|
| 89 |
+
lines.append(f'Provider: {prov}')
|
| 90 |
+
if c.get("license"):
|
| 91 |
+
lines.append(f'License: {c.get("license")}')
|
| 92 |
+
if c.get("sci:doi"):
|
| 93 |
+
lines.append(f'DOI: {c.get("sci:doi")}')
|
| 94 |
+
freq = c.get("cads:update_frequency")
|
| 95 |
+
if freq:
|
| 96 |
+
lines.append(f'Update frequency: {freq}')
|
| 97 |
+
desc = (c.get("description") or "").strip()
|
| 98 |
+
body = "\n".join(lines)
|
| 99 |
+
if desc:
|
| 100 |
+
body += "\n---\n" + desc
|
| 101 |
+
return body
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def mk(store: str, did: str, title: str, text: str) -> dict:
|
| 105 |
+
h = hashlib.md5(text.encode()).hexdigest()
|
| 106 |
+
return {
|
| 107 |
+
"chunk_id": f"{did}__{store}_card__{h[:12]}",
|
| 108 |
+
"product_id": did, # dataset id doubles as product id for CDS-family
|
| 109 |
+
"product_title": title,
|
| 110 |
+
"doc_id": did,
|
| 111 |
+
"doc_type": "CARD",
|
| 112 |
+
"section_path": "catalogue",
|
| 113 |
+
"section_name": "catalogue",
|
| 114 |
+
"chunk_type": "card",
|
| 115 |
+
"chunk_index": 0,
|
| 116 |
+
"token_count": count_tokens(text),
|
| 117 |
+
"text_with_prefix": text,
|
| 118 |
+
"text_raw": text,
|
| 119 |
+
"store": store.upper(), # NEW payload field for cross-store filtering
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def main() -> None:
|
| 124 |
+
rows, toks = [], 0
|
| 125 |
+
for store in ("cds", "ads", "ewds"):
|
| 126 |
+
cols = json.loads((DATA / f"{store}.json").read_text())["collections"]
|
| 127 |
+
cons = json.loads((DATA / f"{store}_constraints.json").read_text())
|
| 128 |
+
for c in cols:
|
| 129 |
+
did = c.get("id", "")
|
| 130 |
+
if not did:
|
| 131 |
+
continue
|
| 132 |
+
text = card_text(store, c, cons)
|
| 133 |
+
r = mk(store, did, c.get("title", ""), text)
|
| 134 |
+
rows.append(r)
|
| 135 |
+
toks += r["token_count"]
|
| 136 |
+
print(f" {store.upper()}: {len(cols)} cards")
|
| 137 |
+
with open(OUT_JSONL, "w", encoding="utf-8") as f:
|
| 138 |
+
for r in rows:
|
| 139 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 140 |
+
print(f"wrote {len(rows)} cards ({toks:,} tokens, "
|
| 141 |
+
f"~${toks/1e6*0.25:.3f} realtime / ${toks/1e6*0.125:.3f} batch) → {OUT_JSONL}")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
main()
|
scripts/marine_rag/build_meta_chunks.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
build_meta_chunks.py — harvest ALL textual catalogue content (what the MCP
|
| 4 |
+
server serves via marine_describe_dataset / marine_search_*) into RAG chunks:
|
| 5 |
+
|
| 6 |
+
- dataset_cards.json → 1251 DATASET-level cards (description, best_for,
|
| 7 |
+
not_good_for, quality_flags, variables, coverage, service types)
|
| 8 |
+
- products.json → 306 PRODUCT descriptions + summaries
|
| 9 |
+
|
| 10 |
+
These complement the PUM/QUID/SQO PDF docs with concise, structured,
|
| 11 |
+
per-dataset "how to use / what it's good/bad for" text.
|
| 12 |
+
|
| 13 |
+
APPENDS to out/chunks.jsonl (existing line order untouched, so the running
|
| 14 |
+
batch embedder's index ranges stay valid). Skips chunk_ids already present.
|
| 15 |
+
"""
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).resolve().parent
|
| 22 |
+
OUT = ROOT / "out"
|
| 23 |
+
DATA = ROOT.parent / "copernicus-mcp-dev" / "src" / "copernicus_mcp" / "backends" / "cmems" / "_data"
|
| 24 |
+
CHUNKS = OUT / "chunks.jsonl"
|
| 25 |
+
sys.path.insert(0, "/Users/dmpantiu/cmip6/cmip6_gpt/rag")
|
| 26 |
+
from chunk_papers import count_tokens # noqa: E402
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def j(v):
|
| 30 |
+
if isinstance(v, list):
|
| 31 |
+
return "; ".join(str(x) for x in v if x is not None)
|
| 32 |
+
return str(v) if v is not None else ""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def card_text(c: dict) -> str:
|
| 36 |
+
lines = [f'Dataset: "{c.get("dataset_name","")}" [{c.get("dataset_id","")}]',
|
| 37 |
+
f'Product: {c.get("product_title","")} [{c.get("product_id","")}]']
|
| 38 |
+
if c.get("spatial_label") or c.get("temporal_label"):
|
| 39 |
+
lines.append(f'Coverage: {j(c.get("spatial_label"))} | {j(c.get("temporal_label"))}')
|
| 40 |
+
if c.get("variables"):
|
| 41 |
+
lines.append(f'Variables: {j(c.get("variables"))}')
|
| 42 |
+
if c.get("service_types"):
|
| 43 |
+
lines.append(f'Service types: {j(c.get("service_types"))}')
|
| 44 |
+
if c.get("best_for"):
|
| 45 |
+
lines.append(f'Best for: {j(c.get("best_for"))}')
|
| 46 |
+
if c.get("not_good_for"):
|
| 47 |
+
lines.append(f'Not good for: {j(c.get("not_good_for"))}')
|
| 48 |
+
if c.get("quality_flags"):
|
| 49 |
+
lines.append(f'Quality flags: {j(c.get("quality_flags"))}')
|
| 50 |
+
desc = (c.get("description") or "").strip()
|
| 51 |
+
body = "\n".join(lines)
|
| 52 |
+
if desc:
|
| 53 |
+
body += "\n---\n" + desc
|
| 54 |
+
return body
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def prod_text(p: dict) -> str:
|
| 58 |
+
lines = [f'Product: "{p.get("product_title","")}" [{p.get("product_id","")}]']
|
| 59 |
+
if p.get("domains") or p.get("regions"):
|
| 60 |
+
lines.append(f'Domains: {j(p.get("domains"))} | Regions: {j(p.get("regions"))}')
|
| 61 |
+
if p.get("variables"):
|
| 62 |
+
lines.append(f'Variables: {j(p.get("variables"))}')
|
| 63 |
+
if p.get("doi"):
|
| 64 |
+
lines.append(f'DOI: {p.get("doi")}')
|
| 65 |
+
parts = [p.get("summary", ""), p.get("description", "")]
|
| 66 |
+
body = "\n".join(lines) + "\n---\n" + "\n\n".join(x for x in parts if x)
|
| 67 |
+
return body.strip()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def mk(product_id, product_title, doc_id, doc_type, chunk_type, text):
|
| 71 |
+
h = hashlib.md5(text.encode()).hexdigest()
|
| 72 |
+
return {
|
| 73 |
+
"chunk_id": f"{product_id}__{doc_type.lower()}_{doc_id}__{h[:12]}",
|
| 74 |
+
"product_id": product_id, "product_title": product_title,
|
| 75 |
+
"doc_id": doc_id, "doc_type": doc_type,
|
| 76 |
+
"section_path": "catalogue", "section_name": "catalogue",
|
| 77 |
+
"chunk_type": chunk_type, "chunk_index": 0,
|
| 78 |
+
"token_count": count_tokens(text),
|
| 79 |
+
"text_with_prefix": text, "text_raw": text,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main() -> None:
|
| 84 |
+
cards = json.loads((DATA / "dataset_cards.json").read_text())
|
| 85 |
+
prods = json.loads((DATA / "products.json").read_text())
|
| 86 |
+
if isinstance(cards, dict):
|
| 87 |
+
cards = list(cards.values())
|
| 88 |
+
|
| 89 |
+
existing = set()
|
| 90 |
+
if CHUNKS.exists():
|
| 91 |
+
for line in open(CHUNKS):
|
| 92 |
+
try:
|
| 93 |
+
existing.add(json.loads(line)["chunk_id"])
|
| 94 |
+
except Exception:
|
| 95 |
+
pass
|
| 96 |
+
|
| 97 |
+
new = []
|
| 98 |
+
for c in cards:
|
| 99 |
+
pid = c.get("product_id", "")
|
| 100 |
+
did = c.get("dataset_id", "")
|
| 101 |
+
if not pid or not did:
|
| 102 |
+
continue
|
| 103 |
+
new.append(mk(pid, c.get("product_title", ""), did, "CARD", "card", card_text(c)))
|
| 104 |
+
for p in prods:
|
| 105 |
+
pid = p.get("product_id", "")
|
| 106 |
+
new.append(mk(pid, p.get("product_title", ""), pid, "DESC", "desc", prod_text(p)))
|
| 107 |
+
|
| 108 |
+
added = 0
|
| 109 |
+
toks = 0
|
| 110 |
+
with open(CHUNKS, "a", encoding="utf-8") as f:
|
| 111 |
+
for r in new:
|
| 112 |
+
if r["chunk_id"] in existing:
|
| 113 |
+
continue
|
| 114 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 115 |
+
existing.add(r["chunk_id"])
|
| 116 |
+
added += 1
|
| 117 |
+
toks += r["token_count"]
|
| 118 |
+
print(f"appended {added} meta chunks ({toks:,} tokens, ~${toks/1e6*0.125:.3f} batch) → {CHUNKS}")
|
| 119 |
+
print(f" cards={len(cards)} products={len(prods)}; total chunks now {len(existing)}")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
main()
|
scripts/marine_rag/build_missing_cds_cards.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""build_missing_cds_cards.py — add L0 cards for the CDS datasets that were in the
|
| 3 |
+
RAG universe (unified_metadata) but absent from the stale cds.json bundle (136 vs 139),
|
| 4 |
+
so build_cds_cards.py never carded them. Builds cards in the EXACT existing format from
|
| 5 |
+
unified_metadata and appends them to out/cds_cards_chunks.jsonl (idempotent, backed up)."""
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parent
|
| 12 |
+
OUT = ROOT / "out"
|
| 13 |
+
OUT_JSONL = OUT / "cds_cards_chunks.jsonl"
|
| 14 |
+
UNI = ROOT.parent / "meta_harvest" / "unified_metadata.json"
|
| 15 |
+
sys.path.insert(0, "/Users/dmpantiu/cmip6/cmip6_gpt/rag")
|
| 16 |
+
from chunk_papers import count_tokens # noqa: E402
|
| 17 |
+
|
| 18 |
+
STORE_LABEL = {"cds": "CDS (Climate Data Store)",
|
| 19 |
+
"ads": "ADS (Atmosphere Data Store)",
|
| 20 |
+
"ewds": "EWDS (Early Warning Data Store)"}
|
| 21 |
+
|
| 22 |
+
MISSING = [
|
| 23 |
+
"satellite-snow-cover-extent",
|
| 24 |
+
"sis-agrometeorological-indicators-timeseries",
|
| 25 |
+
"sis-energy-global-reanalysis",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def j(v):
|
| 30 |
+
if isinstance(v, list):
|
| 31 |
+
return "; ".join(str(x) for x in v if x is not None)
|
| 32 |
+
return str(v) if v is not None else ""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def card_text(did: str, e: dict) -> str:
|
| 36 |
+
store = (e.get("store") or "cds").lower()
|
| 37 |
+
lines = [
|
| 38 |
+
f'Dataset: "{e.get("title","")}" [{did}]',
|
| 39 |
+
f'Store: {STORE_LABEL.get(store, store.upper())}',
|
| 40 |
+
]
|
| 41 |
+
kw = e.get("keywords") or []
|
| 42 |
+
if kw:
|
| 43 |
+
lines.append(f'Keywords: {j(kw)}')
|
| 44 |
+
# coverage from spatial_bbox + temporal_range
|
| 45 |
+
cov = []
|
| 46 |
+
bb = e.get("spatial_bbox") or []
|
| 47 |
+
if len(bb) == 4:
|
| 48 |
+
cov.append(f"bbox {bb[0]},{bb[1]} → {bb[2]},{bb[3]}")
|
| 49 |
+
tr = e.get("temporal_range") or []
|
| 50 |
+
if len(tr) == 2 and tr[0]:
|
| 51 |
+
cov.append(f"time {(tr[0] or '')[:10]} → {(tr[1] or '')[:10]}")
|
| 52 |
+
if cov:
|
| 53 |
+
lines.append(f'Coverage: {" | ".join(cov)}')
|
| 54 |
+
vs = [v.get("short_name") for v in (e.get("variables") or []) if isinstance(v, dict) and v.get("short_name")]
|
| 55 |
+
if vs:
|
| 56 |
+
shown = vs[:40]
|
| 57 |
+
more = f" (+{len(vs)-40} more)" if len(vs) > 40 else ""
|
| 58 |
+
lines.append(f'Variables/options: {j(shown)}{more}')
|
| 59 |
+
if e.get("production_center"):
|
| 60 |
+
lines.append(f'Provider: {e["production_center"]}')
|
| 61 |
+
if e.get("licence"):
|
| 62 |
+
lines.append(f'License: {e["licence"]}')
|
| 63 |
+
if e.get("doi"):
|
| 64 |
+
lines.append(f'DOI: {e["doi"]}')
|
| 65 |
+
if e.get("update_frequency"):
|
| 66 |
+
lines.append(f'Update frequency: {e["update_frequency"]}')
|
| 67 |
+
return "\n".join(lines)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def mk(store: str, did: str, title: str, text: str) -> dict:
|
| 71 |
+
h = hashlib.md5(text.encode()).hexdigest()
|
| 72 |
+
return {
|
| 73 |
+
"chunk_id": f"{did}__{store}_card__{h[:12]}",
|
| 74 |
+
"product_id": did,
|
| 75 |
+
"product_title": title,
|
| 76 |
+
"doc_id": did,
|
| 77 |
+
"doc_type": "CARD",
|
| 78 |
+
"section_path": "catalogue",
|
| 79 |
+
"section_name": "catalogue",
|
| 80 |
+
"chunk_type": "card",
|
| 81 |
+
"chunk_index": 0,
|
| 82 |
+
"token_count": count_tokens(text),
|
| 83 |
+
"text_with_prefix": text,
|
| 84 |
+
"text_raw": text,
|
| 85 |
+
"store": store.upper(),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main() -> None:
|
| 90 |
+
uni = json.loads(UNI.read_text())
|
| 91 |
+
existing_ids = set()
|
| 92 |
+
if OUT_JSONL.exists():
|
| 93 |
+
for line in OUT_JSONL.open():
|
| 94 |
+
line = line.strip()
|
| 95 |
+
if line:
|
| 96 |
+
existing_ids.add(json.loads(line).get("product_id"))
|
| 97 |
+
new_rows = []
|
| 98 |
+
for did in MISSING:
|
| 99 |
+
if did in existing_ids:
|
| 100 |
+
print(f"SKIP (already carded): {did}")
|
| 101 |
+
continue
|
| 102 |
+
e = uni.get(did)
|
| 103 |
+
if not e:
|
| 104 |
+
print(f"WARN not in universe: {did}")
|
| 105 |
+
continue
|
| 106 |
+
store = (e.get("store") or "cds").lower()
|
| 107 |
+
text = card_text(did, e)
|
| 108 |
+
new_rows.append(mk(store, did, e.get("title", ""), text))
|
| 109 |
+
print(f"\n=== CARD {did} ===\n{text}\n")
|
| 110 |
+
if not new_rows:
|
| 111 |
+
print("nothing to add.")
|
| 112 |
+
return
|
| 113 |
+
# backup then append
|
| 114 |
+
if OUT_JSONL.exists():
|
| 115 |
+
bak = OUT_JSONL.with_suffix(".jsonl.bak")
|
| 116 |
+
bak.write_bytes(OUT_JSONL.read_bytes())
|
| 117 |
+
print(f"backup -> {bak}")
|
| 118 |
+
with OUT_JSONL.open("a", encoding="utf-8") as f:
|
| 119 |
+
for r in new_rows:
|
| 120 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 121 |
+
total = sum(1 for line in OUT_JSONL.open() if line.strip())
|
| 122 |
+
print(f"appended {len(new_rows)} cards -> {OUT_JSONL} (now {total} rows)")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|
scripts/marine_rag/build_tree.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
build_tree.py — Beautiful descending trees of the Copernicus Marine catalogue.
|
| 4 |
+
|
| 5 |
+
Outputs:
|
| 6 |
+
out/tree.txt — routing-group view (Catalogue > Group > Product > Datasets)
|
| 7 |
+
out/tree_by_region.txt — geographic view (Region > Domain > Product)
|
| 8 |
+
out/tree.md — nested markdown for docs
|
| 9 |
+
|
| 10 |
+
Doc-coverage badge per product: [PUM|QUID|SQO] (✓ present) or [no docs].
|
| 11 |
+
Pure local. No API.
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
DATA = ROOT.parent / "copernicus-mcp-dev" / "src" / "copernicus_mcp" / "backends" / "cmems" / "_data"
|
| 19 |
+
OUT = ROOT / "out"
|
| 20 |
+
|
| 21 |
+
VB, BR, LA, SP = "│ ", "├─ ", "└─ ", " "
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def badge(c: dict) -> str:
|
| 25 |
+
if not c["has_docs"]:
|
| 26 |
+
return "[no docs]"
|
| 27 |
+
return "[" + "|".join(c["doc_types"]) + "]"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def render_product(c: dict, prefix: str, last: bool, show_datasets: bool) -> list[str]:
|
| 31 |
+
conn = LA if last else BR
|
| 32 |
+
lines = [f"{prefix}{conn}{c['product_id']} {badge(c)} — {c['product_title']}"]
|
| 33 |
+
if show_datasets:
|
| 34 |
+
child_prefix = prefix + (SP if last else VB)
|
| 35 |
+
dss = c["dataset_ids"]
|
| 36 |
+
for i, ds in enumerate(dss):
|
| 37 |
+
dconn = LA if i == len(dss) - 1 else BR
|
| 38 |
+
lines.append(f"{child_prefix}{dconn}{ds}")
|
| 39 |
+
return lines
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main() -> None:
|
| 43 |
+
catalog = json.loads((OUT / "catalog.json").read_text())
|
| 44 |
+
by_pid = {c["product_id"]: c for c in catalog}
|
| 45 |
+
groups = json.loads((DATA / "groups.json").read_text())
|
| 46 |
+
|
| 47 |
+
# ── Tree 1: routing groups ────────────────────────────────────────────
|
| 48 |
+
lines = []
|
| 49 |
+
n_prod_docs = sum(1 for c in catalog if c["has_docs"])
|
| 50 |
+
lines.append("COPERNICUS MARINE (CMEMS) — catalogue documentation tree")
|
| 51 |
+
lines.append(f"{len(catalog)} products · {sum(c['dataset_count'] for c in catalog)} datasets · "
|
| 52 |
+
f"{len(groups)} routing groups · docs: {n_prod_docs}/{len(catalog)} products covered")
|
| 53 |
+
lines.append("=" * 78)
|
| 54 |
+
lines.append("ROOT")
|
| 55 |
+
groups_sorted = sorted(groups, key=lambda g: g["group_id"])
|
| 56 |
+
for gi, g in enumerate(groups_sorted):
|
| 57 |
+
glast = gi == len(groups_sorted) - 1
|
| 58 |
+
gconn = LA if glast else BR
|
| 59 |
+
pids = [p for p in g["product_ids"] if p in by_pid]
|
| 60 |
+
cov = sum(1 for p in pids if by_pid[p]["has_docs"])
|
| 61 |
+
lines.append(f"{gconn}{g['group_id']} ({cov}/{len(pids)} docs) — {g['group_title']}")
|
| 62 |
+
gpref = SP if glast else VB
|
| 63 |
+
for pi, pid in enumerate(sorted(pids)):
|
| 64 |
+
plast = pi == len(pids) - 1
|
| 65 |
+
lines.extend(render_product(by_pid[pid], gpref, plast, show_datasets=False))
|
| 66 |
+
(OUT / "tree.txt").write_text("\n".join(lines) + "\n")
|
| 67 |
+
|
| 68 |
+
# ── Tree 2: by region > domain (from product metadata) ────────────────
|
| 69 |
+
rlines = ["COPERNICUS MARINE — geographic view (region > domain > product)", "=" * 78, "ROOT"]
|
| 70 |
+
region_map: dict[str, dict[str, list[dict]]] = defaultdict(lambda: defaultdict(list))
|
| 71 |
+
for c in catalog:
|
| 72 |
+
region = (c["regions"][0] if c["regions"] else "global").replace("_", " ")
|
| 73 |
+
domain = (c["domains"][0] if c["domains"] else "other").replace("_", " ")
|
| 74 |
+
region_map[region][domain].append(c)
|
| 75 |
+
regions_sorted = sorted(region_map)
|
| 76 |
+
for ri, region in enumerate(regions_sorted):
|
| 77 |
+
rlast = ri == len(regions_sorted) - 1
|
| 78 |
+
rconn = LA if rlast else BR
|
| 79 |
+
rcount = sum(len(v) for v in region_map[region].values())
|
| 80 |
+
rlines.append(f"{rconn}{region} ({rcount} products)")
|
| 81 |
+
rpref = SP if rlast else VB
|
| 82 |
+
domains_sorted = sorted(region_map[region])
|
| 83 |
+
for di, domain in enumerate(domains_sorted):
|
| 84 |
+
dlast = di == len(domains_sorted) - 1
|
| 85 |
+
dconn = LA if dlast else BR
|
| 86 |
+
prods = sorted(region_map[region][domain], key=lambda c: c["product_id"])
|
| 87 |
+
rlines.append(f"{rpref}{dconn}{domain} ({len(prods)})")
|
| 88 |
+
dpref = rpref + (SP if dlast else VB)
|
| 89 |
+
for pi, c in enumerate(prods):
|
| 90 |
+
plast = pi == len(prods) - 1
|
| 91 |
+
rlines.extend(render_product(c, dpref, plast, show_datasets=False))
|
| 92 |
+
(OUT / "tree_by_region.txt").write_text("\n".join(rlines) + "\n")
|
| 93 |
+
|
| 94 |
+
# ── Tree 3: markdown (nested list, by group) ──────────────────────────
|
| 95 |
+
md = ["# Copernicus Marine catalogue tree", "",
|
| 96 |
+
f"- **{len(catalog)} products** · **{sum(c['dataset_count'] for c in catalog)} datasets** · "
|
| 97 |
+
f"**{len(groups)} routing groups** · docs {n_prod_docs}/{len(catalog)} products", ""]
|
| 98 |
+
for g in groups_sorted:
|
| 99 |
+
pids = [p for p in g["product_ids"] if p in by_pid]
|
| 100 |
+
cov = sum(1 for p in pids if by_pid[p]["has_docs"])
|
| 101 |
+
md.append(f"## {g['group_title']} `({cov}/{len(pids)} docs)`")
|
| 102 |
+
md.append(f"<sub>`{g['group_id']}` — {g['summary']}</sub>")
|
| 103 |
+
md.append("")
|
| 104 |
+
for pid in sorted(pids):
|
| 105 |
+
c = by_pid[pid]
|
| 106 |
+
md.append(f"- `{pid}` {badge(c)} — {c['product_title']} "
|
| 107 |
+
f"<sub>({c['dataset_count']} datasets)</sub>")
|
| 108 |
+
md.append("")
|
| 109 |
+
(OUT / "tree.md").write_text("\n".join(md) + "\n")
|
| 110 |
+
|
| 111 |
+
print("wrote out/tree.txt, out/tree_by_region.txt, out/tree.md")
|
| 112 |
+
print(f"products={len(catalog)} groups={len(groups)} docs_covered={n_prod_docs}")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
main()
|
scripts/marine_rag/chunk_docs.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
chunk_docs.py — Section-aware chunking of marine_parsed VLM markdown.
|
| 4 |
+
|
| 5 |
+
Reuses the battle-tested chunker from cmip6_gpt/rag/chunk_papers.py
|
| 6 |
+
(noise filters, OCR-ris fixes, dedup, overlap, token budget) but assembles
|
| 7 |
+
a marine-specific prefix: product, document type (PUM/QUID/SQO), section path.
|
| 8 |
+
Images are ignored (markdown image refs are skipped by the parser).
|
| 9 |
+
|
| 10 |
+
Output: out/chunks.jsonl — one JSON object per chunk. Resumable per md file.
|
| 11 |
+
"""
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import re
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).resolve().parent
|
| 19 |
+
WS = ROOT.parent
|
| 20 |
+
PARSED = WS / "marine_parsed"
|
| 21 |
+
OUT = ROOT / "out"
|
| 22 |
+
CMIP6_RAG = Path("/Users/dmpantiu/cmip6/cmip6_gpt/rag")
|
| 23 |
+
|
| 24 |
+
sys.path.insert(0, str(CMIP6_RAG))
|
| 25 |
+
from chunk_papers import ( # noqa: E402
|
| 26 |
+
parse_markdown_sections, fix_ocr_ris_stripping, clean_ui_from_text,
|
| 27 |
+
is_garbage_section_path, is_figure_axis_gibberish, is_digit_heavy_garbage,
|
| 28 |
+
is_boilerplate_noise, is_affiliation_fragment, is_reference_block,
|
| 29 |
+
has_repeating_loop, is_url_only, chunk_text_block, add_overlap, count_tokens,
|
| 30 |
+
MAX_TOKENS, MIN_QUALITY_TOKENS, MIN_TOKENS, OVERLAP_RATIO, TABLE_MAX_TOKENS,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
DOC_TYPES = ("PUM", "QUID", "SQO")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def doc_type_of(doc_id: str) -> str:
|
| 37 |
+
u = doc_id.upper()
|
| 38 |
+
for t in DOC_TYPES:
|
| 39 |
+
if re.search(rf"(^|[-_]){t}([-_]|$)", u) or t in u:
|
| 40 |
+
return t
|
| 41 |
+
return "OTHER"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def is_noise_table(tbl_text: str) -> bool:
|
| 45 |
+
"""Drop document-meta tables (change record, approval, acronyms) — pure noise."""
|
| 46 |
+
head = "\n".join(tbl_text.lower().splitlines()[:3])
|
| 47 |
+
if "description of change" in head:
|
| 48 |
+
return True
|
| 49 |
+
if ("validated by" in head or "checked by" in head) and ("issue" in head or "date" in head):
|
| 50 |
+
return True
|
| 51 |
+
if "acronym" in head and "description" in head:
|
| 52 |
+
return True
|
| 53 |
+
if head.count("|") >= 4 and ("abbreviation" in head and "meaning" in head):
|
| 54 |
+
return True
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def make_prefix(product_id: str, title: str, doc_id: str, doc_type: str, section_path: str) -> str:
|
| 59 |
+
head = f'Product: "{title}" [{product_id}]' if title else f"Product: {product_id}"
|
| 60 |
+
return (head + f"\nDocument: {doc_type} ({doc_id})"
|
| 61 |
+
+ f"\nSection: {section_path}\n---\n")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def chunk_marine_md(md_path: Path, product_id: str, title: str, doc_id: str | None = None) -> list[dict]:
|
| 65 |
+
if doc_id is None:
|
| 66 |
+
doc_id = md_path.stem
|
| 67 |
+
doc_type = doc_type_of(doc_id)
|
| 68 |
+
md_text = md_path.read_text(encoding="utf-8", errors="replace")
|
| 69 |
+
sections = parse_markdown_sections(md_text)
|
| 70 |
+
|
| 71 |
+
out: list[dict] = []
|
| 72 |
+
counter = 0
|
| 73 |
+
seen: set[str] = set()
|
| 74 |
+
|
| 75 |
+
for section in sections:
|
| 76 |
+
if section.paragraphs == ["__EXCLUDED__"]:
|
| 77 |
+
continue
|
| 78 |
+
section_path = section.path
|
| 79 |
+
if is_garbage_section_path(section.name):
|
| 80 |
+
section_path = "[section unknown]"
|
| 81 |
+
|
| 82 |
+
# ── text ──
|
| 83 |
+
if section.paragraphs:
|
| 84 |
+
full = fix_ocr_ris_stripping("\n\n".join(section.paragraphs))
|
| 85 |
+
raw = [full] if count_tokens(full) <= MAX_TOKENS else chunk_text_block(full, MAX_TOKENS)
|
| 86 |
+
if len(raw) > 1:
|
| 87 |
+
raw = add_overlap(raw, OVERLAP_RATIO)
|
| 88 |
+
capped = []
|
| 89 |
+
for rc in raw:
|
| 90 |
+
capped.extend(chunk_text_block(rc, MAX_TOKENS) if count_tokens(rc) > MAX_TOKENS + 50 else [rc])
|
| 91 |
+
for ct in capped:
|
| 92 |
+
if count_tokens(ct) < MIN_QUALITY_TOKENS:
|
| 93 |
+
continue
|
| 94 |
+
ct = clean_ui_from_text(ct)
|
| 95 |
+
if not ct or count_tokens(ct) < MIN_QUALITY_TOKENS:
|
| 96 |
+
continue
|
| 97 |
+
if (is_figure_axis_gibberish(ct) or is_digit_heavy_garbage(ct)
|
| 98 |
+
or is_boilerplate_noise(ct) or is_affiliation_fragment(ct)
|
| 99 |
+
or is_reference_block(ct) or has_repeating_loop(ct)):
|
| 100 |
+
continue
|
| 101 |
+
h = hashlib.md5(ct.encode()).hexdigest()
|
| 102 |
+
if h in seen:
|
| 103 |
+
continue
|
| 104 |
+
seen.add(h)
|
| 105 |
+
twp = make_prefix(product_id, title, doc_id, doc_type, section_path) + ct
|
| 106 |
+
out.append({
|
| 107 |
+
"chunk_id": f"{product_id}__{doc_id}__{h[:12]}",
|
| 108 |
+
"product_id": product_id, "product_title": title,
|
| 109 |
+
"doc_id": doc_id, "doc_type": doc_type,
|
| 110 |
+
"section_path": section_path, "section_name": section.name,
|
| 111 |
+
"chunk_type": "text", "chunk_index": counter,
|
| 112 |
+
"token_count": count_tokens(twp),
|
| 113 |
+
"text_with_prefix": twp, "text_raw": ct,
|
| 114 |
+
})
|
| 115 |
+
counter += 1
|
| 116 |
+
|
| 117 |
+
# ── tables ──
|
| 118 |
+
for j, tbl in enumerate(section.tables):
|
| 119 |
+
tbl_text = tbl.get("text", "")
|
| 120 |
+
if not tbl_text or count_tokens(tbl_text) < 10:
|
| 121 |
+
continue
|
| 122 |
+
if is_noise_table(tbl_text):
|
| 123 |
+
continue
|
| 124 |
+
caption = section.captions[j] if j < len(section.captions) else ""
|
| 125 |
+
ctx = f"[TABLE in section: {section_path}]" + (f"\nCaption: {caption}" if caption else "")
|
| 126 |
+
if count_tokens(tbl_text) > TABLE_MAX_TOKENS:
|
| 127 |
+
kept, tok = [], 0
|
| 128 |
+
for tl in tbl_text.split("\n"):
|
| 129 |
+
lt = count_tokens(tl)
|
| 130 |
+
if tok + lt > TABLE_MAX_TOKENS - 20:
|
| 131 |
+
break
|
| 132 |
+
kept.append(tl); tok += lt
|
| 133 |
+
tbl_text = "\n".join(kept) + "\n[... TABLE TRUNCATED ...]"
|
| 134 |
+
body = ctx + "\n\n" + tbl_text
|
| 135 |
+
twp = make_prefix(product_id, title, doc_id, doc_type, section_path) + body
|
| 136 |
+
cid = hashlib.md5(f"{product_id}{doc_id}tbl{section_path}{j}".encode()).hexdigest()[:12]
|
| 137 |
+
out.append({
|
| 138 |
+
"chunk_id": f"{product_id}__{doc_id}__tbl_{cid}",
|
| 139 |
+
"product_id": product_id, "product_title": title,
|
| 140 |
+
"doc_id": doc_id, "doc_type": doc_type,
|
| 141 |
+
"section_path": section_path, "section_name": section.name,
|
| 142 |
+
"chunk_type": "table", "chunk_index": counter,
|
| 143 |
+
"token_count": count_tokens(twp),
|
| 144 |
+
"text_with_prefix": twp, "text_raw": body,
|
| 145 |
+
})
|
| 146 |
+
counter += 1
|
| 147 |
+
|
| 148 |
+
# merge tiny adjacent text chunks
|
| 149 |
+
merged: list[dict] = []
|
| 150 |
+
ii = 0
|
| 151 |
+
while ii < len(out):
|
| 152 |
+
c = out[ii]
|
| 153 |
+
if (c["token_count"] < MIN_TOKENS and c["chunk_type"] == "text"
|
| 154 |
+
and ii + 1 < len(out) and out[ii + 1]["section_path"] == c["section_path"]
|
| 155 |
+
and out[ii + 1]["chunk_type"] == "text"):
|
| 156 |
+
nxt = out[ii + 1]
|
| 157 |
+
mt = c["text_raw"] + "\n\n" + nxt["text_raw"]
|
| 158 |
+
nxt["text_raw"] = mt
|
| 159 |
+
nxt["text_with_prefix"] = nxt["text_with_prefix"].split("---\n", 1)[0] + "---\n" + mt
|
| 160 |
+
nxt["token_count"] = count_tokens(nxt["text_with_prefix"])
|
| 161 |
+
ii += 1
|
| 162 |
+
else:
|
| 163 |
+
merged.append(c); ii += 1
|
| 164 |
+
for i, c in enumerate(merged):
|
| 165 |
+
c["chunk_index"] = i
|
| 166 |
+
return merged
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def main() -> None:
|
| 170 |
+
catalog = json.loads((OUT / "catalog.json").read_text())
|
| 171 |
+
title_by_pid = {c["product_id"]: c["product_title"] for c in catalog}
|
| 172 |
+
|
| 173 |
+
# Prefer CLEANED markdown (clean_md.py output) over raw marine_parsed.
|
| 174 |
+
clean_dir = OUT / "cleaned"
|
| 175 |
+
use_clean = clean_dir.exists() and any(clean_dir.glob("*.md"))
|
| 176 |
+
if use_clean:
|
| 177 |
+
md_files = sorted(clean_dir.glob("*.md"))
|
| 178 |
+
print(f"source: CLEANED ({len(md_files)} files)")
|
| 179 |
+
|
| 180 |
+
def product_of(md: Path) -> str:
|
| 181 |
+
return md.stem.split("__", 1)[0]
|
| 182 |
+
else:
|
| 183 |
+
md_files = sorted(PARSED.rglob("vlm/*.md"))
|
| 184 |
+
print(f"source: RAW marine_parsed ({len(md_files)} files)")
|
| 185 |
+
|
| 186 |
+
def product_of(md: Path) -> str:
|
| 187 |
+
return md.relative_to(PARSED).parts[0]
|
| 188 |
+
|
| 189 |
+
out_path = OUT / "chunks.jsonl"
|
| 190 |
+
done_docs: set[str] = set()
|
| 191 |
+
if out_path.exists():
|
| 192 |
+
with open(out_path) as f:
|
| 193 |
+
for line in f:
|
| 194 |
+
try:
|
| 195 |
+
r = json.loads(line)
|
| 196 |
+
done_docs.add(f"{r['product_id']}__{r['doc_id']}")
|
| 197 |
+
except Exception:
|
| 198 |
+
pass
|
| 199 |
+
print(f"resume: {len(done_docs)} docs already chunked")
|
| 200 |
+
|
| 201 |
+
n_docs = n_chunks = 0
|
| 202 |
+
with open(out_path, "a", encoding="utf-8") as fout:
|
| 203 |
+
for md in md_files:
|
| 204 |
+
pid = product_of(md)
|
| 205 |
+
doc_id = md.stem.split("__", 1)[1] if use_clean and "__" in md.stem else md.stem
|
| 206 |
+
doc_key = f"{pid}__{doc_id}"
|
| 207 |
+
if doc_key in done_docs:
|
| 208 |
+
continue
|
| 209 |
+
try:
|
| 210 |
+
chunks = chunk_marine_md(md, pid, title_by_pid.get(pid, ""), doc_id)
|
| 211 |
+
except Exception as e:
|
| 212 |
+
print(f" ERROR {doc_key}: {repr(e)[:120]}", file=sys.stderr)
|
| 213 |
+
continue
|
| 214 |
+
for c in chunks:
|
| 215 |
+
fout.write(json.dumps(c, ensure_ascii=False) + "\n")
|
| 216 |
+
fout.flush()
|
| 217 |
+
n_docs += 1
|
| 218 |
+
n_chunks += len(chunks)
|
| 219 |
+
if n_docs % 50 == 0:
|
| 220 |
+
print(f" [{n_docs} docs] {n_chunks} chunks")
|
| 221 |
+
print(f"DONE: {n_docs} docs newly chunked, {n_chunks} chunks → {out_path}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
main()
|
scripts/marine_rag/clean_md.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
clean_md.py — Clean CMEMS VLM markdown BEFORE chunking (mirrors the cmip6
|
| 4 |
+
preprocess step). For each marine_parsed doc:
|
| 5 |
+
- convert <table> HTML → markdown pipe tables (readable, chunker-detectable)
|
| 6 |
+
- drop image refs
|
| 7 |
+
- strip CMEMS boilerplate sections (CHANGE RECORD, TABLE OF CONTENTS,
|
| 8 |
+
LIST OF TABLES/FIGURES, ACRONYM TABLE, RELEVANT DOCUMENT LIST, REFERENCES…)
|
| 9 |
+
- strip running page header/footer lines (repeated >3× within the doc)
|
| 10 |
+
- strip TOC dotted-leader lines and cover preamble noise
|
| 11 |
+
- fix OCR-ris stripping, collapse blank lines
|
| 12 |
+
|
| 13 |
+
Keeps the science: executive summary, products covered, accuracy, production
|
| 14 |
+
system, validation framework/results, key definitions, system events.
|
| 15 |
+
|
| 16 |
+
Output: out/cleaned/<product_id>__<doc_id>.md (+ out/clean_stats.json)
|
| 17 |
+
"""
|
| 18 |
+
import json
|
| 19 |
+
import re
|
| 20 |
+
import sys
|
| 21 |
+
from collections import Counter
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
ROOT = Path(__file__).resolve().parent
|
| 25 |
+
WS = ROOT.parent
|
| 26 |
+
PARSED = WS / "marine_parsed"
|
| 27 |
+
OUT = ROOT / "out"
|
| 28 |
+
CLEAN_DIR = OUT / "cleaned"
|
| 29 |
+
sys.path.insert(0, "/Users/dmpantiu/cmip6/cmip6_gpt/rag")
|
| 30 |
+
from preprocess_markdown import convert_html_table_to_markdown # noqa: E402
|
| 31 |
+
from chunk_papers import fix_ocr_ris_stripping # noqa: E402
|
| 32 |
+
|
| 33 |
+
# Section headers (normalised, no numbering) to drop entirely.
|
| 34 |
+
STRIP_SECTIONS = {
|
| 35 |
+
"change record", "table of contents", "contents", "list of tables",
|
| 36 |
+
"list of figures", "list of acronyms", "acronym table", "acronyms",
|
| 37 |
+
"abbreviations", "references", "bibliography", "relevant document list",
|
| 38 |
+
"document history", "distribution list", "approval",
|
| 39 |
+
"list of tables and figures", "glossary",
|
| 40 |
+
}
|
| 41 |
+
# Standalone (non-#) all-caps label lines that precede a boilerplate table.
|
| 42 |
+
LABEL_NOISE = {
|
| 43 |
+
"acronym table", "relevant document list", "list of acronyms",
|
| 44 |
+
"applicable documents", "reference documents",
|
| 45 |
+
}
|
| 46 |
+
# Cover/preamble noise lines.
|
| 47 |
+
_preamble_re = re.compile(
|
| 48 |
+
r"^(issue|contributors?|approval date|approved by|prepared by|authors?|"
|
| 49 |
+
r"ref|date|version|nom du fichier|reference)\s*[:\.]", re.IGNORECASE)
|
| 50 |
+
_toc_dotted_re = re.compile(r".*\.{3,}\s*\d+\s*$") # "Change Record....2"
|
| 51 |
+
_num_prefix_re = re.compile(r"^[\dIVXivx]+(\.[\dIVXivx]+)*\.?\s+")
|
| 52 |
+
_img_re = re.compile(r"^!\[.*\]\(.*\)\s*$")
|
| 53 |
+
_header_re = re.compile(r"^(#{1,6})\s+(.+?)\s*#*$")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def norm_header(text: str) -> str:
|
| 57 |
+
t = _num_prefix_re.sub("", text.strip())
|
| 58 |
+
return t.lower().strip().rstrip(":.").strip()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def convert_inline_tables(line: str) -> str:
|
| 62 |
+
"""Replace every <table>…</table> on a line with a markdown table block."""
|
| 63 |
+
def repl(m):
|
| 64 |
+
return "\n" + convert_html_table_to_markdown(m.group(0)) + "\n"
|
| 65 |
+
return re.sub(r"<table>.*?</table>", repl, line, flags=re.DOTALL | re.IGNORECASE)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def clean_md(md_text: str) -> str:
|
| 69 |
+
# 1) table conversion (do before line-splitting; tables are single-line here)
|
| 70 |
+
md_text = convert_inline_tables(md_text)
|
| 71 |
+
md_text = md_text.replace("\\_", "_") # un-escape product ids etc.
|
| 72 |
+
lines = md_text.split("\n")
|
| 73 |
+
|
| 74 |
+
# 2) detect running header/footer lines (repeated >3×) to drop
|
| 75 |
+
norm = [re.sub(r"\s+", " ", l.strip()) for l in lines]
|
| 76 |
+
freq = Counter(n for n in norm if len(n) > 15)
|
| 77 |
+
repeated = {n for n, c in freq.items() if c > 3}
|
| 78 |
+
|
| 79 |
+
out, i, n = [], 0, len(lines)
|
| 80 |
+
skip_section = False
|
| 81 |
+
while i < n:
|
| 82 |
+
line = lines[i]
|
| 83 |
+
s = line.strip()
|
| 84 |
+
nm = re.sub(r"\s+", " ", s)
|
| 85 |
+
|
| 86 |
+
hm = _header_re.match(s)
|
| 87 |
+
if hm:
|
| 88 |
+
skip_section = norm_header(hm.group(2)) in STRIP_SECTIONS
|
| 89 |
+
if skip_section:
|
| 90 |
+
i += 1
|
| 91 |
+
continue
|
| 92 |
+
out.append(f"{hm.group(1)} {hm.group(2)}")
|
| 93 |
+
i += 1
|
| 94 |
+
continue
|
| 95 |
+
if skip_section:
|
| 96 |
+
i += 1
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
+
# standalone label + following table/lines → drop until blank
|
| 100 |
+
if s.lower().rstrip(":. ") in LABEL_NOISE:
|
| 101 |
+
i += 1
|
| 102 |
+
while i < n and lines[i].strip() and not _header_re.match(lines[i].strip()):
|
| 103 |
+
i += 1
|
| 104 |
+
continue
|
| 105 |
+
|
| 106 |
+
if not s:
|
| 107 |
+
out.append("")
|
| 108 |
+
i += 1
|
| 109 |
+
continue
|
| 110 |
+
if _img_re.match(s) or _toc_dotted_re.match(s) or _preamble_re.match(s):
|
| 111 |
+
i += 1
|
| 112 |
+
continue
|
| 113 |
+
if len(nm) > 15 and nm in repeated: # running header/footer
|
| 114 |
+
i += 1
|
| 115 |
+
continue
|
| 116 |
+
out.append(line)
|
| 117 |
+
i += 1
|
| 118 |
+
|
| 119 |
+
text = "\n".join(out)
|
| 120 |
+
text = fix_ocr_ris_stripping(text)
|
| 121 |
+
text = re.sub(r"\n{3,}", "\n\n", text).strip()
|
| 122 |
+
return text + "\n"
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def main() -> None:
|
| 126 |
+
CLEAN_DIR.mkdir(parents=True, exist_ok=True)
|
| 127 |
+
md_files = sorted(PARSED.rglob("vlm/*.md"))
|
| 128 |
+
stats = {"docs": 0, "orig_chars": 0, "clean_chars": 0}
|
| 129 |
+
for md in md_files:
|
| 130 |
+
pid = md.relative_to(PARSED).parts[0]
|
| 131 |
+
doc_id = md.stem
|
| 132 |
+
raw = md.read_text(encoding="utf-8", errors="replace")
|
| 133 |
+
try:
|
| 134 |
+
cleaned = clean_md(raw)
|
| 135 |
+
except Exception as e:
|
| 136 |
+
print(f" ERR {pid}/{doc_id}: {repr(e)[:120]}", file=sys.stderr)
|
| 137 |
+
continue
|
| 138 |
+
(CLEAN_DIR / f"{pid}__{doc_id}.md").write_text(cleaned, encoding="utf-8")
|
| 139 |
+
stats["docs"] += 1
|
| 140 |
+
stats["orig_chars"] += len(raw)
|
| 141 |
+
stats["clean_chars"] += len(cleaned)
|
| 142 |
+
if stats["docs"] % 100 == 0:
|
| 143 |
+
print(f" [{stats['docs']}] cleaned")
|
| 144 |
+
stats["reduction_pct"] = round(100 * (1 - stats["clean_chars"] / max(stats["orig_chars"], 1)), 1)
|
| 145 |
+
(OUT / "clean_stats.json").write_text(json.dumps(stats, indent=1))
|
| 146 |
+
print(json.dumps(stats, indent=1))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
main()
|
scripts/marine_rag/embed.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
embed.py — Embed marine doc chunks with Gemini Embedding 2 (locked model).
|
| 4 |
+
|
| 5 |
+
Model: gemini-embedding-2-preview (768-dim, L2-normalized, RETRIEVAL_DOCUMENT).
|
| 6 |
+
No substitutes. Reranker is handled separately in search.py (Google Vertex Rank API).
|
| 7 |
+
|
| 8 |
+
Key resolution order:
|
| 9 |
+
1. env GOOGLE_API_KEY
|
| 10 |
+
2. env GEMINI_API_KEY
|
| 11 |
+
3. vertex_api_key=... in /Users/dmpantiu/cmip6/cmip6_gpt/.env
|
| 12 |
+
|
| 13 |
+
Modes:
|
| 14 |
+
realtime — streaming API, resumable (default)
|
| 15 |
+
batch — submit Batch API job (50% cost), then `status` / `download`
|
| 16 |
+
status --resume <job>
|
| 17 |
+
download --resume <job>
|
| 18 |
+
|
| 19 |
+
Usage:
|
| 20 |
+
python embed.py --mode realtime
|
| 21 |
+
python embed.py --mode realtime --limit 20 # smoke test
|
| 22 |
+
"""
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import time
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
import net_ipv4 # noqa: F401 — force IPv4 egress (VPN), must precede genai client
|
| 34 |
+
|
| 35 |
+
ROOT = Path(__file__).resolve().parent
|
| 36 |
+
OUT = ROOT / "out"
|
| 37 |
+
IN_JSONL = OUT / "chunks.jsonl"
|
| 38 |
+
OUT_JSONL = OUT / "chunks_embedded.jsonl"
|
| 39 |
+
BATCH_INPUT = OUT / "batch_embed_input.jsonl"
|
| 40 |
+
|
| 41 |
+
MODEL = "gemini-embedding-2-preview"
|
| 42 |
+
TASK_TYPE = "RETRIEVAL_DOCUMENT"
|
| 43 |
+
OUTPUT_DIM = 768
|
| 44 |
+
# AQ express key on gemini-embedding-2-preview is quota-capped at ~5 req/min.
|
| 45 |
+
# Big batches (100 contents/req) + ~13s spacing keep us under the cap.
|
| 46 |
+
RT_BATCH = 100
|
| 47 |
+
RT_SLEEP = 13.0
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def resolve_key() -> str:
|
| 51 |
+
for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
|
| 52 |
+
if os.environ.get(var):
|
| 53 |
+
return os.environ[var]
|
| 54 |
+
# new key lives in copernicus_mcp/.env (field may be misspelled 'veretex_api_key')
|
| 55 |
+
for env in (Path("/Users/dmpantiu/copernicus_mcp/.env"),
|
| 56 |
+
Path("/Users/dmpantiu/cmip6/cmip6_gpt/.env")):
|
| 57 |
+
if env.exists():
|
| 58 |
+
for line in env.read_text().splitlines():
|
| 59 |
+
line = line.strip()
|
| 60 |
+
if "api_key" in line.lower() and "=" in line and not line.startswith("#"):
|
| 61 |
+
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
| 62 |
+
raise SystemExit("No Gemini API key found (GOOGLE_API_KEY / vertex_api_key).")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_client():
|
| 66 |
+
from google import genai
|
| 67 |
+
return genai.Client(api_key=resolve_key())
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def l2(vec):
|
| 71 |
+
a = np.array(vec, dtype=np.float32)
|
| 72 |
+
n = np.linalg.norm(a)
|
| 73 |
+
return (a / n).tolist() if n > 0 else a.tolist()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def load_chunks(limit=None):
|
| 77 |
+
rows = []
|
| 78 |
+
with open(IN_JSONL) as f:
|
| 79 |
+
for i, line in enumerate(f):
|
| 80 |
+
if limit and i >= limit:
|
| 81 |
+
break
|
| 82 |
+
rows.append(json.loads(line))
|
| 83 |
+
return rows
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def embed_realtime(chunks):
|
| 87 |
+
from google.genai import types
|
| 88 |
+
client = get_client()
|
| 89 |
+
done = set()
|
| 90 |
+
if OUT_JSONL.exists():
|
| 91 |
+
for line in open(OUT_JSONL):
|
| 92 |
+
try:
|
| 93 |
+
done.add(json.loads(line)["chunk_id"])
|
| 94 |
+
except Exception:
|
| 95 |
+
pass
|
| 96 |
+
print(f"resume: {len(done)} already embedded")
|
| 97 |
+
todo = [c for c in chunks if c["chunk_id"] not in done]
|
| 98 |
+
print(f"to embed: {len(todo)} / {len(chunks)}")
|
| 99 |
+
n = 0
|
| 100 |
+
with open(OUT_JSONL, "a", encoding="utf-8") as fout:
|
| 101 |
+
for b in range(0, len(todo), RT_BATCH):
|
| 102 |
+
batch = todo[b:b + RT_BATCH]
|
| 103 |
+
texts = [c["text_with_prefix"] for c in batch]
|
| 104 |
+
for attempt in range(6):
|
| 105 |
+
try:
|
| 106 |
+
# genai 1.64 can raise "client has been closed" — recreate on retry
|
| 107 |
+
if attempt > 0:
|
| 108 |
+
client = get_client()
|
| 109 |
+
r = client.models.embed_content(
|
| 110 |
+
model=MODEL, contents=texts,
|
| 111 |
+
config=types.EmbedContentConfig(
|
| 112 |
+
task_type=TASK_TYPE, output_dimensionality=OUTPUT_DIM),
|
| 113 |
+
)
|
| 114 |
+
for c, e in zip(batch, r.embeddings):
|
| 115 |
+
c["embedding"] = l2(e.values)
|
| 116 |
+
fout.write(json.dumps(c, ensure_ascii=False) + "\n")
|
| 117 |
+
n += 1
|
| 118 |
+
fout.flush()
|
| 119 |
+
break
|
| 120 |
+
except Exception as e:
|
| 121 |
+
es = str(e)
|
| 122 |
+
if "IP address restriction" in es:
|
| 123 |
+
raise SystemExit(
|
| 124 |
+
"BLOCKED: Gemini key has IP restriction. Whitelist this host's "
|
| 125 |
+
"IP in Google Cloud Console (API key settings) and re-run.")
|
| 126 |
+
if any(k in es for k in ("429", "RESOURCE_EXHAUSTED", "Quota exceeded")):
|
| 127 |
+
wait = 35 # ~5 RPM quota — wait out the minute window
|
| 128 |
+
elif "client has been closed" in es:
|
| 129 |
+
wait = 2 # flaky genai transport; client recreated on retry
|
| 130 |
+
else:
|
| 131 |
+
wait = min(8 * (2 ** attempt), 60)
|
| 132 |
+
print(f" retry {attempt+1}/8 in {wait}s: {repr(e)[:120]}", file=sys.stderr)
|
| 133 |
+
time.sleep(wait)
|
| 134 |
+
else:
|
| 135 |
+
print(f" FATAL skip {len(batch)}", file=sys.stderr)
|
| 136 |
+
if n % 400 == 0:
|
| 137 |
+
print(f" [{n}/{len(todo)}]")
|
| 138 |
+
time.sleep(RT_SLEEP)
|
| 139 |
+
print(f"DONE: {n} embedded → {OUT_JSONL}")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
JOB_FILE = OUT / "batch_job.txt"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def prepare_batch(chunks):
|
| 146 |
+
# Correct batch schema: request.content (singular) + flat task_type/output_dimensionality.
|
| 147 |
+
with open(BATCH_INPUT, "w", encoding="utf-8") as f:
|
| 148 |
+
for c in chunks:
|
| 149 |
+
f.write(json.dumps({
|
| 150 |
+
"key": c["chunk_id"],
|
| 151 |
+
"request": {
|
| 152 |
+
"content": {"parts": [{"text": c["text_with_prefix"]}]},
|
| 153 |
+
"task_type": TASK_TYPE,
|
| 154 |
+
"output_dimensionality": OUTPUT_DIM,
|
| 155 |
+
},
|
| 156 |
+
}, ensure_ascii=False) + "\n")
|
| 157 |
+
print(f"batch input: {BATCH_INPUT} ({BATCH_INPUT.stat().st_size/1e6:.1f} MB, {len(chunks)} reqs)")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def submit_batch():
|
| 161 |
+
client = get_client()
|
| 162 |
+
up = client.files.upload(file=str(BATCH_INPUT),
|
| 163 |
+
config={"display_name": "marine_embed_input", "mime_type": "jsonl"})
|
| 164 |
+
job = client.batches.create_embeddings(
|
| 165 |
+
model=MODEL, src={"file_name": up.name},
|
| 166 |
+
config={"display_name": "marine_docs_embeddings"})
|
| 167 |
+
JOB_FILE.write_text(job.name)
|
| 168 |
+
print(f"job: {job.name} state: {job.state} (saved to {JOB_FILE})")
|
| 169 |
+
return job.name
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _extract_values(resp: dict):
|
| 173 |
+
"""Pull the embedding vector out of a batch result line, shape-tolerant."""
|
| 174 |
+
for path in (("response", "embeddings"), ("response", "embedding"), ("embeddings",), ("embedding",)):
|
| 175 |
+
node = resp
|
| 176 |
+
ok = True
|
| 177 |
+
for k in path:
|
| 178 |
+
if isinstance(node, dict) and k in node:
|
| 179 |
+
node = node[k]
|
| 180 |
+
else:
|
| 181 |
+
ok = False
|
| 182 |
+
break
|
| 183 |
+
if not ok:
|
| 184 |
+
continue
|
| 185 |
+
if isinstance(node, list) and node and isinstance(node[0], dict) and "values" in node[0]:
|
| 186 |
+
return node[0]["values"]
|
| 187 |
+
if isinstance(node, dict) and "values" in node:
|
| 188 |
+
return node["values"]
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def poll_and_download(chunks, wait=True):
|
| 193 |
+
client = get_client()
|
| 194 |
+
name = JOB_FILE.read_text().strip()
|
| 195 |
+
while True:
|
| 196 |
+
job = client.batches.get(name=name)
|
| 197 |
+
state = str(job.state)
|
| 198 |
+
print(f" job {name}: {state}")
|
| 199 |
+
if "SUCCEEDED" in state or "FAILED" in state or "CANCELLED" in state or "EXPIRED" in state:
|
| 200 |
+
break
|
| 201 |
+
if not wait:
|
| 202 |
+
return False
|
| 203 |
+
time.sleep(30)
|
| 204 |
+
if "SUCCEEDED" not in state:
|
| 205 |
+
print(f"job not successful: {state}")
|
| 206 |
+
return False
|
| 207 |
+
|
| 208 |
+
by_key = {c["chunk_id"]: c for c in chunks}
|
| 209 |
+
dest = getattr(job, "dest", None)
|
| 210 |
+
fn = getattr(dest, "file_name", None) if dest else None
|
| 211 |
+
lines = []
|
| 212 |
+
if fn:
|
| 213 |
+
lines = client.files.download(file=fn).decode("utf-8").strip().split("\n")
|
| 214 |
+
elif dest and getattr(dest, "inlined_responses", None):
|
| 215 |
+
lines = [json.dumps(r) for r in dest.inlined_responses]
|
| 216 |
+
n = 0
|
| 217 |
+
with open(OUT_JSONL, "w", encoding="utf-8") as fout:
|
| 218 |
+
for line in lines:
|
| 219 |
+
if not line.strip():
|
| 220 |
+
continue
|
| 221 |
+
r = json.loads(line)
|
| 222 |
+
k = r.get("key") or r.get("custom_metadata") or r.get("custom_id")
|
| 223 |
+
vals = _extract_values(r)
|
| 224 |
+
if k in by_key and vals:
|
| 225 |
+
c = dict(by_key[k])
|
| 226 |
+
c["embedding"] = l2(vals)
|
| 227 |
+
fout.write(json.dumps(c, ensure_ascii=False) + "\n")
|
| 228 |
+
n += 1
|
| 229 |
+
print(f"DOWNLOADED: {n}/{len(chunks)} embeddings → {OUT_JSONL}")
|
| 230 |
+
return n >= len(chunks) * 0.99
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def main():
|
| 234 |
+
ap = argparse.ArgumentParser()
|
| 235 |
+
ap.add_argument("--mode", choices=["realtime", "batch", "submit", "poll", "status", "download"],
|
| 236 |
+
default="realtime")
|
| 237 |
+
ap.add_argument("--limit", type=int, default=None)
|
| 238 |
+
ap.add_argument("--resume", type=str, default=None)
|
| 239 |
+
a = ap.parse_args()
|
| 240 |
+
|
| 241 |
+
chunks = load_chunks(a.limit)
|
| 242 |
+
toks = sum(c["token_count"] for c in chunks)
|
| 243 |
+
print(f"chunks={len(chunks):,} tokens={toks:,} "
|
| 244 |
+
f"est realtime=${toks/1e6*0.25:.2f} batch=${toks/1e6*0.125:.2f}")
|
| 245 |
+
|
| 246 |
+
if a.mode == "realtime":
|
| 247 |
+
embed_realtime(chunks)
|
| 248 |
+
elif a.mode in ("batch", "submit"):
|
| 249 |
+
prepare_batch(chunks)
|
| 250 |
+
submit_batch()
|
| 251 |
+
if a.mode == "batch":
|
| 252 |
+
poll_and_download(chunks, wait=True)
|
| 253 |
+
elif a.mode == "poll":
|
| 254 |
+
poll_and_download(chunks, wait=True)
|
| 255 |
+
elif a.mode in ("status", "download"):
|
| 256 |
+
client = get_client()
|
| 257 |
+
name = a.resume or JOB_FILE.read_text().strip()
|
| 258 |
+
job = client.batches.get(name=name)
|
| 259 |
+
print(f"state: {job.state}")
|
| 260 |
+
if a.mode == "download":
|
| 261 |
+
poll_and_download(chunks, wait=False)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
main()
|
scripts/marine_rag/embed_cds_batch.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
embed_cds_batch.py — embed the 164 CDS/ADS/EWDS cards via the Gemini Batch API
|
| 4 |
+
(free-tier realtime RPM is ~0 on gemini-embedding-2-preview; batch works).
|
| 5 |
+
|
| 6 |
+
Autonomous: submit → poll every 60s → download → then the caller runs
|
| 7 |
+
load_copernicus_docs.py + verify. Writes out/cds_cards_embedded.jsonl and a
|
| 8 |
+
marker out/CDS_EMBED_DONE on success.
|
| 9 |
+
"""
|
| 10 |
+
import json
|
| 11 |
+
import time
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import net_ipv4 # noqa: F401
|
| 16 |
+
from embed import resolve_key, l2, MODEL, TASK_TYPE, OUTPUT_DIM, _extract_values
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).resolve().parent
|
| 19 |
+
OUT = ROOT / "out"
|
| 20 |
+
IN_JSONL = OUT / "cds_cards_chunks.jsonl"
|
| 21 |
+
OUT_JSONL = OUT / "cds_cards_embedded.jsonl"
|
| 22 |
+
BATCH_INPUT = OUT / "cds_batch_input.jsonl"
|
| 23 |
+
JOB_FILE = OUT / "cds_batch_job.txt"
|
| 24 |
+
DONE = OUT / "CDS_EMBED_DONE"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_client():
|
| 28 |
+
from google import genai
|
| 29 |
+
return genai.Client(api_key=resolve_key())
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def prepare(chunks):
|
| 33 |
+
with open(BATCH_INPUT, "w", encoding="utf-8") as f:
|
| 34 |
+
for c in chunks:
|
| 35 |
+
f.write(json.dumps({
|
| 36 |
+
"key": c["chunk_id"],
|
| 37 |
+
"request": {
|
| 38 |
+
"content": {"parts": [{"text": c["text_with_prefix"]}]},
|
| 39 |
+
"task_type": TASK_TYPE,
|
| 40 |
+
"output_dimensionality": OUTPUT_DIM,
|
| 41 |
+
},
|
| 42 |
+
}, ensure_ascii=False) + "\n")
|
| 43 |
+
print(f"batch input: {BATCH_INPUT} ({len(chunks)} reqs)", flush=True)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def submit():
|
| 47 |
+
client = get_client()
|
| 48 |
+
up = client.files.upload(file=str(BATCH_INPUT),
|
| 49 |
+
config={"display_name": "cds_cards_input", "mime_type": "jsonl"})
|
| 50 |
+
job = client.batches.create_embeddings(
|
| 51 |
+
model=MODEL, src={"file_name": up.name},
|
| 52 |
+
config={"display_name": "copernicus_cds_cards"})
|
| 53 |
+
JOB_FILE.write_text(job.name)
|
| 54 |
+
print(f"job: {job.name} state: {job.state}", flush=True)
|
| 55 |
+
return job.name
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def poll_download(chunks):
|
| 59 |
+
client = get_client()
|
| 60 |
+
name = JOB_FILE.read_text().strip()
|
| 61 |
+
while True:
|
| 62 |
+
job = client.batches.get(name=name)
|
| 63 |
+
state = str(job.state)
|
| 64 |
+
print(f" {name}: {state}", flush=True)
|
| 65 |
+
if any(s in state for s in ("SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED")):
|
| 66 |
+
break
|
| 67 |
+
time.sleep(60)
|
| 68 |
+
if "SUCCEEDED" not in state:
|
| 69 |
+
print(f"job not successful: {state}", flush=True)
|
| 70 |
+
return 0
|
| 71 |
+
by_key = {c["chunk_id"]: c for c in chunks}
|
| 72 |
+
dest = getattr(job, "dest", None)
|
| 73 |
+
fn = getattr(dest, "file_name", None) if dest else None
|
| 74 |
+
lines = []
|
| 75 |
+
if fn:
|
| 76 |
+
lines = client.files.download(file=fn).decode("utf-8").strip().split("\n")
|
| 77 |
+
elif dest and getattr(dest, "inlined_responses", None):
|
| 78 |
+
lines = [json.dumps(r) for r in dest.inlined_responses]
|
| 79 |
+
n = 0
|
| 80 |
+
with open(OUT_JSONL, "w", encoding="utf-8") as fout:
|
| 81 |
+
for line in lines:
|
| 82 |
+
if not line.strip():
|
| 83 |
+
continue
|
| 84 |
+
r = json.loads(line)
|
| 85 |
+
k = r.get("key") or r.get("custom_id")
|
| 86 |
+
vals = _extract_values(r)
|
| 87 |
+
if k in by_key and vals:
|
| 88 |
+
c = dict(by_key[k])
|
| 89 |
+
c["embedding"] = l2(vals)
|
| 90 |
+
fout.write(json.dumps(c, ensure_ascii=False) + "\n")
|
| 91 |
+
n += 1
|
| 92 |
+
print(f"DOWNLOADED: {n}/{len(chunks)} → {OUT_JSONL}", flush=True)
|
| 93 |
+
if n >= len(chunks) * 0.99:
|
| 94 |
+
DONE.write_text(f"{n}/{len(chunks)}")
|
| 95 |
+
return n
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
chunks = [json.loads(l) for l in open(IN_JSONL)]
|
| 100 |
+
resume = "--poll" in sys.argv and JOB_FILE.exists()
|
| 101 |
+
if not resume:
|
| 102 |
+
prepare(chunks)
|
| 103 |
+
submit()
|
| 104 |
+
poll_download(chunks)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
main()
|
scripts/marine_rag/embed_cds_cards.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
embed_cds_cards.py — embed the 164 CDS/ADS/EWDS cards with the locked model
|
| 4 |
+
(gemini-embedding-2-preview, 768-dim, L2). Realtime mode, resumable.
|
| 5 |
+
Reuses embed.py's key resolution + IPv4 egress + L2 norm.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import time
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import net_ipv4 # noqa: F401 — force IPv4 egress before genai client
|
| 13 |
+
from embed import resolve_key, l2, MODEL, TASK_TYPE, OUTPUT_DIM
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parent
|
| 16 |
+
OUT = ROOT / "out"
|
| 17 |
+
IN_JSONL = OUT / "cds_cards_chunks.jsonl"
|
| 18 |
+
OUT_JSONL = OUT / "cds_cards_embedded.jsonl"
|
| 19 |
+
|
| 20 |
+
RT_BATCH = 50 # 164 cards / 50 ≈ 4 requests
|
| 21 |
+
RT_SLEEP = 13.0
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_client():
|
| 25 |
+
from google import genai
|
| 26 |
+
return genai.Client(api_key=resolve_key())
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main():
|
| 30 |
+
from google.genai import types
|
| 31 |
+
chunks = [json.loads(l) for l in open(IN_JSONL)]
|
| 32 |
+
done = set()
|
| 33 |
+
if OUT_JSONL.exists():
|
| 34 |
+
for line in open(OUT_JSONL):
|
| 35 |
+
try:
|
| 36 |
+
done.add(json.loads(line)["chunk_id"])
|
| 37 |
+
except Exception:
|
| 38 |
+
pass
|
| 39 |
+
todo = [c for c in chunks if c["chunk_id"] not in done]
|
| 40 |
+
print(f"to embed: {len(todo)} / {len(chunks)} ({len(done)} already done)")
|
| 41 |
+
client = get_client()
|
| 42 |
+
n = 0
|
| 43 |
+
with open(OUT_JSONL, "a", encoding="utf-8") as fout:
|
| 44 |
+
for b in range(0, len(todo), RT_BATCH):
|
| 45 |
+
batch = todo[b:b + RT_BATCH]
|
| 46 |
+
texts = [c["text_with_prefix"] for c in batch]
|
| 47 |
+
for attempt in range(8):
|
| 48 |
+
try:
|
| 49 |
+
if attempt > 0:
|
| 50 |
+
client = get_client()
|
| 51 |
+
r = client.models.embed_content(
|
| 52 |
+
model=MODEL, contents=texts,
|
| 53 |
+
config=types.EmbedContentConfig(
|
| 54 |
+
task_type=TASK_TYPE, output_dimensionality=OUTPUT_DIM))
|
| 55 |
+
for c, e in zip(batch, r.embeddings):
|
| 56 |
+
c["embedding"] = l2(e.values)
|
| 57 |
+
fout.write(json.dumps(c, ensure_ascii=False) + "\n")
|
| 58 |
+
n += 1
|
| 59 |
+
fout.flush()
|
| 60 |
+
print(f" [{n}/{len(todo)}]")
|
| 61 |
+
break
|
| 62 |
+
except Exception as e:
|
| 63 |
+
es = str(e)
|
| 64 |
+
if "IP address restriction" in es:
|
| 65 |
+
raise SystemExit("BLOCKED: Gemini key IP restriction.")
|
| 66 |
+
if any(k in es for k in ("429", "RESOURCE_EXHAUSTED", "Quota exceeded")):
|
| 67 |
+
wait = 35
|
| 68 |
+
elif "client has been closed" in es:
|
| 69 |
+
wait = 2
|
| 70 |
+
else:
|
| 71 |
+
wait = min(8 * (2 ** attempt), 60)
|
| 72 |
+
print(f" retry {attempt+1}/8 in {wait}s: {repr(e)[:120]}", file=sys.stderr)
|
| 73 |
+
time.sleep(wait)
|
| 74 |
+
else:
|
| 75 |
+
print(f" FATAL skip {len(batch)}", file=sys.stderr)
|
| 76 |
+
time.sleep(RT_SLEEP)
|
| 77 |
+
print(f"DONE: {n} embedded → {OUT_JSONL}")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
main()
|
scripts/marine_rag/load_copernicus_docs.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
load_copernicus_docs.py — build the unified `copernicus_docs` Qdrant collection:
|
| 4 |
+
one metadata card per dataset across ALL four Copernicus stores (~1415).
|
| 5 |
+
|
| 6 |
+
- 164 CDS/ADS/EWDS cards from out/cds_cards_embedded.jsonl (store=CDS/ADS/EWDS)
|
| 7 |
+
- 1251 Marine dataset cards, reusing the already-embedded CARD chunks in
|
| 8 |
+
out/chunks_embedded.jsonl (store=CMEMS)
|
| 9 |
+
|
| 10 |
+
Dense (768-dim Cosine, gemini-embedding-2-preview) + sparse (BM25) hybrid,
|
| 11 |
+
same recipe as marine_docs. Adds a `store` payload keyword for per-store filtering.
|
| 12 |
+
The deep Marine PUM/QUID/SQO doc-RAG (marine_docs) is left untouched.
|
| 13 |
+
"""
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
import uuid
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from qdrant_client import QdrantClient, models
|
| 20 |
+
from fastembed import SparseTextEmbedding
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parent
|
| 23 |
+
OUT = ROOT / "out"
|
| 24 |
+
COLLECTION = "copernicus_docs"
|
| 25 |
+
DENSE_DIM = 768
|
| 26 |
+
LOCAL_DB = OUT / "qdrant_db"
|
| 27 |
+
CDS_EMB = OUT / "cds_cards_embedded.jsonl"
|
| 28 |
+
MARINE_EMB = OUT / "chunks_embedded.jsonl"
|
| 29 |
+
BATCH = 400
|
| 30 |
+
|
| 31 |
+
_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def to_sparse(text: str) -> models.SparseVector:
|
| 35 |
+
r = list(_bm25.embed([text]))[0]
|
| 36 |
+
return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist())
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def iter_cards():
|
| 40 |
+
"""Yield (chunk, store) for every dataset card to index."""
|
| 41 |
+
# CDS/ADS/EWDS — each row already carries a `store` field
|
| 42 |
+
for line in open(CDS_EMB, encoding="utf-8"):
|
| 43 |
+
c = json.loads(line)
|
| 44 |
+
if c.get("embedding"):
|
| 45 |
+
yield c, c.get("store", "CDS")
|
| 46 |
+
# Marine — reuse CARD chunks only, tag store=CMEMS
|
| 47 |
+
seen = set()
|
| 48 |
+
for line in open(MARINE_EMB, encoding="utf-8"):
|
| 49 |
+
c = json.loads(line)
|
| 50 |
+
if c.get("doc_type") != "CARD" or not c.get("embedding"):
|
| 51 |
+
continue
|
| 52 |
+
if c["chunk_id"] in seen:
|
| 53 |
+
continue
|
| 54 |
+
seen.add(c["chunk_id"])
|
| 55 |
+
yield c, "CMEMS"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def create_collection(client: QdrantClient) -> None:
|
| 59 |
+
names = [c.name for c in client.get_collections().collections]
|
| 60 |
+
if COLLECTION in names:
|
| 61 |
+
client.delete_collection(COLLECTION)
|
| 62 |
+
client.create_collection(
|
| 63 |
+
collection_name=COLLECTION,
|
| 64 |
+
vectors_config={"dense": models.VectorParams(size=DENSE_DIM, distance=models.Distance.COSINE)},
|
| 65 |
+
sparse_vectors_config={"sparse": models.SparseVectorParams(modifier=models.Modifier.IDF)},
|
| 66 |
+
)
|
| 67 |
+
for field in ("product_id", "doc_type", "store"):
|
| 68 |
+
client.create_payload_index(collection_name=COLLECTION, field_name=field,
|
| 69 |
+
field_schema=models.PayloadSchemaType.KEYWORD)
|
| 70 |
+
print(f"created '{COLLECTION}' (dense+sparse, 3 payload indexes)")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def load(client: QdrantClient) -> None:
|
| 74 |
+
buf, total, t0 = [], 0, time.time()
|
| 75 |
+
per_store = {}
|
| 76 |
+
for c, store in iter_cards():
|
| 77 |
+
per_store[store] = per_store.get(store, 0) + 1
|
| 78 |
+
raw = c.get("text_raw", c.get("text_with_prefix", ""))
|
| 79 |
+
buf.append(models.PointStruct(
|
| 80 |
+
id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])),
|
| 81 |
+
vector={"dense": c["embedding"], "sparse": to_sparse(raw)},
|
| 82 |
+
payload={
|
| 83 |
+
"chunk_id": c["chunk_id"],
|
| 84 |
+
"product_id": c["product_id"],
|
| 85 |
+
"product_title": c.get("product_title", ""),
|
| 86 |
+
"dataset_id": c.get("doc_id", c["product_id"]),
|
| 87 |
+
"doc_type": c.get("doc_type", "CARD"),
|
| 88 |
+
"chunk_type": c.get("chunk_type", "card"),
|
| 89 |
+
"store": store,
|
| 90 |
+
"text_raw": raw[:2500],
|
| 91 |
+
},
|
| 92 |
+
))
|
| 93 |
+
if len(buf) >= BATCH:
|
| 94 |
+
client.upsert(collection_name=COLLECTION, points=buf)
|
| 95 |
+
total += len(buf); buf = []
|
| 96 |
+
print(f" [{total:,}] {total/(time.time()-t0):.0f} pts/s")
|
| 97 |
+
if buf:
|
| 98 |
+
client.upsert(collection_name=COLLECTION, points=buf)
|
| 99 |
+
total += len(buf)
|
| 100 |
+
print(f"DONE: {total:,} points | per store: {per_store} | "
|
| 101 |
+
f"collection now {client.get_collection(COLLECTION).points_count:,}")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def main():
|
| 105 |
+
client = QdrantClient(path=str(LOCAL_DB))
|
| 106 |
+
print(f"Qdrant local: {LOCAL_DB}")
|
| 107 |
+
create_collection(client)
|
| 108 |
+
load(client)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
main()
|
scripts/marine_rag/load_qdrant.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
load_qdrant.py — Load embedded marine doc chunks into Qdrant (hybrid).
|
| 4 |
+
|
| 5 |
+
Collection `marine_docs`:
|
| 6 |
+
- dense (768-dim, Cosine) from gemini-embedding-2-preview
|
| 7 |
+
- sparse (BM25 via FastEmbed) for keyword search
|
| 8 |
+
- payload indexes: product_id, doc_type, chunk_type, section_path
|
| 9 |
+
|
| 10 |
+
Storage: local persistent Qdrant at out/qdrant_db by default (no server needed);
|
| 11 |
+
pass --url http://localhost:6333 to use a server instead.
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python load_qdrant.py --recreate
|
| 15 |
+
python load_qdrant.py --limit 500
|
| 16 |
+
"""
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
import time
|
| 20 |
+
import uuid
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
from qdrant_client import QdrantClient, models
|
| 24 |
+
from fastembed import SparseTextEmbedding
|
| 25 |
+
|
| 26 |
+
ROOT = Path(__file__).resolve().parent
|
| 27 |
+
OUT = ROOT / "out"
|
| 28 |
+
COLLECTION = "marine_docs"
|
| 29 |
+
DENSE_DIM = 768
|
| 30 |
+
INPUT = OUT / "chunks_embedded.jsonl"
|
| 31 |
+
LOCAL_DB = OUT / "qdrant_db"
|
| 32 |
+
BATCH = 500
|
| 33 |
+
|
| 34 |
+
_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def to_sparse(text: str) -> models.SparseVector:
|
| 38 |
+
r = list(_bm25.embed([text]))[0]
|
| 39 |
+
return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist())
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def create_collection(client: QdrantClient, recreate: bool) -> None:
|
| 43 |
+
names = [c.name for c in client.get_collections().collections]
|
| 44 |
+
if COLLECTION in names:
|
| 45 |
+
if recreate:
|
| 46 |
+
client.delete_collection(COLLECTION)
|
| 47 |
+
else:
|
| 48 |
+
print(f"'{COLLECTION}' exists: {client.get_collection(COLLECTION).points_count} pts")
|
| 49 |
+
return
|
| 50 |
+
client.create_collection(
|
| 51 |
+
collection_name=COLLECTION,
|
| 52 |
+
vectors_config={"dense": models.VectorParams(size=DENSE_DIM, distance=models.Distance.COSINE)},
|
| 53 |
+
sparse_vectors_config={"sparse": models.SparseVectorParams(modifier=models.Modifier.IDF)},
|
| 54 |
+
)
|
| 55 |
+
for field, schema in [
|
| 56 |
+
("product_id", models.PayloadSchemaType.KEYWORD),
|
| 57 |
+
("doc_type", models.PayloadSchemaType.KEYWORD),
|
| 58 |
+
("chunk_type", models.PayloadSchemaType.KEYWORD),
|
| 59 |
+
("section_path", models.PayloadSchemaType.KEYWORD),
|
| 60 |
+
]:
|
| 61 |
+
client.create_payload_index(collection_name=COLLECTION, field_name=field, field_schema=schema)
|
| 62 |
+
print(f"created '{COLLECTION}' (dense+sparse, 4 payload indexes)")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load(client: QdrantClient, limit=None) -> None:
|
| 66 |
+
buf, total, skipped, t0 = [], 0, 0, time.time()
|
| 67 |
+
with open(INPUT, encoding="utf-8") as f:
|
| 68 |
+
for i, line in enumerate(f):
|
| 69 |
+
if limit and i >= limit:
|
| 70 |
+
break
|
| 71 |
+
c = json.loads(line)
|
| 72 |
+
emb = c.get("embedding")
|
| 73 |
+
if not emb:
|
| 74 |
+
skipped += 1
|
| 75 |
+
continue
|
| 76 |
+
raw = c.get("text_raw", c.get("text_with_prefix", ""))
|
| 77 |
+
buf.append(models.PointStruct(
|
| 78 |
+
id=str(uuid.uuid5(uuid.NAMESPACE_DNS, c["chunk_id"])),
|
| 79 |
+
vector={"dense": emb, "sparse": to_sparse(raw)},
|
| 80 |
+
payload={
|
| 81 |
+
"chunk_id": c["chunk_id"], "product_id": c["product_id"],
|
| 82 |
+
"product_title": c.get("product_title", ""),
|
| 83 |
+
"doc_id": c["doc_id"], "doc_type": c["doc_type"],
|
| 84 |
+
"section_path": c.get("section_path", ""),
|
| 85 |
+
"chunk_type": c.get("chunk_type", "text"),
|
| 86 |
+
"text_raw": raw[:2500],
|
| 87 |
+
},
|
| 88 |
+
))
|
| 89 |
+
if len(buf) >= BATCH:
|
| 90 |
+
client.upsert(collection_name=COLLECTION, points=buf)
|
| 91 |
+
total += len(buf)
|
| 92 |
+
print(f" [{total:,}] {total/(time.time()-t0):.0f} pts/s")
|
| 93 |
+
buf = []
|
| 94 |
+
if buf:
|
| 95 |
+
client.upsert(collection_name=COLLECTION, points=buf)
|
| 96 |
+
total += len(buf)
|
| 97 |
+
print(f"DONE: {total:,} points, skipped {skipped}, total now "
|
| 98 |
+
f"{client.get_collection(COLLECTION).points_count:,}")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def main():
|
| 102 |
+
ap = argparse.ArgumentParser()
|
| 103 |
+
ap.add_argument("--limit", type=int, default=None)
|
| 104 |
+
ap.add_argument("--recreate", action="store_true")
|
| 105 |
+
ap.add_argument("--url", type=str, default=None, help="Qdrant server URL; default = local path mode")
|
| 106 |
+
a = ap.parse_args()
|
| 107 |
+
client = QdrantClient(url=a.url, check_compatibility=False) if a.url else QdrantClient(path=str(LOCAL_DB))
|
| 108 |
+
print(f"Qdrant: {'server '+a.url if a.url else 'local '+str(LOCAL_DB)}")
|
| 109 |
+
create_collection(client, a.recreate)
|
| 110 |
+
load(client, a.limit)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
main()
|
scripts/marine_rag/net_ipv4.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Force all outbound DNS resolution to IPv4 so requests egress through the
|
| 2 |
+
IPv4 VPN instead of leaking onto native IPv6 (which bypasses the VPN and trips
|
| 3 |
+
the Gemini key's IP whitelist). Import this module before creating any client.
|
| 4 |
+
|
| 5 |
+
Disable with env FORCE_IPV4=0.
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import socket
|
| 9 |
+
|
| 10 |
+
if os.environ.get("FORCE_IPV4", "1") != "0":
|
| 11 |
+
_orig = socket.getaddrinfo
|
| 12 |
+
|
| 13 |
+
def _v4_only(host, *args, **kwargs):
|
| 14 |
+
res = _orig(host, *args, **kwargs)
|
| 15 |
+
v4 = [r for r in res if r[0] == socket.AF_INET]
|
| 16 |
+
return v4 or res # fall back to original if no v4 (don't break localhost)
|
| 17 |
+
|
| 18 |
+
socket.getaddrinfo = _v4_only
|
scripts/marine_rag/rag_api.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
rag_api.py — the callable RAG layer the MCP server exposes "through MCP".
|
| 4 |
+
|
| 5 |
+
Given a dataset OR product id (and optional question), return the relevant
|
| 6 |
+
documentation chunks (PUM/QUID/SQO) so the agent knows how to analyze the
|
| 7 |
+
dataset before working with it.
|
| 8 |
+
|
| 9 |
+
Public API:
|
| 10 |
+
resolve_product(dataset_or_product_id) -> product_id | None
|
| 11 |
+
get_dataset_docs(id, query=None, top_k=8, rerank=False) -> dict
|
| 12 |
+
{product_id, matched_by, results:[{doc_type, section, text, score}], ...}
|
| 13 |
+
|
| 14 |
+
Backed by Qdrant (dense Gemini + BM25) built by load_qdrant.py; embeddings from
|
| 15 |
+
gemini-embedding-2-preview; optional Google semantic-ranker rerank (search.py).
|
| 16 |
+
Returns descriptors/text only — no raw scientific bytes (MCP large-data rule).
|
| 17 |
+
"""
|
| 18 |
+
import json
|
| 19 |
+
from functools import lru_cache
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import search as S # hybrid(), rerank_google(), get_client(), COLLECTION
|
| 23 |
+
|
| 24 |
+
ROOT = Path(__file__).resolve().parent
|
| 25 |
+
OUT = ROOT / "out"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@lru_cache(maxsize=1)
|
| 29 |
+
def _catalog():
|
| 30 |
+
cat = json.loads((OUT / "catalog.json").read_text())
|
| 31 |
+
by_pid = {c["product_id"]: c for c in cat}
|
| 32 |
+
ds_to_pid = {}
|
| 33 |
+
for c in cat:
|
| 34 |
+
for ds in c.get("dataset_ids", []):
|
| 35 |
+
ds_to_pid[ds] = c["product_id"]
|
| 36 |
+
ds_to_pid[ds.lower()] = c["product_id"]
|
| 37 |
+
return by_pid, ds_to_pid
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def resolve_product(any_id: str) -> str | None:
|
| 41 |
+
by_pid, ds_to_pid = _catalog()
|
| 42 |
+
if any_id in by_pid:
|
| 43 |
+
return any_id
|
| 44 |
+
if any_id in ds_to_pid:
|
| 45 |
+
return ds_to_pid[any_id]
|
| 46 |
+
low = any_id.lower()
|
| 47 |
+
if low in ds_to_pid:
|
| 48 |
+
return ds_to_pid[low]
|
| 49 |
+
# prefix / containment fallback
|
| 50 |
+
for pid in by_pid:
|
| 51 |
+
if pid.lower() == low or low in pid.lower():
|
| 52 |
+
return pid
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_dataset_docs(any_id: str, query: str | None = None,
|
| 57 |
+
top_k: int = 8, rerank: bool = False, url: str | None = None) -> dict:
|
| 58 |
+
pid = resolve_product(any_id)
|
| 59 |
+
if not pid:
|
| 60 |
+
return {"ok": False, "error": f"unknown dataset/product id: {any_id}",
|
| 61 |
+
"hint": "use a CMEMS product_id or dataset_id from marine_search_*"}
|
| 62 |
+
by_pid, _ = _catalog()
|
| 63 |
+
prod = by_pid[pid]
|
| 64 |
+
client = S.get_client(url)
|
| 65 |
+
|
| 66 |
+
# Default question surfaces the "how to analyze" essentials.
|
| 67 |
+
q = query or (f"{prod['product_title']} variables, spatial and temporal coverage, "
|
| 68 |
+
f"accuracy, validation, how to use and interpret this product")
|
| 69 |
+
points = S.hybrid(client, q, top_k=top_k, prefetch=40, product_id=pid)
|
| 70 |
+
if rerank:
|
| 71 |
+
rr = S.rerank_google(q, points, top_k)
|
| 72 |
+
if rr is not None:
|
| 73 |
+
points = rr
|
| 74 |
+
results = []
|
| 75 |
+
for p in points[:top_k]:
|
| 76 |
+
pl = p.payload
|
| 77 |
+
results.append({
|
| 78 |
+
"doc_type": pl.get("doc_type"),
|
| 79 |
+
"doc_id": pl.get("doc_id"),
|
| 80 |
+
"section": pl.get("section_path"),
|
| 81 |
+
"text": pl.get("text_raw"),
|
| 82 |
+
"score": getattr(p, "score", None),
|
| 83 |
+
})
|
| 84 |
+
return {
|
| 85 |
+
"ok": True,
|
| 86 |
+
"product_id": pid,
|
| 87 |
+
"product_title": prod["product_title"],
|
| 88 |
+
"matched_by": "product_id" if any_id == pid else "dataset_id/fuzzy",
|
| 89 |
+
"doc_types_available": prod.get("doc_types", []),
|
| 90 |
+
"dataset_ids": prod.get("dataset_ids", []),
|
| 91 |
+
"query": q,
|
| 92 |
+
"n_results": len(results),
|
| 93 |
+
"results": results,
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
import argparse
|
| 99 |
+
ap = argparse.ArgumentParser()
|
| 100 |
+
ap.add_argument("id")
|
| 101 |
+
ap.add_argument("--query", default=None)
|
| 102 |
+
ap.add_argument("--top-k", type=int, default=6)
|
| 103 |
+
ap.add_argument("--rerank", action="store_true")
|
| 104 |
+
a = ap.parse_args()
|
| 105 |
+
out = get_dataset_docs(a.id, a.query, a.top_k, a.rerank)
|
| 106 |
+
# trim long result text for CLI readability without breaking JSON validity
|
| 107 |
+
for r in out.get("results", []):
|
| 108 |
+
if r.get("text") and len(r["text"]) > 400:
|
| 109 |
+
r["text"] = r["text"][:400] + "…"
|
| 110 |
+
print(json.dumps(out, ensure_ascii=False, indent=1))
|
scripts/marine_rag/rag_server.py
ADDED
|
@@ -0,0 +1,1026 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
rag_server.py — `copernicus-rag` MCP server: RAG discovery + documentation layer
|
| 4 |
+
for Copernicus data, companion to the `copernicus` MCP server (which does the
|
| 5 |
+
actual subsetting/downloading).
|
| 6 |
+
|
| 7 |
+
Two-level flow:
|
| 8 |
+
L0 search_datasets — find datasets by meaning across ALL 4 stores
|
| 9 |
+
(CMEMS 1251 + CDS 136 + ADS 16 + EWDS 12 cards)
|
| 10 |
+
L1 get_dataset_docs — quality/EQC documentation (PUM/QUID/SQO) chunks
|
| 11 |
+
for a CMEMS product, semantically filtered
|
| 12 |
+
search_docs — same 29k doc chunks, searched globally
|
| 13 |
+
list_dataset_documents / read_document — pull full doc markdown
|
| 14 |
+
|
| 15 |
+
Retrieval: Qdrant (embedded, out/qdrant_db) hybrid dense+BM25 with RRF fusion.
|
| 16 |
+
Dense query vector = gemini-embedding-2-preview (768-dim); if the embed call
|
| 17 |
+
fails (quota/net), we degrade to sparse-only BM25 and say so in the response.
|
| 18 |
+
Optional Google semantic-ranker rerank when GCP_PROJECT + ADC are set.
|
| 19 |
+
|
| 20 |
+
Invariants (mirrors copernicus-mcp): text/descriptors only — no raw scientific
|
| 21 |
+
bytes; logging to stderr only; tools never raise — they return {"ok": false}.
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import logging
|
| 27 |
+
import sys
|
| 28 |
+
import threading
|
| 29 |
+
from functools import lru_cache
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
# stdio transport: stdout is the JSON-RPC channel — pin ALL logging to stderr
|
| 33 |
+
# before any library gets a chance to install a stdout handler.
|
| 34 |
+
logging.basicConfig(level=logging.WARNING, stream=sys.stderr, force=True)
|
| 35 |
+
for _name in ("httpx", "httpcore", "google", "google_genai", "fastembed", "qdrant_client"):
|
| 36 |
+
logging.getLogger(_name).setLevel(logging.WARNING)
|
| 37 |
+
|
| 38 |
+
ROOT = Path(__file__).resolve().parent
|
| 39 |
+
sys.path.insert(0, str(ROOT))
|
| 40 |
+
|
| 41 |
+
import net_ipv4 # noqa: F401 — force IPv4 egress (VPN) before any genai call
|
| 42 |
+
|
| 43 |
+
from mcp.server.fastmcp import FastMCP
|
| 44 |
+
from qdrant_client import QdrantClient, models
|
| 45 |
+
|
| 46 |
+
import search as S # embed_query, sparse_query, rerank_google, LOCAL_DB
|
| 47 |
+
|
| 48 |
+
OUT = ROOT / "out"
|
| 49 |
+
CARDS_COLLECTION = "copernicus_docs" # 1 card per dataset, all 4 stores
|
| 50 |
+
DOCS_COLLECTION = "marine_docs" # PUM/QUID/SQO chunks, CMEMS only
|
| 51 |
+
STORES = ("CMEMS", "CDS", "ADS", "EWDS")
|
| 52 |
+
DOC_TYPES = ("PUM", "QUID", "SQO", "CARD")
|
| 53 |
+
MAX_TEXT = 1600 # per-chunk text cap in tool output
|
| 54 |
+
READ_DEFAULT = 20_000 # default read_document window
|
| 55 |
+
|
| 56 |
+
PUBS_DB = ROOT.parent / "pubs_rag" / "qdrant_db"
|
| 57 |
+
PUBS_COLLECTION = "publications"
|
| 58 |
+
REGISTRY = ROOT.parent / "publications" / "registry" / "publications.jsonl"
|
| 59 |
+
PAPERS = ROOT.parent / "pubs_rag" / "out" / "papers.jsonl"
|
| 60 |
+
LINKS_SIDECAR = ROOT.parent / "pubs_rag" / "out" / "links_by_dataset.json"
|
| 61 |
+
PUB_DOMAINS = ("ocean/marine", "atmosphere", "cryosphere", "land",
|
| 62 |
+
"climate-modeling", "climate-general", "emergency")
|
| 63 |
+
|
| 64 |
+
EQC_QA_DB = ROOT.parent / "eqc_qa" / "qdrant_db"
|
| 65 |
+
EQC_QA_COLLECTION = "eqc_qa"
|
| 66 |
+
|
| 67 |
+
# Deep documentation for the non-marine stores (CDS/ADS/EWDS): Confluence user
|
| 68 |
+
# guides / ATBDs / PDFs, chunked like marine_docs. Separate DB (own lock).
|
| 69 |
+
DEEP_DB = ROOT.parent / "deep_docs" / "qdrant_db"
|
| 70 |
+
DEEP_COLLECTION = "cds_docs"
|
| 71 |
+
|
| 72 |
+
# Notebook code layer: runnable example-notebook code ATTACHED to datasets
|
| 73 |
+
# (serve-time join by dataset id — NOT embedded/searched on its own).
|
| 74 |
+
NOTEBOOKS_SIDECAR = ROOT.parent / "eqc_qa" / "notebooks_by_dataset.json"
|
| 75 |
+
|
| 76 |
+
_lock = threading.Lock()
|
| 77 |
+
_client: QdrantClient | None = None
|
| 78 |
+
_pubs_client: QdrantClient | None = None
|
| 79 |
+
_eqc_client: QdrantClient | None = None
|
| 80 |
+
_deep_client: QdrantClient | None = None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _log(msg: str) -> None:
|
| 84 |
+
print(f"[copernicus-rag] {msg}", file=sys.stderr, flush=True)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _qdrant() -> QdrantClient:
|
| 88 |
+
global _client
|
| 89 |
+
with _lock:
|
| 90 |
+
if _client is None:
|
| 91 |
+
_log(f"opening embedded Qdrant at {S.LOCAL_DB}")
|
| 92 |
+
try:
|
| 93 |
+
_client = QdrantClient(path=str(S.LOCAL_DB))
|
| 94 |
+
except Exception as e:
|
| 95 |
+
raise RuntimeError(
|
| 96 |
+
"cannot open marine index (locked by a load script or another "
|
| 97 |
+
f"server instance? retry when it finishes): {repr(e)[:120]}") from e
|
| 98 |
+
return _client
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@lru_cache(maxsize=1)
|
| 102 |
+
def _catalog():
|
| 103 |
+
"""CMEMS product catalog: by product_id + dataset_id -> product_id map."""
|
| 104 |
+
cat = json.loads((OUT / "catalog.json").read_text())
|
| 105 |
+
by_pid = {c["product_id"]: c for c in cat}
|
| 106 |
+
ds_to_pid = {}
|
| 107 |
+
for c in cat:
|
| 108 |
+
for ds in c.get("dataset_ids", []):
|
| 109 |
+
ds_to_pid[ds.lower()] = c["product_id"]
|
| 110 |
+
return by_pid, ds_to_pid
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def resolve_product(any_id: str) -> str | None:
|
| 114 |
+
"""Exact product/dataset id, else UNIQUE prefix, else UNIQUE substring.
|
| 115 |
+
|
| 116 |
+
Ambiguous fragments (e.g. "006" is contained in 13 product ids) return
|
| 117 |
+
None instead of silently picking an arbitrary product.
|
| 118 |
+
"""
|
| 119 |
+
by_pid, ds_to_pid = _catalog()
|
| 120 |
+
if any_id in by_pid:
|
| 121 |
+
return any_id
|
| 122 |
+
low = any_id.lower()
|
| 123 |
+
if not low:
|
| 124 |
+
return None
|
| 125 |
+
if low in ds_to_pid:
|
| 126 |
+
return ds_to_pid[low]
|
| 127 |
+
exact = [pid for pid in by_pid if pid.lower() == low]
|
| 128 |
+
if exact:
|
| 129 |
+
return exact[0]
|
| 130 |
+
starts = [pid for pid in by_pid if pid.lower().startswith(low)]
|
| 131 |
+
if len(starts) == 1:
|
| 132 |
+
return starts[0]
|
| 133 |
+
contains = starts or [pid for pid in by_pid if low in pid.lower()]
|
| 134 |
+
return contains[0] if len(contains) == 1 else None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _pubs_qdrant() -> QdrantClient | None:
|
| 138 |
+
"""Client for the separate publications DB; None until the index is built."""
|
| 139 |
+
global _pubs_client
|
| 140 |
+
with _lock:
|
| 141 |
+
if _pubs_client is None:
|
| 142 |
+
if not PUBS_DB.exists():
|
| 143 |
+
return None
|
| 144 |
+
_log(f"opening embedded Qdrant at {PUBS_DB}")
|
| 145 |
+
try:
|
| 146 |
+
_pubs_client = QdrantClient(path=str(PUBS_DB))
|
| 147 |
+
except Exception as e:
|
| 148 |
+
raise RuntimeError(
|
| 149 |
+
"cannot open publications index (locked by load_pubs_qdrant.py "
|
| 150 |
+
f"or another server instance? retry when it finishes): {repr(e)[:120]}") from e
|
| 151 |
+
return _pubs_client
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _pubs_status() -> str:
|
| 155 |
+
"""Human-readable build status of the publications index."""
|
| 156 |
+
return ("publications index not on disk yet — PDFs are being downloaded "
|
| 157 |
+
"and VLM-parsed; the collection grows as parses land")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _eqc_qdrant() -> QdrantClient | None:
|
| 161 |
+
"""Client for the CDS/C3S EQC quality-assessment DB; None until built."""
|
| 162 |
+
global _eqc_client
|
| 163 |
+
with _lock:
|
| 164 |
+
if _eqc_client is None:
|
| 165 |
+
if not EQC_QA_DB.exists():
|
| 166 |
+
return None
|
| 167 |
+
_log(f"opening embedded Qdrant at {EQC_QA_DB}")
|
| 168 |
+
try:
|
| 169 |
+
_eqc_client = QdrantClient(path=str(EQC_QA_DB))
|
| 170 |
+
except Exception as e:
|
| 171 |
+
raise RuntimeError(
|
| 172 |
+
"cannot open EQC-QA index (locked by load_eqc_qa.py or another "
|
| 173 |
+
f"server instance? retry when it finishes): {repr(e)[:120]}") from e
|
| 174 |
+
return _eqc_client
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _deep_qdrant() -> QdrantClient | None:
|
| 178 |
+
"""Client for the CDS/ADS/EWDS deep-docs DB; None until built."""
|
| 179 |
+
global _deep_client
|
| 180 |
+
with _lock:
|
| 181 |
+
if _deep_client is None:
|
| 182 |
+
if not DEEP_DB.exists():
|
| 183 |
+
return None
|
| 184 |
+
_log(f"opening embedded Qdrant at {DEEP_DB}")
|
| 185 |
+
try:
|
| 186 |
+
_deep_client = QdrantClient(path=str(DEEP_DB))
|
| 187 |
+
except Exception as e:
|
| 188 |
+
raise RuntimeError(
|
| 189 |
+
"cannot open deep-docs index (locked by embed_load.py or another "
|
| 190 |
+
f"server instance? retry when it finishes): {repr(e)[:120]}") from e
|
| 191 |
+
return _deep_client
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@lru_cache(maxsize=1)
|
| 195 |
+
def _notebooks() -> tuple[dict, dict, dict]:
|
| 196 |
+
"""Notebook code recipes attached to datasets (serve-time join, no re-index).
|
| 197 |
+
|
| 198 |
+
Returns (by_dataset_id -> [records], by_notebook_id -> record,
|
| 199 |
+
generic_by_store -> [store-level how-to records]). Cached for process
|
| 200 |
+
lifetime: restart the server to pick up newly attached notebooks.
|
| 201 |
+
"""
|
| 202 |
+
by_ds: dict = {}
|
| 203 |
+
by_id: dict = {}
|
| 204 |
+
generic: dict = {}
|
| 205 |
+
if NOTEBOOKS_SIDECAR.exists():
|
| 206 |
+
data = json.loads(NOTEBOOKS_SIDECAR.read_text())
|
| 207 |
+
by_ds = data.get("by_dataset", {})
|
| 208 |
+
generic = data.get("generic_by_store", {})
|
| 209 |
+
for recs in by_ds.values():
|
| 210 |
+
for r in recs:
|
| 211 |
+
by_id[r["notebook_id"]] = r
|
| 212 |
+
for recs in generic.values():
|
| 213 |
+
for r in recs:
|
| 214 |
+
by_id.setdefault(r["notebook_id"], r)
|
| 215 |
+
return by_ds, by_id, generic
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _nb_refs(dataset_id: str | None, product_id: str | None = None,
|
| 219 |
+
kind: str | None = None) -> list[dict]:
|
| 220 |
+
"""Compact notebook refs attached to a dataset/collection id (for list views)."""
|
| 221 |
+
by_ds, _, _ = _notebooks()
|
| 222 |
+
recs = by_ds.get(dataset_id or "") or by_ds.get(product_id or "") or []
|
| 223 |
+
out = []
|
| 224 |
+
for r in recs:
|
| 225 |
+
if kind and kind not in (r.get("recipe_kinds") or []):
|
| 226 |
+
continue
|
| 227 |
+
out.append({"notebook_id": r["notebook_id"], "title": r.get("title"),
|
| 228 |
+
"recipe_kinds": r.get("recipe_kinds"),
|
| 229 |
+
"n_code_lines": r.get("n_code_lines"),
|
| 230 |
+
"source_repo": r.get("source_repo")})
|
| 231 |
+
return out
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _query(collection: str, query: str, flt: models.Filter | None,
|
| 235 |
+
top_k: int, prefetch: int = 50, client: QdrantClient | None = None):
|
| 236 |
+
"""Hybrid dense+sparse RRF; degrades to sparse-only if dense embed fails.
|
| 237 |
+
|
| 238 |
+
Only the embed call may trigger the fallback (SystemExit included: a
|
| 239 |
+
missing API key must not kill the server); Qdrant errors propagate to
|
| 240 |
+
the caller so they are reported as what they are.
|
| 241 |
+
|
| 242 |
+
Returns (points, retrieval_mode).
|
| 243 |
+
"""
|
| 244 |
+
client = client or _qdrant()
|
| 245 |
+
sparse_vec = S.sparse_query(query)
|
| 246 |
+
dense_vec = None
|
| 247 |
+
try:
|
| 248 |
+
dense_vec = S.embed_query(query)
|
| 249 |
+
except (Exception, SystemExit) as e:
|
| 250 |
+
_log(f"dense embed unavailable ({repr(e)[:120]}); sparse-only fallback")
|
| 251 |
+
if dense_vec is not None:
|
| 252 |
+
res = client.query_points(
|
| 253 |
+
collection_name=collection,
|
| 254 |
+
prefetch=[
|
| 255 |
+
models.Prefetch(query=dense_vec, using="dense", limit=prefetch, filter=flt),
|
| 256 |
+
models.Prefetch(query=sparse_vec, using="sparse", limit=prefetch, filter=flt),
|
| 257 |
+
],
|
| 258 |
+
query=models.FusionQuery(fusion=models.Fusion.RRF),
|
| 259 |
+
limit=top_k, with_payload=True,
|
| 260 |
+
)
|
| 261 |
+
return res.points, "hybrid(dense+bm25)"
|
| 262 |
+
res = client.query_points(
|
| 263 |
+
collection_name=collection, query=sparse_vec, using="sparse",
|
| 264 |
+
limit=top_k, with_payload=True, query_filter=flt,
|
| 265 |
+
)
|
| 266 |
+
return res.points, "bm25-only (dense embed unavailable)"
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _maybe_rerank(query: str, points, top_k: int, rerank: bool):
|
| 270 |
+
if not rerank or not points:
|
| 271 |
+
return points, False
|
| 272 |
+
rr = S.rerank_google(query, points, top_k)
|
| 273 |
+
return (rr, True) if rr is not None else (points, False)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _err(msg: str, **extra) -> dict:
|
| 277 |
+
return {"ok": False, "error": msg, **extra}
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
mcp = FastMCP("copernicus-rag")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@mcp.tool()
|
| 284 |
+
def search_datasets(query: str, store: str | None = None, top_k: int = 10,
|
| 285 |
+
rerank: bool = False) -> dict:
|
| 286 |
+
"""Semantic (RAG) search for Copernicus datasets by description, across all
|
| 287 |
+
four data stores: CMEMS (marine), CDS (climate/ERA5), ADS (atmosphere),
|
| 288 |
+
EWDS (emergency/flood/fire). One card per dataset (~1415 total).
|
| 289 |
+
|
| 290 |
+
Use this FIRST to discover which dataset to work with. Then, for CMEMS
|
| 291 |
+
results, call get_dataset_docs(product_id) to read its quality (EQC)
|
| 292 |
+
documentation before analyzing data.
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
query: natural-language description of the data you need
|
| 296 |
+
(e.g. "daily arctic sea ice concentration satellite").
|
| 297 |
+
store: optional filter — one of CMEMS, CDS, ADS, EWDS.
|
| 298 |
+
top_k: number of datasets to return (default 10).
|
| 299 |
+
rerank: also rerank with Google semantic-ranker (needs GCP ADC).
|
| 300 |
+
"""
|
| 301 |
+
try:
|
| 302 |
+
if store:
|
| 303 |
+
store = store.upper()
|
| 304 |
+
if store not in STORES:
|
| 305 |
+
return _err(f"unknown store '{store}'", valid_stores=list(STORES))
|
| 306 |
+
top_k = max(1, min(int(top_k), 30))
|
| 307 |
+
flt = models.Filter(must=[models.FieldCondition(
|
| 308 |
+
key="store", match=models.MatchValue(value=store))]) if store else None
|
| 309 |
+
points, mode = _query(CARDS_COLLECTION, query, flt, max(top_k, 20))
|
| 310 |
+
points, reranked = _maybe_rerank(query, points, top_k, rerank)
|
| 311 |
+
by_pid, _ = _catalog()
|
| 312 |
+
results = []
|
| 313 |
+
for p in points[:top_k]:
|
| 314 |
+
pl = p.payload
|
| 315 |
+
pid = pl.get("product_id", "")
|
| 316 |
+
has_docs = bool(by_pid.get(pid, {}).get("has_docs"))
|
| 317 |
+
results.append({
|
| 318 |
+
"store": pl.get("store"),
|
| 319 |
+
"dataset_id": pl.get("dataset_id"),
|
| 320 |
+
"product_id": pid,
|
| 321 |
+
"title": pl.get("product_title"),
|
| 322 |
+
"description": (pl.get("text_raw") or "")[:MAX_TEXT],
|
| 323 |
+
"has_eqc_docs": has_docs,
|
| 324 |
+
"notebooks": _nb_refs(pl.get("dataset_id"), pid),
|
| 325 |
+
"score": getattr(p, "score", None),
|
| 326 |
+
})
|
| 327 |
+
return {"ok": True, "query": query, "store": store or "ALL",
|
| 328 |
+
"retrieval": mode, "reranked": reranked,
|
| 329 |
+
"n_results": len(results), "results": results,
|
| 330 |
+
"next_step": ("for CMEMS hits call get_dataset_docs(product_id) "
|
| 331 |
+
"to read quality docs; where a hit has notebooks[], "
|
| 332 |
+
"call get_dataset_code(dataset_id) for runnable code")}
|
| 333 |
+
except Exception as e:
|
| 334 |
+
_log(f"search_datasets failed: {repr(e)}")
|
| 335 |
+
return _err(f"search failed: {repr(e)[:200]}")
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _deep_dataset_docs(dataset_id: str, question: str | None,
|
| 339 |
+
top_k: int, rerank: bool) -> dict | None:
|
| 340 |
+
"""Deep CDS/ADS/EWDS documentation (cds_docs) for a collection id.
|
| 341 |
+
Returns a result dict, or None if the deep index is unavailable / has no
|
| 342 |
+
match for this id (so the caller can fall through to 'unknown id')."""
|
| 343 |
+
client = _deep_qdrant()
|
| 344 |
+
if client is None:
|
| 345 |
+
return None
|
| 346 |
+
top_k = max(1, min(int(top_k), 20))
|
| 347 |
+
q = question or (f"{dataset_id} documentation: variables, methodology, accuracy, "
|
| 348 |
+
"validation, how to use and interpret this dataset")
|
| 349 |
+
must = [models.FieldCondition(key="dataset_ids", match=models.MatchValue(value=dataset_id))]
|
| 350 |
+
points, mode = _query(DEEP_COLLECTION, q, models.Filter(must=must),
|
| 351 |
+
max(top_k, 20), prefetch=40, client=client)
|
| 352 |
+
if not points:
|
| 353 |
+
return None
|
| 354 |
+
points, reranked = _maybe_rerank(q, points, top_k, rerank)
|
| 355 |
+
results = [{
|
| 356 |
+
"store": p.payload.get("store"),
|
| 357 |
+
"doc_title": p.payload.get("doc_title"),
|
| 358 |
+
"doc_url": p.payload.get("doc_url"),
|
| 359 |
+
"section": p.payload.get("section"),
|
| 360 |
+
"text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
|
| 361 |
+
"score": getattr(p, "score", None),
|
| 362 |
+
} for p in points[:top_k]]
|
| 363 |
+
return {"ok": True, "dataset_id": dataset_id, "layer": "deep_docs (CDS/ADS/EWDS)",
|
| 364 |
+
"query": q, "retrieval": mode, "reranked": reranked,
|
| 365 |
+
"n_results": len(results), "results": results,
|
| 366 |
+
"notebooks": _nb_refs(dataset_id, dataset_id),
|
| 367 |
+
"next_step": ("get_eqc_quality_report(dataset_id) for quality assessment; "
|
| 368 |
+
"get_dataset_code(dataset_id) for runnable code")}
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@mcp.tool()
|
| 372 |
+
def get_dataset_docs(dataset_or_product_id: str, question: str | None = None,
|
| 373 |
+
doc_type: str | None = None, top_k: int = 8,
|
| 374 |
+
rerank: bool = False) -> dict:
|
| 375 |
+
"""Level-2 EQC lookup: retrieve the quality/usage documentation chunks
|
| 376 |
+
(PUM = Product User Manual, QUID = Quality Information Document,
|
| 377 |
+
SQO = Scientific Quality Overview) for one CMEMS product or dataset.
|
| 378 |
+
|
| 379 |
+
Call this AFTER search_datasets, BEFORE analyzing data: it tells you the
|
| 380 |
+
variables, units, spatial/temporal coverage, accuracy, validation results
|
| 381 |
+
and known caveats — i.e. how to interpret the numbers you will pull.
|
| 382 |
+
|
| 383 |
+
Args:
|
| 384 |
+
dataset_or_product_id: CMEMS product_id or dataset_id
|
| 385 |
+
(e.g. "MEDSEA_ANALYSISFORECAST_PHY_006_013" or a dataset id).
|
| 386 |
+
question: optional focus (e.g. "salinity validation accuracy");
|
| 387 |
+
default surfaces the how-to-analyze essentials.
|
| 388 |
+
doc_type: optional filter — PUM, QUID or SQO.
|
| 389 |
+
top_k: number of doc chunks to return (default 8).
|
| 390 |
+
rerank: also rerank with Google semantic-ranker (needs GCP ADC).
|
| 391 |
+
"""
|
| 392 |
+
try:
|
| 393 |
+
pid = resolve_product(dataset_or_product_id)
|
| 394 |
+
if not pid:
|
| 395 |
+
deep = _deep_dataset_docs(dataset_or_product_id, question, top_k, rerank)
|
| 396 |
+
if deep is not None:
|
| 397 |
+
return deep
|
| 398 |
+
return _err(f"unknown dataset/product id: {dataset_or_product_id}",
|
| 399 |
+
hint="use an id returned by search_datasets")
|
| 400 |
+
by_pid, _ = _catalog()
|
| 401 |
+
prod = by_pid[pid]
|
| 402 |
+
if doc_type:
|
| 403 |
+
doc_type = doc_type.upper()
|
| 404 |
+
if doc_type not in DOC_TYPES:
|
| 405 |
+
return _err(f"unknown doc_type '{doc_type}'", valid=list(DOC_TYPES))
|
| 406 |
+
top_k = max(1, min(int(top_k), 20))
|
| 407 |
+
q = question or (f"{prod['product_title']} variables, spatial and temporal "
|
| 408 |
+
"coverage, accuracy, validation, how to use and interpret "
|
| 409 |
+
"this product")
|
| 410 |
+
must = [models.FieldCondition(key="product_id", match=models.MatchValue(value=pid))]
|
| 411 |
+
if doc_type:
|
| 412 |
+
must.append(models.FieldCondition(key="doc_type", match=models.MatchValue(value=doc_type)))
|
| 413 |
+
points, mode = _query(DOCS_COLLECTION, q, models.Filter(must=must), max(top_k, 20), prefetch=40)
|
| 414 |
+
points, reranked = _maybe_rerank(q, points, top_k, rerank)
|
| 415 |
+
results = [{
|
| 416 |
+
"doc_type": p.payload.get("doc_type"),
|
| 417 |
+
"doc_id": p.payload.get("doc_id"),
|
| 418 |
+
"section": p.payload.get("section_path"),
|
| 419 |
+
"text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
|
| 420 |
+
"score": getattr(p, "score", None),
|
| 421 |
+
} for p in points[:top_k]]
|
| 422 |
+
return {"ok": True, "product_id": pid, "product_title": prod["product_title"],
|
| 423 |
+
"matched_by": "product_id" if dataset_or_product_id == pid else "dataset_id/fuzzy",
|
| 424 |
+
"doc_types_available": prod.get("doc_types", []),
|
| 425 |
+
"dataset_ids": prod.get("dataset_ids", []),
|
| 426 |
+
"query": q, "retrieval": mode, "reranked": reranked,
|
| 427 |
+
"n_results": len(results), "results": results,
|
| 428 |
+
"next_step": ("read_document(doc_id) pulls a full document; "
|
| 429 |
+
"then subset data via the copernicus MCP server")}
|
| 430 |
+
except Exception as e:
|
| 431 |
+
_log(f"get_dataset_docs failed: {repr(e)}")
|
| 432 |
+
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
@mcp.tool()
|
| 436 |
+
def search_docs(query: str, doc_type: str | None = None, top_k: int = 8,
|
| 437 |
+
rerank: bool = False) -> dict:
|
| 438 |
+
"""Global semantic search across ALL CMEMS quality documentation
|
| 439 |
+
(~29k chunks of PUM/QUID/SQO for 306 products), not limited to one product.
|
| 440 |
+
|
| 441 |
+
Use for cross-product questions like "which products are validated against
|
| 442 |
+
Argo floats" or "sea level trend uncertainty methodology".
|
| 443 |
+
|
| 444 |
+
Args:
|
| 445 |
+
query: natural-language question.
|
| 446 |
+
doc_type: optional filter — PUM, QUID or SQO.
|
| 447 |
+
top_k: number of chunks to return (default 8).
|
| 448 |
+
rerank: also rerank with Google semantic-ranker (needs GCP ADC).
|
| 449 |
+
"""
|
| 450 |
+
try:
|
| 451 |
+
if doc_type:
|
| 452 |
+
doc_type = doc_type.upper()
|
| 453 |
+
if doc_type not in DOC_TYPES:
|
| 454 |
+
return _err(f"unknown doc_type '{doc_type}'", valid=list(DOC_TYPES))
|
| 455 |
+
top_k = max(1, min(int(top_k), 20))
|
| 456 |
+
flt = models.Filter(must=[models.FieldCondition(
|
| 457 |
+
key="doc_type", match=models.MatchValue(value=doc_type))]) if doc_type else None
|
| 458 |
+
points, mode = _query(DOCS_COLLECTION, query, flt, max(top_k, 20))
|
| 459 |
+
points, reranked = _maybe_rerank(query, points, top_k, rerank)
|
| 460 |
+
results = [{
|
| 461 |
+
"product_id": p.payload.get("product_id"),
|
| 462 |
+
"product_title": p.payload.get("product_title"),
|
| 463 |
+
"doc_type": p.payload.get("doc_type"),
|
| 464 |
+
"doc_id": p.payload.get("doc_id"),
|
| 465 |
+
"section": p.payload.get("section_path"),
|
| 466 |
+
"text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
|
| 467 |
+
"score": getattr(p, "score", None),
|
| 468 |
+
} for p in points[:top_k]]
|
| 469 |
+
return {"ok": True, "query": query, "retrieval": mode, "reranked": reranked,
|
| 470 |
+
"n_results": len(results), "results": results}
|
| 471 |
+
except Exception as e:
|
| 472 |
+
_log(f"search_docs failed: {repr(e)}")
|
| 473 |
+
return _err(f"search failed: {repr(e)[:200]}")
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
@mcp.tool()
|
| 477 |
+
def list_dataset_documents(dataset_or_product_id: str) -> dict:
|
| 478 |
+
"""List the full EQC documents available for a CMEMS product/dataset:
|
| 479 |
+
doc_id, type (PUM/QUID/SQO) and size. Feed a doc_id to read_document
|
| 480 |
+
to pull the complete text.
|
| 481 |
+
|
| 482 |
+
Args:
|
| 483 |
+
dataset_or_product_id: CMEMS product_id or dataset_id.
|
| 484 |
+
"""
|
| 485 |
+
try:
|
| 486 |
+
pid = resolve_product(dataset_or_product_id)
|
| 487 |
+
if not pid:
|
| 488 |
+
return _err(f"unknown dataset/product id: {dataset_or_product_id}")
|
| 489 |
+
by_pid, _ = _catalog()
|
| 490 |
+
prod = by_pid[pid]
|
| 491 |
+
docs = [{"doc_id": d["doc_id"], "doc_type": d["doc_type"],
|
| 492 |
+
"size_bytes": d.get("md_bytes"), "available": d.get("has_md", False)}
|
| 493 |
+
for d in prod.get("docs", [])]
|
| 494 |
+
return {"ok": True, "product_id": pid, "product_title": prod["product_title"],
|
| 495 |
+
"dataset_ids": prod.get("dataset_ids", []),
|
| 496 |
+
"doi": prod.get("doi"), "regions": prod.get("regions", []),
|
| 497 |
+
"domains": prod.get("domains", []),
|
| 498 |
+
"n_documents": len(docs), "documents": docs}
|
| 499 |
+
except Exception as e:
|
| 500 |
+
_log(f"list_dataset_documents failed: {repr(e)}")
|
| 501 |
+
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@lru_cache(maxsize=1)
|
| 505 |
+
def _unified_meta() -> dict:
|
| 506 |
+
"""Full harvested upstream metadata, all 4 stores (meta_harvest)."""
|
| 507 |
+
path = ROOT.parent / "meta_harvest" / "unified_metadata.json"
|
| 508 |
+
return json.loads(path.read_text()) if path.exists() else {}
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
@mcp.tool()
|
| 512 |
+
def dataset_metadata(dataset_or_collection_id: str) -> dict:
|
| 513 |
+
"""FULL harvested metadata for one dataset (any store) — much richer than
|
| 514 |
+
the card returned by search_datasets: variables with units/standard_name/
|
| 515 |
+
bbox/depth/time ranges, services, processing level, production centre,
|
| 516 |
+
update frequency, documentation links, scientific references, licence.
|
| 517 |
+
|
| 518 |
+
Use before subsetting data: it tells you exact variable names, units and
|
| 519 |
+
coverage bounds. Accepts a CMEMS dataset_id, a CDS/ADS/EWDS collection id,
|
| 520 |
+
or a CMEMS product_id (then lists the product's datasets).
|
| 521 |
+
|
| 522 |
+
Args:
|
| 523 |
+
dataset_or_collection_id: e.g. "antarctic_omi_si_extent",
|
| 524 |
+
"reanalysis-era5-single-levels", or a CMEMS product_id.
|
| 525 |
+
"""
|
| 526 |
+
try:
|
| 527 |
+
meta = _unified_meta()
|
| 528 |
+
if not meta:
|
| 529 |
+
return _err("unified_metadata.json not found — run the meta_harvest pipeline")
|
| 530 |
+
key = dataset_or_collection_id
|
| 531 |
+
entry = meta.get(key) or meta.get(key.lower())
|
| 532 |
+
if entry is None:
|
| 533 |
+
# maybe a CMEMS product_id → group its datasets
|
| 534 |
+
low = key.lower()
|
| 535 |
+
members = {k: v for k, v in meta.items()
|
| 536 |
+
if (v.get("product_id") or "").lower() == low}
|
| 537 |
+
if members:
|
| 538 |
+
first = next(iter(members.values()))
|
| 539 |
+
return {"ok": True, "matched_by": "product_id",
|
| 540 |
+
"product_id": first.get("product_id"),
|
| 541 |
+
"title": first.get("title"), "doi": first.get("doi"),
|
| 542 |
+
"store": first.get("store"),
|
| 543 |
+
"n_datasets": len(members),
|
| 544 |
+
"dataset_ids": sorted(members),
|
| 545 |
+
"next_step": "call dataset_metadata with one dataset_id"}
|
| 546 |
+
close = [k for k in meta if low in k.lower()][:10]
|
| 547 |
+
return _err(f"unknown id: {key}",
|
| 548 |
+
similar_ids=close,
|
| 549 |
+
hint="use ids from search_datasets / list_dataset_documents")
|
| 550 |
+
out = dict(entry)
|
| 551 |
+
out["dataset_id"] = key if key in meta else key.lower()
|
| 552 |
+
for field, cap in (("variables", 120), ("references", 30),
|
| 553 |
+
("documentation_links", 40), ("keywords", 40)):
|
| 554 |
+
v = out.get(field)
|
| 555 |
+
if isinstance(v, list) and len(v) > cap:
|
| 556 |
+
out[field] = v[:cap]
|
| 557 |
+
out[f"{field}_truncated"] = f"{len(v) - cap} more omitted"
|
| 558 |
+
return {"ok": True, "matched_by": "dataset_id", **out}
|
| 559 |
+
except Exception as e:
|
| 560 |
+
_log(f"dataset_metadata failed: {repr(e)}")
|
| 561 |
+
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
@lru_cache(maxsize=1)
|
| 565 |
+
def _doc_index() -> dict:
|
| 566 |
+
"""doc_id -> absolute md path, from the catalog."""
|
| 567 |
+
by_pid, _ = _catalog()
|
| 568 |
+
idx = {}
|
| 569 |
+
for prod in by_pid.values():
|
| 570 |
+
for d in prod.get("docs", []):
|
| 571 |
+
if d.get("has_md") and d.get("md_path"):
|
| 572 |
+
idx[d["doc_id"]] = ROOT.parent / d["md_path"]
|
| 573 |
+
return idx
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
@mcp.tool()
|
| 577 |
+
def read_document(doc_id: str, offset: int = 0, max_chars: int = READ_DEFAULT) -> dict:
|
| 578 |
+
"""Pull the full markdown text of one EQC document (PUM/QUID/SQO), paginated.
|
| 579 |
+
Get doc_id from list_dataset_documents or from get_dataset_docs results.
|
| 580 |
+
The first page includes an outline (headings + char offsets) so you can jump
|
| 581 |
+
straight to a section with the offset argument.
|
| 582 |
+
|
| 583 |
+
Args:
|
| 584 |
+
doc_id: e.g. "CMEMS-MED-QUID-006-013".
|
| 585 |
+
offset: character offset to start from (default 0).
|
| 586 |
+
max_chars: page size (default 20000, max 60000).
|
| 587 |
+
"""
|
| 588 |
+
try:
|
| 589 |
+
path = _doc_index().get(doc_id)
|
| 590 |
+
if path is None:
|
| 591 |
+
return _err(f"unknown doc_id: {doc_id}",
|
| 592 |
+
hint="use list_dataset_documents to get valid doc_ids")
|
| 593 |
+
if not path.exists():
|
| 594 |
+
return _err(f"document file missing on disk: {path.name}")
|
| 595 |
+
text = path.read_text(encoding="utf-8", errors="replace")
|
| 596 |
+
offset = max(0, int(offset))
|
| 597 |
+
max_chars = max(1000, min(int(max_chars), 60_000))
|
| 598 |
+
page = text[offset:offset + max_chars]
|
| 599 |
+
out = {"ok": True, "doc_id": doc_id, "total_chars": len(text),
|
| 600 |
+
"offset": offset, "returned_chars": len(page),
|
| 601 |
+
"next_offset": offset + len(page) if offset + len(page) < len(text) else None,
|
| 602 |
+
"text": page}
|
| 603 |
+
if offset == 0:
|
| 604 |
+
outline, pos = [], 0
|
| 605 |
+
for line in text.splitlines(keepends=True):
|
| 606 |
+
if line.startswith("#"):
|
| 607 |
+
outline.append({"heading": line.strip()[:120], "offset": pos})
|
| 608 |
+
pos += len(line)
|
| 609 |
+
out["outline"] = outline[:60]
|
| 610 |
+
return out
|
| 611 |
+
except Exception as e:
|
| 612 |
+
_log(f"read_document failed: {repr(e)}")
|
| 613 |
+
return _err(f"read failed: {repr(e)[:200]}")
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
@lru_cache(maxsize=1)
|
| 617 |
+
def _registry() -> list[dict]:
|
| 618 |
+
# cached for process lifetime: restart server to pick up registry updates
|
| 619 |
+
if not REGISTRY.exists():
|
| 620 |
+
return []
|
| 621 |
+
return [json.loads(l) for l in REGISTRY.read_text().splitlines() if l.strip()]
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
@lru_cache(maxsize=1)
|
| 625 |
+
def _links_by_dataset() -> dict:
|
| 626 |
+
# dataset_id -> [paper records] materialized by pubs_rag/build_links_sidecar.py
|
| 627 |
+
# (registry direct + flagship citations, same logic as relink_full.py)
|
| 628 |
+
if not LINKS_SIDECAR.exists():
|
| 629 |
+
return {}
|
| 630 |
+
return json.loads(LINKS_SIDECAR.read_text(encoding="utf-8"))
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
@lru_cache(maxsize=1)
|
| 634 |
+
def _papers_by_id() -> dict:
|
| 635 |
+
"""Orphan-corpus parsed papers: paper_id and doi -> record with md_path.
|
| 636 |
+
|
| 637 |
+
Cached for process lifetime (like _registry): restart to pick up new papers.
|
| 638 |
+
"""
|
| 639 |
+
idx = {}
|
| 640 |
+
if PAPERS.exists():
|
| 641 |
+
for line in PAPERS.read_text().splitlines():
|
| 642 |
+
if not line.strip():
|
| 643 |
+
continue
|
| 644 |
+
p = json.loads(line)
|
| 645 |
+
idx[p["paper_id"]] = p
|
| 646 |
+
if p.get("doi"):
|
| 647 |
+
idx[p["doi"].lower()] = p
|
| 648 |
+
return idx
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
@mcp.tool()
|
| 652 |
+
def search_publications(query: str, domain: str | None = None,
|
| 653 |
+
dataset_or_product_id: str | None = None,
|
| 654 |
+
orphan_only: bool = False, top_k: int = 8,
|
| 655 |
+
rerank: bool = False) -> dict:
|
| 656 |
+
"""Level-3 METHODOLOGY search: semantic search over the scientific
|
| 657 |
+
publications RAG (parsed full-text paper chunks). Use it to learn HOW to
|
| 658 |
+
analyze data: methods, validation approaches, known analysis pitfalls.
|
| 659 |
+
|
| 660 |
+
Args:
|
| 661 |
+
query: natural-language question (e.g. "how to compute ocean heat
|
| 662 |
+
content trends from reanalysis").
|
| 663 |
+
domain: optional filter — one of ocean/marine, atmosphere, cryosphere,
|
| 664 |
+
land, climate-modeling, climate-general, emergency.
|
| 665 |
+
dataset_or_product_id: only papers LINKED to this Copernicus
|
| 666 |
+
product/collection (cited in its documentation).
|
| 667 |
+
orphan_only: only the general (non-dataset-linked) methodology corpus.
|
| 668 |
+
top_k: number of chunks to return (default 8).
|
| 669 |
+
rerank: also rerank with Google semantic-ranker (needs GCP ADC).
|
| 670 |
+
"""
|
| 671 |
+
try:
|
| 672 |
+
client = _pubs_qdrant()
|
| 673 |
+
if client is None:
|
| 674 |
+
return _err("publications index not built yet", status=_pubs_status())
|
| 675 |
+
if domain and domain not in PUB_DOMAINS:
|
| 676 |
+
return _err(f"unknown domain '{domain}'", valid=list(PUB_DOMAINS))
|
| 677 |
+
top_k = max(1, min(int(top_k), 20))
|
| 678 |
+
must = []
|
| 679 |
+
if domain:
|
| 680 |
+
must.append(models.FieldCondition(key="domains", match=models.MatchValue(value=domain)))
|
| 681 |
+
if orphan_only:
|
| 682 |
+
must.append(models.FieldCondition(key="orphan", match=models.MatchValue(value=True)))
|
| 683 |
+
if dataset_or_product_id:
|
| 684 |
+
pid = resolve_product(dataset_or_product_id) or dataset_or_product_id
|
| 685 |
+
must.append(models.FieldCondition(key="linked_products", match=models.MatchValue(value=pid)))
|
| 686 |
+
flt = models.Filter(must=must) if must else None
|
| 687 |
+
points, mode = _query(PUBS_COLLECTION, query, flt, max(top_k, 20), client=client)
|
| 688 |
+
points, reranked = _maybe_rerank(query, points, top_k, rerank)
|
| 689 |
+
results = [{
|
| 690 |
+
"doi": p.payload.get("doi"),
|
| 691 |
+
"title": p.payload.get("title"),
|
| 692 |
+
"journal": p.payload.get("journal"),
|
| 693 |
+
"year": p.payload.get("year"),
|
| 694 |
+
"domains": p.payload.get("domains"),
|
| 695 |
+
"section": p.payload.get("section"),
|
| 696 |
+
"orphan": p.payload.get("orphan"),
|
| 697 |
+
"linked_products": (p.payload.get("linked_products") or [])[:8],
|
| 698 |
+
"text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
|
| 699 |
+
"score": getattr(p, "score", None),
|
| 700 |
+
} for p in points[:top_k]]
|
| 701 |
+
return {"ok": True, "query": query, "retrieval": mode, "reranked": reranked,
|
| 702 |
+
"n_results": len(results), "results": results,
|
| 703 |
+
"next_step": "read_publication(doi) pulls a paper's full parsed text"}
|
| 704 |
+
except Exception as e:
|
| 705 |
+
_log(f"search_publications failed: {repr(e)}")
|
| 706 |
+
return _err(f"search failed: {repr(e)[:200]}")
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
@mcp.tool()
|
| 710 |
+
def get_dataset_publications(dataset_or_product_id: str, top_k: int = 15) -> dict:
|
| 711 |
+
"""List the scientific publications LINKED to one Copernicus dataset —
|
| 712 |
+
i.e. papers cited in its quality documentation (CMEMS PUM/QUID/SQO) or on
|
| 713 |
+
its CDS/ADS/EWDS references section. This is the dataset's literature:
|
| 714 |
+
validation papers, method papers, foundational references.
|
| 715 |
+
|
| 716 |
+
Args:
|
| 717 |
+
dataset_or_product_id: CMEMS product/dataset id or CDS/ADS/EWDS
|
| 718 |
+
collection id.
|
| 719 |
+
top_k: max publications to return (default 15), most-cited first.
|
| 720 |
+
"""
|
| 721 |
+
try:
|
| 722 |
+
pid = resolve_product(dataset_or_product_id) or dataset_or_product_id
|
| 723 |
+
low = {pid.lower(), dataset_or_product_id.lower()}
|
| 724 |
+
parsed = _papers_by_id()
|
| 725 |
+
|
| 726 |
+
# primary: materialized links sidecar (registry direct + flagship citers)
|
| 727 |
+
seen: set[str] = set()
|
| 728 |
+
merged: list[dict] = []
|
| 729 |
+
by_ds = _links_by_dataset()
|
| 730 |
+
for ds, recs in by_ds.items():
|
| 731 |
+
if ds.lower() not in low:
|
| 732 |
+
continue
|
| 733 |
+
for r in recs:
|
| 734 |
+
doi = (r.get("doi") or "").lower()
|
| 735 |
+
if doi in seen:
|
| 736 |
+
continue
|
| 737 |
+
seen.add(doi)
|
| 738 |
+
merged.append({
|
| 739 |
+
"doi": r.get("doi"), "title": r.get("title"),
|
| 740 |
+
"journal": r.get("journal"), "year": r.get("year"),
|
| 741 |
+
"citations_count": r.get("cited_by_count"),
|
| 742 |
+
"link_via": r.get("via"),
|
| 743 |
+
"flagship_labels": r.get("flagship_labels") or None,
|
| 744 |
+
"full_text_available": doi in parsed,
|
| 745 |
+
})
|
| 746 |
+
|
| 747 |
+
# secondary: registry papers not in the parsed corpus (metadata-only)
|
| 748 |
+
for r in _registry():
|
| 749 |
+
doi = (r.get("doi") or "").lower()
|
| 750 |
+
if doi in seen:
|
| 751 |
+
continue
|
| 752 |
+
if not any((p or "").lower() in low for p in r.get("linked_products", [])):
|
| 753 |
+
continue
|
| 754 |
+
seen.add(doi)
|
| 755 |
+
merged.append({
|
| 756 |
+
"doi": r["doi"], "title": r.get("title"),
|
| 757 |
+
"journal": r.get("journal"), "year": r.get("year"),
|
| 758 |
+
"authors": (r.get("authors") or [])[:6],
|
| 759 |
+
"n_mentions": r.get("n_mentions"),
|
| 760 |
+
"citations_count": r.get("citations_count"),
|
| 761 |
+
"pdf_status": r.get("pdf_status"),
|
| 762 |
+
"link_via": ["registry"],
|
| 763 |
+
"full_text_available": doi in parsed,
|
| 764 |
+
})
|
| 765 |
+
|
| 766 |
+
merged.sort(key=lambda r: (-int(bool(r.get("full_text_available"))),
|
| 767 |
+
-(r.get("citations_count") or 0)))
|
| 768 |
+
results = merged[:max(1, min(int(top_k), 50))]
|
| 769 |
+
return {"ok": True, "id": pid, "n_linked_publications": len(merged),
|
| 770 |
+
"results": results,
|
| 771 |
+
"next_step": ("read_publication(doi) for full text where "
|
| 772 |
+
"full_text_available; otherwise metadata only for now")}
|
| 773 |
+
except Exception as e:
|
| 774 |
+
_log(f"get_dataset_publications failed: {repr(e)}")
|
| 775 |
+
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
@mcp.tool()
|
| 779 |
+
def read_publication(doi_or_paper_id: str, offset: int = 0,
|
| 780 |
+
max_chars: int = READ_DEFAULT) -> dict:
|
| 781 |
+
"""Pull the full parsed markdown text of one publication, paginated
|
| 782 |
+
(same contract as read_document: page 0 includes a heading outline).
|
| 783 |
+
Works for papers in the parsed corpus; for registry papers whose PDF is
|
| 784 |
+
not parsed yet it returns their metadata + abstract instead.
|
| 785 |
+
|
| 786 |
+
Args:
|
| 787 |
+
doi_or_paper_id: canonical DOI ("10.x/...") or underscored paper_id.
|
| 788 |
+
offset: character offset (default 0).
|
| 789 |
+
max_chars: page size (default 20000, max 60000).
|
| 790 |
+
"""
|
| 791 |
+
try:
|
| 792 |
+
key = doi_or_paper_id.strip()
|
| 793 |
+
paper = _papers_by_id().get(key) or _papers_by_id().get(key.lower())
|
| 794 |
+
if paper and paper.get("md_path") and Path(paper["md_path"]).exists():
|
| 795 |
+
text = Path(paper["md_path"]).read_text(encoding="utf-8", errors="replace")
|
| 796 |
+
offset = max(0, int(offset))
|
| 797 |
+
max_chars = max(1000, min(int(max_chars), 60_000))
|
| 798 |
+
page = text[offset:offset + max_chars]
|
| 799 |
+
out = {"ok": True, "doi": paper.get("doi"), "title": paper.get("title"),
|
| 800 |
+
"journal": paper.get("journal"), "year": paper.get("year"),
|
| 801 |
+
"total_chars": len(text), "offset": offset,
|
| 802 |
+
"returned_chars": len(page),
|
| 803 |
+
"next_offset": offset + len(page) if offset + len(page) < len(text) else None,
|
| 804 |
+
"text": page}
|
| 805 |
+
if offset == 0:
|
| 806 |
+
outline, pos = [], 0
|
| 807 |
+
for line in text.splitlines(keepends=True):
|
| 808 |
+
if line.startswith("#"):
|
| 809 |
+
outline.append({"heading": line.strip()[:120], "offset": pos})
|
| 810 |
+
pos += len(line)
|
| 811 |
+
out["outline"] = outline[:60]
|
| 812 |
+
return out
|
| 813 |
+
# not parsed — fall back to registry metadata
|
| 814 |
+
low = key.lower()
|
| 815 |
+
rec = next((r for r in _registry() if r["doi"].lower() == low), None)
|
| 816 |
+
if rec:
|
| 817 |
+
return {"ok": True, "full_text": False,
|
| 818 |
+
"reason": f"not parsed yet (pdf_status: {rec.get('pdf_status')})",
|
| 819 |
+
"doi": rec["doi"], "title": rec.get("title"),
|
| 820 |
+
"journal": rec.get("journal"), "year": rec.get("year"),
|
| 821 |
+
"authors": rec.get("authors"), "abstract": rec.get("abstract"),
|
| 822 |
+
"linked_products": (rec.get("linked_products") or [])[:15]}
|
| 823 |
+
return _err(f"unknown publication: {key}",
|
| 824 |
+
hint="use a DOI from search_publications / get_dataset_publications")
|
| 825 |
+
except Exception as e:
|
| 826 |
+
_log(f"read_publication failed: {repr(e)}")
|
| 827 |
+
return _err(f"read failed: {repr(e)[:200]}")
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
@mcp.tool()
|
| 831 |
+
def get_eqc_quality_report(query: str, dataset_id: str | None = None,
|
| 832 |
+
aspect: str | None = None, top_k: int = 8,
|
| 833 |
+
rerank: bool = False) -> dict:
|
| 834 |
+
"""CDS/C3S EQC Quality Assessment reports — the curated fitness-for-purpose
|
| 835 |
+
assessments (consistency, completeness, etc.) for ~27 climate datasets that
|
| 836 |
+
carry the "Quality Assurance" badge in the CDS catalogue. Use this to judge
|
| 837 |
+
whether a CDS/ADS/EWDS dataset is suitable for a use case, to compare
|
| 838 |
+
alternative datasets on quality criteria, or to surface known limitations.
|
| 839 |
+
|
| 840 |
+
Complements get_dataset_docs (which serves CMEMS Marine PUM/QUID/SQO):
|
| 841 |
+
this tool serves the CDS-side quality knowledge.
|
| 842 |
+
|
| 843 |
+
Args:
|
| 844 |
+
query: natural-language question (e.g. "is the C3S atlas temperature
|
| 845 |
+
consistent across origins", "completeness of satellite soil moisture").
|
| 846 |
+
dataset_id: optional filter — a CDS collection id (e.g.
|
| 847 |
+
"multi-origin-c3s-atlas", "satellite-sea-surface-temperature").
|
| 848 |
+
aspect: optional filter — quality aspect prefix (e.g. "consistency",
|
| 849 |
+
"completeness").
|
| 850 |
+
top_k: number of report chunks to return (default 8).
|
| 851 |
+
rerank: also rerank with Google semantic-ranker (needs GCP ADC).
|
| 852 |
+
"""
|
| 853 |
+
try:
|
| 854 |
+
client = _eqc_qdrant()
|
| 855 |
+
if client is None:
|
| 856 |
+
return _err("EQC-QA index not built yet",
|
| 857 |
+
status="CDS quality-assessment reports are being embedded "
|
| 858 |
+
"and indexed — retry shortly")
|
| 859 |
+
top_k = max(1, min(int(top_k), 20))
|
| 860 |
+
must = []
|
| 861 |
+
if dataset_id:
|
| 862 |
+
must.append(models.FieldCondition(key="dataset_id",
|
| 863 |
+
match=models.MatchValue(value=dataset_id)))
|
| 864 |
+
if aspect:
|
| 865 |
+
must.append(models.FieldCondition(key="aspect_base",
|
| 866 |
+
match=models.MatchValue(value=aspect.lower())))
|
| 867 |
+
flt = models.Filter(must=must) if must else None
|
| 868 |
+
points, mode = _query(EQC_QA_COLLECTION, query, flt, max(top_k, 20), client=client)
|
| 869 |
+
points, reranked = _maybe_rerank(query, points, top_k, rerank)
|
| 870 |
+
results = [{
|
| 871 |
+
"dataset_id": p.payload.get("dataset_id"),
|
| 872 |
+
"report_id": p.payload.get("report_id"),
|
| 873 |
+
"aspect": p.payload.get("aspect"),
|
| 874 |
+
"title": p.payload.get("title"),
|
| 875 |
+
"section": p.payload.get("section"),
|
| 876 |
+
"text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
|
| 877 |
+
"code_notebooks": _nb_refs(p.payload.get("dataset_id")),
|
| 878 |
+
"score": getattr(p, "score", None),
|
| 879 |
+
} for p in points[:top_k]]
|
| 880 |
+
return {"ok": True, "query": query, "retrieval": mode, "reranked": reranked,
|
| 881 |
+
"n_results": len(results), "results": results,
|
| 882 |
+
"source": "c3s2-eqc-quality-assessment (CDS EQC QA reports)",
|
| 883 |
+
"next_step": ("where a result has code_notebooks[], call "
|
| 884 |
+
"get_dataset_code(dataset_id, notebook_id=...) for the runnable code")}
|
| 885 |
+
except Exception as e:
|
| 886 |
+
_log(f"get_eqc_quality_report failed: {repr(e)}")
|
| 887 |
+
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
@mcp.tool()
|
| 891 |
+
def get_dataset_code(dataset_id: str, notebook_id: str | None = None,
|
| 892 |
+
kind: str | None = None, offset: int = 0,
|
| 893 |
+
max_chars: int = READ_DEFAULT) -> dict:
|
| 894 |
+
"""Runnable CODE examples (Jupyter notebook cells) ATTACHED to a Copernicus
|
| 895 |
+
dataset: how to DOWNLOAD and ANALYZE it. Code is not embedded/searched on its
|
| 896 |
+
own — it rides along on the dataset, sourced from official example notebooks
|
| 897 |
+
(e.g. the C3S EQC quality-assessment notebooks). Reach it from a
|
| 898 |
+
search_datasets / get_eqc_quality_report hit whose notebooks[] is non-empty.
|
| 899 |
+
|
| 900 |
+
Two modes:
|
| 901 |
+
• dataset_id only -> LIST the notebooks attached to that dataset (id, title,
|
| 902 |
+
recipe kinds download/analyze/plot, size, source repo + licence).
|
| 903 |
+
• + notebook_id -> the FULL reconstructed notebook (verbatim ```python
|
| 904 |
+
cells + markdown + text outputs), paginated like read_document.
|
| 905 |
+
|
| 906 |
+
Args:
|
| 907 |
+
dataset_id: a CDS/ADS/EWDS collection id or CMEMS product/dataset id
|
| 908 |
+
(e.g. "satellite-sea-surface-temperature", "projections-cmip6").
|
| 909 |
+
notebook_id: pull one notebook's full code (from the list mode).
|
| 910 |
+
kind: optional filter for list mode — download, analyze or plot.
|
| 911 |
+
offset: character offset for the full-notebook mode (default 0).
|
| 912 |
+
max_chars: page size for the full-notebook mode (default 20000, max 60000).
|
| 913 |
+
"""
|
| 914 |
+
try:
|
| 915 |
+
by_ds, by_id, generic = _notebooks()
|
| 916 |
+
if not by_ds and not generic:
|
| 917 |
+
return _err("notebook code layer not built yet",
|
| 918 |
+
status="example notebooks are being extracted and attached")
|
| 919 |
+
if notebook_id:
|
| 920 |
+
rec = by_id.get(notebook_id)
|
| 921 |
+
if not rec:
|
| 922 |
+
return _err(f"unknown notebook_id: {notebook_id}",
|
| 923 |
+
hint="call get_dataset_code(dataset_id) to list attached notebooks")
|
| 924 |
+
path = ROOT.parent / rec["md_path"]
|
| 925 |
+
if not path.exists():
|
| 926 |
+
return _err(f"notebook file missing on disk: {path.name}")
|
| 927 |
+
text = path.read_text(encoding="utf-8", errors="replace")
|
| 928 |
+
offset = max(0, int(offset))
|
| 929 |
+
max_chars = max(1000, min(int(max_chars), 60_000))
|
| 930 |
+
page = text[offset:offset + max_chars]
|
| 931 |
+
return {"ok": True, "notebook_id": notebook_id, "title": rec.get("title"),
|
| 932 |
+
"dataset_id": rec.get("matched_dataset_id"), "store": rec.get("store"),
|
| 933 |
+
"recipe_kinds": rec.get("recipe_kinds"),
|
| 934 |
+
"source_repo": rec.get("source_repo"), "license": rec.get("license"),
|
| 935 |
+
"src_path": rec.get("src_path"),
|
| 936 |
+
"total_chars": len(text), "offset": offset,
|
| 937 |
+
"returned_chars": len(page),
|
| 938 |
+
"next_offset": offset + len(page) if offset + len(page) < len(text) else None,
|
| 939 |
+
"text": page}
|
| 940 |
+
# list mode — dataset-specific notebooks + a store-level generic how-to fallback
|
| 941 |
+
recs = by_ds.get(dataset_id) or by_ds.get(dataset_id.lower())
|
| 942 |
+
if not recs:
|
| 943 |
+
pid = resolve_product(dataset_id)
|
| 944 |
+
if pid:
|
| 945 |
+
recs = by_ds.get(pid)
|
| 946 |
+
recs = recs or []
|
| 947 |
+
store = next((r.get("store") for r in recs if r.get("store")), None)
|
| 948 |
+
if not store:
|
| 949 |
+
store = "CMEMS" if resolve_product(dataset_id) else None
|
| 950 |
+
|
| 951 |
+
def _brief(r, scope):
|
| 952 |
+
return {"notebook_id": r["notebook_id"], "title": r.get("title"),
|
| 953 |
+
"scope": scope, "recipe_kinds": r.get("recipe_kinds"),
|
| 954 |
+
"n_code_cells": r.get("n_code_cells"),
|
| 955 |
+
"n_code_lines": r.get("n_code_lines"), "aspect": r.get("aspect"),
|
| 956 |
+
"source_repo": r.get("source_repo"), "license": r.get("license")}
|
| 957 |
+
|
| 958 |
+
notebooks = [_brief(r, "dataset") for r in recs
|
| 959 |
+
if not kind or kind in (r.get("recipe_kinds") or [])]
|
| 960 |
+
generic_how_to = [_brief(r, "generic") for r in (generic.get(store) or [])
|
| 961 |
+
if not kind or kind in (r.get("recipe_kinds") or [])]
|
| 962 |
+
if not notebooks and not generic_how_to:
|
| 963 |
+
return _err(f"no notebooks attached to '{dataset_id}'",
|
| 964 |
+
hint="notebooks cover CDS/ADS/EWDS + CMEMS example datasets",
|
| 965 |
+
example_ids=sorted(by_ds)[:12])
|
| 966 |
+
return {"ok": True, "dataset_id": dataset_id, "store": store,
|
| 967 |
+
"n_notebooks": len(notebooks), "notebooks": notebooks,
|
| 968 |
+
"generic_how_to": generic_how_to,
|
| 969 |
+
"next_step": ("call get_dataset_code(dataset_id, notebook_id=...) "
|
| 970 |
+
"for one notebook's full runnable code")}
|
| 971 |
+
except Exception as e:
|
| 972 |
+
_log(f"get_dataset_code failed: {repr(e)}")
|
| 973 |
+
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
@mcp.tool()
|
| 977 |
+
def search_deep_docs(query: str, store: str | None = None, top_k: int = 8,
|
| 978 |
+
rerank: bool = False) -> dict:
|
| 979 |
+
"""Global semantic search across the DEEP documentation of the non-marine
|
| 980 |
+
stores — CDS (climate/ERA5), ADS (atmosphere/CAMS), EWDS (emergency/flood/
|
| 981 |
+
fire): Confluence user guides, ATBDs, product specs and PDFs (~23k chunks
|
| 982 |
+
over 165 datasets). The non-marine counterpart to search_docs (which covers
|
| 983 |
+
CMEMS PUM/QUID/SQO). Use for cross-dataset climate/atmosphere/emergency
|
| 984 |
+
questions ("ERA5-Land soil moisture accuracy", "CAMS aerosol assimilation").
|
| 985 |
+
|
| 986 |
+
Args:
|
| 987 |
+
query: natural-language question.
|
| 988 |
+
store: optional filter — CDS, ADS or EWDS.
|
| 989 |
+
top_k: number of chunks to return (default 8).
|
| 990 |
+
rerank: also rerank with Google semantic-ranker (needs GCP ADC).
|
| 991 |
+
"""
|
| 992 |
+
try:
|
| 993 |
+
client = _deep_qdrant()
|
| 994 |
+
if client is None:
|
| 995 |
+
return _err("deep-docs index not built yet",
|
| 996 |
+
status="CDS/ADS/EWDS documentation is being fetched, chunked "
|
| 997 |
+
"and embedded — retry shortly")
|
| 998 |
+
if store:
|
| 999 |
+
store = store.upper()
|
| 1000 |
+
if store not in ("CDS", "ADS", "EWDS"):
|
| 1001 |
+
return _err(f"unknown store '{store}'", valid=["CDS", "ADS", "EWDS"])
|
| 1002 |
+
top_k = max(1, min(int(top_k), 20))
|
| 1003 |
+
flt = models.Filter(must=[models.FieldCondition(
|
| 1004 |
+
key="store", match=models.MatchValue(value=store))]) if store else None
|
| 1005 |
+
points, mode = _query(DEEP_COLLECTION, query, flt, max(top_k, 20), client=client)
|
| 1006 |
+
points, reranked = _maybe_rerank(query, points, top_k, rerank)
|
| 1007 |
+
results = [{
|
| 1008 |
+
"store": p.payload.get("store"),
|
| 1009 |
+
"dataset_ids": (p.payload.get("dataset_ids") or [])[:6],
|
| 1010 |
+
"doc_title": p.payload.get("doc_title"),
|
| 1011 |
+
"doc_url": p.payload.get("doc_url"),
|
| 1012 |
+
"section": p.payload.get("section"),
|
| 1013 |
+
"text": (p.payload.get("text_raw") or "")[:MAX_TEXT],
|
| 1014 |
+
"score": getattr(p, "score", None),
|
| 1015 |
+
} for p in points[:top_k]]
|
| 1016 |
+
return {"ok": True, "query": query, "store": store or "CDS/ADS/EWDS",
|
| 1017 |
+
"retrieval": mode, "reranked": reranked,
|
| 1018 |
+
"n_results": len(results), "results": results}
|
| 1019 |
+
except Exception as e:
|
| 1020 |
+
_log(f"search_deep_docs failed: {repr(e)}")
|
| 1021 |
+
return _err(f"search failed: {repr(e)[:200]}")
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
if __name__ == "__main__":
|
| 1025 |
+
_log("starting copernicus-rag MCP server (stdio)")
|
| 1026 |
+
mcp.run()
|
scripts/marine_rag/run_overnight.sh
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# run_overnight.sh — autonomous marine-docs RAG finisher.
|
| 3 |
+
# Retries the API-dependent steps every 10 min until the Gemini key's IP
|
| 4 |
+
# restriction is lifted, then embeds → indexes → verifies, and stops.
|
| 5 |
+
# Phases A/B (catalog, tree, chunking) are already done.
|
| 6 |
+
set -uo pipefail
|
| 7 |
+
|
| 8 |
+
cd /Users/dmpantiu/copernicus_mcp/marine_rag
|
| 9 |
+
PY=/Users/dmpantiu/cmip6/cmip6_gpt/.venv/bin/python
|
| 10 |
+
LOG=out/overnight.log
|
| 11 |
+
INTERVAL=600 # 10 minutes
|
| 12 |
+
MAX_RETRIES=66 # ~11 hours
|
| 13 |
+
TOTAL_CHUNKS=$(wc -l < out/chunks.jsonl | tr -d ' ')
|
| 14 |
+
|
| 15 |
+
ts() { date '+%Y-%m-%d %H:%M:%S'; }
|
| 16 |
+
log() { echo "[$(ts)] $*" | tee -a "$LOG"; }
|
| 17 |
+
|
| 18 |
+
log "=== overnight runner started. total chunks=$TOTAL_CHUNKS ==="
|
| 19 |
+
|
| 20 |
+
embedded_count() { [ -f out/chunks_embedded.jsonl ] && wc -l < out/chunks_embedded.jsonl | tr -d ' ' || echo 0; }
|
| 21 |
+
|
| 22 |
+
attempt=0
|
| 23 |
+
while [ "$attempt" -lt "$MAX_RETRIES" ]; do
|
| 24 |
+
attempt=$((attempt+1))
|
| 25 |
+
have=$(embedded_count)
|
| 26 |
+
log "attempt $attempt/$MAX_RETRIES — embedded $have/$TOTAL_CHUNKS"
|
| 27 |
+
|
| 28 |
+
if [ "$have" -ge "$TOTAL_CHUNKS" ]; then
|
| 29 |
+
log "all chunks embedded — proceeding to index."
|
| 30 |
+
break
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
# Resumable embed; stream output to log (don't buffer — run is ~60 min at 5 RPM).
|
| 34 |
+
$PY embed.py --mode realtime >> "$LOG" 2>&1
|
| 35 |
+
if tail -5 "$LOG" | grep -q "IP address restriction"; then
|
| 36 |
+
log "BLOCKED: Gemini key IP restriction active. Whitelist IP, will retry in ${INTERVAL}s."
|
| 37 |
+
sleep "$INTERVAL"
|
| 38 |
+
continue
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
have=$(embedded_count)
|
| 42 |
+
if [ "$have" -ge "$TOTAL_CHUNKS" ]; then
|
| 43 |
+
log "embedding complete: $have/$TOTAL_CHUNKS"
|
| 44 |
+
break
|
| 45 |
+
fi
|
| 46 |
+
log "partial/failed embed ($have/$TOTAL_CHUNKS) — retry in ${INTERVAL}s"
|
| 47 |
+
sleep "$INTERVAL"
|
| 48 |
+
done
|
| 49 |
+
|
| 50 |
+
have=$(embedded_count)
|
| 51 |
+
if [ "$have" -lt "$TOTAL_CHUNKS" ]; then
|
| 52 |
+
log "EXIT: did not finish embedding ($have/$TOTAL_CHUNKS) after $attempt attempts."
|
| 53 |
+
exit 2
|
| 54 |
+
fi
|
| 55 |
+
|
| 56 |
+
log "indexing into Qdrant (local mode)…"
|
| 57 |
+
$PY load_qdrant.py --recreate 2>&1 | tee -a "$LOG"
|
| 58 |
+
|
| 59 |
+
log "verification search…"
|
| 60 |
+
$PY search.py "how is sea surface salinity validated" --top-k 3 2>&1 | tee -a "$LOG"
|
| 61 |
+
|
| 62 |
+
log "=== overnight runner DONE: embedded=$have, indexed, verified. ==="
|
scripts/marine_rag/search.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
search.py — Hybrid retrieval over marine docs + Google reranker.
|
| 4 |
+
|
| 5 |
+
Pipeline:
|
| 6 |
+
1. embed query with gemini-embedding-2-preview (RETRIEVAL_QUERY, 768-dim)
|
| 7 |
+
2. Qdrant hybrid: dense (Cosine) + sparse (BM25), RRF fusion
|
| 8 |
+
3. rerank top candidates with Google Vertex AI Rank API
|
| 9 |
+
(semantic-ranker-default@latest) — NOT an LLM. Needs GCP ADC + project.
|
| 10 |
+
Falls back to fusion order if ADC/project unavailable.
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python search.py "how is Mediterranean salinity validated" --top-k 5 --rerank
|
| 14 |
+
python search.py "Arctic sea ice concentration accuracy" --product OMI...
|
| 15 |
+
"""
|
| 16 |
+
import argparse
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import threading
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import net_ipv4 # noqa: F401 — force IPv4 egress (VPN), must precede genai client
|
| 23 |
+
|
| 24 |
+
from qdrant_client import QdrantClient, models
|
| 25 |
+
from fastembed import SparseTextEmbedding
|
| 26 |
+
|
| 27 |
+
ROOT = Path(__file__).resolve().parent
|
| 28 |
+
OUT = ROOT / "out"
|
| 29 |
+
COLLECTION = "marine_docs"
|
| 30 |
+
DENSE_DIM = 768
|
| 31 |
+
LOCAL_DB = OUT / "qdrant_db"
|
| 32 |
+
RANK_MODEL = "semantic-ranker-default@latest"
|
| 33 |
+
|
| 34 |
+
_bm25 = None
|
| 35 |
+
_bm25_lock = threading.Lock()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def resolve_key() -> str:
|
| 39 |
+
for var in ("GOOGLE_API_KEY", "GEMINI_API_KEY"):
|
| 40 |
+
if os.environ.get(var):
|
| 41 |
+
return os.environ[var]
|
| 42 |
+
for env in (Path("/Users/dmpantiu/copernicus_mcp/.env"),
|
| 43 |
+
Path("/Users/dmpantiu/cmip6/cmip6_gpt/.env")):
|
| 44 |
+
if env.exists():
|
| 45 |
+
for line in env.read_text().splitlines():
|
| 46 |
+
line = line.strip()
|
| 47 |
+
if "api_key" in line.lower() and "=" in line and not line.startswith("#"):
|
| 48 |
+
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
| 49 |
+
raise SystemExit("No Gemini API key.")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def embed_query(query: str) -> list[float]:
|
| 53 |
+
from google import genai
|
| 54 |
+
from google.genai import types
|
| 55 |
+
client = genai.Client(api_key=resolve_key())
|
| 56 |
+
r = client.models.embed_content(
|
| 57 |
+
model="gemini-embedding-2-preview", contents=query,
|
| 58 |
+
config=types.EmbedContentConfig(task_type="RETRIEVAL_QUERY", output_dimensionality=DENSE_DIM))
|
| 59 |
+
import numpy as np
|
| 60 |
+
v = np.array(list(r.embeddings[0].values), dtype=np.float32)
|
| 61 |
+
n = np.linalg.norm(v)
|
| 62 |
+
return (v / n).tolist() if n > 0 else v.tolist()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def sparse_query(query: str) -> models.SparseVector:
|
| 66 |
+
global _bm25
|
| 67 |
+
with _bm25_lock: # tools may run on multiple threads (FastMCP)
|
| 68 |
+
if _bm25 is None:
|
| 69 |
+
_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
|
| 70 |
+
sp = list(_bm25.query_embed(query))[0]
|
| 71 |
+
return models.SparseVector(indices=sp.indices.tolist(), values=sp.values.tolist())
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_client(url=None) -> QdrantClient:
|
| 75 |
+
return QdrantClient(url=url, check_compatibility=False) if url else QdrantClient(path=str(LOCAL_DB))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def hybrid(client, query, top_k=5, prefetch=50, product_id=None, doc_type=None):
|
| 79 |
+
flt = None
|
| 80 |
+
must = []
|
| 81 |
+
if product_id:
|
| 82 |
+
must.append(models.FieldCondition(key="product_id", match=models.MatchValue(value=product_id)))
|
| 83 |
+
if doc_type:
|
| 84 |
+
must.append(models.FieldCondition(key="doc_type", match=models.MatchValue(value=doc_type)))
|
| 85 |
+
if must:
|
| 86 |
+
flt = models.Filter(must=must)
|
| 87 |
+
res = client.query_points(
|
| 88 |
+
collection_name=COLLECTION,
|
| 89 |
+
prefetch=[
|
| 90 |
+
models.Prefetch(query=embed_query(query), using="dense", limit=prefetch, filter=flt),
|
| 91 |
+
models.Prefetch(query=sparse_query(query), using="sparse", limit=prefetch, filter=flt),
|
| 92 |
+
],
|
| 93 |
+
query=models.FusionQuery(fusion=models.Fusion.RRF),
|
| 94 |
+
limit=prefetch, with_payload=True,
|
| 95 |
+
)
|
| 96 |
+
return res.points[:max(top_k, prefetch)]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def rerank_google(query, points, top_k):
|
| 100 |
+
"""Vertex AI Rank API. Needs ADC + GCP project (GCP_PROJECT env)."""
|
| 101 |
+
try:
|
| 102 |
+
from google.cloud import discoveryengine_v1 as de
|
| 103 |
+
project = os.environ.get("GCP_PROJECT")
|
| 104 |
+
if not project:
|
| 105 |
+
return None
|
| 106 |
+
client = de.RankServiceClient()
|
| 107 |
+
cfg = client.ranking_config_path(project=project, location="global",
|
| 108 |
+
ranking_config="default_ranking_config")
|
| 109 |
+
records = [de.RankingRecord(id=str(i), content=p.payload.get("text_raw", ""))
|
| 110 |
+
for i, p in enumerate(points)]
|
| 111 |
+
resp = client.rank(request=de.RankRequest(
|
| 112 |
+
ranking_config=cfg, model=RANK_MODEL, query=query,
|
| 113 |
+
records=records, top_n=top_k))
|
| 114 |
+
order = [int(r.id) for r in resp.records]
|
| 115 |
+
return [points[i] for i in order][:top_k]
|
| 116 |
+
except Exception as e:
|
| 117 |
+
# stderr only: stdout is the MCP JSON-RPC channel when used by rag_server
|
| 118 |
+
print(f"[rerank] unavailable ({repr(e)[:80]}); using fusion order", file=sys.stderr)
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def main():
|
| 123 |
+
ap = argparse.ArgumentParser()
|
| 124 |
+
ap.add_argument("query")
|
| 125 |
+
ap.add_argument("--top-k", type=int, default=5)
|
| 126 |
+
ap.add_argument("--rerank", action="store_true")
|
| 127 |
+
ap.add_argument("--product", type=str, default=None)
|
| 128 |
+
ap.add_argument("--doc-type", type=str, default=None)
|
| 129 |
+
ap.add_argument("--url", type=str, default=None)
|
| 130 |
+
a = ap.parse_args()
|
| 131 |
+
client = get_client(a.url)
|
| 132 |
+
points = hybrid(client, a.query, a.top_k, 50, a.product, a.doc_type)
|
| 133 |
+
if a.rerank:
|
| 134 |
+
rr = rerank_google(a.query, points, a.top_k)
|
| 135 |
+
if rr is not None:
|
| 136 |
+
points = rr
|
| 137 |
+
for i, p in enumerate(points[:a.top_k], 1):
|
| 138 |
+
pl = p.payload
|
| 139 |
+
print(f"\n#{i} {pl['product_id']} · {pl['doc_type']} · {pl.get('section_path','')[:60]}")
|
| 140 |
+
print(f" {pl.get('text_raw','')[:300].strip()}")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
+
main()
|
scripts/marine_rag/verify_copernicus_docs.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
verify_copernicus_docs.py — sanity-check the unified copernicus_docs index
|
| 4 |
+
WITHOUT hitting the Gemini quota:
|
| 5 |
+
|
| 6 |
+
1. point counts per store
|
| 7 |
+
2. BM25 (sparse) keyword queries per domain — local FastEmbed, no API
|
| 8 |
+
3. dense neighbour check — reuse a stored card vector as the query vector
|
| 9 |
+
|
| 10 |
+
Prints top hits so we can eyeball that the right datasets surface per store.
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from qdrant_client import QdrantClient, models
|
| 16 |
+
from fastembed import SparseTextEmbedding
|
| 17 |
+
|
| 18 |
+
OUT = Path(__file__).resolve().parent / "out"
|
| 19 |
+
COLLECTION = "copernicus_docs"
|
| 20 |
+
client = QdrantClient(path=str(OUT / "qdrant_db"))
|
| 21 |
+
_bm25 = SparseTextEmbedding(model_name="Qdrant/bm25")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def sparse(text):
|
| 25 |
+
r = list(_bm25.embed([text]))[0]
|
| 26 |
+
return models.SparseVector(indices=r.indices.tolist(), values=r.values.tolist())
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def kw_search(q, k=5, store=None):
|
| 30 |
+
flt = models.Filter(must=[models.FieldCondition(key="store", match=models.MatchValue(value=store))]) if store else None
|
| 31 |
+
res = client.query_points(collection_name=COLLECTION, query=sparse(q),
|
| 32 |
+
using="sparse", limit=k, with_payload=True, query_filter=flt).points
|
| 33 |
+
return res
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
info = client.get_collection(COLLECTION)
|
| 38 |
+
print(f"=== {COLLECTION}: {info.points_count} points ===\n")
|
| 39 |
+
|
| 40 |
+
# per-store counts
|
| 41 |
+
print("per-store counts:")
|
| 42 |
+
for s in ("CMEMS", "CDS", "ADS", "EWDS"):
|
| 43 |
+
cnt = client.count(collection_name=COLLECTION,
|
| 44 |
+
count_filter=models.Filter(must=[models.FieldCondition(
|
| 45 |
+
key="store", match=models.MatchValue(value=s))])).count
|
| 46 |
+
print(f" {s:6s} {cnt}")
|
| 47 |
+
|
| 48 |
+
# BM25 keyword probes across domains
|
| 49 |
+
probes = [
|
| 50 |
+
("sea surface temperature satellite", None),
|
| 51 |
+
("greenhouse gas carbon dioxide forecast", "ADS"),
|
| 52 |
+
("river discharge flood forecast europe", "EWDS"),
|
| 53 |
+
("ERA5 reanalysis climate", "CDS"),
|
| 54 |
+
("ocean salinity mediterranean", "CMEMS"),
|
| 55 |
+
("wildfire fire danger", None),
|
| 56 |
+
]
|
| 57 |
+
print("\n=== BM25 keyword probes ===")
|
| 58 |
+
for q, store in probes:
|
| 59 |
+
print(f"\nQ: {q!r}" + (f" [store={store}]" if store else ""))
|
| 60 |
+
for p in kw_search(q, k=4, store=store):
|
| 61 |
+
pl = p.payload
|
| 62 |
+
print(f" {p.score:5.2f} [{pl.get('store'):5s}] {pl.get('dataset_id','')[:45]:45s} {pl.get('product_title','')[:40]}")
|
| 63 |
+
|
| 64 |
+
# dense neighbour check — take one CDS card's stored vector, find nearest
|
| 65 |
+
print("\n=== dense neighbour check (stored vector as query) ===")
|
| 66 |
+
sample = client.scroll(collection_name=COLLECTION, limit=1, with_vectors=True,
|
| 67 |
+
scroll_filter=models.Filter(must=[models.FieldCondition(
|
| 68 |
+
key="store", match=models.MatchValue(value="CDS"))]))[0][0]
|
| 69 |
+
print(f"seed: [{sample.payload['store']}] {sample.payload.get('dataset_id')}")
|
| 70 |
+
nn = client.query_points(collection_name=COLLECTION, query=sample.vector["dense"],
|
| 71 |
+
using="dense", limit=5, with_payload=True).points
|
| 72 |
+
for p in nn:
|
| 73 |
+
print(f" {p.score:5.3f} [{p.payload.get('store'):5s}] {p.payload.get('dataset_id','')[:45]}")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
scripts/meta_harvest/01_dump_cmems.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Dump the full CMEMS catalogue via copernicusmarine.describe() to raw JSON."""
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
OUT = "/Users/dmpantiu/copernicus_mcp/meta_harvest/raw/cmems_describe_full.json"
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
if os.path.exists(OUT) and os.path.getsize(OUT) > 10_000_000:
|
| 12 |
+
print(f"already exists ({os.path.getsize(OUT)} bytes), skipping")
|
| 13 |
+
return
|
| 14 |
+
import copernicusmarine
|
| 15 |
+
t0 = time.time()
|
| 16 |
+
cat = copernicusmarine.describe(
|
| 17 |
+
show_all_versions=True,
|
| 18 |
+
disable_progress_bar=True,
|
| 19 |
+
)
|
| 20 |
+
print(f"describe() took {time.time()-t0:.1f}s")
|
| 21 |
+
# pydantic v2 model
|
| 22 |
+
data = cat.model_dump(mode="json", exclude_none=False)
|
| 23 |
+
tmp = OUT + ".tmp"
|
| 24 |
+
with open(tmp, "w") as f:
|
| 25 |
+
json.dump(data, f)
|
| 26 |
+
os.replace(tmp, OUT)
|
| 27 |
+
print(f"wrote {OUT}: {os.path.getsize(OUT)} bytes, {len(data.get('products', []))} products")
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
sys.exit(main())
|
scripts/meta_harvest/02_harvest_stac.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Harvest full STAC collection records from CDS / ADS / EWDS catalogue APIs.
|
| 3 |
+
|
| 4 |
+
Produces raw/{store}_collections_full.json = list of full per-collection records
|
| 5 |
+
(fetched individually so nothing is truncated by the list endpoint).
|
| 6 |
+
Polite: <=2 req/s per host, retries with backoff, resumable via cache dir.
|
| 7 |
+
"""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
import httpx
|
| 14 |
+
|
| 15 |
+
BASE = "/Users/dmpantiu/copernicus_mcp/meta_harvest"
|
| 16 |
+
CACHE = os.path.join(BASE, "raw", "stac_cache")
|
| 17 |
+
STORES = {
|
| 18 |
+
"cds": "https://cds.climate.copernicus.eu/api/catalogue/v1",
|
| 19 |
+
"ads": "https://ads.atmosphere.copernicus.eu/api/catalogue/v1",
|
| 20 |
+
"ewds": "https://ewds.climate.copernicus.eu/api/catalogue/v1",
|
| 21 |
+
}
|
| 22 |
+
HEADERS = {"User-Agent": "meta-harvest/1.0 (research; contact: local)"}
|
| 23 |
+
MIN_INTERVAL = 0.5 # 2 req/s
|
| 24 |
+
|
| 25 |
+
_last_req = {}
|
| 26 |
+
|
| 27 |
+
def get_json(client, url, host):
|
| 28 |
+
for attempt in range(6):
|
| 29 |
+
wait = MIN_INTERVAL - (time.time() - _last_req.get(host, 0))
|
| 30 |
+
if wait > 0:
|
| 31 |
+
time.sleep(wait)
|
| 32 |
+
try:
|
| 33 |
+
_last_req[host] = time.time()
|
| 34 |
+
r = client.get(url, headers=HEADERS, timeout=60)
|
| 35 |
+
if r.status_code == 200:
|
| 36 |
+
return r.json()
|
| 37 |
+
if r.status_code in (429, 500, 502, 503, 504):
|
| 38 |
+
time.sleep(2 ** attempt)
|
| 39 |
+
continue
|
| 40 |
+
print(f" HTTP {r.status_code} for {url}", flush=True)
|
| 41 |
+
return None
|
| 42 |
+
except (httpx.HTTPError, json.JSONDecodeError) as e:
|
| 43 |
+
print(f" error {e!r} for {url}, retry {attempt}", flush=True)
|
| 44 |
+
time.sleep(2 ** attempt)
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
os.makedirs(CACHE, exist_ok=True)
|
| 49 |
+
with httpx.Client(follow_redirects=True) as client:
|
| 50 |
+
for store, base in STORES.items():
|
| 51 |
+
out = os.path.join(BASE, "raw", f"{store}_collections_full.json")
|
| 52 |
+
if os.path.exists(out) and os.path.getsize(out) > 1000:
|
| 53 |
+
print(f"{store}: output exists, skipping")
|
| 54 |
+
continue
|
| 55 |
+
host = base.split("/")[2]
|
| 56 |
+
listing = get_json(client, f"{base}/collections?limit=1000", host)
|
| 57 |
+
if listing is None:
|
| 58 |
+
print(f"{store}: FAILED to list collections")
|
| 59 |
+
continue
|
| 60 |
+
ids = [c["id"] for c in listing.get("collections", [])]
|
| 61 |
+
print(f"{store}: {len(ids)} collections listed", flush=True)
|
| 62 |
+
full = []
|
| 63 |
+
failed = []
|
| 64 |
+
for i, cid in enumerate(ids):
|
| 65 |
+
cpath = os.path.join(CACHE, f"{store}__{cid}.json")
|
| 66 |
+
if os.path.exists(cpath) and os.path.getsize(cpath) > 100:
|
| 67 |
+
with open(cpath) as f:
|
| 68 |
+
full.append(json.load(f))
|
| 69 |
+
continue
|
| 70 |
+
rec = get_json(client, f"{base}/collections/{cid}", host)
|
| 71 |
+
if rec is None:
|
| 72 |
+
failed.append(cid)
|
| 73 |
+
# fall back to listing record
|
| 74 |
+
rec = next(c for c in listing["collections"] if c["id"] == cid)
|
| 75 |
+
else:
|
| 76 |
+
with open(cpath, "w") as f:
|
| 77 |
+
json.dump(rec, f)
|
| 78 |
+
full.append(rec)
|
| 79 |
+
if (i + 1) % 25 == 0:
|
| 80 |
+
print(f" {store}: {i+1}/{len(ids)}", flush=True)
|
| 81 |
+
tmp = out + ".tmp"
|
| 82 |
+
with open(tmp, "w") as f:
|
| 83 |
+
json.dump(full, f)
|
| 84 |
+
os.replace(tmp, out)
|
| 85 |
+
print(f"{store}: wrote {out} ({os.path.getsize(out)} bytes), "
|
| 86 |
+
f"{len(full)} records, {len(failed)} fetch-failures: {failed}", flush=True)
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
sys.exit(main())
|
scripts/meta_harvest/03_enrich_cmems.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Build cmems_products_enriched.json and cmems_datasets_enriched.json
|
| 3 |
+
from raw/cmems_describe_full.json."""
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
|
| 8 |
+
BASE = "/Users/dmpantiu/copernicus_mcp/meta_harvest"
|
| 9 |
+
RAW = os.path.join(BASE, "raw", "cmems_describe_full.json")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def coord_bounds(coord):
|
| 13 |
+
"""Return (min, max) using min/max fields, falling back to values[]."""
|
| 14 |
+
mn, mx = coord.get("minimum_value"), coord.get("maximum_value")
|
| 15 |
+
vals = coord.get("values")
|
| 16 |
+
if mn is None and vals:
|
| 17 |
+
try:
|
| 18 |
+
mn = min(vals)
|
| 19 |
+
except TypeError:
|
| 20 |
+
mn = vals[0]
|
| 21 |
+
if mx is None and vals:
|
| 22 |
+
try:
|
| 23 |
+
mx = max(vals)
|
| 24 |
+
except TypeError:
|
| 25 |
+
mx = vals[-1]
|
| 26 |
+
return mn, mx
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def to_iso(val, unit):
|
| 30 |
+
if val is None:
|
| 31 |
+
return None
|
| 32 |
+
u = (unit or "").lower()
|
| 33 |
+
try:
|
| 34 |
+
if u.startswith("milliseconds since 1970"):
|
| 35 |
+
return datetime.fromtimestamp(val / 1000.0, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 36 |
+
if u.startswith("seconds since 1970"):
|
| 37 |
+
return datetime.fromtimestamp(float(val), tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 38 |
+
except (OSError, OverflowError, ValueError, TypeError):
|
| 39 |
+
pass
|
| 40 |
+
return val
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def extract_variable(var):
|
| 44 |
+
out = {
|
| 45 |
+
"short_name": var.get("short_name"),
|
| 46 |
+
"standard_name": var.get("standard_name"),
|
| 47 |
+
"units": var.get("units"),
|
| 48 |
+
"bbox": var.get("bbox"),
|
| 49 |
+
}
|
| 50 |
+
depth_range = None
|
| 51 |
+
time_range = None
|
| 52 |
+
for co in var.get("coordinates") or []:
|
| 53 |
+
cid = (co.get("coordinate_id") or "").lower()
|
| 54 |
+
mn, mx = coord_bounds(co)
|
| 55 |
+
if cid == "time":
|
| 56 |
+
unit = co.get("coordinate_unit")
|
| 57 |
+
time_range = [to_iso(mn, unit), to_iso(mx, unit)]
|
| 58 |
+
elif cid in ("depth", "elevation"):
|
| 59 |
+
depth_range = {
|
| 60 |
+
"min": mn,
|
| 61 |
+
"max": mx,
|
| 62 |
+
"units": co.get("coordinate_unit"),
|
| 63 |
+
"coordinate_id": cid,
|
| 64 |
+
}
|
| 65 |
+
out["depth_range"] = depth_range
|
| 66 |
+
out["time_range"] = time_range
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def merge_variable(existing, new):
|
| 71 |
+
"""Widen bounds so the merged variable covers all services/parts."""
|
| 72 |
+
for k in ("standard_name", "units"):
|
| 73 |
+
if not existing.get(k):
|
| 74 |
+
existing[k] = new.get(k)
|
| 75 |
+
b1, b2 = existing.get("bbox"), new.get("bbox")
|
| 76 |
+
if b1 and b2 and len(b1) == 4 and len(b2) == 4:
|
| 77 |
+
existing["bbox"] = [min(b1[0], b2[0]), min(b1[1], b2[1]),
|
| 78 |
+
max(b1[2], b2[2]), max(b1[3], b2[3])]
|
| 79 |
+
elif not b1:
|
| 80 |
+
existing["bbox"] = b2
|
| 81 |
+
d1, d2 = existing.get("depth_range"), new.get("depth_range")
|
| 82 |
+
if d1 and d2:
|
| 83 |
+
try:
|
| 84 |
+
d1["min"] = min(d1["min"], d2["min"]) if None not in (d1["min"], d2["min"]) else d1["min"] or d2["min"]
|
| 85 |
+
d1["max"] = max(d1["max"], d2["max"]) if None not in (d1["max"], d2["max"]) else d1["max"] or d2["max"]
|
| 86 |
+
except TypeError:
|
| 87 |
+
pass
|
| 88 |
+
elif not d1:
|
| 89 |
+
existing["depth_range"] = d2
|
| 90 |
+
t1, t2 = existing.get("time_range"), new.get("time_range")
|
| 91 |
+
if t1 and t2:
|
| 92 |
+
try:
|
| 93 |
+
if t2[0] is not None and (t1[0] is None or str(t2[0]) < str(t1[0])):
|
| 94 |
+
t1[0] = t2[0]
|
| 95 |
+
if t2[1] is not None and (t1[1] is None or str(t2[1]) > str(t1[1])):
|
| 96 |
+
t1[1] = t2[1]
|
| 97 |
+
except TypeError:
|
| 98 |
+
pass
|
| 99 |
+
elif not t1:
|
| 100 |
+
existing["time_range"] = t2
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main():
|
| 104 |
+
with open(RAW) as f:
|
| 105 |
+
cat = json.load(f)
|
| 106 |
+
|
| 107 |
+
products_out = {}
|
| 108 |
+
datasets_out = {}
|
| 109 |
+
|
| 110 |
+
for p in cat["products"]:
|
| 111 |
+
pid = p["product_id"]
|
| 112 |
+
ds_summaries = []
|
| 113 |
+
for ds in p["datasets"]:
|
| 114 |
+
did = ds["dataset_id"]
|
| 115 |
+
versions = sorted(ds.get("versions") or [],
|
| 116 |
+
key=lambda v: v.get("label") or "", reverse=True)
|
| 117 |
+
versions_out = []
|
| 118 |
+
all_vars = {} # short_name -> merged var (from latest version only)
|
| 119 |
+
services_out = []
|
| 120 |
+
for vi, v in enumerate(versions):
|
| 121 |
+
parts_out = []
|
| 122 |
+
for part in v.get("parts") or []:
|
| 123 |
+
svc_list = []
|
| 124 |
+
for svc in part.get("services") or []:
|
| 125 |
+
uri = svc.get("uri") or ""
|
| 126 |
+
svc_list.append({
|
| 127 |
+
"name": svc.get("service_name"),
|
| 128 |
+
"short_name": svc.get("service_short_name"),
|
| 129 |
+
"format": svc.get("service_format"),
|
| 130 |
+
"uri": uri,
|
| 131 |
+
"uri_scheme": uri.split("://", 1)[0] if "://" in uri else None,
|
| 132 |
+
"arco_sparse_type": svc.get("arco_sparse_type"),
|
| 133 |
+
})
|
| 134 |
+
if vi == 0: # latest version: harvest variables
|
| 135 |
+
for var in svc.get("variables") or []:
|
| 136 |
+
ev = extract_variable(var)
|
| 137 |
+
sn = ev["short_name"]
|
| 138 |
+
if sn in all_vars:
|
| 139 |
+
merge_variable(all_vars[sn], ev)
|
| 140 |
+
else:
|
| 141 |
+
all_vars[sn] = ev
|
| 142 |
+
parts_out.append({
|
| 143 |
+
"name": part.get("name"),
|
| 144 |
+
"released_date": part.get("released_date"),
|
| 145 |
+
"retired_date": part.get("retired_date"),
|
| 146 |
+
"url_metadata": part.get("url_metadata"),
|
| 147 |
+
"services": svc_list,
|
| 148 |
+
})
|
| 149 |
+
if vi == 0:
|
| 150 |
+
services_out.extend(svc_list)
|
| 151 |
+
versions_out.append({"label": v.get("label"), "parts": parts_out})
|
| 152 |
+
|
| 153 |
+
datasets_out[did] = {
|
| 154 |
+
"dataset_id": did,
|
| 155 |
+
"dataset_name": ds.get("dataset_name"),
|
| 156 |
+
"product_id": pid,
|
| 157 |
+
"digital_object_identifier": ds.get("digital_object_identifier"),
|
| 158 |
+
"latest_version": versions[0].get("label") if versions else None,
|
| 159 |
+
"versions": versions_out,
|
| 160 |
+
"services": services_out, # latest-version services flattened
|
| 161 |
+
"variables": list(all_vars.values()),
|
| 162 |
+
}
|
| 163 |
+
ds_summaries.append({
|
| 164 |
+
"dataset_id": did,
|
| 165 |
+
"dataset_name": ds.get("dataset_name"),
|
| 166 |
+
"latest_version": versions[0].get("label") if versions else None,
|
| 167 |
+
"n_variables": len(all_vars),
|
| 168 |
+
"variables": sorted(all_vars.keys()),
|
| 169 |
+
})
|
| 170 |
+
|
| 171 |
+
products_out[pid] = {
|
| 172 |
+
"product_id": pid,
|
| 173 |
+
"title": p.get("title"),
|
| 174 |
+
"digital_object_identifier": p.get("digital_object_identifier"),
|
| 175 |
+
"sources": p.get("sources"),
|
| 176 |
+
"processing_level": p.get("processing_level"),
|
| 177 |
+
"production_center": p.get("production_center"),
|
| 178 |
+
"keywords": p.get("keywords"),
|
| 179 |
+
"thumbnail_url": p.get("thumbnail_url"),
|
| 180 |
+
"description": p.get("description"),
|
| 181 |
+
"datasets": ds_summaries,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
with open(os.path.join(BASE, "cmems_products_enriched.json"), "w") as f:
|
| 185 |
+
json.dump(products_out, f)
|
| 186 |
+
with open(os.path.join(BASE, "cmems_datasets_enriched.json"), "w") as f:
|
| 187 |
+
json.dump(datasets_out, f)
|
| 188 |
+
|
| 189 |
+
# quick coverage stats
|
| 190 |
+
nvar = sum(len(d["variables"]) for d in datasets_out.values())
|
| 191 |
+
nunits = sum(1 for d in datasets_out.values() for v in d["variables"] if v.get("units"))
|
| 192 |
+
nstd = sum(1 for d in datasets_out.values() for v in d["variables"] if v.get("standard_name"))
|
| 193 |
+
ntime = sum(1 for d in datasets_out.values() for v in d["variables"] if v.get("time_range"))
|
| 194 |
+
print(f"products: {len(products_out)}, datasets: {len(datasets_out)}, variables: {nvar}")
|
| 195 |
+
print(f" units: {nunits} ({nunits/nvar:.1%}), standard_name: {nstd} ({nstd/nvar:.1%}), time_range: {ntime} ({ntime/nvar:.1%})")
|
| 196 |
+
print(f" products with doi: {sum(1 for p in products_out.values() if p['digital_object_identifier'])}")
|
| 197 |
+
print(f" products with processing_level: {sum(1 for p in products_out.values() if p['processing_level'])}")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
main()
|
scripts/meta_harvest/04_harvest_pages.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Fetch the per-dataset 'layout' JSON (drives the CDS/ADS/EWDS web pages) for
|
| 3 |
+
every collection. This holds the Documentation section and References/Citation
|
| 4 |
+
aside that are NOT in the STAC record proper.
|
| 5 |
+
|
| 6 |
+
Saves raw/pages/{store}/{id}.json ; builds cds_references.json (all 3 stores).
|
| 7 |
+
Polite: <=2 req/s per host, retries with backoff, resumable.
|
| 8 |
+
"""
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import re
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import httpx
|
| 15 |
+
|
| 16 |
+
BASE = "/Users/dmpantiu/copernicus_mcp/meta_harvest"
|
| 17 |
+
STORES = ["cds", "ads", "ewds"]
|
| 18 |
+
HEADERS = {"User-Agent": "meta-harvest/1.0 (research; contact: local)"}
|
| 19 |
+
MIN_INTERVAL = 0.5
|
| 20 |
+
_last_req = {}
|
| 21 |
+
|
| 22 |
+
DOI_RE = re.compile(r"10\.\d{4,9}/[-._;()/:A-Za-z0-9]+")
|
| 23 |
+
MDLINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^)\s]+)\)")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get(client, url):
|
| 27 |
+
host = url.split("/")[2]
|
| 28 |
+
for attempt in range(6):
|
| 29 |
+
wait = MIN_INTERVAL - (time.time() - _last_req.get(host, 0))
|
| 30 |
+
if wait > 0:
|
| 31 |
+
time.sleep(wait)
|
| 32 |
+
try:
|
| 33 |
+
_last_req[host] = time.time()
|
| 34 |
+
r = client.get(url, headers=HEADERS, timeout=60)
|
| 35 |
+
if r.status_code == 200:
|
| 36 |
+
return r
|
| 37 |
+
if r.status_code in (429, 500, 502, 503, 504):
|
| 38 |
+
time.sleep(2 ** attempt)
|
| 39 |
+
continue
|
| 40 |
+
print(f" HTTP {r.status_code} {url}", flush=True)
|
| 41 |
+
return None
|
| 42 |
+
except httpx.HTTPError as e:
|
| 43 |
+
print(f" err {e!r} {url} retry {attempt}", flush=True)
|
| 44 |
+
time.sleep(2 ** attempt)
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def walk_blocks(blocks):
|
| 49 |
+
for b in blocks or []:
|
| 50 |
+
yield b
|
| 51 |
+
yield from walk_blocks(b.get("blocks"))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def extract_from_layout(layout):
|
| 55 |
+
"""Return (documentation_links, references) from a layout JSON."""
|
| 56 |
+
doc_links = []
|
| 57 |
+
references = []
|
| 58 |
+
body = layout.get("body") or {}
|
| 59 |
+
sections = list((body.get("main") or {}).get("sections") or [])
|
| 60 |
+
aside = body.get("aside") or {}
|
| 61 |
+
aside_secs = [aside] if aside else []
|
| 62 |
+
|
| 63 |
+
def clean_doi(s):
|
| 64 |
+
return s.rstrip(".,;)")
|
| 65 |
+
|
| 66 |
+
for sec in sections:
|
| 67 |
+
sid = (sec.get("id") or "").lower()
|
| 68 |
+
stitle = (sec.get("title") or "").lower()
|
| 69 |
+
if "documentation" in sid or "documentation" in stitle:
|
| 70 |
+
for b in walk_blocks(sec.get("blocks")):
|
| 71 |
+
if b.get("type") == "link" and b.get("href"):
|
| 72 |
+
doc_links.append({
|
| 73 |
+
"title": b.get("title"),
|
| 74 |
+
"url": b.get("href"),
|
| 75 |
+
"description": b.get("description"),
|
| 76 |
+
})
|
| 77 |
+
elif b.get("type") in ("markdown", "thumb-markdown"):
|
| 78 |
+
for m in MDLINK_RE.finditer(b.get("content") or ""):
|
| 79 |
+
doc_links.append({"title": m.group(1), "url": m.group(2),
|
| 80 |
+
"description": None})
|
| 81 |
+
for asec in aside_secs:
|
| 82 |
+
for b in walk_blocks(asec.get("blocks")):
|
| 83 |
+
bid = (b.get("id") or "").lower()
|
| 84 |
+
btitle = (b.get("title") or "").lower()
|
| 85 |
+
if bid in ("citation", "doi", "references") or "citation" in btitle:
|
| 86 |
+
content = b.get("content") or ""
|
| 87 |
+
if content:
|
| 88 |
+
dois = sorted({clean_doi(d) for d in DOI_RE.findall(content)})
|
| 89 |
+
references.append({
|
| 90 |
+
"id": b.get("id"),
|
| 91 |
+
"title": b.get("title"),
|
| 92 |
+
"text": content,
|
| 93 |
+
"dois": dois,
|
| 94 |
+
})
|
| 95 |
+
# documentation links can also live in aside (rare)
|
| 96 |
+
if b.get("type") == "link" and b.get("href") and "doc" in bid:
|
| 97 |
+
doc_links.append({"title": b.get("title"), "url": b.get("href"),
|
| 98 |
+
"description": b.get("description")})
|
| 99 |
+
# dedupe doc links by url
|
| 100 |
+
seen = set()
|
| 101 |
+
uniq = []
|
| 102 |
+
for dl in doc_links:
|
| 103 |
+
if dl["url"] not in seen:
|
| 104 |
+
seen.add(dl["url"])
|
| 105 |
+
uniq.append(dl)
|
| 106 |
+
return uniq, references
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
refs_out = {}
|
| 111 |
+
stats = {}
|
| 112 |
+
with httpx.Client(follow_redirects=True) as client:
|
| 113 |
+
for store in STORES:
|
| 114 |
+
with open(os.path.join(BASE, "raw", f"{store}_collections_full.json")) as f:
|
| 115 |
+
recs = json.load(f)
|
| 116 |
+
pdir = os.path.join(BASE, "raw", "pages", store)
|
| 117 |
+
os.makedirs(pdir, exist_ok=True)
|
| 118 |
+
refs_out[store] = {}
|
| 119 |
+
got, nolayout, failed = 0, [], []
|
| 120 |
+
for rec in recs:
|
| 121 |
+
cid = rec["id"]
|
| 122 |
+
layout_url = next((l["href"] for l in rec.get("links", [])
|
| 123 |
+
if l.get("rel") == "layout"), None)
|
| 124 |
+
if not layout_url:
|
| 125 |
+
nolayout.append(cid)
|
| 126 |
+
continue
|
| 127 |
+
path = os.path.join(pdir, f"{cid}.json")
|
| 128 |
+
if os.path.exists(path) and os.path.getsize(path) > 50:
|
| 129 |
+
with open(path) as f:
|
| 130 |
+
layout = json.load(f)
|
| 131 |
+
else:
|
| 132 |
+
r = get(client, layout_url)
|
| 133 |
+
if r is None:
|
| 134 |
+
failed.append(cid)
|
| 135 |
+
continue
|
| 136 |
+
try:
|
| 137 |
+
layout = r.json()
|
| 138 |
+
except json.JSONDecodeError:
|
| 139 |
+
failed.append(cid)
|
| 140 |
+
continue
|
| 141 |
+
with open(path, "w") as f:
|
| 142 |
+
json.dump(layout, f)
|
| 143 |
+
got += 1
|
| 144 |
+
doc_links, references = extract_from_layout(layout)
|
| 145 |
+
refs_out[store][cid] = {
|
| 146 |
+
"documentation_links": doc_links,
|
| 147 |
+
"references": references,
|
| 148 |
+
}
|
| 149 |
+
stats[store] = {"total": len(recs), "layout_fetched": got,
|
| 150 |
+
"no_layout_link": nolayout, "fetch_failed": failed}
|
| 151 |
+
print(f"{store}: {got}/{len(recs)} layouts; no-layout={len(nolayout)} "
|
| 152 |
+
f"failed={len(failed)} {nolayout or ''}{failed or ''}", flush=True)
|
| 153 |
+
|
| 154 |
+
with open(os.path.join(BASE, "cds_references.json"), "w") as f:
|
| 155 |
+
json.dump(refs_out, f)
|
| 156 |
+
with open(os.path.join(BASE, "raw", "pages_harvest_stats.json"), "w") as f:
|
| 157 |
+
json.dump(stats, f, indent=1)
|
| 158 |
+
# coverage
|
| 159 |
+
for store in STORES:
|
| 160 |
+
vals = refs_out[store].values()
|
| 161 |
+
nrefs = sum(1 for v in vals if v["references"])
|
| 162 |
+
ndocs = sum(1 for v in vals if v["documentation_links"])
|
| 163 |
+
print(f"{store}: {nrefs}/{len(vals)} with references, {ndocs}/{len(vals)} with doc links")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
main()
|
scripts/meta_harvest/05_enrich_stac.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Build {cds,ads,ewds}_enriched.json from raw STAC records + layout extracts."""
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
BASE = "/Users/dmpantiu/copernicus_mcp/meta_harvest"
|
| 7 |
+
STORES = ["cds", "ads", "ewds"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
refs_path = os.path.join(BASE, "cds_references.json")
|
| 12 |
+
refs_all = {}
|
| 13 |
+
if os.path.exists(refs_path):
|
| 14 |
+
with open(refs_path) as f:
|
| 15 |
+
refs_all = json.load(f)
|
| 16 |
+
|
| 17 |
+
for store in STORES:
|
| 18 |
+
with open(os.path.join(BASE, "raw", f"{store}_collections_full.json")) as f:
|
| 19 |
+
recs = json.load(f)
|
| 20 |
+
srefs = refs_all.get(store, {})
|
| 21 |
+
out = {}
|
| 22 |
+
for r in recs:
|
| 23 |
+
cid = r["id"]
|
| 24 |
+
page = srefs.get(cid, {})
|
| 25 |
+
doc_links = [
|
| 26 |
+
{"title": dl.get("title"), "url": dl.get("url"),
|
| 27 |
+
"rel": "documentation", "description": dl.get("description")}
|
| 28 |
+
for dl in page.get("documentation_links", [])
|
| 29 |
+
]
|
| 30 |
+
# STAC-native doc-ish links
|
| 31 |
+
for l in r.get("links", []):
|
| 32 |
+
if l.get("rel") in ("documentation", "describedby", "cite-as", "license"):
|
| 33 |
+
doc_links.append({"title": l.get("title"), "url": l.get("href"),
|
| 34 |
+
"rel": l.get("rel"), "description": None})
|
| 35 |
+
ext = r.get("extent") or {}
|
| 36 |
+
out[cid] = {
|
| 37 |
+
"id": cid,
|
| 38 |
+
"store": store,
|
| 39 |
+
"title": r.get("title"),
|
| 40 |
+
"description": r.get("description"),
|
| 41 |
+
"doi": r.get("sci:doi"),
|
| 42 |
+
"license": r.get("license"),
|
| 43 |
+
"update_frequency": r.get("cads:update_frequency"),
|
| 44 |
+
"disabled_reason": r.get("cads:disabled_reason"),
|
| 45 |
+
"message": r.get("cads:message"),
|
| 46 |
+
"providers": r.get("providers"),
|
| 47 |
+
"keywords": r.get("keywords"),
|
| 48 |
+
"published": r.get("published"),
|
| 49 |
+
"updated": r.get("updated"),
|
| 50 |
+
"assets": r.get("assets"),
|
| 51 |
+
"spatial_bbox": (ext.get("spatial") or {}).get("bbox"),
|
| 52 |
+
"temporal_interval": (ext.get("temporal") or {}).get("interval"),
|
| 53 |
+
"documentation_links": doc_links,
|
| 54 |
+
"references": page.get("references", []),
|
| 55 |
+
"related_collections": [
|
| 56 |
+
l["href"].rstrip("/").rsplit("/", 1)[-1]
|
| 57 |
+
for l in r.get("links", []) if l.get("rel") == "related"
|
| 58 |
+
],
|
| 59 |
+
}
|
| 60 |
+
path = os.path.join(BASE, f"{store}_enriched.json")
|
| 61 |
+
with open(path, "w") as f:
|
| 62 |
+
json.dump(out, f)
|
| 63 |
+
n = len(out)
|
| 64 |
+
print(f"{store}: {n} collections -> {path}")
|
| 65 |
+
for field in ("doi", "license", "update_frequency", "documentation_links",
|
| 66 |
+
"references", "published"):
|
| 67 |
+
c = sum(1 for v in out.values() if v.get(field))
|
| 68 |
+
print(f" {field}: {c}/{n}")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
main()
|
scripts/meta_harvest/06_unify.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Merge all enriched artifacts into unified_metadata.json.
|
| 3 |
+
|
| 4 |
+
Key = CMEMS dataset_id or CDS/ADS/EWDS collection id.
|
| 5 |
+
Value = compact, JSON-serializable record for a `dataset_metadata` MCP tool.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
BASE = "/Users/dmpantiu/copernicus_mcp/meta_harvest"
|
| 11 |
+
|
| 12 |
+
CMEMS_LICENCE = ("Copernicus Marine Service Licence — "
|
| 13 |
+
"https://marine.copernicus.eu/user-corner/service-commitments-and-licence")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load(name):
|
| 17 |
+
with open(os.path.join(BASE, name)) as f:
|
| 18 |
+
return json.load(f)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def union_bbox(bboxes):
|
| 22 |
+
bbs = [b for b in bboxes if b and len(b) == 4 and all(isinstance(x, (int, float)) for x in b)]
|
| 23 |
+
if not bbs:
|
| 24 |
+
return None
|
| 25 |
+
return [min(b[0] for b in bbs), min(b[1] for b in bbs),
|
| 26 |
+
max(b[2] for b in bbs), max(b[3] for b in bbs)]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main():
|
| 30 |
+
products = load("cmems_products_enriched.json")
|
| 31 |
+
datasets = load("cmems_datasets_enriched.json")
|
| 32 |
+
unified = {}
|
| 33 |
+
|
| 34 |
+
for did, d in datasets.items():
|
| 35 |
+
p = products.get(d["product_id"], {})
|
| 36 |
+
variables = []
|
| 37 |
+
tmins, tmaxs, dmins, dmaxs = [], [], [], []
|
| 38 |
+
for v in d["variables"]:
|
| 39 |
+
dr = v.get("depth_range") or {}
|
| 40 |
+
tr = v.get("time_range")
|
| 41 |
+
variables.append({
|
| 42 |
+
"short_name": v.get("short_name"),
|
| 43 |
+
"standard_name": v.get("standard_name"),
|
| 44 |
+
"units": v.get("units"),
|
| 45 |
+
"bbox": v.get("bbox"),
|
| 46 |
+
"depth_range": ([dr.get("min"), dr.get("max")] if dr else None),
|
| 47 |
+
"time_range": tr,
|
| 48 |
+
})
|
| 49 |
+
if tr and tr[0] is not None and isinstance(tr[0], str):
|
| 50 |
+
tmins.append(tr[0])
|
| 51 |
+
if tr and tr[1] is not None and isinstance(tr[1], str):
|
| 52 |
+
tmaxs.append(tr[1])
|
| 53 |
+
if dr and isinstance(dr.get("min"), (int, float)):
|
| 54 |
+
dmins.append(dr["min"])
|
| 55 |
+
if dr and isinstance(dr.get("max"), (int, float)):
|
| 56 |
+
dmaxs.append(dr["max"])
|
| 57 |
+
|
| 58 |
+
doc_links = [{"title": "Copernicus Marine product page",
|
| 59 |
+
"url": f"https://data.marine.copernicus.eu/product/{d['product_id']}/description",
|
| 60 |
+
"rel": "documentation"}]
|
| 61 |
+
url_meta = None
|
| 62 |
+
for ver in d.get("versions", []):
|
| 63 |
+
for part in ver.get("parts", []):
|
| 64 |
+
if part.get("url_metadata"):
|
| 65 |
+
url_meta = part["url_metadata"]
|
| 66 |
+
break
|
| 67 |
+
if url_meta:
|
| 68 |
+
break
|
| 69 |
+
if url_meta:
|
| 70 |
+
doc_links.append({"title": "Dataset STAC metadata", "url": url_meta,
|
| 71 |
+
"rel": "metadata"})
|
| 72 |
+
|
| 73 |
+
doi = d.get("digital_object_identifier") or p.get("digital_object_identifier")
|
| 74 |
+
references = []
|
| 75 |
+
if doi:
|
| 76 |
+
references.append({
|
| 77 |
+
"text": f"{p.get('production_center') or 'E.U. Copernicus Marine Service Information'}: "
|
| 78 |
+
f"{p.get('title')} (product {d['product_id']}). DOI: {doi}",
|
| 79 |
+
"doi": doi,
|
| 80 |
+
})
|
| 81 |
+
|
| 82 |
+
unified[did] = {
|
| 83 |
+
"store": "cmems",
|
| 84 |
+
"product_id": d["product_id"],
|
| 85 |
+
"dataset_name": d.get("dataset_name"),
|
| 86 |
+
"title": p.get("title"),
|
| 87 |
+
"doi": doi,
|
| 88 |
+
"variables": variables,
|
| 89 |
+
"spatial_bbox": union_bbox([v.get("bbox") for v in d["variables"]]),
|
| 90 |
+
"temporal_range": [min(tmins) if tmins else None,
|
| 91 |
+
max(tmaxs) if tmaxs else None],
|
| 92 |
+
"depth_range": ([min(dmins), max(dmaxs)] if dmins and dmaxs else None),
|
| 93 |
+
"update_frequency": None, # not exposed by describe(); see GAPS.md
|
| 94 |
+
"processing_level": p.get("processing_level"),
|
| 95 |
+
"production_center": p.get("production_center"),
|
| 96 |
+
"sources": p.get("sources"),
|
| 97 |
+
"keywords": p.get("keywords"),
|
| 98 |
+
"latest_version": d.get("latest_version"),
|
| 99 |
+
"services": sorted({s.get("name") for s in d.get("services", []) if s.get("name")}),
|
| 100 |
+
"documentation_links": doc_links,
|
| 101 |
+
"references": references,
|
| 102 |
+
"licence": CMEMS_LICENCE,
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
for store in ("cds", "ads", "ewds"):
|
| 106 |
+
enr = load(f"{store}_enriched.json")
|
| 107 |
+
for cid, r in enr.items():
|
| 108 |
+
refs = []
|
| 109 |
+
for ref in r.get("references", []):
|
| 110 |
+
refs.append({
|
| 111 |
+
"text": ref.get("text"),
|
| 112 |
+
"doi": (ref.get("dois") or [None])[0],
|
| 113 |
+
"title": ref.get("title"),
|
| 114 |
+
})
|
| 115 |
+
unified[cid] = {
|
| 116 |
+
"store": store,
|
| 117 |
+
"product_id": None,
|
| 118 |
+
"title": r.get("title"),
|
| 119 |
+
"doi": r.get("doi"),
|
| 120 |
+
"variables": None, # form/constraints API needed; see GAPS.md
|
| 121 |
+
"spatial_bbox": (r.get("spatial_bbox") or [None])[0],
|
| 122 |
+
"temporal_range": (r.get("temporal_interval") or [None])[0],
|
| 123 |
+
"depth_range": None,
|
| 124 |
+
"update_frequency": r.get("update_frequency"),
|
| 125 |
+
"processing_level": None,
|
| 126 |
+
"production_center": ", ".join(pv.get("name", "") for pv in (r.get("providers") or [])) or None,
|
| 127 |
+
"sources": None,
|
| 128 |
+
"keywords": r.get("keywords"),
|
| 129 |
+
"published": r.get("published"),
|
| 130 |
+
"updated": r.get("updated"),
|
| 131 |
+
"message": r.get("message"),
|
| 132 |
+
"documentation_links": r.get("documentation_links"),
|
| 133 |
+
"references": refs,
|
| 134 |
+
"licence": r.get("license"),
|
| 135 |
+
"related_collections": r.get("related_collections"),
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
out = os.path.join(BASE, "unified_metadata.json")
|
| 139 |
+
with open(out, "w") as f:
|
| 140 |
+
json.dump(unified, f)
|
| 141 |
+
print(f"unified: {len(unified)} entries, {os.path.getsize(out)} bytes")
|
| 142 |
+
by_store = {}
|
| 143 |
+
for v in unified.values():
|
| 144 |
+
by_store[v["store"]] = by_store.get(v["store"], 0) + 1
|
| 145 |
+
print(by_store)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
main()
|
scripts/meta_harvest/07_stats.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Generate STATS.md coverage report from the produced artifacts."""
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
BASE = "/Users/dmpantiu/copernicus_mcp/meta_harvest"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def load(name):
|
| 10 |
+
with open(os.path.join(BASE, name)) as f:
|
| 11 |
+
return json.load(f)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def pct(n, d):
|
| 15 |
+
return f"{n}/{d} ({n/d:.0%})" if d else "0/0"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
lines = ["# STATS — Copernicus metadata harvest coverage", ""]
|
| 20 |
+
|
| 21 |
+
# CMEMS
|
| 22 |
+
products = load("cmems_products_enriched.json")
|
| 23 |
+
datasets = load("cmems_datasets_enriched.json")
|
| 24 |
+
np_, nd = len(products), len(datasets)
|
| 25 |
+
lines += [f"## CMEMS (Marine)", "",
|
| 26 |
+
f"- Products: **{np_}**, Datasets: **{nd}**", "",
|
| 27 |
+
"| field | coverage |", "|---|---|"]
|
| 28 |
+
for f_ in ("digital_object_identifier", "sources", "processing_level",
|
| 29 |
+
"production_center", "keywords", "thumbnail_url"):
|
| 30 |
+
c = sum(1 for p in products.values() if p.get(f_))
|
| 31 |
+
lines.append(f"| product.{f_} | {pct(c, np_)} |")
|
| 32 |
+
for f_ in ("latest_version", "services", "variables"):
|
| 33 |
+
c = sum(1 for d in datasets.values() if d.get(f_))
|
| 34 |
+
lines.append(f"| dataset.{f_} | {pct(c, nd)} |")
|
| 35 |
+
c = sum(1 for d in datasets.values()
|
| 36 |
+
for v in d.get("versions", []) for pt in v.get("parts", [])
|
| 37 |
+
if pt.get("released_date")) and sum(
|
| 38 |
+
1 for d in datasets.values() if any(
|
| 39 |
+
pt.get("released_date") for v in d.get("versions", [])
|
| 40 |
+
for pt in v.get("parts", [])))
|
| 41 |
+
lines.append(f"| dataset has released_date | {pct(c, nd)} |")
|
| 42 |
+
c = sum(1 for d in datasets.values() if any(
|
| 43 |
+
pt.get("url_metadata") for v in d.get("versions", [])
|
| 44 |
+
for pt in v.get("parts", [])))
|
| 45 |
+
lines.append(f"| dataset has url_metadata | {pct(c, nd)} |")
|
| 46 |
+
allvars = [v for d in datasets.values() for v in d["variables"]]
|
| 47 |
+
nv = len(allvars)
|
| 48 |
+
lines += ["", f"- Variables (latest version, deduped): **{nv}**", "",
|
| 49 |
+
"| variable field | coverage |", "|---|---|"]
|
| 50 |
+
for f_ in ("units", "standard_name", "bbox", "time_range", "depth_range"):
|
| 51 |
+
c = sum(1 for v in allvars if v.get(f_))
|
| 52 |
+
lines.append(f"| {f_} | {pct(c, nv)} |")
|
| 53 |
+
lines.append("")
|
| 54 |
+
|
| 55 |
+
# CDS/ADS/EWDS
|
| 56 |
+
for store in ("cds", "ads", "ewds"):
|
| 57 |
+
enr = load(f"{store}_enriched.json")
|
| 58 |
+
n = len(enr)
|
| 59 |
+
lines += [f"## {store.upper()}", "", f"- Collections: **{n}**", "",
|
| 60 |
+
"| field | coverage |", "|---|---|"]
|
| 61 |
+
for f_ in ("doi", "license", "update_frequency", "providers", "keywords",
|
| 62 |
+
"published", "updated", "assets", "spatial_bbox",
|
| 63 |
+
"temporal_interval", "documentation_links", "references",
|
| 64 |
+
"variables", "message"):
|
| 65 |
+
c = sum(1 for v in enr.values() if v.get(f_))
|
| 66 |
+
lines.append(f"| {f_} | {pct(c, n)} |")
|
| 67 |
+
ndl = sum(len(v.get("documentation_links") or []) for v in enr.values())
|
| 68 |
+
nrf = sum(len(v.get("references") or []) for v in enr.values())
|
| 69 |
+
ndoi_in_refs = sum(1 for v in enr.values()
|
| 70 |
+
if any(r.get("dois") for r in v.get("references") or []))
|
| 71 |
+
lines += [f"| total doc links | {ndl} |",
|
| 72 |
+
f"| total reference blocks | {nrf} |",
|
| 73 |
+
f"| refs containing a DOI | {pct(ndoi_in_refs, n)} |", ""]
|
| 74 |
+
|
| 75 |
+
# unified
|
| 76 |
+
uni = load("unified_metadata.json")
|
| 77 |
+
lines += ["## Unified", "",
|
| 78 |
+
f"- unified_metadata.json entries: **{len(uni)}** "
|
| 79 |
+
f"(cmems={sum(1 for v in uni.values() if v['store']=='cmems')}, "
|
| 80 |
+
f"cds={sum(1 for v in uni.values() if v['store']=='cds')}, "
|
| 81 |
+
f"ads={sum(1 for v in uni.values() if v['store']=='ads')}, "
|
| 82 |
+
f"ewds={sum(1 for v in uni.values() if v['store']=='ewds')})", ""]
|
| 83 |
+
for f_ in ("doi", "keywords", "documentation_links", "references", "licence",
|
| 84 |
+
"update_frequency", "spatial_bbox", "variables"):
|
| 85 |
+
c = sum(1 for v in uni.values() if v.get(f_))
|
| 86 |
+
lines.append(f"- {f_}: {pct(c, len(uni))}")
|
| 87 |
+
c = sum(1 for v in uni.values()
|
| 88 |
+
if v.get("temporal_range") and any(x is not None for x in v["temporal_range"]))
|
| 89 |
+
lines.append(f"- temporal_range (non-null): {pct(c, len(uni))}")
|
| 90 |
+
|
| 91 |
+
# bytes
|
| 92 |
+
lines += ["", "## Harvest volume", ""]
|
| 93 |
+
total = 0
|
| 94 |
+
for root, _, files in os.walk(BASE):
|
| 95 |
+
for fn in files:
|
| 96 |
+
if fn.endswith((".json", ".html")):
|
| 97 |
+
total += os.path.getsize(os.path.join(root, fn))
|
| 98 |
+
lines.append(f"- Total bytes of JSON artifacts (incl. raw): **{total:,}**")
|
| 99 |
+
|
| 100 |
+
with open(os.path.join(BASE, "STATS.md"), "w") as f:
|
| 101 |
+
f.write("\n".join(lines) + "\n")
|
| 102 |
+
print("\n".join(lines))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
main()
|
scripts/meta_harvest/08_harvest_forms.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Fetch the 'form' JSON per collection (CDS/ADS/EWDS) and extract the
|
| 3 |
+
selectable variable names. Saves raw/pages/{store}/{id}.form.json and
|
| 4 |
+
updates {store}_enriched.json + unified_metadata.json with variables[].
|
| 5 |
+
"""
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import httpx
|
| 11 |
+
|
| 12 |
+
BASE = "/Users/dmpantiu/copernicus_mcp/meta_harvest"
|
| 13 |
+
STORES = ["cds", "ads", "ewds"]
|
| 14 |
+
HEADERS = {"User-Agent": "meta-harvest/1.0 (research; contact: local)"}
|
| 15 |
+
MIN_INTERVAL = 0.5
|
| 16 |
+
_last = {}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_json(client, url):
|
| 20 |
+
host = url.split("/")[2]
|
| 21 |
+
for attempt in range(6):
|
| 22 |
+
w = MIN_INTERVAL - (time.time() - _last.get(host, 0))
|
| 23 |
+
if w > 0:
|
| 24 |
+
time.sleep(w)
|
| 25 |
+
try:
|
| 26 |
+
_last[host] = time.time()
|
| 27 |
+
r = client.get(url, headers=HEADERS, timeout=60)
|
| 28 |
+
if r.status_code == 200:
|
| 29 |
+
return r.json()
|
| 30 |
+
if r.status_code in (429, 500, 502, 503, 504):
|
| 31 |
+
time.sleep(2 ** attempt)
|
| 32 |
+
continue
|
| 33 |
+
return None
|
| 34 |
+
except (httpx.HTTPError, json.JSONDecodeError):
|
| 35 |
+
time.sleep(2 ** attempt)
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def widget_values(details):
|
| 40 |
+
vals = []
|
| 41 |
+
if not isinstance(details, dict):
|
| 42 |
+
return vals
|
| 43 |
+
if isinstance(details.get("values"), list):
|
| 44 |
+
vals.extend(v for v in details["values"] if isinstance(v, str))
|
| 45 |
+
for g in details.get("groups") or []:
|
| 46 |
+
if isinstance(g, dict):
|
| 47 |
+
vals.extend(widget_values(g))
|
| 48 |
+
if isinstance(g.get("values"), list):
|
| 49 |
+
pass # handled by recursion? groups don't recurse via details
|
| 50 |
+
# groups may nest: {label, values} or {label, groups}
|
| 51 |
+
return vals
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def collect_group_values(obj):
|
| 55 |
+
vals = []
|
| 56 |
+
if isinstance(obj, dict):
|
| 57 |
+
if isinstance(obj.get("values"), list):
|
| 58 |
+
vals.extend(v for v in obj["values"] if isinstance(v, str))
|
| 59 |
+
for g in obj.get("groups") or []:
|
| 60 |
+
vals.extend(collect_group_values(g))
|
| 61 |
+
return vals
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def extract_variables(form):
|
| 65 |
+
if not isinstance(form, list):
|
| 66 |
+
return []
|
| 67 |
+
out = []
|
| 68 |
+
for w in form:
|
| 69 |
+
name = (w.get("name") or "").lower()
|
| 70 |
+
if name != "variable" and "variable" not in name:
|
| 71 |
+
continue
|
| 72 |
+
details = w.get("details") or {}
|
| 73 |
+
vals = collect_group_values(details)
|
| 74 |
+
labels = details.get("labels")
|
| 75 |
+
if not vals and isinstance(labels, dict):
|
| 76 |
+
vals = list(labels.keys())
|
| 77 |
+
out.extend(vals)
|
| 78 |
+
# dedupe preserving order
|
| 79 |
+
seen, uniq = set(), []
|
| 80 |
+
for v in out:
|
| 81 |
+
if v not in seen:
|
| 82 |
+
seen.add(v)
|
| 83 |
+
uniq.append(v)
|
| 84 |
+
return uniq
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main():
|
| 88 |
+
var_map = {} # store -> cid -> [variables]
|
| 89 |
+
with httpx.Client(follow_redirects=True) as client:
|
| 90 |
+
for store in STORES:
|
| 91 |
+
with open(os.path.join(BASE, "raw", f"{store}_collections_full.json")) as f:
|
| 92 |
+
recs = json.load(f)
|
| 93 |
+
pdir = os.path.join(BASE, "raw", "pages", store)
|
| 94 |
+
var_map[store] = {}
|
| 95 |
+
noform, failed = [], []
|
| 96 |
+
for rec in recs:
|
| 97 |
+
cid = rec["id"]
|
| 98 |
+
form_url = next((l["href"] for l in rec.get("links", [])
|
| 99 |
+
if l.get("rel") == "form"), None)
|
| 100 |
+
if not form_url:
|
| 101 |
+
noform.append(cid)
|
| 102 |
+
continue
|
| 103 |
+
path = os.path.join(pdir, f"{cid}.form.json")
|
| 104 |
+
if os.path.exists(path) and os.path.getsize(path) > 10:
|
| 105 |
+
with open(path) as f:
|
| 106 |
+
form = json.load(f)
|
| 107 |
+
else:
|
| 108 |
+
form = get_json(client, form_url)
|
| 109 |
+
if form is None:
|
| 110 |
+
failed.append(cid)
|
| 111 |
+
continue
|
| 112 |
+
with open(path, "w") as f:
|
| 113 |
+
json.dump(form, f)
|
| 114 |
+
var_map[store][cid] = extract_variables(form)
|
| 115 |
+
nvars = sum(1 for v in var_map[store].values() if v)
|
| 116 |
+
print(f"{store}: forms ok={len(var_map[store])}, with variables={nvars}, "
|
| 117 |
+
f"no-form-link={len(noform)}, failed={len(failed)}", flush=True)
|
| 118 |
+
if noform:
|
| 119 |
+
print(f" no form link: {noform}")
|
| 120 |
+
if failed:
|
| 121 |
+
print(f" failed: {failed}")
|
| 122 |
+
|
| 123 |
+
# patch enriched + unified
|
| 124 |
+
uni_path = os.path.join(BASE, "unified_metadata.json")
|
| 125 |
+
with open(uni_path) as f:
|
| 126 |
+
uni = json.load(f)
|
| 127 |
+
for store in STORES:
|
| 128 |
+
epath = os.path.join(BASE, f"{store}_enriched.json")
|
| 129 |
+
with open(epath) as f:
|
| 130 |
+
enr = json.load(f)
|
| 131 |
+
for cid, vs in var_map[store].items():
|
| 132 |
+
if cid in enr:
|
| 133 |
+
enr[cid]["variables"] = vs
|
| 134 |
+
if cid in uni:
|
| 135 |
+
uni[cid]["variables"] = [{"short_name": v} for v in vs] if vs else None
|
| 136 |
+
with open(epath, "w") as f:
|
| 137 |
+
json.dump(enr, f)
|
| 138 |
+
with open(uni_path, "w") as f:
|
| 139 |
+
json.dump(uni, f)
|
| 140 |
+
n = sum(1 for v in uni.values() if v["store"] != "cmems" and v.get("variables"))
|
| 141 |
+
print(f"unified: {n} CDS/ADS/EWDS entries now have variables")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
main()
|
scripts/meta_harvest/GAPS.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GAPS — what upstream still cannot provide programmatically
|
| 2 |
+
|
| 3 |
+
Harvest date: 2026-07-02. All catalogue reads were anonymous (no credentials).
|
| 4 |
+
|
| 5 |
+
## CMEMS (Marine Data Store)
|
| 6 |
+
|
| 7 |
+
- **115/1269 datasets have zero variable metadata** (no short_name/units/bounds).
|
| 8 |
+
These are exposed upstream only through the `original-files` (native S3) service
|
| 9 |
+
with an empty `variables[]` list — mostly OCEANCOLOUR (62), SEAICE (17), WAVE (12),
|
| 10 |
+
INSITU (7) climatology / in-situ / irregular-grid datasets. Verified that *no*
|
| 11 |
+
version (not just the latest) carries variables; the only recourse would be
|
| 12 |
+
opening the actual NetCDF files, which is out of scope for a catalogue harvest.
|
| 13 |
+
- **`units` missing for ~5% of variables, `standard_name` for ~14%** — absent in
|
| 14 |
+
the upstream describe() payload itself (typically OMI/insitu variables with no
|
| 15 |
+
CF standard name).
|
| 16 |
+
- **`depth_range` only on ~30% of variables** — correct behaviour: most datasets
|
| 17 |
+
are surface-only; but describe() does not distinguish "surface-only" from
|
| 18 |
+
"depth axis not described".
|
| 19 |
+
- **`update_frequency` is not exposed** anywhere in `copernicusmarine.describe()`.
|
| 20 |
+
It exists only in the per-dataset STAC (`url_metadata` → dataset.stac.json,
|
| 21 |
+
`properties.cmems_arco:updateFrequency` on some) and on the product web page.
|
| 22 |
+
Not harvested (would be ~1300 extra requests); `url_metadata` links are saved in
|
| 23 |
+
`cmems_datasets_enriched.json` so it can be back-filled later.
|
| 24 |
+
- **Licence text**: describe() carries no licence field. The Copernicus Marine
|
| 25 |
+
Service Licence is uniform across all products, so `unified_metadata.json`
|
| 26 |
+
records the canonical licence URL as a constant, not a harvested value.
|
| 27 |
+
- **Citation text**: CMEMS provides no formatted citation via API; the reference
|
| 28 |
+
entries in `unified_metadata.json` for CMEMS are synthesized from
|
| 29 |
+
production_center + title + DOI (DOI itself is upstream data).
|
| 30 |
+
- **1 product without DOI or keywords**: `NWATL_ANALYSISFORECAST_PHY_ICE_017_001`
|
| 31 |
+
(checked: both fields are null upstream).
|
| 32 |
+
- **`released_date` present for only 74% of dataset version-parts** — null upstream
|
| 33 |
+
for older versions released before the field was introduced.
|
| 34 |
+
- **`processing_level` null for 88/307 products** — null upstream (mostly OMIs and
|
| 35 |
+
model products where the concept does not apply).
|
| 36 |
+
|
| 37 |
+
## CDS / ADS / EWDS (Climate / Atmosphere / Emergency Data Stores)
|
| 38 |
+
|
| 39 |
+
- Web pages are React shells; the actual "Documentation" and "References/Citation"
|
| 40 |
+
content is served from the **`rel="layout"` JSON** linked from each STAC record
|
| 41 |
+
(object store, anonymous). All 167/167 layouts were fetched — no HTML scraping
|
| 42 |
+
was needed, so no page-level gap remains.
|
| 43 |
+
- **`provider-c3s-data-rescue-without` (CDS)** is the single collection with no
|
| 44 |
+
documentation links, no references, no DOI, no keywords and no form: it is a
|
| 45 |
+
provider landing page, not a dataset.
|
| 46 |
+
- **DOI missing for 6 CDS collections** (null upstream): the five `*-timeseries`
|
| 47 |
+
spin-offs (`reanalysis-era5-land-timeseries`, `reanalysis-era5-single-levels-timeseries`,
|
| 48 |
+
`derived-utci-historical-timeseries`, `reanalysis-oras5-timeseries`,
|
| 49 |
+
`sis-ecde-climate-indicators`) and `provider-c3s-data-rescue-without`.
|
| 50 |
+
Their citation blocks point to the parent dataset's DOI where one exists.
|
| 51 |
+
- **`update_frequency` (`cads:update_frequency`) null for 32/139 CDS and 14/16 ADS
|
| 52 |
+
collections** — the field simply isn't populated upstream for those records.
|
| 53 |
+
- **Variable lists for CDS/ADS/EWDS come from the download `form` JSON**
|
| 54 |
+
(`rel="form"`): names only — the form carries **no units, standard_names, or
|
| 55 |
+
per-variable bounds**. 3 dataset collections have a form without a "variable"
|
| 56 |
+
widget: `reanalysis-era5-complete` and `reanalysis-uerra-europe-complete`
|
| 57 |
+
(MARS-native datasets where variables are free-form `param` codes) and
|
| 58 |
+
`cams-solar-radiation-timeseries` (single implicit product). Recorded with
|
| 59 |
+
`variables: null` in `unified_metadata.json`.
|
| 60 |
+
Full per-variable physics would require parsing each dataset's Confluence/user-guide
|
| 61 |
+
PDF — out of scope.
|
| 62 |
+
- **`cads:message`** (service messages) present for only 7 CDS + 2 ADS collections —
|
| 63 |
+
that is genuine (messages exist only when there is an active notice).
|
| 64 |
+
- No per-dataset **spatial resolution / grid** field exists in the STAC record;
|
| 65 |
+
it lives only in free-text "Data description" tables inside the layout JSON
|
| 66 |
+
(kept verbatim in `raw/pages/{store}/{id}.json` if needed later).
|
| 67 |
+
|
| 68 |
+
## General
|
| 69 |
+
|
| 70 |
+
- CMEMS `describe()` output is a point-in-time snapshot (~63 MB); temporal ranges
|
| 71 |
+
of forecast products (e.g. max time 2026-07-10) move daily. Re-run
|
| 72 |
+
`01_dump_cmems.py` (delete the raw file first) to refresh.
|
| 73 |
+
- No API exposes cross-store product lineage (e.g. which CMEMS product feeds a
|
| 74 |
+
C3S indicator); `related_collections` links exist only within a single store.
|
scripts/meta_harvest/STATS.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# STATS — Copernicus metadata harvest coverage
|
| 2 |
+
|
| 3 |
+
## CMEMS (Marine)
|
| 4 |
+
|
| 5 |
+
- Products: **307**, Datasets: **1269**
|
| 6 |
+
|
| 7 |
+
| field | coverage |
|
| 8 |
+
|---|---|
|
| 9 |
+
| product.digital_object_identifier | 306/307 (100%) |
|
| 10 |
+
| product.sources | 307/307 (100%) |
|
| 11 |
+
| product.processing_level | 219/307 (71%) |
|
| 12 |
+
| product.production_center | 307/307 (100%) |
|
| 13 |
+
| product.keywords | 306/307 (100%) |
|
| 14 |
+
| product.thumbnail_url | 307/307 (100%) |
|
| 15 |
+
| dataset.latest_version | 1269/1269 (100%) |
|
| 16 |
+
| dataset.services | 1269/1269 (100%) |
|
| 17 |
+
| dataset.variables | 1154/1269 (91%) |
|
| 18 |
+
| dataset has released_date | 943/1269 (74%) |
|
| 19 |
+
| dataset has url_metadata | 1269/1269 (100%) |
|
| 20 |
+
|
| 21 |
+
- Variables (latest version, deduped): **8567**
|
| 22 |
+
|
| 23 |
+
| variable field | coverage |
|
| 24 |
+
|---|---|
|
| 25 |
+
| units | 8155/8567 (95%) |
|
| 26 |
+
| standard_name | 7406/8567 (86%) |
|
| 27 |
+
| bbox | 8567/8567 (100%) |
|
| 28 |
+
| time_range | 8042/8567 (94%) |
|
| 29 |
+
| depth_range | 2583/8567 (30%) |
|
| 30 |
+
|
| 31 |
+
## CDS
|
| 32 |
+
|
| 33 |
+
- Collections: **139**
|
| 34 |
+
|
| 35 |
+
| field | coverage |
|
| 36 |
+
|---|---|
|
| 37 |
+
| doi | 133/139 (96%) |
|
| 38 |
+
| license | 139/139 (100%) |
|
| 39 |
+
| update_frequency | 107/139 (77%) |
|
| 40 |
+
| providers | 137/139 (99%) |
|
| 41 |
+
| keywords | 138/139 (99%) |
|
| 42 |
+
| published | 139/139 (100%) |
|
| 43 |
+
| updated | 139/139 (100%) |
|
| 44 |
+
| assets | 139/139 (100%) |
|
| 45 |
+
| spatial_bbox | 139/139 (100%) |
|
| 46 |
+
| temporal_interval | 139/139 (100%) |
|
| 47 |
+
| documentation_links | 138/139 (99%) |
|
| 48 |
+
| references | 138/139 (99%) |
|
| 49 |
+
| variables | 136/139 (98%) |
|
| 50 |
+
| message | 7/139 (5%) |
|
| 51 |
+
| total doc links | 1123 |
|
| 52 |
+
| total reference blocks | 269 |
|
| 53 |
+
| refs containing a DOI | 134/139 (96%) |
|
| 54 |
+
|
| 55 |
+
## ADS
|
| 56 |
+
|
| 57 |
+
- Collections: **16**
|
| 58 |
+
|
| 59 |
+
| field | coverage |
|
| 60 |
+
|---|---|
|
| 61 |
+
| doi | 16/16 (100%) |
|
| 62 |
+
| license | 16/16 (100%) |
|
| 63 |
+
| update_frequency | 2/16 (12%) |
|
| 64 |
+
| providers | 16/16 (100%) |
|
| 65 |
+
| keywords | 16/16 (100%) |
|
| 66 |
+
| published | 16/16 (100%) |
|
| 67 |
+
| updated | 16/16 (100%) |
|
| 68 |
+
| assets | 16/16 (100%) |
|
| 69 |
+
| spatial_bbox | 16/16 (100%) |
|
| 70 |
+
| temporal_interval | 16/16 (100%) |
|
| 71 |
+
| documentation_links | 16/16 (100%) |
|
| 72 |
+
| references | 16/16 (100%) |
|
| 73 |
+
| variables | 15/16 (94%) |
|
| 74 |
+
| message | 2/16 (12%) |
|
| 75 |
+
| total doc links | 53 |
|
| 76 |
+
| total reference blocks | 32 |
|
| 77 |
+
| refs containing a DOI | 16/16 (100%) |
|
| 78 |
+
|
| 79 |
+
## EWDS
|
| 80 |
+
|
| 81 |
+
- Collections: **12**
|
| 82 |
+
|
| 83 |
+
| field | coverage |
|
| 84 |
+
|---|---|
|
| 85 |
+
| doi | 12/12 (100%) |
|
| 86 |
+
| license | 12/12 (100%) |
|
| 87 |
+
| update_frequency | 12/12 (100%) |
|
| 88 |
+
| providers | 12/12 (100%) |
|
| 89 |
+
| keywords | 12/12 (100%) |
|
| 90 |
+
| published | 12/12 (100%) |
|
| 91 |
+
| updated | 12/12 (100%) |
|
| 92 |
+
| assets | 12/12 (100%) |
|
| 93 |
+
| spatial_bbox | 12/12 (100%) |
|
| 94 |
+
| temporal_interval | 12/12 (100%) |
|
| 95 |
+
| documentation_links | 12/12 (100%) |
|
| 96 |
+
| references | 12/12 (100%) |
|
| 97 |
+
| variables | 12/12 (100%) |
|
| 98 |
+
| message | 0/12 (0%) |
|
| 99 |
+
| total doc links | 58 |
|
| 100 |
+
| total reference blocks | 24 |
|
| 101 |
+
| refs containing a DOI | 12/12 (100%) |
|
| 102 |
+
|
| 103 |
+
## Unified
|
| 104 |
+
|
| 105 |
+
- unified_metadata.json entries: **1436** (cmems=1269, cds=139, ads=16, ewds=12)
|
| 106 |
+
|
| 107 |
+
- doi: 1422/1436 (99%)
|
| 108 |
+
- keywords: 1427/1436 (99%)
|
| 109 |
+
- documentation_links: 1435/1436 (100%)
|
| 110 |
+
- references: 1427/1436 (99%)
|
| 111 |
+
- licence: 1436/1436 (100%)
|
| 112 |
+
- update_frequency: 121/1436 (8%)
|
| 113 |
+
- spatial_bbox: 1321/1436 (92%)
|
| 114 |
+
- variables: 1317/1436 (92%)
|
| 115 |
+
- temporal_range (non-null): 1228/1436 (86%)
|
| 116 |
+
|
| 117 |
+
## Harvest volume
|
| 118 |
+
|
| 119 |
+
- Total bytes of JSON artifacts (incl. raw): **87,820,588**
|
scripts/notebook_harvest/parse_gallery.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Code-preserving parse of copernicus-marine-notebook-gallery notebooks.
|
| 3 |
+
Reuses the extract_code.py pattern: verbatim markdown + verbatim ```python
|
| 4 |
+
code cells + trimmed ```text outputs; classify recipe_kinds via regex.
|
| 5 |
+
Writes parsed/<name>/<notebook_id>.md and prints a JSON manifest to stdout.
|
| 6 |
+
"""
|
| 7 |
+
import json, re, sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
REPO = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/repos/copernicus-marine-notebook-gallery")
|
| 11 |
+
OUT = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/parsed/copernicus-marine-notebook-gallery")
|
| 12 |
+
ROOT = Path("/Users/dmpantiu/copernicus_mcp")
|
| 13 |
+
|
| 14 |
+
DOWNLOAD_RE = re.compile(
|
| 15 |
+
r"cdsapi|\.retrieve\(|copernicusmarine|\bcm\.(subset|get|open_dataset)|"
|
| 16 |
+
r"motuclient|--service-id|--product-id|!?\bwget\b|urlretrieve|requests\.get|\.hda\b|EO:",
|
| 17 |
+
re.I)
|
| 18 |
+
ANALYZE_RE = re.compile(
|
| 19 |
+
r"\bimport xarray|\bxr\.|\.open_dataset|\.open_mfdataset|\bimport pandas|\bpd\.|"
|
| 20 |
+
r"\bimport numpy|\bnp\.|\bscipy|nc\.Dataset|netCDF4|\.groupby\(|\.resample\(|"
|
| 21 |
+
r"\.mean\(|\.sel\(|\.isel\(", re.I)
|
| 22 |
+
PLOT_RE = re.compile(
|
| 23 |
+
r"\bmatplotlib|\bplt\.|\bcartopy|\bccrs\b|\bcmocean|\.plot\(|\.plot\.|seaborn|\bsns\.|pcolor|contourf",
|
| 24 |
+
re.I)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _src(cell):
|
| 28 |
+
s = cell.get("source", "")
|
| 29 |
+
return "".join(s) if isinstance(s, list) else s
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def code_line_count(code):
|
| 33 |
+
n = 0
|
| 34 |
+
for ln in code.splitlines():
|
| 35 |
+
st = ln.strip()
|
| 36 |
+
if st and not st.startswith("#"):
|
| 37 |
+
n += 1
|
| 38 |
+
return n
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def text_outputs(cell):
|
| 42 |
+
out = []
|
| 43 |
+
for o in cell.get("outputs", []):
|
| 44 |
+
ot = o.get("output_type"); s = None
|
| 45 |
+
if ot == "stream":
|
| 46 |
+
t = o.get("text", ""); s = "".join(t) if isinstance(t, list) else t
|
| 47 |
+
elif ot in ("execute_result", "display_data"):
|
| 48 |
+
tp = (o.get("data") or {}).get("text/plain")
|
| 49 |
+
if tp is not None:
|
| 50 |
+
s = "".join(tp) if isinstance(tp, list) else tp
|
| 51 |
+
if not s:
|
| 52 |
+
continue
|
| 53 |
+
s = s.strip()
|
| 54 |
+
if not s or re.fullmatch(r"<[^>]+>", s) or s.startswith("<Figure"):
|
| 55 |
+
continue
|
| 56 |
+
lines = [ln for ln in s.splitlines()
|
| 57 |
+
if "%|" not in ln and "it/s]" not in ln and "B/s]" not in ln]
|
| 58 |
+
s = "\n".join(lines).strip()
|
| 59 |
+
if len(s) >= 8:
|
| 60 |
+
out.append(s[:1500])
|
| 61 |
+
return out
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def classify(code):
|
| 65 |
+
kinds = []
|
| 66 |
+
if DOWNLOAD_RE.search(code): kinds.append("download")
|
| 67 |
+
if ANALYZE_RE.search(code): kinds.append("analyze")
|
| 68 |
+
if PLOT_RE.search(code): kinds.append("plot")
|
| 69 |
+
return kinds or ["other"]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def slug(path):
|
| 73 |
+
return re.sub(r"[^A-Za-z0-9._-]+", "-", path.stem).strip("-")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def extract(path):
|
| 77 |
+
nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
|
| 78 |
+
parts = []; n_cells = 0; n_lines = 0; kinds = set(); title = ""
|
| 79 |
+
for cell in nb.get("cells", []):
|
| 80 |
+
ct = cell.get("cell_type")
|
| 81 |
+
if ct == "markdown":
|
| 82 |
+
txt = _src(cell).strip()
|
| 83 |
+
if txt:
|
| 84 |
+
parts.append(txt)
|
| 85 |
+
if not title:
|
| 86 |
+
for ln in txt.splitlines():
|
| 87 |
+
if ln.startswith("# "):
|
| 88 |
+
title = ln[2:].strip(); break
|
| 89 |
+
elif ct == "code":
|
| 90 |
+
src = _src(cell).rstrip()
|
| 91 |
+
if not src.strip():
|
| 92 |
+
continue
|
| 93 |
+
n_cells += 1; n_lines += code_line_count(src)
|
| 94 |
+
kinds.update(classify(src))
|
| 95 |
+
parts.append("```python\n" + src + "\n```")
|
| 96 |
+
for to in text_outputs(cell):
|
| 97 |
+
parts.append("```text\n" + to + "\n```")
|
| 98 |
+
return {"md": "\n\n".join(parts).strip(), "title": title or path.stem,
|
| 99 |
+
"n_code_cells": n_cells, "n_code_lines": n_lines,
|
| 100 |
+
"recipe_kinds": sorted(kinds)}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main():
|
| 104 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 105 |
+
recs = []
|
| 106 |
+
for nb in sorted(REPO.rglob("*.ipynb")):
|
| 107 |
+
if ".ipynb_checkpoints" in nb.parts:
|
| 108 |
+
continue
|
| 109 |
+
nid = slug(nb)
|
| 110 |
+
ex = extract(nb)
|
| 111 |
+
if ex["n_code_cells"] == 0:
|
| 112 |
+
print(f"SKIP prose-only: {nid}", file=sys.stderr); continue
|
| 113 |
+
md = OUT / f"{nid}.md"
|
| 114 |
+
md.write_text(ex["md"], encoding="utf-8")
|
| 115 |
+
recs.append({
|
| 116 |
+
"notebook_id": nid, "title": ex["title"],
|
| 117 |
+
"src_path": str(nb.relative_to(REPO)),
|
| 118 |
+
"md_path": str(md.relative_to(ROOT)),
|
| 119 |
+
"n_code_cells": ex["n_code_cells"], "n_code_lines": ex["n_code_lines"],
|
| 120 |
+
"recipe_kinds": ex["recipe_kinds"],
|
| 121 |
+
})
|
| 122 |
+
print(json.dumps(recs, indent=2))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|
scripts/notebook_harvest/parse_instac.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Code-preserving parse + dataset mapping for CopernicusMarineInsitu/INSTACTraining."""
|
| 3 |
+
import json, re, sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
REPO = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/repos/INSTACTraining")
|
| 7 |
+
OUT = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/parsed/INSTACTraining")
|
| 8 |
+
CATALOG = Path("/Users/dmpantiu/copernicus_mcp/marine_rag/out/catalog.json")
|
| 9 |
+
|
| 10 |
+
DOWNLOAD_RE = re.compile(
|
| 11 |
+
r"cdsapi|\.retrieve\(|copernicusmarine|\bcm\.(subset|get|open_dataset)|"
|
| 12 |
+
r"motuclient|!?\bwget\b|!?\bcurl\b|urlretrieve|requests\.get|\bftplib\b|"
|
| 13 |
+
r"FTP\(|\.hda\b|urlopen|ftp://", re.I)
|
| 14 |
+
ANALYZE_RE = re.compile(
|
| 15 |
+
r"\bimport xarray|\bxr\.|\.open_dataset|\.open_mfdataset|\bimport pandas|\bpd\.|"
|
| 16 |
+
r"\bimport numpy|\bnp\.|\bnetCDF4|\bDataset\(|\bscipy|\.groupby\(|\.resample\(|"
|
| 17 |
+
r"\.mean\(|\.sel\(|\.isel\(", re.I)
|
| 18 |
+
PLOT_RE = re.compile(
|
| 19 |
+
r"\bmatplotlib|\bplt\.|\bcartopy|\bccrs\b|\bcmocean|\.plot\(|\.plot\.|seaborn|"
|
| 20 |
+
r"\bsns\.|\bfolium\b|basemap|\bBasemap\b", re.I)
|
| 21 |
+
|
| 22 |
+
# product id patterns (legacy + current)
|
| 23 |
+
PID_RE = re.compile(r"INSITU_[A-Z]+_[A-Z_]*?OBSERVATIONS_0\d\d_\d\d\d(?:_[a-z])?|"
|
| 24 |
+
r"INSITU_[A-Z]+_[A-Z_]+_0\d\d_\d\d\d", re.I)
|
| 25 |
+
DSID_RE = re.compile(r"cmems_obs-ins_[a-z0-9_-]+", re.I)
|
| 26 |
+
SUFFIX_RE = re.compile(r"(0\d\d_\d\d\d)")
|
| 27 |
+
|
| 28 |
+
# CMEMS INSTAC platform-file naming convention: <REGION>_<DATATYPE>_<PLATFORM>_<id>.nc
|
| 29 |
+
# region prefix (first token) -> regional DISCRETE_MYNRT product numeric suffix
|
| 30 |
+
REGION2SUFFIX = {"GL": "013_030", "AR": "013_031", "BO": "013_032", "BS": "013_034",
|
| 31 |
+
"IR": "013_033", "IB": "013_033", "MO": "013_035", "NO": "013_036"}
|
| 32 |
+
FILENAME_RE = re.compile(
|
| 33 |
+
r"\b(GL|AR|BO|BS|IR|IB|MO|NO)_(TS|PR|WS|CT|GL|TG|SF|WV|RF|HF)_[A-Z]{2}_[A-Za-z0-9_]+\.nc")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _src(cell):
|
| 37 |
+
s = cell.get("source", "")
|
| 38 |
+
return "".join(s) if isinstance(s, list) else s
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def code_line_count(code):
|
| 42 |
+
return sum(1 for ln in code.splitlines()
|
| 43 |
+
if ln.strip() and not ln.strip().startswith("#"))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def text_outputs(cell):
|
| 47 |
+
out = []
|
| 48 |
+
for o in cell.get("outputs", []):
|
| 49 |
+
ot = o.get("output_type"); s = None
|
| 50 |
+
if ot == "stream":
|
| 51 |
+
t = o.get("text", ""); s = "".join(t) if isinstance(t, list) else t
|
| 52 |
+
elif ot in ("execute_result", "display_data"):
|
| 53 |
+
tp = (o.get("data") or {}).get("text/plain")
|
| 54 |
+
if tp is not None:
|
| 55 |
+
s = "".join(tp) if isinstance(tp, list) else tp
|
| 56 |
+
if not s:
|
| 57 |
+
continue
|
| 58 |
+
s = s.strip()
|
| 59 |
+
if not s or re.fullmatch(r"<[^>]+>", s) or s.startswith("<Figure"):
|
| 60 |
+
continue
|
| 61 |
+
lines = [ln for ln in s.splitlines()
|
| 62 |
+
if "%|" not in ln and "it/s]" not in ln and "B/s]" not in ln]
|
| 63 |
+
s = "\n".join(lines).strip()
|
| 64 |
+
if len(s) >= 8:
|
| 65 |
+
out.append(s[:1500])
|
| 66 |
+
return out
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def classify(code):
|
| 70 |
+
kinds = []
|
| 71 |
+
if DOWNLOAD_RE.search(code): kinds.append("download")
|
| 72 |
+
if ANALYZE_RE.search(code): kinds.append("analyze")
|
| 73 |
+
if PLOT_RE.search(code): kinds.append("plot")
|
| 74 |
+
return kinds or ["other"]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def slug(path):
|
| 78 |
+
rel = path.relative_to(REPO).with_suffix("")
|
| 79 |
+
return "__".join(rel.parts).replace(" ", "_")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def extract_notebook(path):
|
| 83 |
+
nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
|
| 84 |
+
parts, n_code_cells, n_code_lines = [], 0, 0
|
| 85 |
+
kinds, title = set(), ""
|
| 86 |
+
raw_all = []
|
| 87 |
+
for cell in nb.get("cells", []):
|
| 88 |
+
ct = cell.get("cell_type")
|
| 89 |
+
if ct == "markdown":
|
| 90 |
+
txt = _src(cell).strip()
|
| 91 |
+
if txt:
|
| 92 |
+
parts.append(txt); raw_all.append(txt)
|
| 93 |
+
if not title:
|
| 94 |
+
for ln in txt.splitlines():
|
| 95 |
+
if ln.startswith("# "):
|
| 96 |
+
title = ln[2:].strip(); break
|
| 97 |
+
elif ct == "code":
|
| 98 |
+
src = _src(cell).rstrip()
|
| 99 |
+
if not src.strip():
|
| 100 |
+
continue
|
| 101 |
+
n_code_cells += 1
|
| 102 |
+
n_code_lines += code_line_count(src)
|
| 103 |
+
kinds.update(classify(src))
|
| 104 |
+
raw_all.append(src)
|
| 105 |
+
parts.append("```python\n" + src + "\n```")
|
| 106 |
+
for to in text_outputs(cell):
|
| 107 |
+
parts.append("```text\n" + to + "\n```")
|
| 108 |
+
raw_all.append(to)
|
| 109 |
+
return {
|
| 110 |
+
"content_md": "\n\n".join(parts).strip(),
|
| 111 |
+
"title": title or path.stem,
|
| 112 |
+
"n_code_cells": n_code_cells,
|
| 113 |
+
"n_code_lines": n_code_lines,
|
| 114 |
+
"recipe_kinds": sorted(kinds),
|
| 115 |
+
"raw": "\n".join(raw_all),
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def main():
|
| 120 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 121 |
+
catalog = json.load(open(CATALOG))
|
| 122 |
+
suffix2pid = {}
|
| 123 |
+
valid_pids = set()
|
| 124 |
+
dsid2pid = {}
|
| 125 |
+
for e in catalog:
|
| 126 |
+
pid = e.get("product_id")
|
| 127 |
+
if not pid:
|
| 128 |
+
continue
|
| 129 |
+
valid_pids.add(pid)
|
| 130 |
+
m = SUFFIX_RE.search(pid)
|
| 131 |
+
if m:
|
| 132 |
+
suffix2pid.setdefault(m.group(1), pid)
|
| 133 |
+
for ds in (e.get("dataset_ids") or []):
|
| 134 |
+
dsid2pid[ds] = pid
|
| 135 |
+
|
| 136 |
+
records = []
|
| 137 |
+
nbs = sorted(p for p in REPO.rglob("*.ipynb")
|
| 138 |
+
if ".ipynb_checkpoints" not in p.parts)
|
| 139 |
+
for nb in nbs:
|
| 140 |
+
ex = extract_notebook(nb)
|
| 141 |
+
nid = slug(nb)
|
| 142 |
+
if ex["n_code_cells"] == 0:
|
| 143 |
+
print(f"SKIP prose-only: {nid}", file=sys.stderr)
|
| 144 |
+
continue
|
| 145 |
+
(OUT / f"{nid}.md").write_text(ex["content_md"], encoding="utf-8")
|
| 146 |
+
|
| 147 |
+
raw = ex["raw"]
|
| 148 |
+
found_pids = set()
|
| 149 |
+
raw_ids = set()
|
| 150 |
+
for m in PID_RE.findall(raw):
|
| 151 |
+
raw_ids.add(m)
|
| 152 |
+
sm = SUFFIX_RE.search(m)
|
| 153 |
+
if sm and sm.group(1) in suffix2pid:
|
| 154 |
+
found_pids.add(suffix2pid[sm.group(1)])
|
| 155 |
+
for m in DSID_RE.findall(raw):
|
| 156 |
+
raw_ids.add(m)
|
| 157 |
+
if m in dsid2pid:
|
| 158 |
+
found_pids.add(dsid2pid[m])
|
| 159 |
+
# fallback: infer product from INSTAC platform-file naming convention
|
| 160 |
+
if not found_pids:
|
| 161 |
+
for region, dtype in FILENAME_RE.findall(raw):
|
| 162 |
+
suf = REGION2SUFFIX.get(region.upper())
|
| 163 |
+
if suf and suf in suffix2pid:
|
| 164 |
+
found_pids.add(suffix2pid[suf])
|
| 165 |
+
fm = FILENAME_RE.search(raw)
|
| 166 |
+
if fm:
|
| 167 |
+
raw_ids.add("file:" + fm.group(0))
|
| 168 |
+
matched = sorted(found_pids)
|
| 169 |
+
scope = "dataset" if matched else "generic"
|
| 170 |
+
records.append({
|
| 171 |
+
"notebook_id": nid,
|
| 172 |
+
"title": ex["title"],
|
| 173 |
+
"matched_dataset_ids": matched,
|
| 174 |
+
"raw_ids": sorted(raw_ids),
|
| 175 |
+
"store": "CMEMS in-situ",
|
| 176 |
+
"scope": scope,
|
| 177 |
+
"source_repo": "CopernicusMarineInsitu/INSTACTraining",
|
| 178 |
+
"license": "MIT",
|
| 179 |
+
"src_path": str(nb.relative_to(REPO)),
|
| 180 |
+
"md_path": f"notebook_harvest/parsed/INSTACTraining/{nid}.md",
|
| 181 |
+
"n_code_cells": ex["n_code_cells"],
|
| 182 |
+
"n_code_lines": ex["n_code_lines"],
|
| 183 |
+
"recipe_kinds": ex["recipe_kinds"],
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
print(json.dumps(records, indent=2))
|
| 187 |
+
tot_lines = sum(r["n_code_lines"] for r in records)
|
| 188 |
+
print(f"\nNOTEBOOKS={len(records)} TOTAL_CODE_LINES={tot_lines}", file=sys.stderr)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
main()
|