File size: 7,567 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 194 195 196 197 198 199 200 201 202 203 204 | #!/usr/bin/env python3
"""
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)
# ── catalogue for dataset mapping ────────────────────────────────────────────
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"
# fuzzy: substring either direction (guard against trivially short ids)
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"
# ── text extraction ──────────────────────────────────────────────────────────
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("%"): # skip trivial / magics
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:
# skip pure object reprs like "<Figure ...>" / matplotlib handles
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)
# image/png, image/jpeg, image/svg+xml, application/* -> skipped entirely
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 = first H1
title = ""
for ln in md.splitlines():
if ln.startswith("# "):
title = ln[2:].strip()
break
if not title:
title = path.stem
return md, title
# ── manifest build ───────────────────────────────────────────────────────────
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()
|