Module 05: Projects

Retrieval4 projects0 of 4 complete

Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.

Four projects: two starters and two stretches (the scan-to-search project is optional). Everything runs keylessly — parsing, cleaning, chunking, metadata, pipelines, synthetic-data scaffolding and quality checks are all local Python on the module's generated Acme corpus. The only steps that need an API key are the hosted question-generation and VLM-OCR extensions, which are marked as such; the lessons' illustrative provider samples show the call shapes if you want to try them.

First time? Create the shared project once, exactly as 05.1 sets it up:

bash
uv init data-pipeline --bare --python 3.13 && cd data-pipeline
mkdir -p data/raw data/parsed data/chunks data/exports scripts

Then add the dependency groups from 05.1's Setup (or just uv add the packages each project's Setup names). Run scripts with uv run python file.py.

The reusable spine. The projects assemble the modules the lessons built: ParsedDocument and parse_pdf (05.2), the parser registry pattern (05.3), cleaner.py (05.5), Chunk/to_chunks and the splitters (05.6, and 05.7 if you took that optional lesson), meta_models.py (05.8), pipeline.py (05.9), synth_eval.py (10A.2) and the dq.py suite (05.10). Where a project says "copy the file from lesson X", the full source is in that lesson — copy it verbatim, then modify.


Starter

Starter: Document ingestion pipeline#

Goal: Turn the running Acme corpus — PDFs, HTML pages, JSONL tickets, a CSV, a docx and some deliberately unparseable scans — into chunks.jsonl: clean text, sensible chunk boundaries, and metadata rich enough to filter, cite and audit every record.

What you'll practise:

  • Generating the shared corpus and auditing it before building (lesson 05.1, 8.2, 5.2)
  • Parsing each format into a common shape, including the born-digital vs scanned routing decision (05.2, Part 9, 10.2; 05.3, 11.2)
  • Main-content extraction and metadata from HTML (05.3, 2.4, 2.7)
  • Rows-to-text for structured records (05.1, 4.3)
  • Cleaning with the composable cleaner.py, keeping raw and cleaned text (05.5, 11.2)
  • Chunking with the Chunk model, deterministic content-addressed IDs and neighbour pointers (05.6, 4.4, 6.3)
  • Attaching document and chunk metadata, including ACLs and lineage (05.8, 2.7, 3.3)

Setup:

bash
uv add pydantic ftfy pytest
uv add beautifulsoup4 lxml trafilatura markdownify
uv add python-docx pypdf pdfminer.six pdfplumber

(Or pip install the same package names.) These install the newest release of each package; the samples were checked against the versions in the lessons' Setup sections, and pypdf is already on its 7.x line, so read the note in 05.2, 2.2 if your PDF output differs. python-docx reads the policy file; pdfplumber/pypdf read the handbook and contract PDFs; trafilatura + BeautifulSoup handle the help centre. pymupdf is deliberately not installed — its AGPL licence is a real decision (05.2, 2.5).

