File size: 7,164 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
#!/usr/bin/env python3
"""Code-preserving parse + dataset mapping for CopernicusMarineInsitu/INSTACTraining."""
import json, re, sys
from pathlib import Path

REPO = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/repos/INSTACTraining")
OUT = Path("/Users/dmpantiu/copernicus_mcp/notebook_harvest/parsed/INSTACTraining")
CATALOG = Path("/Users/dmpantiu/copernicus_mcp/marine_rag/out/catalog.json")

DOWNLOAD_RE = re.compile(
    r"cdsapi|\.retrieve\(|copernicusmarine|\bcm\.(subset|get|open_dataset)|"
    r"motuclient|!?\bwget\b|!?\bcurl\b|urlretrieve|requests\.get|\bftplib\b|"
    r"FTP\(|\.hda\b|urlopen|ftp://", re.I)
ANALYZE_RE = re.compile(
    r"\bimport xarray|\bxr\.|\.open_dataset|\.open_mfdataset|\bimport pandas|\bpd\.|"
    r"\bimport numpy|\bnp\.|\bnetCDF4|\bDataset\(|\bscipy|\.groupby\(|\.resample\(|"
    r"\.mean\(|\.sel\(|\.isel\(", re.I)
PLOT_RE = re.compile(
    r"\bmatplotlib|\bplt\.|\bcartopy|\bccrs\b|\bcmocean|\.plot\(|\.plot\.|seaborn|"
    r"\bsns\.|\bfolium\b|basemap|\bBasemap\b", re.I)

# product id patterns (legacy + current)
PID_RE = re.compile(r"INSITU_[A-Z]+_[A-Z_]*?OBSERVATIONS_0\d\d_\d\d\d(?:_[a-z])?|"
                    r"INSITU_[A-Z]+_[A-Z_]+_0\d\d_\d\d\d", re.I)
DSID_RE = re.compile(r"cmems_obs-ins_[a-z0-9_-]+", re.I)
SUFFIX_RE = re.compile(r"(0\d\d_\d\d\d)")

# CMEMS INSTAC platform-file naming convention: <REGION>_<DATATYPE>_<PLATFORM>_<id>.nc
# region prefix (first token) -> regional DISCRETE_MYNRT product numeric suffix
REGION2SUFFIX = {"GL": "013_030", "AR": "013_031", "BO": "013_032", "BS": "013_034",
                 "IR": "013_033", "IB": "013_033", "MO": "013_035", "NO": "013_036"}
FILENAME_RE = re.compile(
    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")


def _src(cell):
    s = cell.get("source", "")
    return "".join(s) if isinstance(s, list) else s


def code_line_count(code):
    return sum(1 for ln in code.splitlines()
               if ln.strip() and not ln.strip().startswith("#"))


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):
    rel = path.relative_to(REPO).with_suffix("")
    return "__".join(rel.parts).replace(" ", "_")


def extract_notebook(path):
    nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
    parts, n_code_cells, n_code_lines = [], 0, 0
    kinds, title = set(), ""
    raw_all = []
    for cell in nb.get("cells", []):
        ct = cell.get("cell_type")
        if ct == "markdown":
            txt = _src(cell).strip()
            if txt:
                parts.append(txt); raw_all.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))
            raw_all.append(src)
            parts.append("```python\n" + src + "\n```")
            for to in text_outputs(cell):
                parts.append("```text\n" + to + "\n```")
                raw_all.append(to)
    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),
        "raw": "\n".join(raw_all),
    }


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    catalog = json.load(open(CATALOG))
    suffix2pid = {}
    valid_pids = set()
    dsid2pid = {}
    for e in catalog:
        pid = e.get("product_id")
        if not pid:
            continue
        valid_pids.add(pid)
        m = SUFFIX_RE.search(pid)
        if m:
            suffix2pid.setdefault(m.group(1), pid)
        for ds in (e.get("dataset_ids") or []):
            dsid2pid[ds] = pid

    records = []
    nbs = sorted(p for p in REPO.rglob("*.ipynb")
                 if ".ipynb_checkpoints" not in p.parts)
    for nb in nbs:
        ex = extract_notebook(nb)
        nid = slug(nb)
        if ex["n_code_cells"] == 0:
            print(f"SKIP prose-only: {nid}", file=sys.stderr)
            continue
        (OUT / f"{nid}.md").write_text(ex["content_md"], encoding="utf-8")

        raw = ex["raw"]
        found_pids = set()
        raw_ids = set()
        for m in PID_RE.findall(raw):
            raw_ids.add(m)
            sm = SUFFIX_RE.search(m)
            if sm and sm.group(1) in suffix2pid:
                found_pids.add(suffix2pid[sm.group(1)])
        for m in DSID_RE.findall(raw):
            raw_ids.add(m)
            if m in dsid2pid:
                found_pids.add(dsid2pid[m])
        # fallback: infer product from INSTAC platform-file naming convention
        if not found_pids:
            for region, dtype in FILENAME_RE.findall(raw):
                suf = REGION2SUFFIX.get(region.upper())
                if suf and suf in suffix2pid:
                    found_pids.add(suffix2pid[suf])
                    fm = FILENAME_RE.search(raw)
                    if fm:
                        raw_ids.add("file:" + fm.group(0))
        matched = sorted(found_pids)
        scope = "dataset" if matched else "generic"
        records.append({
            "notebook_id": nid,
            "title": ex["title"],
            "matched_dataset_ids": matched,
            "raw_ids": sorted(raw_ids),
            "store": "CMEMS in-situ",
            "scope": scope,
            "source_repo": "CopernicusMarineInsitu/INSTACTraining",
            "license": "MIT",
            "src_path": str(nb.relative_to(REPO)),
            "md_path": f"notebook_harvest/parsed/INSTACTraining/{nid}.md",
            "n_code_cells": ex["n_code_cells"],
            "n_code_lines": ex["n_code_lines"],
            "recipe_kinds": ex["recipe_kinds"],
        })

    print(json.dumps(records, indent=2))
    tot_lines = sum(r["n_code_lines"] for r in records)
    print(f"\nNOTEBOOKS={len(records)} TOTAL_CODE_LINES={tot_lines}", file=sys.stderr)


if __name__ == "__main__":
    main()