File size: 4,527 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
#!/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/<name>/<notebook_id>.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("<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):
    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()