| |
| """ |
| parse_reports.py — extract TEXT only from each EQC QA notebook. |
| |
| For every repo/**/*.ipynb (parsed as JSON, no nbformat dependency): |
| - markdown cells -> kept verbatim (prose: methodology, findings, verdicts; |
| headings preserved for section-aware chunking) |
| - code cells -> comment lines from source (prose intent) + TEXT outputs |
| (stream stdout/stderr, execute_result/display_data |
| 'text/plain'). SKIP image/png/jpeg/svg/base64/raw data. |
| |
| Filename encodes dataset + report type: |
| <prefix>_<dataset_id>_<aspect>_q<NN>.ipynb |
| e.g. satellite_satellite-sea-surface-temperature_consistency_q01 |
| -> dataset=satellite-sea-surface-temperature aspect=consistency q=q01 |
| |
| Dataset mapping: cross-reference dataset_id against the CDS/ADS/EWDS catalogue |
| (meta_harvest/{cds,ads,ewds}_enriched.json); exact -> fuzzy substring -> unmatched. |
| |
| Outputs: |
| eqc_qa/parsed/<report_id>.md |
| eqc_qa/reports.jsonl (manifest, one line per report) |
| |
| templates/template.ipynb is a scaffold (not a dataset report): parsed for text |
| but flagged is_template and left dataset-unmatched. |
| """ |
| import json |
| import sys |
| import re |
| from pathlib import Path |
|
|
| ROOT = Path(__file__).resolve().parent |
| REPO = ROOT / "repo" |
| PARSED = ROOT / "parsed" |
| MANIFEST = ROOT / "reports.jsonl" |
| META = ROOT.parent / "meta_harvest" |
|
|
|
|
| def log(*a): |
| print(*a, file=sys.stderr, flush=True) |
|
|
|
|
| |
| def load_catalogue() -> dict[str, str]: |
| ids: dict[str, str] = {} |
| for name, store in (("cds", "CDS"), ("ads", "ADS"), ("ewds", "EWDS")): |
| p = META / f"{name}_enriched.json" |
| if p.exists(): |
| for k in json.loads(p.read_text()): |
| ids[k] = store |
| return ids |
|
|
|
|
| def map_dataset(dataset_id: str, catalogue: dict[str, str]) -> tuple[str, str, str]: |
| """Return (matched_id, store, confidence:{exact,fuzzy,unmatched}).""" |
| if not dataset_id: |
| return "", "", "unmatched" |
| if dataset_id in catalogue: |
| return dataset_id, catalogue[dataset_id], "exact" |
| |
| if len(dataset_id) >= 5: |
| cands = [k for k in catalogue if dataset_id in k or k in dataset_id] |
| if cands: |
| best = min(cands, key=len) |
| return best, catalogue[best], "fuzzy" |
| return "", "", "unmatched" |
|
|
|
|
| |
| def _src(cell) -> str: |
| s = cell.get("source", "") |
| return "".join(s) if isinstance(s, list) else s |
|
|
|
|
| def comment_lines(code: str) -> list[str]: |
| out = [] |
| for ln in code.splitlines(): |
| st = ln.strip() |
| if st.startswith("#") and not st.startswith("#!"): |
| txt = st.lstrip("#").strip() |
| if len(txt) >= 12 and not txt.startswith("%"): |
| out.append(txt) |
| return out |
|
|
|
|
| def text_outputs(cell) -> list[str]: |
| out = [] |
| for o in cell.get("outputs", []): |
| ot = o.get("output_type") |
| if ot == "stream": |
| t = o.get("text", "") |
| out.append("".join(t) if isinstance(t, list) else t) |
| elif ot in ("execute_result", "display_data"): |
| data = o.get("data", {}) |
| tp = data.get("text/plain") |
| if tp is not None: |
| |
| s = "".join(tp) if isinstance(tp, list) else tp |
| s = s.strip() |
| if s and not re.fullmatch(r"<[^>]+>", s) and not s.startswith("<Figure"): |
| out.append(s) |
| |
| return out |
|
|
|
|
| def parse_notebook(path: Path) -> tuple[str, str]: |
| """Return (markdown_text, title).""" |
| nb = json.loads(path.read_text(encoding="utf-8", errors="replace")) |
| parts: list[str] = [] |
| for cell in nb.get("cells", []): |
| ct = cell.get("cell_type") |
| if ct == "markdown": |
| txt = _src(cell).strip() |
| if txt: |
| parts.append(txt) |
| elif ct == "code": |
| src = _src(cell) |
| cmts = comment_lines(src) |
| if cmts: |
| parts.append("\n".join(cmts)) |
| for to in text_outputs(cell): |
| to = to.strip() |
| if to and len(to) >= 8: |
| parts.append("```text\n" + to + "\n```") |
| md = "\n\n".join(parts).strip() |
| |
| title = "" |
| for ln in md.splitlines(): |
| if ln.startswith("# "): |
| title = ln[2:].strip() |
| break |
| if not title: |
| title = path.stem |
| return md, title |
|
|
|
|
| |
| def main() -> None: |
| PARSED.mkdir(exist_ok=True) |
| catalogue = load_catalogue() |
| log(f"catalogue: {len(catalogue)} collection ids") |
|
|
| nbs = sorted(REPO.rglob("*.ipynb")) |
| log(f"parsing {len(nbs)} notebooks") |
|
|
| records = [] |
| stats = {"exact": 0, "fuzzy": 0, "unmatched": 0} |
| for nb in nbs: |
| rel = nb.relative_to(REPO) |
| category = rel.parts[0] |
| report_id = nb.stem |
| toks = report_id.split("_") |
| is_template = len(toks) != 4 |
| if is_template: |
| dataset_id, aspect_base, qnum = "", "", "" |
| else: |
| _prefix, dataset_id, aspect_base, qnum = toks |
| aspect = f"{aspect_base}_{qnum}" if aspect_base else "" |
|
|
| matched_id, store, conf = map_dataset(dataset_id, catalogue) |
| if is_template: |
| conf = "unmatched" |
| stats[conf] += 1 |
|
|
| md, title = parse_notebook(nb) |
| md_path = PARSED / f"{report_id}.md" |
| md_path.write_text(md, encoding="utf-8") |
|
|
| rec = { |
| "report_id": report_id, |
| "dataset_id": dataset_id, |
| "matched_dataset_id": matched_id, |
| "store": store, |
| "match_confidence": conf, |
| "category": category, |
| "aspect": aspect, |
| "aspect_base": aspect_base, |
| "qnum": qnum, |
| "title": title, |
| "md_path": str(md_path.relative_to(ROOT)), |
| "n_chars": len(md), |
| "is_template": is_template, |
| "src_path": str(rel), |
| } |
| records.append(rec) |
|
|
| with open(MANIFEST, "w", encoding="utf-8") as f: |
| for r in records: |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") |
|
|
| reports = [r for r in records if not r["is_template"]] |
| log(f"wrote {len(records)} manifest rows ({len(reports)} reports + " |
| f"{len(records)-len(reports)} template) -> {MANIFEST}") |
| log(f"mapping: exact={stats['exact']} fuzzy={stats['fuzzy']} unmatched={stats['unmatched']}") |
| ndatasets = len({r['matched_dataset_id'] for r in reports if r['match_confidence'] != 'unmatched'}) |
| log(f"reports mapped to a known collection: " |
| f"{sum(1 for r in reports if r['match_confidence']!='unmatched')}/{len(reports)} " |
| f"across {ndatasets} unique collections") |
| log(f"total chars: {sum(r['n_chars'] for r in records):,}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|