Download src/classifier.py from Zayeemk/DocuPurse: direct link, hf CLI and curl.
- Browser
- Download file 2.02 kB
-
https://huggingface.co/spaces/Zayeemk/DocuPurse/resolve/main/src/classifier.py
- Command line
-
hf download hf://spaces/Zayeemk/DocuPurse/src/classifier.py
-
curl -L -o classifier.py https://huggingface.co/spaces/Zayeemk/DocuPurse/resolve/main/src/classifier.py
2.02 kB
| """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) | |