"""Rank only recognizer-provided beams using deterministic field constraints.""" from datetime import date import re from .contracts import BeamCandidate, NumericPolicy, RankedCandidate from .egyptian_nid import is_structurally_valid_egyptian_nid from .normalize import normalize_numeric_text def _luhn(value: str) -> bool: if not value.isdigit(): return False total = 0 parity = len(value) % 2 for index, char in enumerate(value): digit = int(char) if index % 2 == parity: digit *= 2 if digit > 9: digit -= 9 total += digit return total % 10 == 0 def _valid_date(value: str) -> bool: parts = re.split(r"[/.-]", value) if len(parts) != 3: return False try: if len(parts[0]) == 4: year, month, day = map(int, parts) else: day, month, year = map(int, parts) if year < 100: year += 2000 date(year, month, day) return True except ValueError: return False def _prefix_valid(digits: str, semantic_class: str) -> bool: if semantic_class == "nid": if not digits: return True if digits[0] not in {"2", "3"}: return False if len(digits) >= 7: century = {"2": "19", "3": "20"}.get(digits[:1], "") birth_date = century + digits[1:3] + "/" + digits[3:5] + "/" + digits[5:7] return _valid_date(birth_date) return True if semantic_class == "tax_id": return len(digits) <= 9 return True def _validate(value: str, policy: NumericPolicy) -> tuple[bool, bool | None]: digits = re.sub(r"\D", "", value) expected = policy.expected_length if not _prefix_valid(digits, policy.semantic_class): return False, None if policy.semantic_class == "date": return _valid_date(value), None if policy.semantic_class == "nid": valid = is_structurally_valid_egyptian_nid(value) return valid, None if policy.semantic_class == "pan": checksum = len(digits) in range(13, 20) and _luhn(digits) return checksum, checksum if policy.semantic_class in {"amount", "percentage"}: valid = bool(re.fullmatch(r"-?\d{1,3}(?:,?\d{3})*(?:\.\d+)?%?", value)) return valid, None valid = digits == value and (expected is None or len(digits) == expected) return valid, None def rank_candidates(candidates: list[BeamCandidate], policy: NumericPolicy) -> list[RankedCandidate]: ranked = [] for candidate in candidates: try: value, script = normalize_numeric_text(candidate.text) except ValueError as error: # A beam with no digits / a stray character is a failed read, not a bad # request: drop it. If none survive, the service answers 200 with # candidate=None + decision "abstain" instead of a 422 that the gateway # treats as an outage (30 s cooldown -> numeric flips to "offline"). # Any other ValueError is a real failure and must still surface. if str(error) not in { "unsupported character in numeric evidence", "numeric evidence contains no digits", }: raise continue schema_valid, checksum_valid = _validate(value, policy) ranked.append(RankedCandidate( normalized_text=value, source_script=script, probability=candidate.probability, # Raw probability × 100. decide() does not treat this as calibrated. calibrated_confidence=candidate.probability * 100, min_character_confidence=candidate.min_character_probability * 100, beam_margin=candidate.beam_margin, schema_valid=schema_valid, checksum_valid=checksum_valid, character_confidences=candidate.character_confidences, character_confidence_sources=candidate.character_confidence_sources, preprocessing_variant=candidate.preprocessing_variant, character_alternatives=candidate.character_alternatives, )) return sorted( ranked, key=lambda item: (item.schema_valid, item.checksum_valid is True, item.probability), reverse=True, )