File size: 7,649 Bytes
0ec8fd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | #!/usr/bin/env python3
"""
extract_code.py — CODE-PRESERVING re-extraction of the EQC notebooks.
Companion to parse_reports.py (which is text-only and DROPS runnable code).
This one keeps every code cell verbatim so the notebooks can be ATTACHED to
RAG chunks (payload riders keyed by dataset_id) — the agent then sees the real
cdsapi / copernicusmarine / xarray / plot code, not just prose.
Does NOT mutate any Qdrant index and does NOT touch existing parsed/*.md.
Outputs (all new):
eqc_qa/notebooks_code/<report_id>.md full reconstruction (```python fences)
eqc_qa/notebooks_by_dataset.json dataset_id -> [notebook attach records]
eqc_qa/extract_code_stats.json summary
Mapping reuses eqc_qa/reports.jsonl (matched_dataset_id / store / confidence).
"""
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
REPO = ROOT / "repo"
MANIFEST = ROOT / "reports.jsonl"
OUT_MD = ROOT / "notebooks_code"
OUT_SIDECAR = ROOT / "notebooks_by_dataset.json"
OUT_STATS = ROOT / "extract_code_stats.json"
SOURCE_REPO = "ecmwf-projects/c3s2-eqc-quality-assessment"
LICENSE = "Apache-2.0"
DOWNLOAD_RE = re.compile(
r"cdsapi|\.retrieve\(|copernicusmarine|\bcm\.(subset|get|open_dataset)|"
r"c3s_eqc_automatic_quality_control|\bdownload\.|from .*import .*download|"
r"!?\bwget\b|urlretrieve|requests\.get|\.hda\b|EO:",
re.I,
)
ANALYZE_RE = re.compile(
r"\bimport xarray|\bxr\.|\.open_dataset|\.open_mfdataset|\bimport pandas|\bpd\.|"
r"\bimport numpy|\bnp\.|\bscipy|\bxskillscore|\bruptures|\.groupby\(|\.resample\(|"
r"\.mean\(|\.sel\(|\.isel\(",
re.I,
)
PLOT_RE = re.compile(
r"\bmatplotlib|\bplt\.|\bcartopy|\bccrs\b|\bcmocean|\.plot\(|\.plot\.|seaborn|\bsns\.",
re.I,
)
def log(*a):
print(*a, file=sys.stderr, flush=True)
def _src(cell) -> str:
s = cell.get("source", "")
return "".join(s) if isinstance(s, list) else s
def code_line_count(code: str) -> int:
n = 0
for ln in code.splitlines():
st = ln.strip()
if st and not st.startswith("#"):
n += 1
return n
def text_outputs(cell) -> list[str]:
"""Trimmed text outputs (stdout/stderr/text-plain), dropping progress-bar / warning noise."""
out = []
for o in cell.get("outputs", []):
ot = o.get("output_type")
s = None
if ot == "stream":
t = o.get("text", "")
s = "".join(t) if isinstance(t, list) else t
elif ot in ("execute_result", "display_data"):
tp = (o.get("data") or {}).get("text/plain")
if tp is not None:
s = "".join(tp) if isinstance(tp, list) else tp
if not s:
continue
s = s.strip()
if not s or re.fullmatch(r"<[^>]+>", s) or s.startswith("<Figure"):
continue
# drop tqdm-style progress bars and pure warning spew
lines = [ln for ln in s.splitlines()
if "%|" not in ln and "it/s]" not in ln and "B/s]" not in ln]
s = "\n".join(lines).strip()
if len(s) >= 8:
out.append(s[:1500]) # cap giant dumps
return out
def classify(code: str) -> list[str]:
kinds = []
if DOWNLOAD_RE.search(code):
kinds.append("download")
if ANALYZE_RE.search(code):
kinds.append("analyze")
if PLOT_RE.search(code):
kinds.append("plot")
return kinds or ["other"]
def extract_notebook(path: Path) -> dict:
nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
parts = [] # reconstructed md
n_code_cells = 0
n_code_lines = 0
kinds = set()
title = ""
for cell in nb.get("cells", []):
ct = cell.get("cell_type")
if ct == "markdown":
txt = _src(cell).strip()
if txt:
parts.append(txt)
if not title:
for ln in txt.splitlines():
if ln.startswith("# "):
title = ln[2:].strip()
break
elif ct == "code":
src = _src(cell).rstrip()
if not src.strip():
continue
n_code_cells += 1
n_code_lines += code_line_count(src)
kinds.update(classify(src))
parts.append("```python\n" + src + "\n```")
for to in text_outputs(cell):
parts.append("```text\n" + to + "\n```")
return {
"content_md": "\n\n".join(parts).strip(),
"title": title or path.stem,
"n_code_cells": n_code_cells,
"n_code_lines": n_code_lines,
"recipe_kinds": sorted(kinds),
}
def main():
OUT_MD.mkdir(exist_ok=True)
manifest = {r["report_id"]: r for r in
(json.loads(l) for l in MANIFEST.read_text().splitlines() if l.strip())}
log(f"manifest: {len(manifest)} reports")
sidecar: dict[str, list] = {}
unmatched: list = []
stats = {"notebooks": 0, "code_cells": 0, "code_lines": 0,
"with_download": 0, "with_analyze": 0, "with_plot": 0,
"attached_datasets": 0, "unmatched_notebooks": 0}
for nb in sorted(REPO.rglob("*.ipynb")):
report_id = nb.stem
rec = manifest.get(report_id, {})
ex = extract_notebook(nb)
if ex["n_code_cells"] == 0:
continue # prose-only (e.g. Applications write-ups) — nothing to attach
# write full reconstruction
(OUT_MD / f"{report_id}.md").write_text(ex["content_md"], encoding="utf-8")
attach = {
"notebook_id": report_id,
"title": ex["title"],
"store": rec.get("store") or "CDS",
"matched_dataset_id": rec.get("matched_dataset_id") or "",
"raw_dataset_id": rec.get("dataset_id") or "",
"category": rec.get("category") or "",
"aspect": rec.get("aspect") or "",
"match_confidence": rec.get("match_confidence") or "unmatched",
"source_repo": SOURCE_REPO,
"license": LICENSE,
"src_path": rec.get("src_path") or str(nb.relative_to(REPO)),
"md_path": str((OUT_MD / f"{report_id}.md").relative_to(ROOT.parent)),
"n_code_cells": ex["n_code_cells"],
"n_code_lines": ex["n_code_lines"],
"recipe_kinds": ex["recipe_kinds"],
}
stats["notebooks"] += 1
stats["code_cells"] += ex["n_code_cells"]
stats["code_lines"] += ex["n_code_lines"]
stats["with_download"] += "download" in ex["recipe_kinds"]
stats["with_analyze"] += "analyze" in ex["recipe_kinds"]
stats["with_plot"] += "plot" in ex["recipe_kinds"]
key = attach["matched_dataset_id"]
if key:
sidecar.setdefault(key, []).append(attach)
else:
unmatched.append(attach)
stats["unmatched_notebooks"] += 1
stats["attached_datasets"] = len(sidecar)
OUT_SIDECAR.write_text(json.dumps(
{"by_dataset": sidecar, "unmatched": unmatched}, ensure_ascii=False, indent=2))
OUT_STATS.write_text(json.dumps(stats, indent=2))
log(f"notebooks with code : {stats['notebooks']}")
log(f"code cells / lines : {stats['code_cells']} / {stats['code_lines']:,}")
log(f"download/analyze/plot: {stats['with_download']}/{stats['with_analyze']}/{stats['with_plot']}")
log(f"attached to datasets : {stats['attached_datasets']} (unmatched notebooks: {stats['unmatched_notebooks']})")
log(f"-> {OUT_SIDECAR.relative_to(ROOT.parent)}, {OUT_MD.relative_to(ROOT.parent)}/*.md")
if __name__ == "__main__":
main()
|