#!/usr/bin/env python3 """Code-preserving parse of copernicus-marine-notebook-gallery notebooks. Reuses the extract_code.py pattern: verbatim markdown + verbatim ```python code cells + trimmed ```text outputs; classify recipe_kinds via regex. Writes parsed//.md and prints a JSON manifest to stdout. """ import json, re, sys from pathlib import Path REPO = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/repos/copernicus-marine-notebook-gallery") OUT = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/parsed/copernicus-marine-notebook-gallery") ROOT = Path("/Users/dmpantiu/copernicus_mcp") DOWNLOAD_RE = re.compile( r"cdsapi|\.retrieve\(|copernicusmarine|\bcm\.(subset|get|open_dataset)|" r"motuclient|--service-id|--product-id|!?\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|nc\.Dataset|netCDF4|\.groupby\(|\.resample\(|" r"\.mean\(|\.sel\(|\.isel\(", re.I) PLOT_RE = re.compile( r"\bmatplotlib|\bplt\.|\bcartopy|\bccrs\b|\bcmocean|\.plot\(|\.plot\.|seaborn|\bsns\.|pcolor|contourf", re.I) def _src(cell): s = cell.get("source", "") return "".join(s) if isinstance(s, list) else s def code_line_count(code): n = 0 for ln in code.splitlines(): st = ln.strip() if st and not st.startswith("#"): n += 1 return n def text_outputs(cell): 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("= 8: out.append(s[:1500]) return out def classify(code): 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 slug(path): return re.sub(r"[^A-Za-z0-9._-]+", "-", path.stem).strip("-") def extract(path): nb = json.loads(path.read_text(encoding="utf-8", errors="replace")) parts = []; n_cells = 0; n_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_cells += 1; n_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 {"md": "\n\n".join(parts).strip(), "title": title or path.stem, "n_code_cells": n_cells, "n_code_lines": n_lines, "recipe_kinds": sorted(kinds)} def main(): OUT.mkdir(parents=True, exist_ok=True) recs = [] for nb in sorted(REPO.rglob("*.ipynb")): if ".ipynb_checkpoints" in nb.parts: continue nid = slug(nb) ex = extract(nb) if ex["n_code_cells"] == 0: print(f"SKIP prose-only: {nid}", file=sys.stderr); continue md = OUT / f"{nid}.md" md.write_text(ex["md"], encoding="utf-8") recs.append({ "notebook_id": nid, "title": ex["title"], "src_path": str(nb.relative_to(REPO)), "md_path": str(md.relative_to(ROOT)), "n_code_cells": ex["n_code_cells"], "n_code_lines": ex["n_code_lines"], "recipe_kinds": ex["recipe_kinds"], }) print(json.dumps(recs, indent=2)) if __name__ == "__main__": main()