Spaces:
Configuration error

File size: 4,468 Bytes
f1ba785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""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,
    )