File size: 2,018 Bytes
26b8deb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Document type classifier using keyword heuristics."""
from __future__ import annotations
import re
from typing import Tuple

_INVOICE_KEYWORDS = [
    r"\binvoice\b", r"\binv[-\s]?\d", r"\bbill\s+to\b", r"\bdue\s+date\b",
    r"\btax\s+invoice\b", r"\bgstin\b", r"\bremit\s+to\b", r"\bpayment\s+due\b",
    r"\binvoice\s+number\b", r"\binvoice\s+no\b", r"\binvoice\s+date\b",
]
_RECEIPT_KEYWORDS = [
    r"\breceipt\b", r"\bcashier\b", r"\bamount\s+paid\b", r"\bpayment\s+received\b",
    r"\bthank\s+you\s+for\b", r"\bchange\b", r"\bcash\s+tender\b", r"\breceived\s+from\b",
    r"\bpos\s+terminal\b", r"\btransaction\s+id\b",
]
_PO_KEYWORDS = [
    r"\bpurchase\s+order\b", r"\bpo\s+number\b", r"\bpo\s+no\b",
    r"\bship\s+to\b", r"\border\s+date\b", r"\bdelivery\s+date\b",
    r"\bvendor\b", r"\bbuyer\b", r"\bprocurement\b", r"\brequisition\b",
]


def _count_matches(text: str, patterns: list) -> int:
    count = 0
    t = text.lower()
    for pattern in patterns:
        if re.search(pattern, t):
            count += 1
    return count


def classify_document(text: str) -> Tuple[str, float]:
    """
    Classify document type from extracted text.
    Returns (document_type, confidence) where confidence is 0.0 to 1.0.
    """
    invoice_score = _count_matches(text, _INVOICE_KEYWORDS)
    receipt_score = _count_matches(text, _RECEIPT_KEYWORDS)
    po_score = _count_matches(text, _PO_KEYWORDS)

    scores = {
        "invoice": invoice_score,
        "receipt": receipt_score,
        "purchase_order": po_score,
    }
    max_score = max(scores.values())
    if max_score == 0:
        return "unknown", 0.0

    best = max(scores, key=scores.get)
    total = sum(scores.values())
    confidence = max_score / total if total > 0 else 0.0

    if max_score >= 3:
        confidence = min(0.95, confidence + 0.3)
    elif max_score >= 2:
        confidence = min(0.85, confidence + 0.15)
    elif max_score == 1:
        confidence = min(0.65, confidence)

    return best, round(confidence, 4)