"""Package each chapter's canonical text, atoms and misconceptions for the tutor. Reads every chapter in syllabus/igcse/quizzes/*.json (the source of truth for chapters), follows its atoms_file to the atoms workbook and the matching content//*.md, and writes apps/selfcheck-space/data/chapters/.json. Run from the project root: python apps/selfcheck-space/tools/build_tutor_data.py """ import json import pathlib import re import openpyxl ROOT = pathlib.Path(__file__).resolve().parents[3] IGCSE = ROOT / "syllabus" / "igcse" OUT = ROOT / "apps" / "selfcheck-space" / "data" / "chapters" def rows(ws): it = ws.iter_rows(values_only=True) head = [str(c or "").strip().lower() for c in next(it)] for r in it: if r and r[0]: yield {h: ("" if v is None else str(v).strip()) for h, v in zip(head, r)} def col(row, *prefixes): for p in prefixes: for k, v in row.items(): if k.startswith(p): return v return "" def split_ids(s): return [x for x in re.split(r"[;,\s]+", s or "") if x and x.lower() not in ("none", "-")] def main(): OUT.mkdir(parents=True, exist_ok=True) for sc in sorted((IGCSE / "quizzes").glob("*.json")): s = json.loads(sc.read_text(encoding="utf-8")) s["id"] = s["chapterId"] atoms_path = ROOT / s["atoms_file"] slug = atoms_path.stem.removesuffix("_atoms") content = sorted((IGCSE / "content" / s["code"]).glob(f"{slug}*.md")) if not content: raise SystemExit(f"no content file for {s['id']} ({slug})") wb = openpyxl.load_workbook(atoms_path, read_only=True, data_only=True) atoms = [] for r in rows(wb["atoms"]): if r.get("type") == "misconception": continue atoms.append({ "id": r["id"], "type": r.get("type", ""), "statement": r.get("statement", ""), "why": col(r, "why"), "prerequisites": split_ids(r.get("prerequisites", "")), "tier": r.get("tier", ""), "paragraphs": col(r, "source_paragraphs"), }) misconceptions = [{ "id": r["id"], "wrong": col(r, "wrong belief"), "correct": col(r, "correcting statement", "correcting stat"), "atoms": split_ids(col(r, "correcting atom")), } for r in rows(wb["misconceptions"])] ids = {a["id"] for a in atoms} for a in atoms: # keep only prerequisites inside this chapter a["prerequisites"] = [p for p in a["prerequisites"] if p in ids] doc = { "id": s["id"], "subject": s["subject"], "code": s["code"], "chapter": s["chapter"], "text": content[0].read_text(encoding="utf-8"), "atoms": atoms, "misconceptions": misconceptions, } (OUT / f"{s['id']}.json").write_text(json.dumps(doc, ensure_ascii=False), encoding="utf-8") print(f"{s['id']}: {len(atoms)} atoms, {len(misconceptions)} misconceptions, " f"{len(doc['text'].split())} words <- {content[0].name}") if __name__ == "__main__": main()