"""@module numeric-inference/arabic_tesseract — spatial whitelisted PyTesseract numeric OCR.""" from __future__ import annotations from typing import Any, Literal from .contracts import SemanticClass ARABIC_INDIC_WHITELIST = "٠١٢٣٤٥٦٧٨٩/.-،:" LATIN_NUMERIC_WHITELIST = "0123456789/.-," EXTENDED_ARABIC_INDIC = "۰۱۲۳۴۵۶۷۸۹" FULL_NUMERIC_WHITELIST = ( LATIN_NUMERIC_WHITELIST + ARABIC_INDIC_WHITELIST + EXTENDED_ARABIC_INDIC ) ScriptMode = Literal["arabic_indic", "latin", "full"] POLARITY_RETRY_MEAN_CONF = 82.0 TOKEN_CONF_FLOOR = 40.0 # Tesseract PSM: 6 uniform block, 7 single line, 8 single word _PSM_BY_CLASS: dict[SemanticClass, int] = { "nid": 7, "date": 7, "registration_number": 6, "tax_id": 8, "account_number": 8, "pan": 8, "amount": 7, "percentage": 7, "generic_numeric": 6, } def build_whitelist(script_mode: ScriptMode = "full") -> str: if script_mode == "arabic_indic": return ARABIC_INDIC_WHITELIST if script_mode == "latin": return LATIN_NUMERIC_WHITELIST return FULL_NUMERIC_WHITELIST def resolve_script_mode(semantic_class: SemanticClass, prefer_arabic: bool = True) -> ScriptMode: if semantic_class in {"nid", "date"} and prefer_arabic: return "arabic_indic" return "full" def resolve_psm(semantic_class: SemanticClass) -> int: return _PSM_BY_CLASS.get(semantic_class, 6) def _require_cv2(): try: import cv2 # type: ignore[import-untyped] except ImportError as error: raise RuntimeError("opencv_unavailable") from error return cv2 def _require_pytesseract(): try: import pytesseract # type: ignore[import-untyped] except ImportError as error: raise RuntimeError("pytesseract_unavailable") from error return pytesseract def bytes_to_bgr(image_bytes: bytes): cv2 = _require_cv2() import numpy as np buffer = np.frombuffer(image_bytes, dtype=np.uint8) image = cv2.imdecode(buffer, cv2.IMREAD_COLOR) if image is None: raise ValueError("invalid_image_payload") return image def noir_filter_preprocess(img_bgr: Any) -> Any: """Adaptive threshold for guilloché / low-contrast security backgrounds.""" cv2 = _require_cv2() gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) if len(img_bgr.shape) == 3 else img_bgr return cv2.adaptiveThreshold( gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10, ) def invert_polarity(processed: Any) -> Any: cv2 = _require_cv2() return cv2.bitwise_not(processed) def _tesseract_config(whitelist: str, psm: int) -> str: return f"--oem 3 --psm {psm} -c tessedit_char_whitelist={whitelist}" def extract_structured_numeric_tokens_from_processed( processed: Any, *, whitelist: str, psm: int, lang: str = "ara+eng", ) -> list[dict[str, Any]]: pytesseract = _require_pytesseract() config = _tesseract_config(whitelist, psm) data = pytesseract.image_to_data( processed, lang=lang, config=config, output_type=pytesseract.Output.DICT, ) tokens: list[dict[str, Any]] = [] for index, text in enumerate(data["text"]): cleaned = (text or "").strip() if not cleaned: continue try: conf = float(data["conf"][index]) except (TypeError, ValueError): continue if conf <= TOKEN_CONF_FLOOR: continue tokens.append( { "text": cleaned, "confidence": conf, "left": data["left"][index], "top": data["top"][index], "width": data["width"][index], "height": data["height"][index], } ) tokens.sort(key=lambda item: item["left"]) return tokens def extract_structured_numeric_tokens( img_bgr: Any, *, semantic_class: SemanticClass = "generic_numeric", script_mode: ScriptMode | None = None, processed: Any | None = None, ) -> list[dict[str, Any]]: """Production path: image_to_data + whitelist + conf gate + X-ascending sort.""" mode = script_mode or resolve_script_mode(semantic_class) whitelist = build_whitelist(mode) psm = resolve_psm(semantic_class) matrix = processed if processed is not None else noir_filter_preprocess(img_bgr) return extract_structured_numeric_tokens_from_processed( matrix, whitelist=whitelist, psm=psm ) def mean_token_confidence(tokens: list[dict[str, Any]]) -> float: if not tokens: return 0.0 return sum(float(item["confidence"]) for item in tokens) / len(tokens) def tokens_to_text(tokens: list[dict[str, Any]], semantic_class: SemanticClass) -> str: if not tokens: return "" joined = "".join(item["text"] for item in tokens) if semantic_class == "nid": return joined if semantic_class == "date": return joined.replace(" ", "") return joined.replace(" ", "") def extract_arabic_indic_boxes( img_bgr: Any, script_mode: ScriptMode = "arabic_indic", ) -> tuple[Any, list[dict[str, Any]]]: """Audit/debug: image_to_boxes + Y-origin inversion (not used for BeamCandidate text).""" cv2 = _require_cv2() pytesseract = _require_pytesseract() processed = noir_filter_preprocess(img_bgr) img_height, _ = processed.shape[:2] whitelist = build_whitelist(script_mode) config = _tesseract_config(whitelist, 6) boxes_raw = pytesseract.image_to_boxes(processed, config=config) annotated = img_bgr.copy() parsed: list[dict[str, Any]] = [] for line in boxes_raw.splitlines(): parts = line.split(" ") if len(parts) < 6: continue char = parts[0] x_min, y_bottom, x_max, y_top = ( int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4]), ) cv_y_top = img_height - y_top cv_y_bottom = img_height - y_bottom parsed.append( { "char": char, "bbox": (x_min, cv_y_top, x_max - x_min, cv_y_bottom - cv_y_top), } ) cv2.rectangle(annotated, (x_min, cv_y_top), (x_max, cv_y_bottom), (0, 255, 0), 1) cv2.putText( annotated, char, (x_min, max(10, cv_y_top - 8)), cv2.FONT_HERSHEY_COMPLEX, 0.45, (0, 0, 255), 1, ) return annotated, parsed