| |
| """ |
| 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 |
| |
| 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]) |
| 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 = [] |
| 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 |
| |
| (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() |
|
|