Source code for automated_document_parser.intelligence.classification

"""Deterministic document type classification."""

from __future__ import annotations

import re
from collections import defaultdict
from pathlib import Path

from ..models import ParsedDocument
from .models import ClassificationCandidate, DocumentClassification

_RULES: dict[str, tuple[tuple[str, float], ...]] = {
    "invoice": (
        (r"\binvoice\b", 3.0),
        (r"\bsubtotal\b", 1.5),
        (r"\bamount due\b", 2.0),
        (r"\binvoice number\b", 2.5),
        (r"\btax invoice\b", 2.5),
    ),
    "receipt": (
        (r"\breceipt\b", 3.0),
        (r"\bpayment received\b", 2.0),
        (r"\btransaction id\b", 1.5),
        (r"\bchange due\b", 1.5),
    ),
    "contract": (
        (r"\bagreement\b", 2.0),
        (r"\bcontract\b", 3.0),
        (r"\bwhereas\b", 1.5),
        (r"\bgoverning law\b", 2.0),
        (r"\bterms and conditions\b", 1.0),
        (r"\bindemnif\w*\b", 1.5),
    ),
    "resume": (
        (r"\bresume\b|\bcurriculum vitae\b", 3.0),
        (r"\bwork experience\b", 2.0),
        (r"\beducation\b", 1.0),
        (r"\bskills\b", 1.0),
        (r"\bemployment history\b", 2.0),
    ),
    "bank_statement": (
        (r"\bbank statement\b", 3.0),
        (r"\baccount number\b", 1.5),
        (r"\bopening balance\b", 2.0),
        (r"\bclosing balance\b", 2.0),
        (r"\bdebit\b", 0.75),
        (r"\bcredit\b", 0.75),
    ),
    "purchase_order": (
        (r"\bpurchase order\b|\bpo number\b", 3.0),
        (r"\bship to\b", 1.0),
        (r"\bquantity\b", 0.75),
        (r"\bunit price\b", 1.0),
    ),
    "report": (
        (r"\bexecutive summary\b", 2.0),
        (r"\bmethodology\b", 1.5),
        (r"\bfindings\b", 1.0),
        (r"\bconclusion\b", 1.0),
        (r"\bannual report\b", 2.5),
    ),
    "form": (
        (r"\bapplication form\b", 2.5),
        (r"\bplease complete\b", 1.5),
        (r"\bdate of birth\b", 1.0),
        (r"\bsignature\b", 0.5),
    ),
    "letter": (
        (r"\bdear\s+[A-Z][\w'-]+", 1.5),
        (r"\byours sincerely\b|\byours faithfully\b", 2.5),
        (r"\bkind regards\b", 1.0),
    ),
}


[docs] def classify_document( document: ParsedDocument, *, top_k: int = 3 ) -> DocumentClassification: """Rank likely document types using transparent keyword and filename rules.""" if top_k < 1: raise ValueError("top_k must be at least 1") content = document.content.lower() filename = Path(document.source).stem.lower().replace("_", " ").replace("-", " ") scores: dict[str, float] = defaultdict(float) signals: dict[str, list[str]] = defaultdict(list) for label, rules in _RULES.items(): for pattern, weight in rules: match = re.search(pattern, content, re.IGNORECASE) if match: scores[label] += weight signals[label].append(f"text:{match.group(0).lower()}") if re.search(rf"\b{re.escape(label.replace('_', ' '))}\b", filename): scores[label] += 2.0 signals[label].append("filename") if not scores: return DocumentClassification("unknown", 0.0, ()) ranked = sorted(scores, key=lambda label: (-scores[label], label)) total = sum(scores.values()) best_score = scores[ranked[0]] # Confidence reflects score strength and separation, not a calibrated probability. confidence = min(0.99, 0.45 + 0.12 * best_score + 0.08 * (best_score / total)) ambiguous = len(ranked) > 1 and scores[ranked[1]] / best_score > 0.85 if ambiguous: confidence = min(confidence, 0.60) candidates = tuple( ClassificationCandidate( label=label, confidence=( confidence if index == 0 else min( 0.99, 0.45 + 0.12 * scores[label] + 0.08 * scores[label] / total, ) ), signals=tuple(signals[label]), ) for index, label in enumerate(ranked[:top_k]) ) return DocumentClassification(ranked[0], confidence, candidates)