Module 05: Projects
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:
uv init data-pipeline --bare --python 3.13 && cd data-pipeline
mkdir -p data/raw data/parsed data/chunks data/exports scriptsThen 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: 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
Chunkmodel, 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:
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:
- Generate and audit the corpus. Copy
scripts/make_corpus.pyfrom 05.1, Part 8 intoscripts/and runuv run python scripts/make_corpus.py. Then run the audit scripts5_2_audit_corpus.pyfrom the same lesson ondata/corpusand 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 threescan-*.pngimages, two transcripts,pricing.csvand the policy docx (pricing.xlsxappears only ifopenpyxlis installed when you run the generator). - Build
parsed_document.py. Copy theBBox,TextBlock,TableBlock,ImageBlock,ParsedPage,ParseInfoandParsedDocumentmodels from 05.2, Part 9 verbatim. This is the contract every parser feeds. - Build
parsers.py. Write aparse_file(path) -> ParsedDocumentdispatcher in the style of the registry in 05.3, 11.2, but returningParsedDocumentinstead ofParseResult:.html→ extract main content withtrafilatura.extract(..., output_format="markdown")(fall back to BeautifulSoupget_textwithscript/style/nav/footerremoved if trafilatura returnsNone), plus title/canonical/date metadata intoParseInfo.metadata(05.3, 2.4, 2.7)..pdf→ adapt theparse_pdffunction 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: oneTextBlockper paragraph,kind="heading"andlevelfrom 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 aParsedDocumentwithwarnings=["no parser for …"]and mark every pageneeds_review=True. The scans are project 4's job; the xlsx can be added withopenpyxlas a stretch. Wrap each parser call intry/exceptand record the failure inwarnings— one bad file must not kill the run (05.2, 10.3).
- Write
ingest.py. Walkdata/corpus, callparse_fileper file, and write one JSON line per document todata/parsed/parsed.jsonl(usemodel_dump_json()). Print a per-file summary: pages/blocks, char count, warnings. - Clean. Save the 05.5
cleaner.py(clean(),STEPS,CleanResult) into the project. Iningest.py(or a second passclean.py), runclean(text, explain=True)on each document's flattened text. Writedata/parsed/cleaned.jsonlcarrying both the raw text and the cleaned text plus the per-step change counts fromCleanResult— the raw text is never overwritten (05.5, 1.2). Read the change log with a critical eye:s_boilerplateonly 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. ExtendBOILER_REfor it, or rely on the parser-level removal, and say which you chose. - Chunk. Reuse the splitters from 05.6:
recursive_splitfor prose documents andmarkdown_chunksfor the HTML-derived Markdown and the handbook (structure-aware boundaries beat blind recursion — see the 7.1 decision table). Convert each splitter's output throughto_chunks(doc_id, pieces, chunker_version)so every chunk gets its deterministicchk_…ID,prev/nextpointers andoccurrencedisambiguation (05.6, 6.3).to_chunksexpects a list of dicts whose keys areChunkfield names (text,section_path, optionalchar_start/char_end): wraprecursive_split's plain strings as{"text": s}, and drop the extrasectionkey frommarkdown_chunks' dicts, as the demo at the end of 05.6 Part 6.3 does, orChunk(**p)raises aTypeError. Setchunker_version="starter-v1"andsection_pathfrom headings where the splitter provides them. - Attach metadata. Import
DocumentMeta,ChunkMeta,Lineage,QualityFlagsand friends frommeta_models.py(05.8, 2.7). For each document build aDocumentMeta:doc_id=doc_plus the first 24 hex characters of the sha256 of the source path and content hash (the model's pattern is exactlydoc_+ 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_typefrom the folder (handbook,help_article,ticket,contract,transcript,spreadsheet,policy),language="en",confidentiality/aclfrom a small dict you write in the code (contracts/→internalplus anAclEntry(principal_type="group", principal_id="legal"), everything elseinternalplusall-staff; the flatallowed_groupskey is derived for you bystore_payload()), and the dates (ingested_at= now,modified_at= file mtime). Then build oneChunkMetaper chunk:chunk_id,doc=doc,chunk_index,section_path,prev_chunk_id/next_chunk_id,chunk_text_hash(sha256 of the chunk text) andlineage=Lineage(parser_name=…, parser_version=…, cleaning_version=…, chunker_name=…, chunker_version=…, ingestion_run_id=…).ChunkMetaforbids extra fields, so the chunktextandembed_input(fromchunk.embed_input()) do not go inside it: they sit beside it in the JSONL record of step 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 flatChunkMeta.store_payload()). Keep it flat — vector stores want flat, null-free payloads (05.8, 6.3). - 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:
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 -5What 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_idstarts withchk_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_inputwith a breadcrumb likeAcme Help > Shipping and deliveryand no nav/footer text — check onetextfield against the raw HTML. - The
scan-*.pngfiles produced warnings, not silence: they appear in the report asneeds_review, proving failure isolation works. tickets.jsonlproduced 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):
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.jsonlexists, the metadata of every chunk validates against yourChunkMetamodel (validate before you flatten it withstore_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
lineageanddoc_idfields. - 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-*.pngfiles 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_chunkswith real section paths, and compare chunk counts and breadcrumbs against the recursive baseline (05.6, 4.5). - Add the
dq.pysuite from 05.10, 12.2 as a final stage:check_chunk_coverage,check_chunk_sizes,check_chunk_uniqueness, thengate()and print the verdict (05.10, 10.1). - Run the
hidden_text_reportscan from 05.5, 2.7 on every raw document before cleaning and add its counts torun_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 inlineage.
Common problems:
- BeautifulSoup
get_text()includes JavaScript. Removescript,style,nav,footer,noscriptand[hidden]elements before extracting, or trafilatura's output will be polluted (05.3, 2.4). - The corpus PDF is minimal.
make_corpus.pywrites 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 withreportlabas 05.2's exercises suggest. .xlsxhas no parser in the registry. Either addopenpyxl(data_only=Truefor 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_idstability. If you hash the file path, moving the corpus re-IDs everything; hash source identity + content instead (05.8, 3.1).
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:
uv add pydantic
# hosted generation only — pick the providers you have keys for:
uv add python-dotenv openai anthropic google-genaichunks.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:
- Save the pipeline. Copy
synth_eval.pyfrom 10A.2, Part 11 verbatim — it is complete and runs on the stub. Also copyquestion_model.pyandgen_questions_prompt.txtfrom 2.5 and 2.4 for the hosted step. - Run the stub end to end.
synth_eval.pyexpects plain chunk dicts, not the full records of project 1, so first writeexport_chunks.py, which readschunks.jsonland emits the five-field shape (chunk_id,doc_id,doc_typefrommeta,source=doc_id,text). Thenuv run python synth_eval.py chunks_for_eval.jsonl. Read the stats:kept + dedup_dropped + rejectedmust equaltotal_generated— every call lands in exactly one bucket. - Inspect the output. Open
eval_questions.jsonl: every item hasid,question,question_type,reference_answer,answerable,cited_chunk_ids,evidence_span,persona,language,generator,prompt_version,created_at. Verify everycited_chunk_idsvalue exists in your chunks file and every non-nullevidence_spanis a verbatim substring of the cited chunk's text (the pipeline checks this; confirm it yourself on three items). - Read the card.
eval_questions_card.mdstates 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. - Swap in a real generator (needs a key). Implement
hosted_generate(chunk, qtype, persona)with the signaturegenerateexpects, 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 intoGeneratedQuestion, and return it as a dict. Run the samesynth_eval.py— every downstream stage is unchanged. - 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.
- Version the dataset. Bump
prompt_versionin 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:
uv run python synth_eval.py chunks_for_eval.jsonl
cat eval_questions_card.mdThe lesson's own real run on a six-chunk toy file printed:
{
"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.jsonlexists 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
unanswerableandmulti_hop_crossitems 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 withdegrade_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_generatederives questions mechanically; its card says so. Never quote stub accuracy as evidence about a model. - Judge circularity. Judging
claude-*output withclaude-*shares blind spots; pick a different family for the judge role. - Evidence span drift. If you clean or re-chunk after generating,
evidence_spanstops being verbatim — regenerate items citing changed chunks rather than fudging the check.
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.pyquality suite in as a gate stage (05.10, 12.7, 10.1)
Setup:
uv add httpx # only for the optional conditional-fetch stepThe 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:
- Run the lesson's pipeline as-is. Copy
pipeline.pyinto a scratch folder and create the toysources/folder by runningmake_sources.pyfrom 05.9, 4.1 (six small.md/.txtfiles, 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-runreports without writing, and--repairfixes reconciliation drift (you will use it in step 4). Read Part 4 so the outputs make sense. - Replace the toy stages. The appendix's
parse_cleanandchunk_documentare deliberately trivial. Point them at your real stages:parse_file→clean()→recursive_split/markdown_chunks→to_chunks. Keep the pipeline's ownmake_chunk_id/manifest schema intact — the point is that your stages now run inside the lesson's state machinery. BumpCHUNKER_VERSIONandPARSER_VERSIONto your real values. - Point it at the corpus. Copy
data/corpustodata/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) toDOC_SUFFIXESand give each a route inparse_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. - Prove incremental correctness. Run the verification sequence from the lesson's exercises: run twice (second run:
0 embed calls, allunchanged); edit one sentence inside a section and re-run — only the chunks whose text changed should appear inchunks_new, the restchunks_reused; delete a file — its chunks and vector rows must disappear; add a file — only it processes. Checkpipeline.dbtablesdocuments,chunks,runs,errors,tombstonesandvectors.dbafter each step. Finally, simulate drift (delete one row from the vector store by hand), confirm the end-of-run reconciliation reports it asmanifest_only, then re-run with--repairand confirm the next report shows zero drift (05.9, 3.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-deriveddoc_idmakes it delete+new — discuss the fix: hash a stable source ID, 05.9, 2.5); corrupt one file (it lands inerrorswith stage+message and retries next run). - Add the quality gate. After
run_update, run the relevantdq.pychecks on this run's outputs —check_chunk_coverage,check_chunk_sizes,check_chunk_uniqueness,check_garbage_ratio,check_pii_scan— thengate(results)andrender_report(...). Persist theGateResultverdict into therunstable (add averdictcolumn) so every run has a recorded quality outcome (05.10, 12.7). - Add an HTTP source (optional). Implement
conditional_fetchfrom 05.9, 2.3 withhttpx: storeetag/last_modifiedper URL in the manifest, get304 Not Modifiedfor unchanged pages, and feed changed bodies through the same parse→clean→chunk path. - Make it a service shape. Wrap
run_updatein awhile True: run_update(); sleep(N)loop or acron/launchdentry — 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). - Test it. Write pytest tests: idempotency (two runs → second does zero chunk work), per-stage unit tests, a golden-document test using
golden.py'sgolden_compareon one parsed doc, and a contract test assertingchunks.jsonlrecords still satisfyChunkMeta(05.9, Part 11, 05.10, Part 5).
Verify it, and what you should see:
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 6Expected 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
runscounters. - 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.
reconcilereports nomanifest_onlydrift (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_VERSIONbump. - 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 (Drivechangesfeed or an S3 event notification) following 05.9, 2.4.
Common problems:
doc_idderived 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_indexinside 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.
classifymust treat a storedchunker_version/parser_versionmismatch aschangedeven 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): Scan-to-search#
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:
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-genaiVerify the binary first: tesseract --version and tesseract --list-langs (05.4's Setup shows the expected output).
Steps:
- Build scan fixtures. The corpus's
scan-*.pngfiles are placeholders; make realistic ones. Render contract text to images with Pillow, then degrade copies usingdegrade_scan.pyfrom 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. - 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 definitionallyocr_classicalunless your quality gate saysvlm. - 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.
- 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/11on the two-column fixture and record which wins. - Measure. Build
eval/withpage.png,page.ocr.txtand a hand-writtenpage.reference.txtper 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. - Route by confidence. Compute the fraction of words below confidence 60 per page; pages over your threshold go to
review_queue.jsonlwith the low-confidence words highlighted, instead of silently entering the corpus (05.4, 6.5). - 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.
- 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. - Join the pipeline. Feed accepted OCR text through
clean()→ chunker →to_chunksexactly like project 1, withlineage.parser_name="tesseract"(or the VLM model ID) andocr_mean_confidenceinQualityFlags— the metadata fields already exist for this (05.8, 2.6).
Verify it, and what you should see:
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 gateWhat 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.jsonlsilently. - 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 sameChunkMetavalidation 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 skipso born-digital pages are untouched) and verifypdftotextnow 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 + configso 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
lengthfinishes 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.
pytesseractis only a wrapper — installtesseractand the language data, then re-runtesseract --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 6assumes a uniform block; columns and sparse pages want--psm 3or--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.00orO→0in totals is the classic post-OCR disaster; validate numeric fields and keep corrections conservative (05.4, 11).