Files
aiinvoice_pharmacyDashboard/ocr_corrector.py
T
2026-10-07 17:31:08 +05:30

899 lines
40 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
OCR Corrector — Deterministic post-extraction fixes for structured fields.
Handles fields whose format is KNOWN (GSTIN, HSN, dates) so OCR character
confusion (0↔O, 1↔I, 5↔S, 8↔B, 2↔Z, 6↔G) can be resolved positionally
in code — no extra LLM call needed.
Fields handled:
- GSTIN : 15-char, known digit/letter positions
- HSN/SAC codes: pure digits
- Dates : leap-year-aware clamping
"""
import re
import calendar
from datetime import datetime
from typing import Optional, Any
# ─────────────────────────────────────────────────────────────────────────────
# GSTIN correction
# ─────────────────────────────────────────────────────────────────────────────
# GSTIN structure (0-indexed):
# Pos 0- 1 : State code → DIGIT
# Pos 2- 6 : PAN first 5 chars → LETTER
# Pos 7-10 : PAN next 4 chars → DIGIT
# Pos 11 : PAN last char → LETTER
# Pos 12 : Entity number → DIGIT
# Pos 13 : Check letter → LETTER (usually Z)
# Pos 14 : Check digit/letter → DIGIT or LETTER (often 'Z' → keep)
GSTIN_POSITION_TYPES = [
'D','D', # 0-1 state code digits
'L','L','L','L','L', # 2-6 PAN letters
'D','D','D','D', # 7-10 PAN digits
'L', # 11 PAN letter
'D', # 12 entity number digit
'L', # 13 check letter
'X', # 14 can be digit or letter — leave as-is
]
# OCR confusion maps
_DIGIT_FOR_LETTER = {'O': '0', 'I': '1', 'l': '1', 'S': '5',
'B': '8', 'Z': '2', 'G': '6', 'A': '4'}
_LETTER_FOR_DIGIT = {'0': 'O', '1': 'I', '5': 'S',
'8': 'B', '2': 'Z', '6': 'G', '4': 'A'}
def _fix_gstin_char(char: str, expected_type: str) -> str:
"""Fix a single GSTIN character given its expected position type."""
c = char.upper()
if expected_type == 'D':
return _DIGIT_FOR_LETTER.get(c, c)
elif expected_type == 'L':
return _LETTER_FOR_DIGIT.get(c, c)
return c # 'X' — leave as-is
def correct_gstin(value: Any) -> Optional[str]:
"""
Apply position-aware OCR correction to a GSTIN string.
Returns the corrected GSTIN, or None if the input is None/empty.
Does NOT validate the checksum — only corrects obvious OCR confusion.
"""
if not value:
return value
raw = str(value).strip().replace(' ', '').upper()
if len(raw) != 15:
# Can't apply positional fix if length is wrong — return as-is
return raw
corrected = ''.join(
_fix_gstin_char(raw[i], GSTIN_POSITION_TYPES[i])
for i in range(15)
)
if corrected != raw:
print(f"[OCR-FIX] GSTIN: '{raw}' → '{corrected}'")
return corrected
# ─────────────────────────────────────────────────────────────────────────────
# HSN / SAC code correction
# ─────────────────────────────────────────────────────────────────────────────
_HSN_DIGIT_FIXES = str.maketrans('OIlSBZG', '0115826')
def correct_hsn(value: Any) -> Optional[str]:
"""
Fix OCR character confusion in HSN/SAC codes (pure digit fields).
Replaces O→0, I/l→1, S→5, B→8, Z→2, G→6.
"""
if not value:
return value
raw = str(value).strip()
corrected = raw.translate(_HSN_DIGIT_FIXES)
if corrected != raw:
print(f"[OCR-FIX] HSN: '{raw}' → '{corrected}'")
return corrected
# ─────────────────────────────────────────────────────────────────────────────
# Date correction — leap-year-aware and time-stripping
# ─────────────────────────────────────────────────────────────────────────────
_MONTH_NAMES_MAP = {
'jan': 1, 'january': 1,
'feb': 2, 'february': 2,
'mar': 3, 'march': 3,
'apr': 4, 'april': 4,
'may': 5,
'jun': 6, 'june': 6,
'jul': 7, 'july': 7,
'aug': 8, 'august': 8,
'sep': 9, 'september': 9, 'sept': 9,
'oct': 10, 'october': 10,
'nov': 11, 'november': 11,
'dec': 12, 'december': 12
}
_DATE_FORMAT_OUT = '%d/%m/%Y'
def is_leap_year(year: int) -> bool:
"""
Standard Gregorian leap year calculation:
- Year divisible by 4 is a leap year,
- EXCEPT century years (divisible by 100) which are NOT leap years,
- UNLESS also divisible by 400 (which ARE leap years).
e.g. 2024 (leap), 2028 (leap), 2032 (leap), 2000 (leap), 2026 (non-leap), 2100 (non-leap).
"""
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
def get_last_day_of_month(year: int, month: int) -> int:
"""
Return the last calendar day of the given month and year.
February: 29 in leap years, 28 in non-leap years.
April, June, September, November: 30 days.
All others: 31 days.
"""
if month == 2:
return 29 if is_leap_year(year) else 28
if month in (4, 6, 9, 11):
return 30
return 31
def _clamp_date(day: int, month: int, year: int) -> datetime:
"""Return a datetime with day clamped to the max valid day for month/year."""
max_day = get_last_day_of_month(year, month)
return datetime(year, month, min(day, max_day))
def correct_date(value: Any) -> Optional[str]:
"""
Parse a date string, strip any time/timestamp, and return strictly in DD/MM/YYYY format.
Handles:
- Dates with times: "09/09/2026 14:30:00", "28-02-2025 10:00:00", "2026-09-09T10:30:00Z"
- Month-Year formats (e.g. "Feb-26", "Feb -2026", "Feb / 26", "02/26", "02 - 2026"):
converts to the LAST DAY of that month with full leap year calculation:
e.g. Feb-2026 -> 28/02/2026; Feb-2024 -> 29/02/2024; Feb-2028 -> 29/02/2028.
- Full date formats: DD/MM/YYYY, DD-MM-YYYY, YYYY-MM-DD, DD-Mon-YYYY (28-Feb-2025)
- 2-digit years: converts YY to 20YY
- Leap-year clamping: 29-Feb in non-leap year -> 28-Feb
- Prefixes: invoice number prefixes like "INV-123 28/02/2025"
"""
if not value:
return value
s = str(value).strip()
# 1. ISO format with 'T': "2026-09-09T14:30:00" -> "2026-09-09"
if 'T' in s and re.match(r'^\d{4}[-/.]\d{1,2}[-/.]\d{1,2}T', s):
s = s.split('T')[0].strip()
# 2. Strip explicit trailing time patterns:
# e.g. " 14:30:00", " 10:30 AM", ", 14:30", " Time: 10:30:00"
s_notime = re.sub(
r'[,]?\s*(?:time\s*[:=-]?\s*)?\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:\s*[AP]M)?(?:\s*[A-Z]{1,4})?$',
'',
s,
flags=re.IGNORECASE
).strip()
if s_notime:
s = s_notime
# 3. Strip invoice numbers or alphanumeric labels before the date
# e.g. "INV-123 28/02/2025" or "Date: 28/02/2025"
s = re.sub(r'^(?:date|inv|dt|invoice\s*no\.?|bill\s*date)?\s*[:=-]?\s*', '', s, flags=re.IGNORECASE).strip()
s_cleaned = re.sub(r'^[A-Za-z0-9#\-_/]+\s+(?=\d{1,2}[-/.])', '', s, flags=re.IGNORECASE).strip()
if s_cleaned:
s = s_cleaned
# 4. Pattern: YYYY-MM-DD (e.g. 2026-09-09, 2026/09/09, 2026 - 09 - 09)
m_iso = re.search(r'\b(\d{4})\s*[-/.]\s*(\d{1,2})\s*[-/.]\s*(\d{1,2})(?!\d)', s)
if m_iso:
y, m, d = int(m_iso.group(1)), int(m_iso.group(2)), int(m_iso.group(3))
if 1 <= m <= 12 and 1 <= d <= 31:
max_d = get_last_day_of_month(y, m)
return f"{min(d, max_d):02d}/{m:02d}/{y:04d}"
# 5. Pattern: Full date with Month name: DD-Month-YYYY or DD Month YYYY (e.g. 28-Feb-2025, 28 Feb 2026)
m_full_mon = re.search(r'\b(\d{1,2})\s*[-/.]?\s*([a-zA-Z]{3,9})\s*[-/.]?\s*(\d{2,4})\b', s)
if m_full_mon:
d = int(m_full_mon.group(1))
mon_str = m_full_mon.group(2).lower()
y = int(m_full_mon.group(3))
if y < 100:
y += 2000
if mon_str in _MONTH_NAMES_MAP or mon_str[:3] in _MONTH_NAMES_MAP:
m = _MONTH_NAMES_MAP.get(mon_str) or _MONTH_NAMES_MAP.get(mon_str[:3])
max_d = get_last_day_of_month(y, m)
return f"{min(d, max_d):02d}/{m:02d}/{y:04d}"
# 6. Pattern: Month name and Year ONLY (e.g. 'feb -26', 'feb -2026', 'feb / 26', 'feb 26', 'Feb-28')
# Uses LAST DAY OF MONTH with full leap year calculation
m_mon_yr = re.search(r'\b([a-zA-Z]{3,9})\s*[-/.]?\s*(\d{2,4})\b', s)
if m_mon_yr:
mon_str = m_mon_yr.group(1).lower()
y = int(m_mon_yr.group(2))
if y < 100:
y += 2000
if mon_str in _MONTH_NAMES_MAP or mon_str[:3] in _MONTH_NAMES_MAP:
m = _MONTH_NAMES_MAP.get(mon_str) or _MONTH_NAMES_MAP.get(mon_str[:3])
max_d = get_last_day_of_month(y, m)
return f"{max_d:02d}/{m:02d}/{y:04d}"
# 6b. Pattern: Year and Month name (e.g. '2026-Feb', '26 - Feb')
m_yr_mon = re.search(r'\b(\d{2,4})\s*[-/.]?\s*([a-zA-Z]{3,9})\b', s)
if m_yr_mon:
y = int(m_yr_mon.group(1))
if y < 100:
y += 2000
mon_str = m_yr_mon.group(2).lower()
if mon_str in _MONTH_NAMES_MAP or mon_str[:3] in _MONTH_NAMES_MAP:
m = _MONTH_NAMES_MAP.get(mon_str) or _MONTH_NAMES_MAP.get(mon_str[:3])
max_d = get_last_day_of_month(y, m)
return f"{max_d:02d}/{m:02d}/{y:04d}"
# 7. Pattern: DD/MM/YYYY or DD-MM-YYYY (full numeric date, e.g. 09/09/2026, 28-02-2025, 28.02.2025)
m_dmy = re.search(r'\b(\d{1,2})\s*[-/.]\s*(\d{1,2})\s*[-/.]\s*(\d{2,4})(?!\d)', s)
if m_dmy:
d = int(m_dmy.group(1))
m = int(m_dmy.group(2))
y = int(m_dmy.group(3))
if y < 100:
y += 2000
if 1 <= m <= 12 and 1 <= d <= 31:
max_d = get_last_day_of_month(y, m)
return f"{min(d, max_d):02d}/{m:02d}/{y:04d}"
# 8. Pattern: MM/YYYY or MM-YYYY or MM/YY or MM - 26 (numeric Month-Year only, e.g. '02 - 26', '02/2026', '06-28')
m_my = re.search(r'\b(\d{1,2})\s*[-/.]\s*(\d{2,4})\b', s)
if m_my:
m = int(m_my.group(1))
y = int(m_my.group(2))
if y < 100:
y += 2000
if 1 <= m <= 12:
max_d = get_last_day_of_month(y, m)
return f"{max_d:02d}/{m:02d}/{y:04d}"
# If all parsing fails, return stripped input
return s
# ─────────────────────────────────────────────────────────────────────────────
# Batch code: ambiguity detection and known-batch correction
# ─────────────────────────────────────────────────────────────────────────────
# Characters that are visually ambiguous in small compressed JPEG text
_BATCH_AMBIGUOUS_PAIRS = [
('W', 'V'), # most common — W misread as V
('M', 'N'), # second most common
('1', 'J'), # digit 1 vs letter J (J→1 when surrounded by digits)
('1', 'I'), # digit 1 vs letter I
('0', 'O'), # digit 0 vs letter O
('8', 'B'), # rare but happens
('5', 'S'), # rare
]
# Only swap these pairs when both neighbours suggest the same type
# (digit-only neighbours → must be digit; letter-only neighbours → must be letter)
# For W/V and M/N we always swap — they're both letters, context doesn't help
_CONTEXT_SENSITIVE_PAIRS = {
('1', 'J'), ('1', 'I'), # digit vs letter — use neighbours
('0', 'O'), # digit vs letter — use neighbours
('8', 'B'), # digit vs letter — use neighbours
('5', 'S'), # digit vs letter — use neighbours
}
_ALWAYS_SWAP_PAIRS = {
('W', 'V'), ('V', 'W'),
('M', 'N'), ('N', 'M'),
}
_AMBIGUOUS_CHARS = set()
for a, b in _BATCH_AMBIGUOUS_PAIRS:
_AMBIGUOUS_CHARS.add(a.upper())
_AMBIGUOUS_CHARS.add(b.upper())
# Per-invoice batch registry: built from the first pass, used to cross-check
# subsequent items on the same invoice. For example if batch "ABWG0002" appears
# on invoice/seller X, and later we see "ABVG0002" for the same seller, we know
# W/V confusion happened.
#
# This is populated dynamically by apply_ocr_corrections() at call time.
# It does NOT persist across invoices.
def _batch_has_ambiguous_chars(batch: str) -> list[int]:
"""Return list of positions in batch string that contain ambiguous characters."""
return [i for i, c in enumerate(batch.upper()) if c in _AMBIGUOUS_CHARS]
def _batch_alternatives(batch: str) -> list[str]:
"""
Generate 1-char substitution variants of a batch string using the confusion
pair map, filtered by neighbour context for digit/letter ambiguous pairs.
Rules:
- W/V and M/N: always generate the swap (both are letters)
- 1/J, 1/I, 0/O, 8/B, 5/S: only swap when both adjacent characters
suggest the replacement type (digit neighbours → use digit form,
letter neighbours → use letter form)
Returns list of corrected variants (may be empty).
"""
variants = []
upper = batch.upper()
n = len(upper)
# Build pair map: char → its confusion partner
pair_map: dict[str, str] = {}
for a, b in _BATCH_AMBIGUOUS_PAIRS:
pair_map[a.upper()] = b.upper()
pair_map[b.upper()] = a.upper()
def _is_digit(c: str) -> bool:
return c.isdigit()
def _is_letter(c: str) -> bool:
return c.isalpha()
for i, char in enumerate(upper):
if char not in pair_map:
continue
partner = pair_map[char]
pair_key_fwd = (char, partner)
pair_key_rev = (partner, char)
# Always-swap pairs (W↔V, M↔N)
if pair_key_fwd in _ALWAYS_SWAP_PAIRS or pair_key_rev in _ALWAYS_SWAP_PAIRS:
swapped = list(upper)
swapped[i] = partner
variants.append(''.join(swapped))
continue
# Context-sensitive pairs: apply neighbour rule
# Look at left and right neighbours (skip if at boundary)
left = upper[i - 1] if i > 0 else None
right = upper[i + 1] if i < n - 1 else None
neighbours = [c for c in [left, right] if c is not None]
n_digits = sum(1 for c in neighbours if _is_digit(c))
n_letters = sum(1 for c in neighbours if _is_letter(c))
# Partner is a digit: only propose if both neighbours are digits
if _is_digit(partner) and n_digits == len(neighbours) and len(neighbours) > 0:
swapped = list(upper)
swapped[i] = partner
variants.append(''.join(swapped))
# Partner is a letter: only propose if both neighbours are letters
elif _is_letter(partner) and n_letters == len(neighbours) and len(neighbours) > 0:
swapped = list(upper)
swapped[i] = partner
variants.append(''.join(swapped))
# Mixed or boundary — generate the swap (conservative: let registry decide)
else:
swapped = list(upper)
swapped[i] = partner
variants.append(''.join(swapped))
return variants
def correct_batch_with_registry(batch: str, registry: set[str]) -> tuple[str, bool]:
"""
Try to correct a batch code by checking if any 1-char swap matches a
previously seen batch on this invoice.
Args:
batch : The batch string to check (may contain OCR error).
registry : Set of batches already confirmed on this invoice.
Returns:
(corrected_batch, was_corrected)
This handles the case where ABWG0002 appears on item 3 correctly, then
ABVG0002 appears on item 7 for the same product family. The registry
contains ABWG0002, so when we see ABVG0002 we generate variant ABWG0002,
find it in the registry, and correct.
"""
if not batch or not registry:
return batch, False
upper = batch.upper()
if upper in registry:
return batch, False # already correct, already in registry
for variant in _batch_alternatives(upper):
if variant in registry:
print(f"[OCR-FIX] Batch '{batch}' corrected to '{variant}' (registry match)")
return variant, True
return batch, False
def flag_ambiguous_batches(items: list[dict]) -> list[dict]:
"""
Two-pass algorithm over all items in an invoice:
Pass 1 — Build a registry of all batch strings that contain NO ambiguous
characters (i.e. unambiguous batches we can trust as ground truth).
Pass 2 — For each item whose batch HAS ambiguous characters, check if any
1-char swap matches a registry entry. If yes → correct it.
If no registry match → mark the item with _batch_ambiguous=True
so the reviewer knows to double-check it.
Also detects same-batch duplicates with 1-char difference (e.g. ABWG0002
and ABVG0002 both appear on the invoice) and corrects the second to match
the first.
"""
if not items:
return items
# ── Pass 1: build registry of unambiguous batches ────────────────────────
clean_registry: set[str] = set()
for item in items:
batch = str(item.get('Batch') or '').strip().upper()
if not batch:
continue
ambig = _batch_has_ambiguous_chars(batch)
if not ambig:
clean_registry.add(batch)
# ── Pass 2: correct or flag ambiguous batches ─────────────────────────────
# Also build a running registry that grows as we confirm batches,
# so later items can benefit from corrections made to earlier ones.
full_registry = set(clean_registry)
for item in items:
batch = str(item.get('Batch') or '').strip().upper()
if not batch:
continue
ambig_positions = _batch_has_ambiguous_chars(batch)
if not ambig_positions:
# No ambiguous chars — add to registry as ground truth
full_registry.add(batch)
continue
# Try to correct via registry
corrected, was_corrected = correct_batch_with_registry(batch, full_registry)
if was_corrected:
item['Batch'] = corrected
full_registry.add(corrected)
item.pop('_batch_ambiguous', None)
else:
# No registry match — flag for human review
ambig_chars = [batch[i] for i in ambig_positions]
item['_batch_ambiguous'] = True
item['_batch_ambiguous_chars'] = ambig_positions
alts = _batch_alternatives(batch)
if alts:
item['_batch_alternatives'] = alts
print(f"[OCR-FLAG] Batch '{batch}' has ambiguous chars {ambig_chars} "
f"at positions {ambig_positions} — flagged for review. "
f"Alternatives: {alts}")
full_registry.add(batch) # add as-is so subsequent items can reference it
return items
# ─────────────────────────────────────────────────────────────────────────────
# Top-level: apply all corrections to extracted invoice data
# ─────────────────────────────────────────────────────────────────────────────
def realign_shifted_items(items: list[dict], page_texts: list[str] = None) -> list[dict]:
"""
Detect and correct off-by-one metadata cascade shifts across page boundaries.
Problem addressed:
When an item (e.g. Item 4) ends at the bottom of Page N without its sub-row
Batch/Expiry/Code printed, those lines appear at the TOP of Page N+1.
If the vision model attaches the top metadata to the first item on Page N+1 (Item 5),
Item 5 takes Item 4's metadata, Item 6 takes Item 5's metadata, and Item 6's
metadata is dropped, leaving Item 4 with null batch/expiry.
This function detects when:
1) An item at index k has null batch and expiry_date.
2) The subsequent page's text contains M batches while there are only N items
(M = N + 1), meaning the first batch on the page belongs to item k.
It realigns all shifted items 100% deterministically.
"""
if not items:
return items
if not page_texts or len(page_texts) < 2:
return items
batch_pattern = re.compile(r'Batch\s*(?:&|and)?\s*Expiry\s*:\s*([^,\n\r]+)[,\s]+([^\n\r]+)', re.I)
code_pattern = re.compile(r'Item\s*Code\s*:\s*([A-Za-z0-9\-_/]+)', re.I)
pages_batches = [batch_pattern.findall(t or '') for t in page_texts]
pages_codes = [code_pattern.findall(t or '') for t in page_texts]
for p in range(len(page_texts) - 1):
batches_next = pages_batches[p + 1]
codes_next = pages_codes[p + 1]
if not batches_next:
continue
# Find the first item that has null batch and null expiry
null_item_idx = None
for idx, it in enumerate(items):
b = str(it.get('Batch') or '').strip()
e = str(it.get('expiry_date') or '').strip()
if not b and not e:
null_item_idx = idx
break
if null_item_idx is not None:
num_subsequent = len(items) - null_item_idx
# If the number of extracted batches on page p+1 matches the number of remaining items
# (including the null boundary item), a cascade shift occurred!
if len(batches_next) == num_subsequent:
print(f"[RE-ALIGN] Detected multi-page cascade shift across page {p+1}->{p+2} boundary!")
print(f"[RE-ALIGN] Realigning {num_subsequent} items starting from item index {null_item_idx}")
for offset, target_idx in enumerate(range(null_item_idx, len(items))):
raw_b, raw_e = batches_next[offset]
items[target_idx]['Batch'] = raw_b.strip()
items[target_idx]['expiry_date'] = correct_date(raw_e.strip())
if offset < len(codes_next):
items[target_idx]['item_code'] = codes_next[offset].strip()
desc = str(items[target_idx].get('description', ''))[:30]
print(f" [RE-ALIGN] Item {target_idx+1} ({desc}): Batch='{items[target_idx]['Batch']}', "
f"Expiry='{items[target_idx]['expiry_date']}', Code='{items[target_idx].get('item_code')}'")
break
return items
def apply_ocr_corrections(data: dict, page_texts: list[str] = None) -> dict:
"""
Apply all deterministic OCR corrections to an extracted invoice dict.
Corrects in-place and returns the same dict.
Prints a log line for every correction made.
"""
if not data or not isinstance(data, dict):
return data
corrections_made = 0
# ── Load human-verified batch corrections ─────────────────────────────────
import json as _json
import pathlib as _pathlib
import re as _re
_corrections_file = _pathlib.Path(__file__).parent / 'batch_corrections.json'
_batch_corrections: dict[str, str] = {}
_desc_corrections: dict[str, str] = {}
if _corrections_file.exists():
try:
_raw = _json.loads(_corrections_file.read_text(encoding='utf-8'))
for k, v in _raw.items():
if k.startswith('_'):
continue
if ' ' in k:
_desc_corrections[k.upper()] = v
else:
_batch_corrections[k.upper()] = v.upper()
except Exception as e:
print(f"[OCR-FIX] Could not load batch_corrections.json: {e}")
# ── Multi-page cross-boundary realignment ─────────────────────────────────
_pts = page_texts or data.get('_page_texts')
if data.get('items') and _pts:
try:
realign_shifted_items(data['items'], _pts)
except Exception as _realign_err:
print(f"[OCR-FIX] Multi-page realignment failed (non-fatal): {_realign_err}")
# ── GSTIN fields ──────────────────────────────────────────────────────────
for field in ('seller_gstin', 'customer_gstin'):
original = data.get(field)
if original:
fixed = correct_gstin(original)
if fixed != str(original).strip().upper():
data[field] = fixed
corrections_made += 1
# ── Header dates ──────────────────────────────────────────────────────────
for field in ('invoice_date', 'due_date', 'DC_date'):
original = data.get(field)
if original:
fixed = correct_date(original)
if fixed != original:
data[field] = fixed
corrections_made += 1
# ── PO number: fix malformed slash patterns ───────────────────────────────
# Common OCR error: "DMH/PO/..." gets read as "DMHP/O/..." (slash shifts left).
# Pattern: word immediately followed by /O/ → insert slash before P.
po = data.get('PO_number')
if po and isinstance(po, str):
# Fix: any sequence like XXXP/O/ where X are word chars → XXX/PO/
fixed_po = _re.sub(r'([A-Z]+)P/O/', r'\1/PO/', po)
if fixed_po != po:
data['PO_number'] = fixed_po
corrections_made += 1
print(f"[OCR-FIX] PO_number: '{po}' -> '{fixed_po}'")
# ── Invoice number: fix repeated-letter OCR errors ───────────────────────
# Common error: CC-1472 read as CG-1472 (second C looks like G).
# Rule: if invoice_number starts with two letters followed by a hyphen and
# the second letter is G but the prefix looks like it should be repeated
# (e.g., CC, SS, TT), correct G→C at position 1.
inv_num = data.get('invoice_number')
if inv_num and isinstance(inv_num, str):
# Pattern: Letter + G + hyphen + digits → check if G should be same as first letter
m = _re.match(r'^([A-Z])G(-\d)', inv_num, _re.IGNORECASE)
if m:
first_letter = m.group(1).upper()
# Only correct if the first letter is C, S, O (letters where G is a common swap)
if first_letter in ('C', 'S', 'O'):
fixed_inv = first_letter + first_letter + inv_num[2:]
data['invoice_number'] = fixed_inv
if data.get('invoice_id') == inv_num:
data['invoice_id'] = fixed_inv
corrections_made += 1
print(f"[OCR-FIX] invoice_number: '{inv_num}' -> '{fixed_inv}' (C/G confusion)")
# ── Items ─────────────────────────────────────────────────────────────────
for item in data.get('items', []):
# HSN / SAC
original_hsn = item.get('hsn_sac')
if original_hsn:
fixed = correct_hsn(original_hsn)
if fixed != original_hsn:
item['hsn_sac'] = fixed
corrections_made += 1
# Expiry date
original_exp = item.get('expiry_date')
if original_exp:
fixed = correct_date(original_exp)
if fixed != original_exp:
item['expiry_date'] = fixed
corrections_made += 1
# ── Human-verified batch corrections ──────────────────────────────────
original_batch = item.get('Batch')
if original_batch and isinstance(original_batch, str):
lookup = original_batch.strip().upper()
lookup_clean = lookup.replace(" ", "")
target_key = lookup if lookup in _batch_corrections else (lookup_clean if lookup_clean in _batch_corrections else None)
if target_key:
corrected = _batch_corrections[target_key]
item['Batch'] = corrected
corrections_made += 1
print(f"[OCR-FIX] Batch '{original_batch}' -> '{corrected}' (batch correction)")
# ── Parse embedded fields out of description ──────────────────────────
# Some invoices print Batch/Expiry/Code/MRP/CATALOG NO as sub-lines
# inside the product name cell.
desc = item.get('description') or ''
if isinstance(desc, str):
# Step 1: Strip CATALOG NO from description (Kanchan, Progress Healthcare pattern)
# "5F INTRODUCER SHEATH PEADIATRIC CATALOG NO : 504605S"
# → description = "5F INTRODUCER SHEATH PEADIATRIC"
catalog_match = _re.search(r'\s*\bCATALOG\s+NO\s*:.*$', desc, _re.IGNORECASE)
if catalog_match:
clean_desc = desc[:catalog_match.start()].strip().rstrip(',').rstrip()
if clean_desc != desc:
item['description'] = clean_desc
desc = clean_desc
corrections_made += 1
print(f"[OCR-FIX] CATALOG NO stripped from description: '{clean_desc}'")
# Step 2: Strip Batch/Expiry/Code/MRP sub-lines
if _re.search(r'\b(Batch|Expiry|Code|MRP|OLD MRP)\s*:', desc, _re.IGNORECASE):
# Extract batch from description if Batch field is empty
m_batch = _re.search(r'\bBatch\s*:\s*([A-Z0-9/ -]+?)(?:\s+(?:Expiry|Code|MRP|$)|\s*$)',
desc, _re.IGNORECASE)
if m_batch and not str(item.get('Batch') or '').strip():
item['Batch'] = m_batch.group(1).strip()
corrections_made += 1
print(f"[OCR-FIX] Batch extracted from description: '{item['Batch']}'")
# Extract expiry from description if expiry_date field is empty
m_exp = _re.search(
r'\bExpiry\s*:\s*(\d{1,2}[-/]\w{3,9}[-/]\d{2,4}|\d{2}[-/]\d{2}[-/]\d{2,4})',
desc, _re.IGNORECASE)
if m_exp and not str(item.get('expiry_date') or '').strip():
raw_exp = m_exp.group(1).strip()
item['expiry_date'] = correct_date(raw_exp)
corrections_made += 1
print(f"[OCR-FIX] Expiry extracted from description: '{item['expiry_date']}'")
# Extract item_code from description if item_code field is empty
m_code = _re.search(r'\bCode\s*:\s*([A-Z]{2}-\d{2}-\d{4})', desc, _re.IGNORECASE)
if m_code and not str(item.get('item_code') or '').strip():
item['item_code'] = m_code.group(1).strip()
corrections_made += 1
print(f"[OCR-FIX] item_code extracted from description: '{item['item_code']}'")
# Extract MRP — prefer new MRP over OLD MRP
m_mrp = _re.search(r'(?<!OLD\s)\bMRP\s*:\s*([\d.,]+)', desc, _re.IGNORECASE)
m_old_mrp = _re.search(r'\bOLD\s+MRP\s*:\s*([\d.,]+)', desc, _re.IGNORECASE)
if m_mrp and not item.get('MRP'):
item['MRP'] = m_mrp.group(1).replace(',', '')
corrections_made += 1
print(f"[OCR-FIX] MRP extracted from description: '{item['MRP']}'")
elif m_old_mrp and not item.get('MRP'):
item['MRP'] = m_old_mrp.group(1).replace(',', '')
# Clean description: strip everything from first Batch:/Expiry:/Code:/MRP: onward
clean_desc = _re.split(
r'\s+(?:Batch|Expiry|Code|MRP|OLD\s+MRP)\s*:', desc, flags=_re.IGNORECASE
)[0].strip().rstrip(',').rstrip()
if clean_desc != desc:
item['description'] = clean_desc
corrections_made += 1
print(f"[OCR-FIX] Description cleaned: '{clean_desc}'")
# Use prefix match so "SYMBOL 60 TAB (AL-01-5861)" matches key "SYMBOL 60 TAB"
original_desc = item.get('description')
if original_desc and isinstance(original_desc, str):
desc_upper = original_desc.strip().upper()
for wrong, right in _desc_corrections.items():
if desc_upper == wrong or desc_upper.startswith(wrong + ' ') or desc_upper.startswith(wrong + '('):
# Replace only the matched prefix, keep any suffix (item code etc.)
suffix = original_desc.strip()[len(wrong):]
corrected_desc = right + suffix
item['description'] = corrected_desc
corrections_made += 1
print(f"[OCR-FIX] Description '{original_desc}' -> '{corrected_desc}' (human correction)")
break
# ── Value = null unless it's clearly from a real "Value" column ──────
# Rule: Value must ONLY be from an explicit "Value" column.
# If Value == taxable_value → null (model copied TAXABLE into Value)
# If Value == total_price → null (model copied AMOUNT into Value)
# Only keep Value when it differs from BOTH taxable_value AND total_price
# (that means it genuinely came from a separate "Value" column)
def _to_f(v):
try:
return float(str(v).replace(',', '').replace('₹', '').strip()) if v is not None else None
except Exception:
return None
try:
val = _to_f(item.get('Value'))
tv = _to_f(item.get('taxable_value'))
tp = _to_f(item.get('total_price'))
if val is not None:
same_as_taxable = (tv is not None and abs(val - tv) < 0.05)
same_as_total = (tp is not None and abs(val - tp) < 0.05)
if same_as_taxable or same_as_total:
item['Value'] = None
corrections_made += 1
reason = 'taxable_value' if same_as_taxable else 'total_price'
print(f"[OCR-FIX] Value=null (was copy of {reason}={val}) "
f"[{item.get('description','')[:35]}]")
except Exception:
pass
# ── Pack field OCR correction ─────────────────────────────────────────
# The Pack field (e.g. VIAL, AMPOULE, TAB, CAP) is a small, constrained
# vocabulary. OCR errors like VIAL→VALL, AMPOULE→AMULE, CAP→COP are
# common because short uppercase strings get distorted in compressed images.
#
# Strategy: compare the extracted value (normalised) against a known pharma
# Pack vocabulary. If the extracted value is within 1 character edit-distance
# of a known term (and the extracted value is not itself a known term),
# correct it — unless the edit creates ambiguity (two candidates equally close).
#
# This is purely deterministic; no API call needed.
# ─────────────────────────────────────────────────────────────────────
_PACK_VOCAB = {
# Unit forms
'VIAL', 'AMPOULE', 'AMP', 'AMPULE',
'TAB', 'TABLET', 'TABLETS',
'CAP', 'CAPSULE', 'CAPSULES',
'BOTTLE', 'BOT',
'BOX', 'PKT', 'PACKET', 'PACK',
'TUBE', 'SACHET', 'STRIP',
'INJ', 'INJECTION',
'SYRINGE', 'SYR',
'CREAM', 'GEL', 'OINT', 'OINTMENT', 'LOTION', 'DROPS',
'SUSP', 'SUSPENSION', 'SYRUP', 'SYP',
'NOS', 'PCS', 'UNIT', 'UNITS',
'ML', 'MG',
}
def _pack_edit_distance(a: str, b: str) -> int:
"""Levenshtein distance — pure Python, O(len(a)×len(b))."""
if a == b:
return 0
la, lb = len(a), len(b)
if la == 0: return lb
if lb == 0: return la
prev = list(range(lb + 1))
for i, ca in enumerate(a):
curr = [i + 1] + [0] * lb
for j, cb in enumerate(b):
ins = curr[j] + 1
dele = prev[j + 1] + 1
sub = prev[j] + (0 if ca == cb else 1)
curr[j + 1] = min(ins, dele, sub)
prev = curr
return prev[lb]
raw_pack = item.get('Pack')
if raw_pack and isinstance(raw_pack, str):
# Separate leading number from unit token, e.g. "10 VIAL" → "10", "VIAL"
# or "10VIAL" → "10", "VIAL"
m_pack = _re.match(r'^(\d+\.?\d*)\s*([A-Za-z]+.*)$', raw_pack.strip())
if m_pack:
num_part = m_pack.group(1)
unit_part = m_pack.group(2).strip().upper()
else:
num_part = ''
unit_part = raw_pack.strip().upper()
# Only attempt correction for purely alphabetic tokens (no digits mixed in)
if unit_part and unit_part.isalpha():
if unit_part not in _PACK_VOCAB:
# Allowed edit distance scales with token length:
# ≤4 chars → allow up to 2 edits (short words compress badly)
# 5+ chars → allow only 1 edit
# Example: VIAL(4) → VALL(4) = 2 edits → corrected
# TABLET(6) → TEBLET(6) = 1 edit → corrected
max_dist = 2 if len(unit_part) <= 4 else 1
candidates = [v for v in _PACK_VOCAB
if _pack_edit_distance(unit_part, v) <= max_dist]
if len(candidates) == 1:
corrected_unit = candidates[0]
corrected_pack = (f"{num_part} {corrected_unit}".strip()
if num_part else corrected_unit)
print(f"[OCR-FIX] Pack '{raw_pack}' -> '{corrected_pack}' "
f"(edit-dist-{max_dist} correction)")
item['Pack'] = corrected_pack
corrections_made += 1
elif len(candidates) > 1:
# Ambiguous — keep original, just log it
print(f"[OCR-FIX] Pack '{raw_pack}': ambiguous candidates "
f"{candidates} — kept as-is")
# Item code — normalize slashes to hyphens, strip surrounding dots/spaces
original_code = item.get('item_code')
if original_code and isinstance(original_code, str):
fixed_code = original_code.strip().rstrip('.')
fixed_code = _re.sub(r'([A-Za-z]{2})/(\d{2})/(\d{4})', r'\1-\2-\3', fixed_code)
fixed_code = _re.sub(r'\s*-\s*', '-', fixed_code)
if fixed_code != original_code:
item['item_code'] = fixed_code
corrections_made += 1
print(f"[OCR-FIX] Item code normalized: '{original_code}' -> '{fixed_code}'")
if corrections_made:
print(f"[OCR-FIX] Total corrections applied: {corrections_made}")
else:
print("[OCR-FIX] No corrections needed.")
# ── Batch ambiguity detection — disabled in favour of batch_corrections.json ──
# The flag_ambiguous_batches function over-flags real batches (0, 8, V, M all
# get flagged as ambiguous on every invoice). The corrections file approach is
# more reliable: human-verified, zero false positives, zero API calls.
# To re-enable: uncomment the lines below.
# items = data.get('items', [])
# if items:
# data['items'] = flag_ambiguous_batches(items)
return data