Building a Training Set for an OCR Error-Correction Model
Machine LearningModel answerLast updated
Design a scalable pipeline that scores noisy OCR pages, distills a small verified gold set from a stronger LLM, and filters out pages too degraded to repair.
Scenario
Your team has scanned 100,000 document pages and run them through an OCR engine. The text that comes out is messy:
- characters are swapped for lookalikes (
lvs1,Ovs0), - line breaks fall in the wrong places and words get split,
- low-contrast regions produce characters that are not on the page at all.
You want to fine-tune a compact language model to act as an OCR post-correction model: it reads noisy OCR text and returns the corrected text. Almost none of the pages have reference transcriptions.
Task
Propose an end-to-end approach for turning this raw material into a fine-tuning corpus. Cover three areas:
- Cleaning and detection. Which heuristic rules or statistical signals would you use to flag low-confidence OCR segments? How would you treat artifacts such as repeated characters and unnatural word splits?
- Gold data from a stronger model. With no ground truth for most pages, how would you use a much larger LLM as a teacher to build a smaller, trustworthy dataset for fine-tuning the target model?
- Filtering hopeless pages. What metric or classifier would you use to discard pages so degraded (blurry, distorted, garbled) that even a strong model cannot recover them?
Example
Input: The 1nvestment was 500,000 dol1ars in 202O.
Expected output: The investment was 500,000 dollars in 2020.
Constraints
- The target model has a 4,096-token context window.
- Weigh the cost of calling a proprietary LLM API on every page against labeling only a sample.
- The approach must scale to repositories measured in multiple terabytes.
State any assumptions you make, and discuss trade-offs and failure modes.
Hints
Hint 1
Separate cheap scoring and routing (runs over everything) from expensive correction (runs only on a small sample). Do a quick token-count estimate to see why labeling the whole corpus with an API is impractical.
Hint 2
A teacher model's output is not ground truth. Think about checks you can run automatically: how much it changed, where it changed things, whether repeated samples agree, and whether digits only changed in plausible ways.
Hint 3
Real noisy/clean pairs can be manufactured by rendering clean text, degrading the image, and re-running the same OCR engine. Also think about what happens if the student never sees clean text that should be left alone.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The core idea is to split the work into three layers:
- Cheap scoring and routing that runs on every page.
- Expensive teacher labeling that runs on a small, stratified sample.
- A fine-tuned student that does the bulk correction.
Two risks need to be managed throughout: trusting teacher labels blindly, and a student that over-corrects text that was already right.
Clarifying questions and scale
- Document types and languages (invoices, contracts, books)?
- Does the OCR engine output per-token confidences and bounding boxes? Are page images kept?
- Are any digital-born PDFs available? Their text layer is free ground truth.
- Student size (say 1-3B parameters)?
Rough numbers: about 500 words per page is roughly 700 tokens, so 100k pages is about 70M tokens. A multi-terabyte archive could be around 10^8 pages, i.e. tens of billions of tokens. Labeling 100k pages once with a frontier model is affordable (low thousands of dollars), but labeling the whole archive with verification passes is not. So the teacher labels about 5-10k pages and the student handles the rest.
Context budget: input and output are about the same length, so chunk pages to at most about 1,500 input tokens, split at paragraph or line boundaries with roughly 100 tokens of overlap. That leaves room for the instruction and the output.
Pipeline architecture
Raw OCR (+ images, confidences)
-> normalize + layout-aware segmentation
-> features -> error-density score + recoverability score
-> route: clean | correctable | unrecoverable
-> stratified sample -> teacher labels -> verification --+
-> synthetic noisy/clean pairs ---------------------------+-> SFT corpus -> student
-> student inference over all "correctable" pages
Every stage is a stateless per-page map, so it runs on Spark or Ray sharded by page ID, with Parquet intermediates for reproducibility.
1. Detecting and handling OCR noise
Safe deterministic fixes
- Unicode NFKC normalization; strip control characters.
- De-hyphenation: join
invest-/mentonly if the joined word is in the lexicon. - Line joining: merge when the previous line has no terminal punctuation and the next starts lowercase, never across layout blocks.
Signals for low-confidence segments
- OCR token confidence, when available.
- Out-of-vocabulary rate (SymSpell-style edit-distance lookup).
- Character n-gram perplexity from a KenLM model trained on clean in-domain text; strings like
rnoclernstand out. - Mixed letter/digit tokens (
1nvestment,202O), with an allowlist for legitimate codes such asA4. - Runs of 3+ identical characters outside whitelisted patterns (
...,---,000). - High symbol-to-alphanumeric ratio.
- Many very short fragments, which suggests splits like
inv est ment.
Combine these into a per-line error density, either as a weighted sum or as the output of a small logistic regression trained on teacher-labeled data.
Artifacts
- Collapse repeated characters only if the collapsed form is a dictionary word.
- Merge split pieces if the concatenation is in the lexicon and the pieces are not, or if merging lowers LM perplexity.
Important: these rules are for scoring and routing, not for generating training inputs. At inference time the student sees raw OCR, so training inputs must stay raw. Heavy regex cleaning of inputs creates a train/serve mismatch.
2. Gold data via a teacher LLM
Sampling. Stratify the 5-10k pages by error-density decile, document type, and layout. Oversample the medium-noise band, where the student adds the most value. Nearly clean pages teach little; hopeless pages teach noise.
Prompting. Ask for minimal edits: fix recognition errors only, no paraphrasing, preserve formatting and numbers unless clearly misread. Request JSON with corrected_text and uncertain_spans. If the teacher is multimodal, include the image crop; seeing pixels is the best defense against hallucination (is 202O 2020 or 2029?).
Verifying labels
- Edit budget: the character error rate between input and teacher output should stay within roughly 2x the predicted error density. Big rewrites mean paraphrase or hallucination.
- Edit locality: align input and output; most edits should land on low-confidence or OOV tokens.
- Self-consistency: two samples at temperature > 0, or two different teachers; drop chunks whose outputs diverge.
- Numeric/entity guard: digits, dates and amounts may change only via known confusions (O->0, l->1, S->5).
- Human audit of about 300 chunks to calibrate thresholds and estimate teacher error.
Synthetic pairs with true ground truth
- Render-degrade-OCR: take clean text (digital-born PDFs or high-confidence pages), render, add blur/noise/skew/low contrast, and run the same OCR engine. This yields realistic pairs with exact labels at almost no cost.
- Confusion-matrix injection: estimate substitutions (
rn<->m,l<->1,O<->0), splits and bad breaks from teacher alignments and apply them to clean text. Cheaper, less realistic. - Identity examples (15-20%): clean in, identical text out. These teach the model to leave good text alone.
A reasonable corpus is around 10k verified teacher chunks plus 50-100k synthetic pairs, trained with standard SFT with loss on output tokens only.
3. Filtering unrecoverable pages
Train a page-level recoverability classifier, e.g. gradient-boosted trees, on:
- Image features: Laplacian variance (blur), contrast, skew, DPI.
- OCR features: mean confidence, share of low-confidence tokens.
- Text features: char-LM perplexity, dictionary hit rate, and a gibberish score from a fastText or char-CNN classifier trained on clean vs. heavily corrupted text.
Labels come from the teacher sample: a page is unrecoverable if the teacher marks most spans uncertain, two teachers disagree strongly, or the dictionary hit rate stays low after correction. Tune for high precision on "unrecoverable" so good data is not thrown away. Send flagged pages to re-OCR (higher DPI or another engine) or a human queue, not to the student.
Evaluation
- Hold out a human-verified set stratified by noise level.
- Report CER and WER before and after correction, plus a separate over-correction rate on clean text (how often the model changes something that was right).
- Track numeric-field accuracy separately, since silent digit errors are the costliest.
- At inference, flag outputs whose edit rate far exceeds the predicted error density for review.
Trade-offs and common mistakes
- Cleaning inputs too aggressively causes a train/serve mismatch.
- Trusting teacher output bakes hallucinations into the student.
- No identity examples leads to over-correction and rewritten correct text.
- Labeling everything with the API is costly and unnecessary; sampling plus synthetic data gets most of the benefit.
- Splitting chunks mid-sentence or mid-table hurts quality; segment by layout.
- Leaking pages from the same document across train and eval inflates metrics; split by document.
- Language or layout skew: multi-column and table pages need their own strata or the student will do poorly on them.