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