ed-tech-studio / src /edtech_core /ingest_textbook.py
BenjaminKaindu0506's picture
Precalculus Studio: placement, worked examples, retrieval quizzes, peer instruction (part 5)
1289247 verified
Raw History Blame Contribute Delete
4.1 kB
"""One-time ingestion: OpenStax Precalculus 2e PDF → section-tagged chunks → Chroma.
python -m src.edtech_core.ingest_textbook
Unlike v2 (page-only metadata), every chunk carries chapter / section / section title /
curriculum topic, taken from the PDF's own bookmark outline. That's what lets the
Retrieval Agent fetch "context for the topic this quiz item belongs to" and cite the
section in feedback. Answer-key and index pages are excluded (see config).
Resumable: chunk ids are deterministic and existing ids are skipped.
"""
from __future__ import annotations
import re
import chromadb
from langchain_text_splitters import RecursiveCharacterTextSplitter
from pypdf import PdfReader
from src.config import CHROMA_COLLECTIONS, CHROMA_PATH, TEXTBOOK_CONTENT_PAGES, TEXTBOOK_NAME, TEXTBOOK_PDF
from src.edtech_core.curriculum import topic_for_section
from src.edtech_core.embeddings import BgeM3EmbeddingFunction
_SECTION_RE = re.compile(r"^(\d{1,2}\.\d{1,2})\s+(.+)$")
_CHAPTER_RE = re.compile(r"^Chapter\s+(\d{1,2})\b")
def section_page_map(reader: PdfReader) -> list[tuple[int, str, str, int]]:
"""[(start_page_1idx, section, section_title, chapter)] sorted by start page."""
marks: list[tuple[int, str, str, int]] = []
chapter = 0
def walk(outline):
nonlocal chapter
for node in outline:
if isinstance(node, list):
walk(node)
continue
page = reader.get_destination_page_number(node) + 1
if m := _CHAPTER_RE.match(node.title):
chapter = int(m.group(1))
marks.append((page, f"{chapter}.0", f"Chapter {chapter} introduction", chapter))
elif m := _SECTION_RE.match(node.title):
marks.append((page, m.group(1), m.group(2), chapter))
elif node.title in ("Chapter Review", "Exercises") and chapter:
marks.append((page, f"{chapter}.review", f"Chapter {chapter} {node.title.lower()}", chapter))
walk(reader.outline)
return sorted(marks)
def _locate(page: int, marks) -> tuple[str, str, int]:
current = (None, "", 0)
for start, section, title, chapter in marks:
if start > page:
break
current = (section, title, chapter)
return current # type: ignore[return-value]
def main(batch: int = 32) -> None:
reader = PdfReader(str(TEXTBOOK_PDF))
marks = section_page_map(reader)
first, last = TEXTBOOK_CONTENT_PAGES
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
docs, metas, ids = [], [], []
for page in range(first, last + 1):
text = reader.pages[page - 1].extract_text() or ""
if not text.strip():
continue
section, title, chapter = _locate(page, marks)
topic = topic_for_section(section) or ""
for j, chunk in enumerate(splitter.split_text(text)):
docs.append(chunk)
metas.append({"source": TEXTBOOK_NAME, "page": page, "chapter": chapter,
"section": section or "", "section_title": title, "topic": topic})
ids.append(f"precalc2e.p{page}.c{j}")
print(f"[textbook] {len(docs)} chunks from pages {first}-{last}", flush=True)
coll = chromadb.PersistentClient(path=CHROMA_PATH).get_or_create_collection(
CHROMA_COLLECTIONS["textbook"], embedding_function=BgeM3EmbeddingFunction(),
metadata={"hnsw:space": "cosine"},
)
have = set(coll.get(include=[])["ids"])
todo = [i for i, cid in enumerate(ids) if cid not in have]
print(f"[textbook] {len(have)} already embedded, {len(todo)} to go", flush=True)
for k in range(0, len(todo), batch):
idx = todo[k : k + batch]
coll.add(ids=[ids[i] for i in idx], documents=[docs[i] for i in idx], metadatas=[metas[i] for i in idx])
if (k // batch) % 20 == 0:
print(f"[textbook] {min(k + batch, len(todo))}/{len(todo)}", flush=True)
print(f"[textbook] done — {coll.count()} chunks in '{CHROMA_COLLECTIONS['textbook']}'")
if __name__ == "__main__":
main()