Sub topic 9
Cleaning and Validating OCR Output
This chapter assumes you can run Tesseract through pytesseract, read the image_to_data dictionary (words, confidence, boxes), and write basic Python with regular expressions. Recognition gives you a string, and that string still has errors. Post-processing tidies it, and validation tells you which parts to trust.
Why raw OCR output is not data yet
An OCR engine returns what it thinks it saw. It has no idea what the text means. A receipt total of $10.50 can come back as $1O.5O and nothing in the engine objects. The errors fall into three groups:
- Layout noise: extra spaces, stray form-feed characters, broken lines, and words split by hyphens at line ends.
- Character confusions: shapes that look alike, such as
0/O,1/l/I,5/S, and8/B. - Word-level mistakes: a misread letter that turns a real word into a non-word, or one real word into another.
Each group needs a different fix. Layout noise is repaired with rules. Character confusions are repaired with knowledge of what the field should contain. Word errors are repaired by comparing against a known vocabulary. Whatever remains is caught by validation, which rejects values that cannot be correct.
Normalizing the text
Start with changes that cannot make the text worse. Tesseract ends its output with a form-feed character (\x0c). It may emit ligature characters such as fi, and it may use curly quotes. It keeps the original line breaks, which rarely match your needs.
import re
import unicodedata
QUOTES = str.maketrans({
"\u2018": "'", "\u2019": "'",
"\u201c": '"', "\u201d": '"',
})
def normalize_text(raw):
text = unicodedata.normalize("NFKC", raw) # ligatures such as the fi glyph become "fi"
text = text.translate(QUOTES)
text = text.replace("\x0c", "\n") # Tesseract page separator
text = re.sub(r"(\w)-\n(\w)", r"\1\2", text) # rejoin words hyphenated at line end
text = re.sub(r"[ \t]+", " ", text) # collapse runs of spaces
text = re.sub(r"\n{3,}", "\n\n", text) # limit blank lines
lines = [line.strip() for line in text.splitlines()]
return "\n".join(lines).strip()
print(normalize_text("The inter-\nnational fee\x0c"))This prints The international fee.
The dehyphenation rule has a failure mode. A word that is hyphenated on purpose, such as well-\nknown, becomes wellknown. If you need accuracy over convenience, rejoin the pieces only when the joined word appears in a dictionary. Otherwise keep the hyphen.
Using confidence scores to decide what to touch
In the previous chapter you filtered words below a confidence threshold. In post-processing, do not simply discard them. Use confidence to decide which words to review and which to leave alone. A word at 95 rarely needs correction, and a word at 30 probably does.
image_to_data also returns -1 as the confidence for rows that are not words (page, block, and line rows). Handle that case explicitly.
def split_by_confidence(data, threshold=60):
accepted, review = [], []
for word, conf in zip(data["text"], data["conf"]):
if not word.strip():
continue
conf = float(conf)
if conf < 0: # structural row, not a recognized word
continue
target = accepted if conf >= threshold else review
target.append((word, conf))
return accepted, review
sample = {
"text": ["", "Total", "$1O.5O", "Thank", "y0u"],
"conf": ["-1", "96", "41", "93", "38"],
}
accepted, review = split_by_confidence(sample)
print(accepted)
print(review)The output is:
[('Total', 96.0), ('Thank', 93.0)]
[('$1O.5O', 41.0), ('y0u', 38.0)]The threshold is a trade-off. A high threshold sends more words to review and misses fewer errors. A low threshold saves effort but lets more wrong words through. Pick it by measuring on a labeled sample from your own images. Confidence is also not a probability. A word can be confidently wrong, which is why validation below is still needed.
Correcting characters by field type
Confusable characters can be fixed safely when you know a field's type. A field that must be numeric can never contain the letter O, so every O there is a misread 0. The correction is a lookup applied only to that field.
| Misread as | Likely intended | Applies to | Column |
|---|---|---|---|
| `O`, `o` | `0` | numeric fields | |
| `I`, `l`, `\ | ` | `1` | numeric fields |
| `S` | `5` | numeric fields | |
| `B` | `8` | numeric fields | |
| `Z` | `2` | numeric fields | |
| `0` | `O` | codes that must be letters, such as a country prefix |
The table is not symmetrical. Fixing letters into digits is safe in a digit-only field. Doing the reverse needs a field that is known to be alphabetic.
from datetime import datetime
from decimal import Decimal, InvalidOperation
DIGIT_FIXES = str.maketrans({
"O": "0", "o": "0",
"I": "1", "l": "1", "|": "1",
"S": "5", "B": "8", "Z": "2",
})
def fix_digits(token):
return token.translate(DIGIT_FIXES)
def parse_amount(token):
cleaned = fix_digits(token.replace("$", "").replace(",", "").strip())
try:
value = Decimal(cleaned)
except InvalidOperation:
return None
return value if value.is_finite() else None
def parse_date(token):
cleaned = fix_digits(token.strip())
for fmt in ("%Y-%m-%d", "%d/%m/%Y"):
try:
return datetime.strptime(cleaned, fmt).date()
except ValueError:
continue
return None
print(parse_amount("$1O.5O"))
print(parse_date("2O24-O3-15"))
print(parse_amount("n/a"))This prints 10.50, 2024-03-15, and None.
A few points about this code:
- It returns
Nonewhen parsing fails. It does not guess. A missing value that gets flagged is better than a wrong value that looks fine. - It uses
Decimalrather thanfloat, so money values compare exactly.0.1 + 0.2is not0.3in floating point. Decimal("nan")parses successfully, so theis_finite()check is needed.- The date formats are tried in order. A date such as
03/04/2024is ambiguous between day-first and month-first. The parser cannot resolve that, and neither can OCR. Use the document's origin to choose one format and do not try both.
Validating with rules and arithmetic
Validation asks whether a value could be right. It cannot prove that a value is right. Use the strongest check available for each field, from weakest to strongest:
- Format: a regular expression for the shape, such as
INV-followed by six digits. - Range: a plausible date window or a positive amount.
- Cross-field consistency: line items must sum to the total.
- Checksums: credit card numbers use the Luhn algorithm, and many ID numbers carry check digits.
Arithmetic and checksum checks are the most useful, because a single misread digit almost always breaks them. A format check will pass INV-004217 and INV-004211 equally.
import re
from decimal import Decimal
INVOICE_RE = re.compile(r"^INV-\d{6}$")
def valid_invoice_number(value):
return bool(INVOICE_RE.fullmatch(value))
def totals_match(line_items, total):
return sum(line_items, Decimal("0")) == total
def luhn_valid(number):
digits = [int(c) for c in number if c.isdigit()]
if len(digits) < 2:
return False
checksum = 0
for index, digit in enumerate(reversed(digits)):
if index % 2 == 1:
digit *= 2
if digit > 9:
digit -= 9
checksum += digit
return checksum % 10 == 0
print(valid_invoice_number("INV-004217"))
print(valid_invoice_number("INV-0O4217"))
print(totals_match([Decimal("4.25"), Decimal("6.25")], Decimal("10.50")))
print(totals_match([Decimal("4.25"), Decimal("6.25")], Decimal("10.60")))
print(luhn_valid("4539 1488 0343 6467"))
print(luhn_valid("4539 1488 0343 6468"))The output is True, False, True, False, True, False. The second invoice number fails because of the letter O. That is exactly the kind of failure that tells you to run the digit correction first and validate afterward.
A useful technique combines the pieces. When a total fails to match, try the plausible alternatives for each low-confidence digit, such as 0 versus 8 or 1 versus 7. Keep the combination that satisfies the arithmetic. Limit this search to a few uncertain characters, because the number of combinations grows exponentially.
Snapping words to a vocabulary
Some fields come from a closed list: receipt labels, country names, product categories. For these you can compare each recognized word to the list and pick the closest entry. The standard library's difflib does this with no extra packages.
from difflib import get_close_matches
LABELS = ["subtotal", "total", "tax", "discount", "shipping"]
def snap_label(word, cutoff=0.8):
matches = get_close_matches(word.lower(), LABELS, n=1, cutoff=cutoff)
return matches[0] if matches else None
print(snap_label("Subtota1"))
print(snap_label("Thanks"))The first call prints subtotal and the second prints None.
The cutoff value controls how aggressive the snapping is. Set it too low and unrelated words get forced onto list entries, such as Tax appearing where Fax was printed. Set it too high and real misreads pass through. A returned None means "no confident match", and your code should treat that as unresolved. It should not fall back to the raw word silently.
Be careful with free text. A spell checker run over names, addresses, or codes will "fix" correct words into common ones. Snap to a vocabulary only when the vocabulary is complete for that field.
Keeping the original and recording what changed
Post-processing is a place where silent damage happens. Three habits make it auditable:
- Keep the raw text next to the cleaned text. If a rule turns out to be wrong, you can reprocess without rerunning OCR.
- Record each change as a field-level note, for example "fixed
O→0in amount". Counting these notes over a batch shows which images and rules cause the most trouble. - Measure the effect. Use the character error rate function from the evaluation chapter on text before and after cleaning, against ground truth. A rule that raises the error rate should be removed, however sensible it looks.
Common mistakes
- Applying digit fixes to the whole page instead of numeric fields.
- Validating before correcting, so correctable values are rejected.
- Treating a passed format check as proof of correctness.
- Using
floatfor currency. - Dropping low-confidence words instead of routing them to review.
- Snapping to a vocabulary with a low cutoff and no way to see what was changed.
Exercise
A receipt scan gives the line items 4.25 and 6.2S, and the total 10.50. Using the ideas in this chapter, how do you decide that 6.2S should be 6.25? Why is a format check on 6.2S alone not enough to settle it?
Show answer
The line item sits in a numeric field, so S is most likely a misread 5. After the digit fix, the items are 4.25 and 6.25. Their sum is 10.50, which matches the total, so the cross-field arithmetic confirms the correction. A format check only tests the shape of the value. 6.25, 6.26, and 6.28 all have the same valid shape, so format cannot tell you which digit is right. The total check can.
Exercise
Your cleaning step replaces O with 0 in the entire OCR text of a scanned letter, and the character error rate gets worse. Explain why, and name a safer way to apply the rule.
Show answer
Most O characters in a letter are real letters in words such as Order and October. The global replacement changes them to 0, which adds errors. Apply the rule only to fields known to be numeric, such as amounts, dates, and invoice digits, after you have located those fields by label, position, or regular expression. Then compare the character error rate before and after to confirm that the rule helps.