"""Build the Precalculus problem bank from Hugging Face datasets (local, one-time). python -m src.edtech_core.ingest_datasets # download + normalize → JSONL python -m src.edtech_core.ingest_datasets --embed # also embed into Chroma (resumable) Sources (see src/config.py): - toloka/u-math, subject == precalculus_review only. - shiwk24/MathCanvas-Instruct, config Analytic_Geometry, filtered to precalculus sub-topics. Read column-by-column from the parquet shards so the ~350 MB/shard of solution images is never downloaded. Every record keeps the dataset's own answer (`answer`) as the answer key — quiz answer keys are never produced by an LLM. """ from __future__ import annotations import argparse import base64 import io import json from collections import Counter import pyarrow.parquet as pq from huggingface_hub import HfFileSystem, hf_hub_download from PIL import Image from src.config import ( MATHCANVAS_CONFIG, MATHCANVAS_DATASET, MATHCANVAS_IMAGES_PER_SUBTOPIC, MATHCANVAS_SUBKNOWLEDGE, PROBLEM_BANK_FILE, PROBLEMS_DIR, UMATH_DATASET, UMATH_SUBJECTS, ) from src.edtech_core.curriculum import MATHCANVAS_SUBKNOWLEDGE_TOPICS, classify_text IMAGES_DIR = PROBLEMS_DIR / "images" _TEXT_COLS = ["id", "question_interleave", "solution_interleave", "answer", "options", "subknowledge"] def _rel(path) -> str: return str(path.relative_to(PROBLEMS_DIR.parent.parent)) # repo-relative, portable def _answer_format(options: list, answer: str) -> str: if options: return "multiple_choice" if "<2>" in (answer or ""): return "multi_part" return "short_answer" # ---------------------------------------------------------------------------- U-MATH def load_umath() -> list[dict]: path = hf_hub_download(UMATH_DATASET, "data/test-00000-of-00001.parquet", repo_type="dataset") rows = pq.read_table(path).to_pylist() out = [] for r in rows: if r["subject"] not in UMATH_SUBJECTS: continue image_paths = [] if r["has_image"] and r["image"] and r["image"].startswith("data:image"): img_path = IMAGES_DIR / "umath" / f"{r['uuid']}.png" img_path.parent.mkdir(parents=True, exist_ok=True) img_path.write_bytes(base64.b64decode(r["image"].split(",", 1)[1])) image_paths.append(_rel(img_path)) out.append({ "id": f"umath.{r['uuid']}", "source": UMATH_DATASET, "source_label": r["subject"], "topic": classify_text(r["problem_statement"]), "statement": r["problem_statement"], "answer": r["golden_answer"], "options": [], "solution": None, # U-MATH ships golden answers only "answer_format": "short_answer", "needs_image": bool(r["has_image"]), "image_paths": image_paths, }) return out # ------------------------------------------------------------------------ MathCanvas def _join_text(parts: list[dict]) -> str: chunks = [] for p in parts or []: chunks.append(p["content"] if p["type"] == "text" else "[figure]") return "\n".join(chunks).strip() def _save_question_images(row_id: str, images: list[dict]) -> list[str]: paths = [] for i, img in enumerate(images or []): data = img.get("bytes") if isinstance(img, dict) else None if not data: continue p = IMAGES_DIR / "mathcanvas" / f"{row_id}-q{i}.png" p.parent.mkdir(parents=True, exist_ok=True) Image.open(io.BytesIO(data)).save(p) paths.append(_rel(p)) return paths def load_mathcanvas() -> list[dict]: fs = HfFileSystem() shards = sorted(fs.glob(f"datasets/{MATHCANVAS_DATASET}/data/train/{MATHCANVAS_CONFIG}-*.parquet")) keep = set(MATHCANVAS_SUBKNOWLEDGE) images_saved: Counter = Counter() out = [] for shard in shards: pf = pq.ParquetFile(fs.open(shard)) for g in range(pf.num_row_groups): rows = pf.read_row_group(g, columns=_TEXT_COLS).to_pylist() selected = [i for i, r in enumerate(rows) if r["subknowledge"] in keep] if not selected: continue # Only fetch the (heavy) question_images column if some selected row in this # row group still has image budget left. def wants_image(r): cap = MATHCANVAS_IMAGES_PER_SUBTOPIC has_fig = any(p["type"] == "image" for p in r["question_interleave"] or []) return has_fig and (cap is None or images_saved[r["subknowledge"]] < cap) q_images = None if any(wants_image(rows[i]) for i in selected): q_images = pf.read_row_group(g, columns=["question_images"]).column(0).to_pylist() for i in selected: r = rows[i] statement = _join_text(r["question_interleave"]) needs_image = "[figure]" in statement image_paths = [] if needs_image and q_images is not None and wants_image(r): image_paths = _save_question_images(r["id"], q_images[i]) if image_paths: images_saved[r["subknowledge"]] += 1 candidates = MATHCANVAS_SUBKNOWLEDGE_TOPICS[r["subknowledge"]] options = [{"letter": o["letter"], "value": o["value"]} for o in (r["options"] or [])] out.append({ "id": f"mathcanvas.{r['id']}", "source": MATHCANVAS_DATASET, "source_label": r["subknowledge"], "topic": classify_text(statement, candidates=candidates, default=candidates[0]), "statement": statement, "answer": r["answer"], "options": options, "solution": _join_text(r["solution_interleave"]), "answer_format": _answer_format(options, r["answer"]), "needs_image": needs_image, "image_paths": image_paths, }) print(f"[mathcanvas] {shard.rsplit('/', 1)[-1]}: {len(out)} problems so far", flush=True) return out # ---------------------------------------------------------------------------- embed def embed_problem_bank(batch: int = 32) -> None: """Resumable: only embeds problems whose id isn't already in the collection.""" import chromadb from src.config import CHROMA_COLLECTIONS, CHROMA_PATH from src.edtech_core.curriculum import TOPIC_BY_ID from src.edtech_core.embeddings import BgeM3EmbeddingFunction problems = [json.loads(line) for line in PROBLEM_BANK_FILE.open()] coll = chromadb.PersistentClient(path=CHROMA_PATH).get_or_create_collection( CHROMA_COLLECTIONS["problems"], embedding_function=BgeM3EmbeddingFunction(), metadata={"hnsw:space": "cosine"}, ) have = set(coll.get(include=[])["ids"]) todo = [p for p in problems if p["id"] not in have] print(f"[embed] {len(have)} already embedded, {len(todo)} to go", flush=True) for i in range(0, len(todo), batch): chunk = todo[i : i + batch] coll.add( ids=[p["id"] for p in chunk], documents=[f"{TOPIC_BY_ID[p['topic']].title}: {p['statement'][:1500]}" for p in chunk], metadatas=[{"topic": p["topic"], "source": p["source"], "answer_format": p["answer_format"], "quizzable": (not p["needs_image"]) or bool(p["image_paths"])} for p in chunk], ) if (i // batch) % 25 == 0: print(f"[embed] {min(i + batch, len(todo))}/{len(todo)}", flush=True) print(f"[embed] done — {coll.count()} problems in collection", flush=True) sync_topic_metadata(coll, problems) def sync_topic_metadata(coll, problems: list[dict], batch: int = 500) -> None: """Push re-tagged topics (curriculum keyword fixes) into Chroma metadata — no re-embedding.""" want = {p["id"]: p["topic"] for p in problems} got = coll.get(include=["metadatas"]) stale = [(i, m) for i, m in zip(got["ids"], got["metadatas"]) if i in want and m.get("topic") != want[i]] for k in range(0, len(stale), batch): chunk = stale[k : k + batch] coll.update(ids=[i for i, _ in chunk], metadatas=[{**m, "topic": want[i]} for i, m in chunk]) print(f"[embed] topic metadata synced for {len(stale)} problems", flush=True) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--embed", action="store_true", help="also embed the bank into Chroma") ap.add_argument("--embed-only", action="store_true", help="skip download, just (resume) embedding") args = ap.parse_args() if not args.embed_only: PROBLEMS_DIR.mkdir(parents=True, exist_ok=True) umath = load_umath() print(f"[u-math] {len(umath)} precalculus problems", flush=True) mc = load_mathcanvas() bank = umath + mc with PROBLEM_BANK_FILE.open("w") as f: for p in bank: f.write(json.dumps(p, ensure_ascii=False) + "\n") print(f"[bank] wrote {len(bank)} problems → {PROBLEM_BANK_FILE}") print("[bank] by topic:", dict(Counter(p["topic"] for p in bank).most_common())) quizzable = sum(1 for p in bank if not p["needs_image"] or p["image_paths"]) print(f"[bank] quizzable (text-only or image saved): {quizzable}") if args.embed or args.embed_only: embed_problem_bank() if __name__ == "__main__": main()