Steps:

  1. Generate and audit the corpus. Copy scripts/make_corpus.py from 05.1, Part 8 into scripts/ and run uv run python scripts/make_corpus.py. Then run the audit script s5_2_audit_corpus.py from the same lesson on data/corpus and keep its output — it is your baseline for "what should exist". Expect the inventory to show 14 files: the handbook PDF, four help-centre HTML pages, tickets.jsonl, one contract PDF (vendor-agreement.pdf) plus three scan-*.png images, two transcripts, pricing.csv and the policy docx (pricing.xlsx appears only if openpyxl is installed when you run the generator).
  2. Build parsed_document.py. Copy the BBox, TextBlock, TableBlock, ImageBlock, ParsedPage, ParseInfo and ParsedDocument models from 05.2, Part 9 verbatim. This is the contract every parser feeds.
  3. Build parsers.py. Write a parse_file(path) -> ParsedDocument dispatcher in the style of the registry in 05.3, 11.2, but returning ParsedDocument instead of ParseResult:
    • .html → extract main content with trafilatura.extract(..., output_format="markdown") (fall back to BeautifulSoup get_text with script/style/nav/footer removed if trafilatura returns None), plus title/canonical/date metadata into ParseInfo.metadata (05.3, 2.4, 2.7).
    • .pdf → adapt the parse_pdf function from 05.2, 10.2 (pdfplumber primary, pypdf fallback, per-page coverage check). The corpus PDFs are born-digital, so no OCR path fires.
    • .docx → python-docx: one TextBlock per paragraph, kind="heading" and level from the style name (05.3, 6.2).
    • .jsonl → row-as-document: render each ticket as a short document ("Ticket T-1002 — Dana Whitfield — …") using the template approach in 05.1, 4.3.
    • .csv → the same rows-to-text treatment; keep the header row as the column vocabulary.
    • .txt (transcripts) → keep speaker turns and [HH:MM:SS] timestamps as lines; do not strip them.
    • .png/.xlsx → no parser yet: emit a ParsedDocument with warnings=["no parser for …"] and mark every page needs_review=True. The scans are project 4's job; the xlsx can be added with openpyxl as a stretch. Wrap each parser call in try/except and record the failure in warnings — one bad file must not kill the run (05.2, 10.3).
  4. Write ingest.py. Walk data/corpus, call parse_file per file, and write one JSON line per document to data/parsed/parsed.jsonl (use model_dump_json()). Print a per-file summary: pages/blocks, char count, warnings.
  5. Clean. Save the 05.5 cleaner.py (clean(), STEPS, CleanResult) into the project. In ingest.py (or a second pass clean.py), run clean(text, explain=True) on each document's flattened text. Write data/parsed/cleaned.jsonl carrying both the raw text and the cleaned text plus the per-step change counts from CleanResult — the raw text is never overwritten (05.5, 1.2). Read the change log with a critical eye: s_boilerplate only removes banner-shaped lines (Page 3 of 12, Confidential — …, All rights reserved., © 2026 …), and the help-centre footer © Acme. All rights reserved. is none of those, so on this corpus it survives unless trafilatura already dropped it. Extend BOILER_RE for it, or rely on the parser-level removal, and say which you chose.
  6. Chunk. Reuse the splitters from 05.6: recursive_split for prose documents and markdown_chunks for the HTML-derived Markdown and the handbook (structure-aware boundaries beat blind recursion — see the 7.1 decision table). Convert each splitter's output through to_chunks(doc_id, pieces, chunker_version) so every chunk gets its deterministic chk_… ID, prev/next pointers and occurrence disambiguation (05.6, 6.3). to_chunks expects a list of dicts whose keys are Chunk field names (text, section_path, optional char_start/char_end): wrap recursive_split's plain strings as {"text": s}, and drop the extra section key from markdown_chunks' dicts, as the demo at the end of 05.6 Part 6.3 does, or Chunk(**p) raises a TypeError. Set chunker_version="starter-v1" and section_path from headings where the splitter provides them.
  7. Attach metadata. Import DocumentMeta, ChunkMeta, Lineage, QualityFlags and friends from meta_models.py (05.8, 2.7). For each document build a DocumentMeta: doc_id = doc_ plus the first 24 hex characters of the sha256 of the source path and content hash (the model's pattern is exactly doc_ + 24 hex characters, so a full 64-character digest fails validation), slug, tenant_id="acme", source_system="filesystem", source_uri, content_hash (sha256 of the raw bytes), doc_type from the folder (handbook, help_article, ticket, contract, transcript, spreadsheet, policy), language="en", confidentiality/acl from a small dict you write in the code (contracts/ → internal plus an AclEntry(principal_type="group", principal_id="legal"), everything else internal plus all-staff; the flat allowed_groups key is derived for you by store_payload()), and the dates (ingested_at = now, modified_at = file mtime). Then build one ChunkMeta per chunk: chunk_id, doc=doc, chunk_index, section_path, prev_chunk_id/next_chunk_id, chunk_text_hash (sha256 of the chunk text) and lineage=Lineage(parser_name=…, parser_version=…, cleaning_version=…, chunker_name=…, chunker_version=…, ingestion_run_id=…). ChunkMeta forbids extra fields, so the chunk text and embed_input (from chunk.embed_input()) do not go inside it: they sit beside it in the JSONL record of step 8.
  8. Write data/chunks/chunks.jsonl. One JSON object per chunk: chunk_id, doc_id, text, embed_input, section_path, prev_chunk_id, next_chunk_id, meta (the flat ChunkMeta.store_payload()). Keep it flat — vector stores want flat, null-free payloads (05.8, 6.3).
  9. Report. Print: files seen, files parsed, files warned/failed, documents produced, chunks produced, chunks per doc_type, and the total change counts the cleaner reported. Save the same as data/exports/run_report.json.

Verify it, and what you should see:

bash
uv run python ingest.py            # first run: parses + cleans + chunks everything
uv run python ingest.py            # second run: identical chunks.jsonl
wc -l data/chunks/chunks.jsonl     # dozens of chunks, not hundreds — toy corpus
uv run python -c "import json; [print(json.loads(l)['chunk_id'], json.loads(l)['doc_id']) for l in open('data/chunks/chunks.jsonl')]" | head -5

What to check, concretely:

  • The second run produces a byte-identical chunks.jsonl (same IDs, same order). If IDs change between runs, something nondeterministic slipped in — a timestamp inside an ID, an unordered dict iteration, or a random seed. 05.9, 1.2 is the contract you're testing early.
  • Every chunk_id starts with chk_ and is stable when you re-run; deleting a middle chunk's neighbour does not re-ID the survivors (position is excluded from the ID by design, 05.6, 6.4).
  • The help-centre chunks carry embed_input with a breadcrumb like Acme Help > Shipping and delivery and no nav/footer text — check one text field against the raw HTML.
  • The scan-*.png files produced warnings, not silence: they appear in the report as needs_review, proving failure isolation works.
  • tickets.jsonl produced one document per ticket (or a small number of entity-centric docs if you chose that route), each chunkable on its own.

Expected shape (counts will differ with your splitter settings — the structure is what matters):

Example output · illustrative4 lines
files seen: 14 -> parsed 11, warned 3 (scan-*.png), failed 0
chunks: 24 across handbook(4) help_article(8) ticket(3) contract(2) transcript(2) policy(1) spreadsheet(4)
cleaner: 2 lines removed by s_boilerplate, 0 mojibake fixes (ftfy skipped or no change), idempotent on re-run
sample chunk: chk_9f2c… doc_id=doc_41ab… section='Acme Help > Tracking'

Done when:

  • chunks.jsonl exists, the metadata of every chunk validates against your ChunkMeta model (validate before you flatten it with store_payload()), and the second run is byte-identical.
  • You can point at one chunk and trace it back: chunk → document → source file → raw bytes, through the lineage and doc_id fields.
  • At least three distinct failure modes were handled explicitly (the scans, at least one parser fallback, and the cleaner's change log) — not silently.
  • Your run report accounts for every file in data/corpus: parsed, warned or failed, with reasons.

Stretch ideas:

  • Add OCR routing for the scan-*.png files using the 05.4, 4.2 routing function — that's project 4 in miniature.
  • Add near-duplicate detection with MinHash/LSH from 05.5, 6.3 and report how many chunks it would drop.
  • Switch the help-centre chunks to markdown_chunks with real section paths, and compare chunk counts and breadcrumbs against the recursive baseline (05.6, 4.5).
  • Add the dq.py suite from 05.10, 12.2 as a final stage: check_chunk_coverage, check_chunk_sizes, check_chunk_uniqueness, then gate() and print the verdict (05.10, 10.1).
  • Run the hidden_text_report scan from 05.5, 2.7 on every raw document before cleaning and add its counts to run_report.json; plant one document with a benign tag-character placeholder (as in the lesson's demo) and confirm the report catches it and the document goes to a review list.
  • Compare your chunker with the library chunkers of 05.6, 4.5.1 on the handbook PDF, using the recall@k harness of 05.6 Part 7.
  • Needs a key (optional): run deterministic + LLM enrichment from 05.8, 7.3 to fill topics/audience, with the prompt and model versioned in lineage.

Common problems:

  • BeautifulSoup get_text() includes JavaScript. Remove script, style, nav, footer, noscript and [hidden] elements before extracting, or trafilatura's output will be polluted (05.3, 2.4).
  • The corpus PDF is minimal. make_corpus.py writes a single-font, single-column PDF with no tables — it exercises the plumbing, not the layout failures. For table/column cases, generate a richer PDF with reportlab as 05.2's exercises suggest.
  • .xlsx has no parser in the registry. Either add openpyxl (data_only=True for cached values — the formula-vs-value gotcha is 05.3, 6.3) or leave it warned like the scans.
  • Cleaner is not magic. If clean() strips too much (numbers, clause references), that's the over-cleaning failure from 05.5, 1.4 — check the change log per step before blaming the chunker.
  • doc_id stability. If you hash the file path, moving the corpus re-IDs everything; hash source identity + content instead (05.8, 3.1).

Starter

Starter: Synthetic evaluation set#

Goal: Turn the chunks.jsonl from the first project into eval_questions.jsonl — a versioned set of questions with reference answers, cited chunk IDs and provenance — plus an honest dataset card. The keyless path uses the lesson's deterministic stub; wiring a hosted model is the marked extension.

What you'll practise:

  • Stratified chunk sampling instead of shuffling (10.2, 2.2)
  • The question-type taxonomy and the generation prompt (10A.2, 2.3, 2.4)
  • Schema-validated generation with GeneratedQuestion (10A.2, 2.5)
  • Structural validation, deduplication and dataset accounting (10A.2, 3.1, 3.2)
  • The complete chunks → questions → JSONL → card pipeline (10A.2, Part 11)
  • Why lexical leakage, circularity and licence terms matter (10A.2, 1.3, 1.4, 2.8)

Setup: the same data-pipeline project as project 1, plus:

bash
uv add pydantic
# hosted generation only — pick the providers you have keys for:
uv add python-dotenv openai anthropic google-genai

chunks.jsonl comes from project 1. If you skipped it, write a six-line toy file yourself — one JSON object per line with {"chunk_id", "doc_id", "doc_type", "source", "text"} (the exact shape synth_eval.py's load_chunks expects); three chunks sharing an opening sentence is enough to make dedup fire.

Steps:

  1. Save the pipeline. Copy synth_eval.py from 10A.2, Part 11 verbatim — it is complete and runs on the stub. Also copy question_model.py and gen_questions_prompt.txt from 2.5 and 2.4 for the hosted step.
  2. Run the stub end to end. synth_eval.py expects plain chunk dicts, not the full records of project 1, so first write export_chunks.py, which reads chunks.jsonl and emits the five-field shape (chunk_id, doc_id, doc_type from meta, source = doc_id, text). Then uv run python synth_eval.py chunks_for_eval.jsonl. Read the stats: kept + dedup_dropped + rejected must equal total_generated — every call lands in exactly one bucket.
  3. Inspect the output. Open eval_questions.jsonl: every item has id, question, question_type, reference_answer, answerable, cited_chunk_ids, evidence_span, persona, language, generator, prompt_version, created_at. Verify every cited_chunk_ids value exists in your chunks file and every non-null evidence_span is a verbatim substring of the cited chunk's text (the pipeline checks this; confirm it yourself on three items).
  4. Read the card. eval_questions_card.md states items kept/generated, rejection reasons, the by-type and by-doc-type breakdown, and — deliberately — what was not done (no judge, no human review). Keep that honesty; a card that overclaims is worse than none.
  5. Swap in a real generator (needs a key). Implement hosted_generate(chunk, qtype, persona) with the signature generate expects, wrapping the provider call from 10A.2, 2.5: build the user message from the 2.4 template, call your provider's structured-output path, validate the result into GeneratedQuestion, and return it as a dict. Run the same synth_eval.py — every downstream stage is unchanged.
  6. Add the validation stages the pipeline leaves out. Between dedup and write, add: the answerability check from 3.1, difficulty rating from 3.3, an LLM-judge pass from a different model family than your generator (3.4 — using the same family is the circularity trap), and a stratified human review of ~10% of items (3.6). Record verdicts back into the card.
  7. Version the dataset. Bump prompt_version in the item provenance whenever you change the prompt or model, and regenerate only items citing changed chunks (10A.2, 3.7).

Verify it, and what you should see:

bash
uv run python synth_eval.py chunks_for_eval.jsonl
cat eval_questions_card.md

The lesson's own real run on a six-chunk toy file printed:

text
{
  "total_generated": 12,
  "kept": 7,
  "dedup_dropped": 5,
  "rejected": {},
  "by_type": {"factoid": 5, "numeric": 2},
  "by_doc_type": {"handbook": 3, "ticket": 4},
  "seconds": 0.0
}

On your corpus the numbers differ, but the invariants hold: every generated item is accounted for, cited_chunk_ids all resolve, evidence_span is verbatim, and the card admits the stub/judge/review gaps. A hosted run (needs a key) should produce natural questions whose question_type mix matches what you asked for — and whose word overlap with the source chunk you can measure with the leakage check in 2.8 rather than eyeball.

Done when:

  • eval_questions.jsonl exists with the full provenance fields on every item, and every citation resolves to a real chunk.
  • The stats buckets sum correctly and the dedup drop rate is reported, not hidden.
  • The dataset card states generator, prompt version, validation performed and known limits honestly.
  • You can name which failure modes your current set is exposed to (leakage, circularity, homogeneity) and which step would catch each.

Stretch ideas:

  • Generate unanswerable and multi_hop_cross items deliberately — they are what abstention and multi-chunk retrieval evals need (10A.2, 2.7).
  • Build noisy fixtures with noisy_docs.py (10A.2, 4.3) and corrupted scans with degrade_scan.py (4.5) to stress-test the project-1 pipeline itself.
  • Add a two-model user simulator from Part 5 and export transcripts for Module 08A's agent testing.
  • Measure diversity of your question set with diversity_metrics.py (7.5) before and after rotating personas.
  • Needs a key: estimate the real cost first with gen_cost.py (Part 10) — tokens per item × items × (1 + judge fraction + regeneration churn).

Common problems:

  • Lexical leakage. If questions copy the chunk's distinctive words, BM25 wins trivially and your eval flatters the system. Add the paraphrase rule to the prompt and measure overlap (10A.2, 2.8).
  • Dedup too aggressive. Shingle-Jaccard at 0.7 can drop legitimately distinct questions about the same topic — sweep the threshold on your set (10A.2, 3.2).
  • Stub output is placeholders. stub_generate derives questions mechanically; its card says so. Never quote stub accuracy as evidence about a model.
  • Judge circularity. Judging claude-* output with claude-* shares blind spots; pick a different family for the judge role.
  • Evidence span drift. If you clean or re-chunk after generating, evidence_span stops being verbatim — regenerate items citing changed chunks rather than fudging the check.

Stretch

Stretch: Incremental ingestion service#

Goal: Turn the lesson's minimal pipeline into a service that ingests your project-1 corpus incrementally: a SQLite manifest classifies every source as new/changed/unchanged/deleted, only changed documents re-process, unchanged chunks keep their embeddings by content-addressed ID, failures quarantine instead of killing the run, and a quality gate decides pass/warn/fail on every run.

What you'll practise:

  • The engineering contract: idempotency, determinism, immutable raw data, stage separation (05.9, 1.2)
  • Content hashing and meaningful change detection (05.9, 2.2, 2.5)
  • The manifest schema and the classify → process → diff → delete → reconcile algorithm (05.9, 3.1, 3.2)
  • Chunk-level diffing and embedding reuse via content-addressed IDs (05.9, 3.3; 05.6, 6.4)
  • Atomic write-then-flip and manifest↔store reconciliation (05.9, 3.4, 3.5)
  • Per-document error isolation, poison documents and dry-run (05.9, 8.1, 8.2, 4.5)
  • Wiring the dq.py quality suite in as a gate stage (05.10, 12.7, 10.1)

Setup:

bash
uv add httpx        # only for the optional conditional-fetch step

The core is pure standard library. You need pipeline.py from the 05.9 appendix and the dq.py, profiling.py, golden.py files from 05.10, Part 12, plus the stage functions from projects 1–2 (parsers.py, cleaner.py, the chunker, meta_models.py).

Steps:

  1. Run the lesson's pipeline as-is. Copy pipeline.py into a scratch folder and create the toy sources/ folder by running make_sources.py from 05.9, 4.1 (six small .md/.txt files, one of them deliberately broken, so your counters match the ones the lesson prints). Then run the commands from 05.9's Setup: first run ingests everything, second run does nothing, --dry-run reports without writing, and --repair fixes reconciliation drift (you will use it in step 4). Read Part 4 so the outputs make sense.
  2. Replace the toy stages. The appendix's parse_clean and chunk_document are deliberately trivial. Point them at your real stages: parse_file → clean() → recursive_split/markdown_chunks → to_chunks. Keep the pipeline's own make_chunk_id/manifest schema intact — the point is that your stages now run inside the lesson's state machinery. Bump CHUNKER_VERSION and PARSER_VERSION to your real values.
  3. Point it at the corpus. Copy data/corpus to data/corpus_ingest/ (step 4 edits and deletes files, and you want the project-1 baseline untouched) and pass that folder as --sources. Add the corpus suffixes (.html, .jsonl, .csv, .docx, .png) to DOC_SUFFIXES and give each a route in parse_clean; unknown types should produce a warning record, not a crash. Documents the parser can't handle (the scans) become per-document errors that quarantine — exactly the fail-soft behaviour in 05.9, 8.1.
  4. Prove incremental correctness. Run the verification sequence from the lesson's exercises: run twice (second run: 0 embed calls, all unchanged); edit one sentence inside a section and re-run — only the chunks whose text changed should appear in chunks_new, the rest chunks_reused; delete a file — its chunks and vector rows must disappear; add a file — only it processes. Check pipeline.db tables documents, chunks, runs, errors, tombstones and vectors.db after each step. Finally, simulate drift (delete one row from the vector store by hand), confirm the end-of-run reconciliation reports it as manifest_only, then re-run with --repair and confirm the next report shows zero drift (05.9, 3.5).
  5. Exercise the edge cases. Add a trailing-newline-only change (should be unchanged — hash the meaningful content or accept the conservative re-process and say which you chose, 05.9, 2.2); rename a file (URI-derived doc_id makes it delete+new — discuss the fix: hash a stable source ID, 05.9, 2.5); corrupt one file (it lands in errors with stage+message and retries next run).
  6. Add the quality gate. After run_update, run the relevant dq.py checks on this run's outputs — check_chunk_coverage, check_chunk_sizes, check_chunk_uniqueness, check_garbage_ratio, check_pii_scan — then gate(results) and render_report(...). Persist the GateResult verdict into the runs table (add a verdict column) so every run has a recorded quality outcome (05.10, 12.7).
  7. Add an HTTP source (optional). Implement conditional_fetch from 05.9, 2.3 with httpx: store etag/last_modified per URL in the manifest, get 304 Not Modified for unchanged pages, and feed changed bodies through the same parse→clean→chunk path.
  8. Make it a service shape. Wrap run_update in a while True: run_update(); sleep(N) loop or a cron/launchd entry — the lesson's 6.6 decision table argues plain Python + scheduler is right at this scale. For the orchestrator version, port the flow to Prefect tasks or Dagster assets using 6.4/6.5 as the pattern (illustrative — install only if you want the UI).
  9. Test it. Write pytest tests: idempotency (two runs → second does zero chunk work), per-stage unit tests, a golden-document test using golden.py's golden_compare on one parsed doc, and a contract test asserting chunks.jsonl records still satisfy ChunkMeta (05.9, Part 11, 05.10, Part 5).

Verify it, and what you should see:

bash
uv run python pipeline.py --sources data/corpus_ingest --db pipeline.db --vectors vectors.db
uv run python pipeline.py --sources data/corpus_ingest --db pipeline.db --vectors vectors.db   # all unchanged
# edit one sentence in a handbook section, then:
uv run python pipeline.py --sources data/corpus_ingest --db pipeline.db --vectors vectors.db
sqlite3 pipeline.db "SELECT new, changed, unchanged, deleted, chunks_new, chunks_reused FROM runs ORDER BY started_at DESC LIMIT 1"
sqlite3 pipeline.db "SELECT verdict FROM runs ORDER BY started_at DESC LIMIT 1"   # after step 6

Expected behaviour (the lesson's real toy-corpus run shows the same shape): the second run reports zero embed calls and every document unchanged; a one-sentence edit re-embeds only the chunks whose text changed (chunks_new small, chunks_reused large); a deletion removes both chunks and vectors rows; --dry-run leaves runs untouched while still printing what would happen; the corrupted file appears in errors with its stage and message and is retried next run rather than crashing it. The quality gate prints a GateResult like verdict=warn, reasons=[garbage_ratio on doc X, pii_scan hits: 2] — warn, not fail, because severity discipline is the circuit breaker (05.10, 7.3).

Done when:

  • Three consecutive runs are idempotent: run 2 and 3 do zero chunk/embed work and produce identical state.
  • You have demonstrated all four classifications (new/changed/unchanged/deleted) with real file operations, and chunk-level reuse is visible in the runs counters.
  • A deliberately corrupted file quarantines with a structured error and the run still completes.
  • Every run records a quality-gate verdict, and you can explain which check produced each warn/fail reason.
  • reconcile reports no manifest_only drift (the dangerous direction — chunks missing vectors).

Stretch ideas:

  • Implement the cost estimator from 05.9, 5.4 and gate a full re-embed behind a budget before allowing a CHUNKER_VERSION bump.
  • Build the blue/green reindex flow: new index, shadow evaluation, alias flip, keep-old-for-rollback (05.9, 5.2).
  • Add dead-letter handling so a document that fails N runs stops retrying and alerts instead (05.9, 8.2).
  • Add a deletion-propagation drill: delete a contract, verify its chunks, vectors and any cached OCR/enrichment artefacts are gone — the right-to-erasure pattern from 05.9, 9.3.
  • Needs accounts/keys: swap the toy sources/ for a real connector (Drive changes feed or an S3 event notification) following 05.9, 2.4.

Common problems:

  • doc_id derived from the file path. Renames look like delete+new and re-embed everything; derive identity from a stable source-system ID or content, and keep URI as provenance (05.9, 2.5).
  • chunk_index inside the chunk ID. One inserted paragraph then re-IDs the whole tail — position is metadata, never identity (05.9, 3.3).
  • Timestamps inside stages. datetime.now() in a stage makes runs non-deterministic and breaks idempotency — keep run IDs and timestamps in the manifest layer only (05.9, 1.2).
  • Version mismatch passes silently. classify must treat a stored chunker_version/parser_version mismatch as changed even when the hash matches, or the index mixes two chunkings (05.9 check-yourself).
  • Drift direction matters. manifest_only (chunks without vectors) breaks retrieval; store_only (orphan vectors) wastes space and can leak deleted content — reconcile both but fix the first first (05.9, 3.5).

Stretch (optional)

Goal: Give the corpus's contracts/scan-*.png files a real path to text: detect which pages need OCR, preprocess them, run a classical engine, measure quality with CER/WER against hand-written references, route low-confidence output to a review queue or a VLM, correct common OCR errors with an auditable change log — and emit chunks that join the same chunks.jsonl format as project 1.

What you'll practise:

  • Born-digital vs scanned detection and per-page routing (05.4, 4.1, 4.2; 05.2, 1.5)
  • Image preprocessing — resolution, grayscale, deskew — and knowing what hurts (05.4, Part 3)
  • Classical OCR with pytesseract: TSV output, word-level confidence, PSM modes (05.4, 5.2, 5.3)
  • Measuring OCR quality: CER/WER in plain Python and a tiny ground-truth set (05.4, 6.3, 6.4)
  • Confidence-based review queues and post-OCR correction with a change log (05.4, 6.5, Part 11)
  • VLM OCR as the escalation path: faithful-transcription prompts, per-page cost model, verification (05.4, Part 8) — the model calls are the only key-needing steps

Setup:

bash
brew install tesseract poppler          # macOS; or: sudo apt install tesseract-ocr poppler-utils
uv add pillow pytesseract pypdfium2 img2pdf pdf2image fpdf2
uv add rapidocr               # optional second engine for comparison
# hosted VLM only: uv add python-dotenv openai anthropic google-genai

Verify the binary first: tesseract --version and tesseract --list-langs (05.4's Setup shows the expected output).

Steps:

  1. Build scan fixtures. The corpus's scan-*.png files are placeholders; make realistic ones. Render contract text to images with Pillow, then degrade copies using degrade_scan.py from 10A.2, 4.5 — rotation, blur, low resolution — so you have a difficulty ladder: clean scan, skewed scan, degraded scan, and (if you like) a two-column page.
  2. Route. For each fixture run the signals from 05.4, 4.1: a "PDF" fixture can go through route_page() from 4.2; a bare PNG is definitionally ocr_classical unless your quality gate says vlm.
  3. Preprocess. Apply the Part 3 recipe that helps: target ~300 DPI, grayscale, autocontrast, deskew if needed — and record which steps you applied per image, because the lesson's before/after table shows some preprocessing hurts modern engines.
  4. OCR with Tesseract. Use pytesseract.image_to_data(..., config="--psm 6") for block text and keep the TSV: level-5 rows carry real word confidence, structural levels carry -1 (05.4, 6.2). Sweep --psm 3/4/6/11 on the two-column fixture and record which wins.
  5. Measure. Build eval/ with page.png, page.ocr.txt and a hand-written page.reference.txt per fixture. Implement (or verify) the edit-distance CER/WER from 05.4, 6.3 — it is pure Python, so the output is real, not illustrative. Produce a per-fixture CER table: clean scan should be near zero, degraded scan measurably worse.
  6. Route by confidence. Compute the fraction of words below confidence 60 per page; pages over your threshold go to review_queue.jsonl with the low-confidence words highlighted, instead of silently entering the corpus (05.4, 6.5).
  7. Correct conservatively. Apply domain fixes (O/0, l/1/I, known Acme terms) via the corrector pattern in 05.4, Part 11: keep the raw OCR text, emit a change log, and never let the corrector touch numbers silently.
  8. Escalate the hard tail (needs a key). For the degraded fixture, transcribe with a vision model using the faithful-transcription prompt from 05.4, 8.2 and the provider call shapes in 8.4. Score it with the same CER harness and compare against Tesseract — then fill ocr_cost.py's parameters (8.5) to find the break-even fraction of hard pages.
  9. Join the pipeline. Feed accepted OCR text through clean() → chunker → to_chunks exactly like project 1, with lineage.parser_name="tesseract" (or the VLM model ID) and ocr_mean_confidence in QualityFlags — the metadata fields already exist for this (05.8, 2.6).

Verify it, and what you should see:

bash
tesseract --version && tesseract --list-langs
uv run python ocr_fixtures.py          # routes + preprocesses + OCRs every fixture
uv run python score_eval.py            # CER/WER per fixture
cat review_queue.jsonl                 # the pages that failed your confidence gate

What to look for: the clean scan's CER is near zero and almost no words fall below confidence 60; the degraded scan's CER rises and a meaningful fraction of its words queue for review; the two-column fixture shows why --psm matters (plain --psm 3 interleaves columns); every correction appears in the change log with before/after; and the VLM transcription — when you run it — either beats Tesseract on the degraded page or exposes a hallucination the CER harness catches. Numbers are yours to measure; the shape (clean ≈ 0, degraded worse, queue non-empty) is the acceptance signal.

Done when:

  • Every fixture has a recorded route (ocr_classical/review/vlm), preprocessing recipe, OCR output, CER/WER score and confidence stats.
  • Low-confidence pages land in a review queue with reasons — none enter chunks.jsonl silently.
  • Post-OCR corrections are auditable: raw text preserved, change log emitted.
  • OCR'd chunks carry correct lineage (parser_name, ocr_mean_confidence) and pass the same ChunkMeta validation as project 1.
  • You can state, with your own measurements, at what degradation level Tesseract stops being good enough — and what that implies for the VLM escalation rate.

Stretch ideas:

  • Produce a searchable PDF with OCRmyPDF (--mode skip so born-digital pages are untouched) and verify pdftotext now extracts the scan layer (05.4, 5.6).
  • Compare engines head-to-head: Tesseract vs RapidOCR vs EasyOCR on the same fixtures, with CER and pages/sec (05.4, 2.5 decision table).
  • Add table structure recovery for a scanned price list and decide Markdown-vs-row-sentences representation (05.4, 7.2; 05.2, 4.4).
  • Cache OCR results by content hash + engine + version + config so re-runs only process new scans (05.4, 12.3).
  • Needs a GPU you control (optional): serve one open-weight document VLM from 05.4, 2.4.1 behind an OpenAI-compatible endpoint, run it on the same fixtures with the call shape of that section, and compare CER, repetition-loop or length finishes and cost per 1,000 pages with Tesseract. Record the model revision and its weights licence in your report.
  • Needs accounts/keys: try one cloud document-AI service (Mistral OCR, Google Document AI, Azure DI or Textract) on the same fixtures and compare structured output, per-page cost structure and data-residency implications (05.4, 2.3).

Common problems:

  • Tesseract binary missing. pytesseract is only a wrapper — install tesseract and the language data, then re-run tesseract --list-langs (05.4 Setup).
  • DPI too low. Below ~150–200 DPI characters lack pixels; render fixtures at ~300 DPI (05.4, 3.1).
  • Wrong PSM for the layout. --psm 6 assumes a uniform block; columns and sparse pages want --psm 3 or --psm 11 — sweep and measure, don't guess.
  • Confidence ≠ accuracy. Engines are confidently wrong on stylised fonts; the score routes and flags, it does not prove correctness — that's what your CER harness is for (05.4, 6.2).
  • VLM "fixes" become hallucinations. A vision model may invent plausible text on degraded scans; always cross-check against the classical engine or a reference, and keep the raw OCR (05.4, 8.6).
  • Numbers get "corrected". 1,090.00 → 1.090.00 or O→0 in totals is the classic post-OCR disaster; validate numeric fields and keep corrections conservative (05.4, 11).
Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close