""" Indian registration-number grammar and constrained decoding. The OCR model is a fixed-slot classifier: for every one of ``max_plate_slots`` positions it outputs a probability distribution over the alphabet (plus a pad character). Instead of taking the per-slot argmax (which happily produces "MHO5DS8679" with a letter O in a digit position), we search over the legal Indian plate layouts and pick the layout + characters that maximise the total log-probability. This fixes the classic 0/O, 1/I, 8/B, 5/S, 2/Z confusions and rejects impossible state codes. Supported layouts ----------------- * Standard: SS RR [L]{0,3} NNNN e.g. KA01AB1234, KA05M1234, DL3CAB1234, KA011234 (RTO code may be 1 or 2 digits; numbers with fewer than 4 digits are allowed with a penalty because older plates exist) * Bharat: YY BH NNNN L{1,2} e.g. 22BH1234AB """ from __future__ import annotations import re from dataclasses import dataclass from functools import lru_cache import numpy as np STATE_CODES = ( "AN AP AR AS BR CG CH DD DL DN GA GJ HP HR JH JK KA KL LA LD MH ML MN MP MZ NL OD OR PB PY " "RJ SK TN TR TS UK UP WB" ).split() STANDARD_RE = re.compile(r"^(?:%s)(?:[0-9]{2}|[1-9])[A-Z]{0,3}[0-9]{1,4}$" % "|".join(STATE_CODES)) BH_RE = re.compile(r"^[0-9]{2}BH[0-9]{4}[A-Z]{1,2}$") DIGITS = "0123456789" LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def is_valid_indian_plate(text: str) -> bool: return bool(STANDARD_RE.match(text) or BH_RE.match(text)) def format_plate(text: str) -> str: """Human friendly spacing: KA01AB1234 -> KA 01 AB 1234.""" m = re.match(r"^([A-Z]{2})([0-9]{1,2})([A-Z]{0,3})([0-9]{1,4})$", text) if m: return " ".join(part for part in m.groups() if part) m = re.match(r"^([0-9]{2})(BH)([0-9]{4})([A-Z]{1,2})$", text) if m: return " ".join(m.groups()) return text @dataclass(frozen=True) class Template: # each element is "S" (state pair handled specially), "D", "L", or a literal char slots: tuple[str, ...] prior: float # log-prior penalty (<= 0) @lru_cache(maxsize=8) def templates(max_slots: int) -> tuple[Template, ...]: out: list[Template] = [] for rto in (2, 1): for series in (2, 1, 3, 0): for num in (4, 3, 2, 1): length = 2 + rto + series + num if length > max_slots: continue prior = 0.0 prior -= {2: 0.0, 1: 0.6}[rto] prior -= {2: 0.0, 1: 0.3, 3: 0.8, 0: 1.0}[series] prior -= {4: 0.0, 3: 2.0, 2: 2.5, 1: 3.0}[num] out.append(Template(("S",) + ("D",) * rto + ("L",) * series + ("D",) * num, prior)) for tail in (2, 1): if 2 + 2 + 4 + tail <= max_slots: out.append(Template(("D", "D", "B", "H") + ("D",) * 4 + ("L",) * tail, -0.5 - 0.3 * (tail == 1))) return tuple(out) @dataclass(frozen=True) class DecodeResult: text: str confidence: float # geometric-mean probability of chosen characters (incl. pads) min_char_prob: float valid: bool raw_text: str # unconstrained per-slot argmax raw_confidence: float def decode_constrained(probs: np.ndarray, alphabet: str, pad_char: str = "_", max_penalty: float = 6.0) -> DecodeResult: """ probs: (slots, len(alphabet)) probability matrix. Returns the best legal Indian plate; falls back to the raw argmax when no legal layout scores within ``max_penalty`` nats of the raw reading. """ probs = np.asarray(probs, dtype=np.float64) slots = probs.shape[0] logp = np.log(np.clip(probs, 1e-9, 1.0)) idx = {c: i for i, c in enumerate(alphabet)} pad = idx[pad_char] digit_ids = np.array([idx[c] for c in DIGITS if c in idx]) letter_ids = np.array([idx[c] for c in LETTERS if c in idx]) raw_ids = probs.argmax(axis=1) raw_text = "".join(alphabet[i] for i in raw_ids).replace(pad_char, "") raw_score = float(logp[np.arange(slots), raw_ids].sum()) best_dig = digit_ids[logp[:, digit_ids].argmax(axis=1)] best_let = letter_ids[logp[:, letter_ids].argmax(axis=1)] pad_lp = logp[:, pad] # state code pair score (positions 0, 1) state_scores = [(logp[0, idx[s[0]]] + logp[1, idx[s[1]]], s) for s in STATE_CODES] best_state_score, best_state = max(state_scores) best: tuple[float, str, list[float]] | None = None for tpl in templates(slots): score = tpl.prior chars: list[str] = [] char_lps: list[float] = [] pos = 0 for kind in tpl.slots: if kind == "S": score += best_state_score chars.extend(best_state) char_lps.extend([logp[0, idx[best_state[0]]], logp[1, idx[best_state[1]]]]) pos += 2 continue if kind == "D": cid = best_dig[pos] elif kind == "L": cid = best_let[pos] else: cid = idx[kind] score += logp[pos, cid] char_lps.append(logp[pos, cid]) chars.append(alphabet[cid]) pos += 1 score += pad_lp[pos:].sum() char_lps.extend(pad_lp[pos:].tolist()) if best is None or score > best[0]: best = (score, "".join(chars), char_lps) raw_conf = float(np.exp(raw_score / slots)) if best is None or (raw_score - best[0]) > max_penalty: return DecodeResult(raw_text, raw_conf, float(probs[np.arange(slots), raw_ids].min()), is_valid_indian_plate(raw_text), raw_text, raw_conf) score, text, char_lps = best lp = np.array(char_lps) return DecodeResult( text=text, confidence=float(np.exp(lp.mean())), min_char_prob=float(np.exp(lp.min())), valid=is_valid_indian_plate(text), raw_text=raw_text, raw_confidence=raw_conf, ) _DIGIT_FIX = str.maketrans({"O": "0", "D": "0", "Q": "0", "I": "1", "L": "1", "Z": "2", "S": "5", "B": "8", "G": "6", "T": "7", "A": "4"}) _LETTER_FIX = str.maketrans({"0": "O", "1": "I", "2": "Z", "5": "S", "8": "B", "6": "G", "7": "T", "4": "A"}) def repair_text(text: str) -> str: """ Rule-based repair for OCR backends that only return a string (e.g. EasyOCR). Coerces characters to the expected class for the most likely standard layout. """ text = re.sub(r"[^A-Z0-9]", "", text.upper()) if is_valid_indian_plate(text) or len(text) < 6: return text # last 4 are digits, first 2 letters, next 1-2 digits, middle letters head = text[:2].translate(_LETTER_FIX) tail = text[-4:].translate(_DIGIT_FIX) middle = text[2:-4] rto_len = 2 if len(middle) >= 3 else 1 rto = middle[:rto_len].translate(_DIGIT_FIX) series = middle[rto_len:].translate(_LETTER_FIX) candidate = head + rto + series + tail return candidate if is_valid_indian_plate(candidate) else text