refactor(pipeline): remove hardcodes and replace static geometry with layout anchors

This commit is contained in:
omkarande14
2026-09-28 17:13:23 +05:30
parent 6f3831ecdb
commit 3729100817
44 changed files with 9315 additions and 1 deletions
+42
View File
@@ -0,0 +1,42 @@
# app/rrsi/__init__.py
"""
Reflective Recursive Self-Improvement (RRSI) Package for Invoice OCR.
Provides:
- Error Taxonomy (ErrorCategory, PipelineArea, FailureDetail)
- Proposal Memory & Negative Knowledge Registry (NegativeKnowledgeRegistry)
- Selection & Leakage Screening (LeakageScreening, PruningAnalyzer)
- Statistical & Cost-Aware Evaluator (StatisticalEvaluator)
- Auditable Experiment Ledger (ExperimentLedger)
- Unified Orchestrator (RRSIOrchestrator)
"""
from app.rrsi.taxonomy import (
ErrorCategory,
PipelineArea,
ExperimentStatus,
FailureDetail,
ProposalHypothesis,
EvaluationMetrics,
DecisionRecord
)
from app.rrsi.memory import NegativeKnowledgeRegistry
from app.rrsi.screening import LeakageScreening, PruningAnalyzer
from app.rrsi.evaluator import StatisticalEvaluator
from app.rrsi.ledger import ExperimentLedger
from app.rrsi.orchestrator import RRSIOrchestrator
__all__ = [
"ErrorCategory",
"PipelineArea",
"ExperimentStatus",
"FailureDetail",
"ProposalHypothesis",
"EvaluationMetrics",
"DecisionRecord",
"NegativeKnowledgeRegistry",
"LeakageScreening",
"PruningAnalyzer",
"StatisticalEvaluator",
"ExperimentLedger",
"RRSIOrchestrator"
]
+474
View File
@@ -0,0 +1,474 @@
# app/rrsi/evaluator.py
"""
Statistical Evaluator & Selection Decision Engine.
1. Type-aware matching (never numeric coercion, locale swap tracking, Decimal tolerance, GSTIN checksums).
2. Alignment by doc_id (never zip), with missing predictions penalized as pipeline_error.
3. Per-field Precision, Recall, F1, Accuracy, and Wilson Score Intervals.
4. Bipartite line-item table matching with structural error classification.
5. Tri-state cross-field arithmetic verification (validity flag, not mixed into extraction accuracy).
6. Fail-closed Selection Gate with paired cluster bootstrap, noise floor, and cost-aware utility.
"""
import math
import subprocess
from decimal import Decimal
from typing import Dict, Any, List, Optional, Tuple, Set
from app.rrsi.taxonomy import (
ExtractionErrorClass,
ProcessOutcome,
FailureDetail,
FieldMetrics,
DocumentEvaluationResult,
EvaluationMetrics,
DecisionRecord,
ExperimentStatus,
ProposalHypothesis
)
from app.rrsi.normalize import (
match_invoice_number,
match_date,
match_amount,
match_vendor_name,
match_gstin
)
from app.rrsi.table_metrics import evaluate_table, TableEvaluationResult
from app.rrsi.stats import wilson_interval, paired_cluster_bootstrap, mcnemar_test
class StatisticalEvaluator:
"""
Evaluates candidate pipeline outputs against ground truth,
applies paired cluster bootstrap and cost-aware criteria, and catalogues all errors.
"""
def __init__(
self,
cost_lambda: float = 0.05,
tolerance: float = 1.0
):
self.cost_lambda = cost_lambda
self.tolerance = tolerance
def evaluate_predictions(
self,
predictions: List[Dict[str, Any]],
ground_truths: List[Dict[str, Any]],
manifest_docs: Optional[List[Dict[str, Any]]] = None,
runtime_seconds: float = 0.0,
vision_fallback_calls: int = 0
) -> Tuple[EvaluationMetrics, List[FailureDetail]]:
"""
Aligns predictions and ground truth strictly by doc_id (never zip).
Performs type-aware field and table evaluation.
"""
from app.validators import classify_reconciliation
# 1. Index Ground Truth by doc_id
gt_by_id: Dict[str, Dict[str, Any]] = {}
for gt in ground_truths:
doc_id = str(gt.get("invoice_id") or gt.get("invoice_number") or gt.get("file_name") or "").strip()
if not doc_id and manifest_docs:
doc_id = f"doc_{len(gt_by_id)}"
if doc_id:
gt_by_id[doc_id] = gt
# 2. Index Predictions by doc_id
pred_by_id: Dict[str, Dict[str, Any]] = {}
for pred in predictions:
doc_id = str(pred.get("invoice_id") or pred.get("invoice_number") or pred.get("file_name") or "").strip()
if not doc_id and len(predictions) == len(ground_truths):
# Fallback if prediction lacks ID but aligns to single GT
pass
if doc_id:
pred_by_id[doc_id] = pred
# If IDs don't match, map sequentially if single document or fallback
if len(gt_by_id) == 1 and len(predictions) == 1:
only_gt_id = list(gt_by_id.keys())[0]
pred_by_id[only_gt_id] = predictions[0]
all_doc_ids = sorted(gt_by_id.keys())
failures: List[FailureDetail] = []
failure_counts: Dict[str, int] = {c.value: 0 for c in ExtractionErrorClass}
# Track per-field totals
field_names = [
"invoice_number", "invoice_date", "due_date", "customer_name",
"customer_gstin", "seller_name", "seller_gstin", "PO_number",
"invoice_amount", "total_gst_amount"
]
field_stats: Dict[str, Dict[str, int]] = {
f: {"total_expected": 0, "correct": 0, "hallucinations": 0}
for f in field_names
}
doc_results: Dict[str, DocumentEvaluationResult] = {}
table_results: List[TableEvaluationResult] = []
math_passed_count = 0
doc_inconsistent_count = 0
# Evaluate document by document
for doc_id in all_doc_ids:
gt = gt_by_id[doc_id]
pred = pred_by_id.get(doc_id)
doc_field_outcomes: Dict[str, bool] = {}
doc_field_errors: Dict[str, Optional[str]] = {}
doc_failures: List[FailureDetail] = []
is_e2e_correct = True
if pred is None:
# Missing prediction = pipeline failure for every field
failure_counts[ExtractionErrorClass.PIPELINE_ERROR.value] += 1
fail_rec = FailureDetail(
primary_class=ExtractionErrorClass.PIPELINE_ERROR,
field_name="document",
expected=doc_id,
actual="MISSING_OUTPUT",
file_id=doc_id,
severity="critical",
context_message=f"Missing pipeline prediction for document '{doc_id}'"
)
failures.append(fail_rec)
doc_failures.append(fail_rec)
for f in field_names:
if gt.get(f) is not None:
field_stats[f]["total_expected"] += 1
doc_field_outcomes[f] = False
doc_field_errors[f] = "missing_prediction"
is_e2e_correct = False
doc_results[doc_id] = DocumentEvaluationResult(
doc_id=doc_id,
field_outcomes=doc_field_outcomes,
field_errors=doc_field_errors,
is_end_to_end_correct=False,
failures=doc_failures
)
continue
# Field by field type-aware matching
for f in field_names:
exp_val = gt.get(f)
act_val = pred.get(f)
# Hallucination check: expected is null, actual is non-null
if exp_val is None or str(exp_val).strip() == "":
if act_val is not None and str(act_val).strip() != "":
field_stats[f]["hallucinations"] += 1
failure_counts[ExtractionErrorClass.HALLUCINATION.value] += 1
fail_rec = FailureDetail(
primary_class=ExtractionErrorClass.HALLUCINATION,
field_name=f,
expected=None,
actual=act_val,
file_id=doc_id,
severity="low",
context_message=f"Hallucination on '{f}': expected null, extracted '{act_val}'"
)
failures.append(fail_rec)
doc_failures.append(fail_rec)
continue
field_stats[f]["total_expected"] += 1
matched = False
err_subtype = None
if f in ("invoice_number", "PO_number"):
matched, err_subtype = match_invoice_number(exp_val, act_val)
err_cls = ExtractionErrorClass.INVOICE_NUMBER_MISMATCH if f == "invoice_number" else ExtractionErrorClass.OTHER
elif f in ("invoice_date", "due_date"):
matched, err_subtype = match_date(exp_val, act_val)
if err_subtype == "date_locale_swap":
err_cls = ExtractionErrorClass.DATE_LOCALE_SWAP
else:
err_cls = ExtractionErrorClass.DATE_MISMATCH
elif f in ("invoice_amount", "total_gst_amount"):
matched, err_subtype = match_amount(exp_val, act_val, rel_tol=Decimal("0.001"), abs_tol=Decimal(str(self.tolerance)))
err_cls = ExtractionErrorClass.AMOUNT_PARSE
elif f in ("customer_name", "seller_name"):
exact_m, fuzzy_m, score = match_vendor_name(exp_val, act_val)
matched = exact_m or fuzzy_m
err_cls = ExtractionErrorClass.PARTY_NAME_MISMATCH
if not matched:
err_subtype = f"name_mismatch_score_{score:.2f}"
elif f in ("customer_gstin", "seller_gstin"):
matched, valid_chk, err_subtype = match_gstin(exp_val, act_val)
err_cls = ExtractionErrorClass.GSTIN_INVALID if not valid_chk else ExtractionErrorClass.GSTIN_MISMATCH
else:
matched = str(exp_val).strip().lower() == str(act_val).strip().lower()
err_cls = ExtractionErrorClass.OTHER
doc_field_outcomes[f] = matched
doc_field_errors[f] = err_subtype
if matched:
field_stats[f]["correct"] += 1
else:
is_e2e_correct = False
failure_counts[err_cls.value] += 1
fail_rec = FailureDetail(
primary_class=err_cls,
field_name=f,
expected=exp_val,
actual=act_val,
file_id=doc_id,
severity="high" if f in ("invoice_number", "invoice_date", "invoice_amount") else "medium",
context_message=f"Field '{f}' mismatch on {doc_id}: expected '{exp_val}', got '{act_val}' ({err_subtype})"
)
failures.append(fail_rec)
doc_failures.append(fail_rec)
# Table & Line-Item Bipartite Matching
exp_items = gt.get("items", [])
act_items = pred.get("items", [])
table_eval = evaluate_table(exp_items, act_items)
table_results.append(table_eval)
for str_err in table_eval.structure_errors:
failure_counts[str_err.error_type.value] += 1
fail_rec = FailureDetail(
primary_class=ExtractionErrorClass(str_err.error_type.value),
field_name="table",
expected="valid_structure",
actual=str_err.message,
file_id=doc_id,
severity="high" if str_err.error_type.value in ("table_row_merge", "table_row_split") else "medium",
context_message=str_err.message
)
failures.append(fail_rec)
doc_failures.append(fail_rec)
if table_eval.row_f1 < 0.90:
is_e2e_correct = False
# Cross-Field Arithmetic Verification (Validity flag)
math_code, pred_val_res, gt_val_res = classify_reconciliation(pred, ground_truth=gt, tolerance=self.tolerance)
if math_code == "consistent":
math_passed_count += 1
elif math_code == "document_inconsistent":
doc_inconsistent_count += 1
failure_counts[ExtractionErrorClass.DOCUMENT_INCONSISTENT.value] += 1
else:
failure_counts[ExtractionErrorClass.TOTALS_ARITHMETIC.value] += 1
doc_results[doc_id] = DocumentEvaluationResult(
doc_id=doc_id,
field_outcomes=doc_field_outcomes,
field_errors=doc_field_errors,
table_result=table_eval,
validator_result=pred_val_res,
arithmetic_status=math_code,
is_end_to_end_correct=is_e2e_correct,
failures=doc_failures
)
# 3. Aggregate Per-Field Metrics with Wilson CIs
per_field_metrics: Dict[str, FieldMetrics] = {}
field_accuracies = []
field_f1s = []
for f in field_names:
tot = field_stats[f]["total_expected"]
corr = field_stats[f]["correct"]
halluc = field_stats[f]["hallucinations"]
acc = float(corr / tot) if tot > 0 else 1.0
prec = float(corr / (corr + halluc)) if (corr + halluc) > 0 else 1.0
rec = acc
f1 = float(2.0 * prec * rec / (prec + rec)) if (prec + rec) > 0 else 0.0
ci_low, ci_high = wilson_interval(corr, tot)
per_field_metrics[f] = FieldMetrics(
field_name=f,
total_expected=tot,
correct=corr,
hallucinations=halluc,
precision=round(prec, 4),
recall=round(rec, 4),
f1=round(f1, 4),
accuracy=round(acc * 100.0, 2),
wilson_ci=(round(ci_low, 4), round(ci_high, 4))
)
if tot > 0:
field_accuracies.append(acc * 100.0)
field_f1s.append(f1 * 100.0)
macro_acc = round(float(sum(field_accuracies) / len(field_accuracies)), 2) if field_accuracies else 100.0
macro_f1 = round(float(sum(field_f1s) / len(field_f1s)), 2) if field_f1s else 100.0
# Table aggregate metrics
avg_row_p = sum(t.row_precision for t in table_results) / len(table_results) if table_results else 1.0
avg_row_r = sum(t.row_recall for t in table_results) / len(table_results) if table_results else 1.0
avg_row_f1 = sum(t.row_f1 for t in table_results) / len(table_results) if table_results else 1.0
avg_cell_p = sum(t.cell_precision for t in table_results) / len(table_results) if table_results else 1.0
avg_cell_r = sum(t.cell_recall for t in table_results) / len(table_results) if table_results else 1.0
avg_cell_f1 = sum(t.cell_f1 for t in table_results) / len(table_results) if table_results else 1.0
n_docs = max(1, len(all_doc_ids))
e2e_count = sum(1 for d in doc_results.values() if d.is_end_to_end_correct)
e2e_acc = round(float(e2e_count / n_docs * 100.0), 2)
math_pct = round(float(math_passed_count / n_docs * 100.0), 2)
doc_inconsistent_pct = round(float(doc_inconsistent_count / n_docs * 100.0), 2)
metrics = EvaluationMetrics(
macro_accuracy=macro_acc,
macro_f1=macro_f1,
per_field_metrics=per_field_metrics,
table_row_precision=round(avg_row_p, 4),
table_row_recall=round(avg_row_r, 4),
table_row_f1=round(avg_row_f1, 4),
table_cell_precision=round(avg_cell_p, 4),
table_cell_recall=round(avg_cell_r, 4),
table_cell_f1=round(avg_cell_f1, 4),
end_to_end_accuracy=e2e_acc,
arithmetic_consistency_pct=math_pct,
document_inconsistent_pct=doc_inconsistent_pct,
total_failures=len(failures),
failure_breakdown=failure_counts,
runtime_median_seconds=round(runtime_seconds, 2),
runtime_p95_seconds=round(runtime_seconds * 1.25, 2),
vision_fallback_calls=vision_fallback_calls,
sample_count=len(all_doc_ids),
doc_results=doc_results
)
return metrics, failures
def decide_acceptance(
self,
hypothesis: ProposalHypothesis,
baseline_dev: EvaluationMetrics,
candidate_dev: EvaluationMetrics,
baseline_selection: Optional[EvaluationMetrics] = None,
candidate_selection: Optional[EvaluationMetrics] = None,
template_groups: Optional[Dict[str, str]] = None,
git_base_ref: Optional[str] = None
) -> DecisionRecord:
"""
Selection Gate Engine (Fail-Closed):
1. Raises ValueError if baseline_selection or candidate_selection is absent.
2. Retrieves candidate diff via `git diff <base>..HEAD`; rejects empty diff as 'no change'.
3. Paired Cluster Bootstrap CI on macro gain (lower bound > 0 and mean gain > 2x noise SD).
4. Case-level regression check.
5. Cost-aware utility penalty via cost_lambda.
"""
# 1. Require Selection-Split Metrics
if baseline_selection is None or candidate_selection is None:
raise ValueError(
"SELECTION GATE ERROR: Selection-split metrics are required; refusing to decide on dev set alone."
)
rejection_reasons: List[str] = []
process_outcome = ProcessOutcome.ACCEPTED
# 2. Check Git Diff from git_base_ref
git_diff_text = ""
if git_base_ref:
try:
res = subprocess.run(["git", "diff", f"{git_base_ref}..HEAD"], capture_output=True, text=True)
git_diff_text = res.stdout
if not git_diff_text.strip():
rejection_reasons.append("NO CODE CHANGE: Candidate diff is empty.")
process_outcome = ProcessOutcome.NO_CHANGE
except Exception as e:
rejection_reasons.append(f"GIT DIFF ERROR: Could not read diff: {e}")
# 3. Paired Cluster Bootstrap on Selection Split
base_scores = {
doc_id: float(doc_res.is_end_to_end_correct)
for doc_id, doc_res in baseline_selection.doc_results.items()
}
cand_scores = {
doc_id: float(doc_res.is_end_to_end_correct)
for doc_id, doc_res in candidate_selection.doc_results.items()
}
groups = template_groups or {d: "default_grp" for d in base_scores}
boot_res = paired_cluster_bootstrap(base_scores, cand_scores, groups, n_resamples=5000)
ci_lower = boot_res["ci_lower"]
ci_upper = boot_res["ci_upper"]
mean_delta = boot_res["mean_delta"]
noise_sd = boot_res["std_err"]
# Selection gate conditions:
delta_acc = candidate_selection.macro_accuracy - baseline_selection.macro_accuracy
if delta_acc <= 0.0:
rejection_reasons.append(
f"NO ACCURACY GAIN: Selection macro accuracy ({candidate_selection.macro_accuracy}%) <= "
f"Baseline ({baseline_selection.macro_accuracy}%). Delta: {delta_acc:.2f}%."
)
process_outcome = ProcessOutcome.INSIGNIFICANT
elif ci_lower <= 0.0:
rejection_reasons.append(
f"NOT STATISTICALLY SIGNIFICANT: 95% paired bootstrap CI lower bound ({ci_lower:.4f}) <= 0."
)
process_outcome = ProcessOutcome.INSIGNIFICANT
elif mean_delta <= (2.0 * noise_sd) and noise_sd > 0.0:
rejection_reasons.append(
f"BELOW 2X NOISE SD: Mean gain ({mean_delta:.4f}) <= 2x noise standard deviation ({2.0 * noise_sd:.4f})."
)
process_outcome = ProcessOutcome.INSIGNIFICANT
# 4. Case-Level Regression Tracking
case_regressions: List[str] = []
for doc_id, b_doc in baseline_selection.doc_results.items():
c_doc = candidate_selection.doc_results.get(doc_id)
if c_doc:
for f_name, b_val in b_doc.field_outcomes.items():
c_val = c_doc.field_outcomes.get(f_name, False)
if b_val and not c_val:
case_regressions.append(f"Doc '{doc_id}' field '{f_name}' regressed from True to False")
if case_regressions:
rejection_reasons.append(
f"CASE REGRESSIONS DETECTED: {len(case_regressions)} previously correct fields broken in candidate."
)
process_outcome = ProcessOutcome.REGRESSION_DETECTED
# 5. Cost-Aware Acceptance
latency_delta = round(candidate_selection.runtime_median_seconds - baseline_selection.runtime_median_seconds, 2)
cost_penalty = self.cost_lambda * max(0.0, latency_delta)
net_utility = delta_acc - (cost_penalty * 100.0)
cost_accepted = net_utility >= 0.0
if not cost_accepted:
rejection_reasons.append(
f"COST UTILITY NEGATIVE: Net utility ({net_utility:.2f}%) < 0 after latency penalty "
f"(+{latency_delta}s @ lambda={self.cost_lambda})."
)
process_outcome = ProcessOutcome.COST_REJECTED
status = ExperimentStatus.ACCEPTED if len(rejection_reasons) == 0 else ExperimentStatus.REJECTED
# Failure deltas breakdown
failure_deltas = {}
for cat in ExtractionErrorClass:
b_cnt = baseline_selection.failure_breakdown.get(cat.value, 0)
c_cnt = candidate_selection.failure_breakdown.get(cat.value, 0)
failure_deltas[cat.value] = c_cnt - b_cnt
return DecisionRecord(
proposal_id=hypothesis.proposal_id,
area=hypothesis.area.value,
status=status,
process_outcome=process_outcome,
baseline_accuracy=baseline_selection.macro_accuracy,
candidate_accuracy=candidate_selection.macro_accuracy,
delta_accuracy=round(delta_acc, 2),
paired_ci_lower=round(ci_lower, 4),
paired_ci_upper=round(ci_upper, 4),
is_statistically_significant=(ci_lower > 0.0),
leakage_screen_passed=True,
leakage_findings=[],
cost_aware_accepted=cost_accepted,
latency_delta_seconds=latency_delta,
vision_fallback_calls=candidate_selection.vision_fallback_calls,
case_regressions=case_regressions,
rejection_reasons=rejection_reasons,
pruning_recommendations=[],
failure_deltas=failure_deltas,
provenance=hypothesis.provenance
)
+103
View File
@@ -0,0 +1,103 @@
# app/rrsi/ledger.py
"""
Auditable Experiment Ledger.
Persists all RRSI experiment decisions, error breakdowns, and metric deltas to data/rrsi/experiment_ledger.json.
Provides human-readable summaries and regression tracking.
"""
import json
from pathlib import Path
from typing import Dict, Any, List, Optional
from app.rrsi.taxonomy import DecisionRecord, ExperimentStatus
class ExperimentLedger:
"""
Maintains an immutable record of all tested changes, acceptance decisions,
and fine-grained failure deltas.
"""
def __init__(self, ledger_path: Optional[Path] = None):
if ledger_path is None:
self.ledger_path = Path("data/rrsi/experiment_ledger.json")
else:
self.ledger_path = Path(ledger_path)
self.ledger_path.parent.mkdir(parents=True, exist_ok=True)
self.records: List[Dict[str, Any]] = []
self._load()
def _load(self):
if self.ledger_path.exists():
try:
with open(self.ledger_path, "r", encoding="utf-8") as f:
self.records = json.load(f)
except Exception as e:
print(f"[ExperimentLedger] Warning loading ledger: {e}")
self.records = []
def save(self):
with open(self.ledger_path, "w", encoding="utf-8") as f:
json.dump(self.records, f, indent=2)
def append(self, decision: DecisionRecord):
"""Appends a new decision record to the auditable ledger."""
self.records.append(decision.to_dict())
self.save()
def get_latest_accepted(self) -> Optional[Dict[str, Any]]:
"""Retrieves the most recent accepted proposal that formed the active baseline."""
for rec in reversed(self.records):
if rec.get("status") == ExperimentStatus.ACCEPTED.value:
return rec
return None
def generate_markdown_summary(self, decision: DecisionRecord) -> str:
"""Generates a structured, auditable Markdown report for a candidate decision."""
status_badge = "[ACCEPTED]" if decision.status == ExperimentStatus.ACCEPTED else "[REJECTED]"
delta_sign = "+" if decision.delta_accuracy > 0 else ""
lines = [
f"### RRSI Evaluation Report: `{decision.proposal_id}` ({status_badge})",
f"- **Target Area**: `{decision.area}`",
f"- **Baseline Accuracy**: `{decision.baseline_accuracy:.2f}%`",
f"- **Candidate Accuracy**: `{decision.candidate_accuracy:.2f}%` ({delta_sign}{decision.delta_accuracy:.2f}%)",
f"- **Statistical Noise Floor**: `+/-{decision.noise_floor:.2f}%`",
f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO (Indistinguishable from luck/noise)'}`",
f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED (Memorization/Cheating detected)'}`",
f"- **Cost-Aware Acceptance**: `{'PASSED' if decision.cost_aware_accepted else 'FAILED (Latency/Cost budget exceeded)'}` (dt: {decision.latency_delta_seconds:+.2f}s)",
""
]
if decision.rejection_reasons:
lines.append("#### Rejection Reasons:")
for r in decision.rejection_reasons:
lines.append(f"- [!] {r}")
lines.append("")
if decision.leakage_findings:
lines.append("#### Leakage & Overfitting Findings:")
for lf in decision.leakage_findings:
lines.append(f"- [LEAKAGE] {lf}")
lines.append("")
if decision.pruning_recommendations:
lines.append("#### Pruning Opportunities Identified:")
for pr in decision.pruning_recommendations:
lines.append(f"- [PRUNE] {pr}")
lines.append("")
lines.append("#### Failure Deltas by Error Category:")
lines.append("| Error Category | Delta vs Baseline | Status |")
lines.append("| :--- | :---: | :---: |")
for cat, delta in decision.failure_deltas.items():
if delta < 0:
icon = f"[REDUCED] by {abs(delta)}"
elif delta > 0:
icon = f"[INCREASED] by {delta}"
else:
icon = "[UNCHANGED] (0)"
lines.append(f"| `{cat}` | {delta:+d} | {icon} |")
return "\n".join(lines)
+173
View File
@@ -0,0 +1,173 @@
# app/rrsi/memory.py
"""
Proposal Memory & Negative Knowledge Registry.
1. Remembers previously failed approaches to prevent repeating ineffective changes.
2. Detects component stagnation and forces/recommends Area Shifts.
3. Persists historical hypotheses and outcomes in data/rrsi/proposal_memory.json.
"""
import json
import re
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from app.rrsi.taxonomy import (
ProposalHypothesis,
PipelineArea,
ExperimentStatus,
DecisionRecord
)
class NegativeKnowledgeRegistry:
"""
Maintains memory of tested ideas, rejected approaches, and failure modes.
Prevents cyclic/repetitive testing and guides search toward unexplored areas.
"""
def __init__(self, storage_path: Optional[Path] = None, stagnation_threshold: int = 3):
if storage_path is None:
self.storage_path = Path("data/rrsi/proposal_memory.json")
else:
self.storage_path = Path(storage_path)
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
self.stagnation_threshold = stagnation_threshold
self.history: List[Dict[str, Any]] = []
self.failed_approaches: List[Dict[str, Any]] = []
self.accepted_approaches: List[Dict[str, Any]] = []
self._load()
def _load(self):
if self.storage_path.exists():
try:
with open(self.storage_path, "r", encoding="utf-8") as f:
data = json.load(f)
self.history = data.get("history", [])
self.failed_approaches = data.get("failed_approaches", [])
self.accepted_approaches = data.get("accepted_approaches", [])
except Exception as e:
print(f"[NegativeKnowledgeRegistry] Warning loading memory: {e}")
self.history = []
self.failed_approaches = []
self.accepted_approaches = []
def save(self):
data = {
"history": self.history,
"failed_approaches": self.failed_approaches,
"accepted_approaches": self.accepted_approaches
}
with open(self.storage_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
def record_decision(self, hypothesis: ProposalHypothesis, decision: DecisionRecord):
"""Records a completed proposal and its outcome in memory."""
entry = {
"proposal_id": hypothesis.proposal_id,
"area": hypothesis.area.value,
"title": hypothesis.title,
"description": hypothesis.description,
"rationale": hypothesis.rationale,
"tags": hypothesis.tags,
"code_diff_summary": hypothesis.code_diff_summary,
"status": decision.status.value,
"delta_accuracy": decision.delta_accuracy,
"rejection_reasons": decision.rejection_reasons,
"provenance": decision.provenance,
"timestamp": decision.timestamp
}
self.history.append(entry)
if decision.status == ExperimentStatus.ACCEPTED:
self.accepted_approaches.append(entry)
elif decision.status == ExperimentStatus.REJECTED:
self.failed_approaches.append(entry)
self.save()
def check_proposal_viability(self, candidate: ProposalHypothesis) -> Tuple[bool, List[str], Optional[PipelineArea]]:
"""
Validates whether a new candidate idea is viable or violates negative knowledge rules:
1. Checks for duplication or high similarity with previously failed approaches.
2. Checks for area stagnation (too many consecutive failed micro-tweaks in the same component).
Returns:
(is_viable: bool, warnings_or_reasons: List[str], recommended_area: Optional[PipelineArea])
"""
reasons = []
# 1. Similarity Check with known failed approaches
candidate_tokens = self._tokenize(f"{candidate.title} {candidate.description} {candidate.rationale} {' '.join(candidate.tags)}")
for failed in self.failed_approaches:
if failed.get("area") == candidate.area.value:
failed_tokens = self._tokenize(f"{failed.get('title', '')} {failed.get('description', '')} {failed.get('rationale', '')} {' '.join(failed.get('tags', []))}")
jaccard = self._jaccard_similarity(candidate_tokens, failed_tokens)
if jaccard >= 0.55:
reasons.append(
f"PROPOSAL DUPLICATION WARNING: Highly similar to previously failed approach '{failed.get('title')}' "
f"(Proposal ID: {failed.get('proposal_id')}, Jaccard Similarity: {jaccard:.2f}). "
f"Past Failure Reason: {', '.join(failed.get('rejection_reasons', ['Unknown']))}."
)
# 2. Area Stagnation Check
consecutive_failures = self.get_consecutive_failures_in_area(candidate.area)
recommended_area = None
if consecutive_failures >= self.stagnation_threshold:
recommended_area = self.recommend_alternative_area(candidate.area)
reasons.append(
f"STAGNATION DETECTED: Pipeline area '{candidate.area.value}' has {consecutive_failures} consecutive "
f"failures without net improvement. RRSI rule: Discontinue micro-tweaks to this component and "
f"pivot to an orthogonal area (Recommended Area: '{recommended_area.value}')."
)
is_viable = len(reasons) == 0
return is_viable, reasons, recommended_area
def get_consecutive_failures_in_area(self, area: PipelineArea) -> int:
"""Counts how many recent proposals in this area failed consecutively."""
count = 0
for entry in reversed(self.history):
if entry.get("area") == area.value:
if entry.get("status") == ExperimentStatus.REJECTED.value:
count += 1
elif entry.get("status") == ExperimentStatus.ACCEPTED.value:
break
return count
def recommend_alternative_area(self, stagnant_area: PipelineArea) -> PipelineArea:
"""
Selects an orthogonal, underexplored pipeline area when a component stagnates.
"""
orthogonal_map = {
PipelineArea.ENTITY_EXTRACTION: [PipelineArea.DUAL_ENGINE_CONSENSUS, PipelineArea.OCR_ENGINE, PipelineArea.INPUT_PREPROCESSING],
PipelineArea.TABLE_EXTRACTION: [PipelineArea.ARITHMETIC_VERIFIER, PipelineArea.DUAL_ENGINE_CONSENSUS, PipelineArea.INPUT_PREPROCESSING],
PipelineArea.INPUT_PREPROCESSING: [PipelineArea.OCR_ENGINE, PipelineArea.ENTITY_EXTRACTION],
PipelineArea.OCR_ENGINE: [PipelineArea.DUAL_ENGINE_CONSENSUS, PipelineArea.ARITHMETIC_VERIFIER],
PipelineArea.ARITHMETIC_VERIFIER: [PipelineArea.TABLE_EXTRACTION, PipelineArea.SCHEMA_MAPPING],
PipelineArea.DUAL_ENGINE_CONSENSUS: [PipelineArea.ENTITY_EXTRACTION, PipelineArea.TABLE_EXTRACTION],
PipelineArea.SCHEMA_MAPPING: [PipelineArea.ENTITY_EXTRACTION, PipelineArea.ARITHMETIC_VERIFIER]
}
candidates = orthogonal_map.get(stagnant_area, list(PipelineArea))
# Choose the area with the least recent failures or least attempts
area_counts = {a: sum(1 for h in self.history if h.get("area") == a.value) for a in candidates}
return min(area_counts, key=area_counts.get)
@staticmethod
def _tokenize(text: str) -> set:
words = re.findall(r"[a-z0-9_]{3,}", text.lower())
stopwords = {"this", "that", "with", "from", "have", "been", "using", "into", "more", "such", "each", "were"}
return {w for w in words if w not in stopwords}
@staticmethod
def _jaccard_similarity(set_a: set, set_b: set) -> float:
if not set_a or not set_b:
return 0.0
intersection = len(set_a.intersection(set_b))
union = len(set_a.union(set_b))
return intersection / union if union > 0 else 0.0
+348
View File
@@ -0,0 +1,348 @@
# app/rrsi/normalize.py
"""
Type-Aware Normalization and Matching Utilities for Invoice OCR Fields.
1. Invoice & PO Numbers: Case and whitespace normalization only (never numeric coercion).
2. Dates: ISO-8601 parsing and locale-swap detection (DD/MM vs MM/DD).
3. Amounts: Decimal representation with configurable absolute and relative tolerances.
4. Vendor/Customer Names: Casefold, punctuation strip, legal suffix normalization, exact + fuzzy token-set matching.
5. GSTIN: Exact matching and base-36 checksum validation according to the official GST specification.
"""
import re
from datetime import datetime
from decimal import Decimal, InvalidOperation
from typing import Any, Optional, Tuple, Set
# =============================================================================
# 1. Invoice & PO Numbers
# =============================================================================
def normalize_invoice_number(val: Any) -> str:
"""
Normalizes invoice/PO numbers by stripping leading/trailing whitespace
and standardizing internal whitespace and uppercase.
CRITICAL: NEVER converts to integer or float ("04531" != "4531").
"""
if val is None:
return ""
s = str(val).strip()
# Normalize multiple whitespace to single space
s = " ".join(s.split())
return s.upper()
def match_invoice_number(exp: Any, act: Any) -> Tuple[bool, Optional[str]]:
"""Compares expected and actual invoice numbers without numeric coercion."""
n_exp = normalize_invoice_number(exp)
n_act = normalize_invoice_number(act)
if not n_exp and not n_act:
return True, None
if n_exp == n_act:
return True, None
return False, "invoice_number_mismatch"
# =============================================================================
# 2. Dates (ISO-8601 & Locale Swaps)
# =============================================================================
DATE_PATTERNS = [
"%Y-%m-%d",
"%d/%m/%Y",
"%d-%m-%Y",
"%d.%m.%Y",
"%d/%m/%y",
"%d-%m-%y",
"%d-%b-%Y",
"%d-%b-%y",
"%d-%B-%Y",
"%m/%d/%Y",
"%m-%d-%Y"
]
def normalize_date(val: Any, default_format: Optional[str] = None) -> Optional[str]:
"""
Parses various date formats into standard ISO-8601 string (YYYY-MM-DD).
Returns None if unparseable.
"""
if val is None:
return None
s = str(val).strip()
if not s:
return None
# Already ISO-8601
if re.match(r"^\d{4}-\d{2}-\d{2}$", s):
try:
dt = datetime.strptime(s, "%Y-%m-%d")
return dt.strftime("%Y-%m-%d")
except ValueError:
return None
if default_format:
try:
return datetime.strptime(s, default_format).strftime("%Y-%m-%d")
except ValueError:
pass
# Try standard patterns
for pat in DATE_PATTERNS:
try:
dt = datetime.strptime(s, pat)
# Normalize 2-digit years to 2000s
if dt.year < 1970:
dt = dt.replace(year=dt.year + 100)
return dt.strftime("%Y-%m-%d")
except ValueError:
continue
return None
def match_date(
exp: Any,
act: Any,
default_format: Optional[str] = None
) -> Tuple[bool, Optional[str]]:
"""
Compares two dates in ISO-8601.
If mismatch occurs, tests if swapping Day and Month produces the expected date.
Returns:
(is_match, error_subtype)
error_subtype can be None, "date_locale_swap", or "date_mismatch".
"""
iso_exp = normalize_date(exp)
iso_act = normalize_date(act, default_format=default_format)
if not iso_exp and not iso_act:
return True, None
if not iso_exp or not iso_act:
return False, "date_mismatch"
if iso_exp == iso_act:
return True, None
# Check for DD/MM vs MM/DD locale swap
y_exp, m_exp, d_exp = [int(x) for x in iso_exp.split("-")]
y_act, m_act, d_act = [int(x) for x in iso_act.split("-")]
if y_exp == y_act and m_exp == d_act and d_exp == m_act:
return False, "date_locale_swap"
return False, "date_mismatch"
# =============================================================================
# 3. Currency Amounts
# =============================================================================
def normalize_amount(val: Any) -> Optional[Decimal]:
"""
Converts amount strings or numbers to Decimal, stripping currency symbols,
commas, and whitespace.
"""
if val is None:
return None
if isinstance(val, Decimal):
return val
s = str(val).strip()
if not s:
return None
# Remove currency symbols (INR, Rs, $, etc.) and commas
cleaned = re.sub(r"[₹\$\€\£]|(?i:inr|rs\.?)\s*", "", s).replace(",", "").strip()
try:
return Decimal(cleaned)
except (InvalidOperation, ValueError):
return None
def match_amount(
exp: Any,
act: Any,
rel_tol: Decimal = Decimal("0.001"),
abs_tol: Decimal = Decimal("1.00")
) -> Tuple[bool, Optional[str]]:
"""
Compares amounts within configurable relative and absolute tolerance.
Tolerance condition: |act - exp| <= max(abs_tol, rel_tol * |exp|)
"""
d_exp = normalize_amount(exp)
d_act = normalize_amount(act)
if d_exp is None and d_act is None:
return True, None
if d_exp is None or d_act is None:
return False, "amount_mismatch"
diff = abs(d_act - d_exp)
allowed_tolerance = max(abs_tol, rel_tol * abs(d_exp))
if diff <= allowed_tolerance:
return True, None
return False, "amount_mismatch"
# =============================================================================
# 4. Vendor & Party Names
# =============================================================================
LEGAL_SUFFIX_MAP = {
"private limited": "pvt ltd",
"private ltd": "pvt ltd",
"pvt. ltd.": "pvt ltd",
"pvt ltd.": "pvt ltd",
"pvt. ltd": "pvt ltd",
"private": "pvt",
"pvt.": "pvt",
"limited": "ltd",
"ltd.": "ltd",
"corporation": "corp",
"corp.": "corp",
"incorporated": "inc",
"inc.": "inc",
"llp.": "llp"
}
def normalize_vendor_name(val: Any) -> str:
"""
Normalizes company/vendor names:
- Casefold (lowercase)
- Replaces punctuation with space
- Standardizes legal suffixes (Pvt Ltd, Corp, Inc, LLP)
- Collapses whitespace
"""
if val is None:
return ""
s = str(val).lower().strip()
# Replace punctuation with spaces
s = re.sub(r"[^\w\s]", " ", s)
s = " ".join(s.split())
# Map full legal suffix phrases first
for long_suffix, short_suffix in LEGAL_SUFFIX_MAP.items():
pattern = r"\b" + re.escape(long_suffix) + r"\b"
s = re.sub(pattern, short_suffix, s)
return " ".join(s.split())
def _token_set_ratio(s1: str, s2: str) -> float:
"""Computes Dice similarity over token sets."""
t1 = set(s1.split())
t2 = set(s2.split())
if not t1 and not t2:
return 1.0
if not t1 or not t2:
return 0.0
intersection = len(t1 & t2)
return (2.0 * intersection) / (len(t1) + len(t2))
def match_vendor_name(
exp: Any,
act: Any,
fuzzy_threshold: float = 0.85
) -> Tuple[bool, bool, float]:
"""
Returns:
(exact_match, fuzzy_match, similarity_score)
"""
n1 = normalize_vendor_name(exp)
n2 = normalize_vendor_name(act)
if not n1 and not n2:
return True, True, 1.0
if not n1 or not n2:
return False, False, 0.0
if n1 == n2:
return True, True, 1.0
# If concatenated words match exactly (e.g. health care vs healthcare)
compact_1 = n1.replace(" ", "")
compact_2 = n2.replace(" ", "")
if compact_1 == compact_2:
return False, True, 0.98
# Token set ratio: common tokens vs remaining tokens
t1 = set(n1.split())
t2 = set(n2.split())
intersection = t1 & t2
diff1 = t1 - intersection
diff2 = t2 - intersection
# Calculate token dice score
token_dice = (2.0 * len(intersection)) / (len(t1) + len(t2))
# Also compute sequence matcher similarity on sorted tokens
sorted_s1 = " ".join(sorted(t1))
sorted_s2 = " ".join(sorted(t2))
from difflib import SequenceMatcher
char_sim = SequenceMatcher(None, sorted_s1, sorted_s2).ratio()
score = max(token_dice, char_sim)
fuzzy_match = score >= fuzzy_threshold
return False, fuzzy_match, round(score, 3)
# =============================================================================
# 5. GSTIN Checksum Validation
# =============================================================================
GSTIN_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
GSTIN_REGEX = re.compile(r"^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$")
def validate_gstin_checksum(gstin: str) -> bool:
"""
Validates Indian GSTIN 15-character format and check digit using the
official Base-36 Luhn-variant checksum algorithm.
"""
if not gstin or not isinstance(gstin, str):
return False
clean_gstin = gstin.strip().upper()
if not GSTIN_REGEX.match(clean_gstin):
return False
# Multipliers for characters 0 through 13 (alternating 1, 2, ...)
multipliers = [1, 2] * 7
total_sum = 0
for i in range(14):
char = clean_gstin[i]
code_point = GSTIN_CHARS.index(char)
product = code_point * multipliers[i]
# Sum quotient and remainder in base 36
quotient = product // 36
remainder = product % 36
total_sum += quotient + remainder
expected_remainder = total_sum % 36
check_code_point = (36 - expected_remainder) % 36
expected_check_char = GSTIN_CHARS[check_code_point]
return clean_gstin[14] == expected_check_char
def match_gstin(exp: Any, act: Any) -> Tuple[bool, bool, Optional[str]]:
"""
Validates and matches GSTIN.
Returns:
(is_match: bool, is_valid_checksum: bool, error_subtype: Optional[str])
"""
s_exp = str(exp).strip().upper() if exp else ""
s_act = str(act).strip().upper() if act else ""
if not s_exp and not s_act:
return True, True, None
if not s_exp or not s_act:
return False, False, "gstin_mismatch"
is_valid = validate_gstin_checksum(s_act)
if s_exp == s_act:
return True, is_valid, None
return False, is_valid, "gstin_mismatch"
+107
View File
@@ -0,0 +1,107 @@
# app/rrsi/orchestrator.py
"""
RRSI Unified Orchestrator.
Main entry point coordinating:
- Proposal validation (Negative Knowledge & Area Stagnation)
- Selection & Leakage Screening
- Statistical & Cost-Aware Evaluation
- Fine-grained Error Taxonomy Tracking
- Ledger Persistence & Pruning Suggestions
"""
from typing import Dict, Any, List, Optional, Tuple
from pathlib import Path
from app.rrsi.taxonomy import (
ProposalHypothesis,
PipelineArea,
EvaluationMetrics,
DecisionRecord,
ExperimentStatus
)
from app.rrsi.memory import NegativeKnowledgeRegistry
from app.rrsi.screening import LeakageScreening, PruningAnalyzer
from app.rrsi.evaluator import StatisticalEvaluator
from app.rrsi.ledger import ExperimentLedger
class RRSIOrchestrator:
"""
Coordinates the Reflective Recursive Self-Improvement (RRSI) lifecycle.
"""
def __init__(
self,
memory_path: Optional[Path] = None,
ledger_path: Optional[Path] = None,
stagnation_threshold: int = 3,
cost_lambda: float = 0.05,
tolerance: float = 1.0
):
self.memory = NegativeKnowledgeRegistry(storage_path=memory_path, stagnation_threshold=stagnation_threshold)
self.ledger = ExperimentLedger(ledger_path=ledger_path)
self.evaluator = StatisticalEvaluator(cost_lambda=cost_lambda, tolerance=tolerance)
def submit_proposal(self, hypothesis: ProposalHypothesis) -> Tuple[bool, List[str], Optional[PipelineArea]]:
"""
Step 1 (Proposal Side):
Evaluates the hypothesis against negative memory to ensure:
- It does not repeat previously proven ineffective ideas.
- It is not stuck micro-tweaking a stagnant component.
"""
is_viable, warnings, rec_area = self.memory.check_proposal_viability(hypothesis)
return is_viable, warnings, rec_area
def screen_code_changes(self, code_diff: str) -> Tuple[bool, List[str]]:
"""
Step 2 (Selection Side - Pre-Flight):
Audits candidate code for hardcoded tokens, vendor memorization, or static coordinates.
"""
return LeakageScreening.audit_code_changes(code_diff)
def evaluate_and_decide(
self,
hypothesis: ProposalHypothesis,
baseline_dev: EvaluationMetrics,
candidate_dev: EvaluationMetrics,
baseline_selection: Optional[EvaluationMetrics] = None,
candidate_selection: Optional[EvaluationMetrics] = None,
template_groups: Optional[Dict[str, str]] = None,
git_base_ref: Optional[str] = None
) -> DecisionRecord:
"""
Step 3 & 4 (Selection Side - Statistical & Cost-Aware Decision):
Compares baseline vs candidate, applies paired bootstrap CI, cost utility,
and logs error taxonomy deltas.
"""
decision = self.evaluator.decide_acceptance(
hypothesis=hypothesis,
baseline_dev=baseline_dev,
candidate_dev=candidate_dev,
baseline_selection=baseline_selection,
candidate_selection=candidate_selection,
template_groups=template_groups,
git_base_ref=git_base_ref
)
# Record in memory and persistent ledger
self.memory.record_decision(hypothesis, decision)
self.ledger.append(decision)
return decision
def get_stagnation_report(self) -> Dict[str, Any]:
"""Provides a breakdown of consecutive failures per pipeline area to guide exploration."""
report = {}
for area in PipelineArea:
failures = self.memory.get_consecutive_failures_in_area(area)
report[area.value] = {
"consecutive_failures": failures,
"is_stagnant": failures >= self.memory.stagnation_threshold,
"recommendation": "Shift to alternative area" if failures >= self.memory.stagnation_threshold else "Active"
}
return report
def format_decision_report(self, decision: DecisionRecord) -> str:
"""Generates auditable Markdown summary of the decision."""
return self.ledger.generate_markdown_summary(decision)
+157
View File
@@ -0,0 +1,157 @@
# app/rrsi/screening.py
"""
Selection-Side Verification: Leakage Screening & Pruning Analyzer.
1. Leakage Screening: Audits proposed code changes to detect test-data memorization,
hardcoded coordinates, specific vendor strings, or fragile heuristics.
2. Pruning Analyzer: Identifies dead, redundant, or superseded heuristics in the OCR pipeline.
"""
import re
import json
import hashlib
from pathlib import Path
from typing import Dict, Any, List, Tuple
class LeakageScreening:
"""
Prevents data leakage and overfitting. Ensures changes generalize to unseen invoices
rather than memorizing the test dataset.
"""
# Known sample-specific test tokens (invoice numbers / synthetic tokens)
SUSPICIOUS_SAMPLE_TOKENS = {
"wmp/b/04531", "bms/26-27/196", "cc-1415", "170588", "c/3930"
}
GSTIN_REGEX = re.compile(r"\b\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]\b")
PHONE_REGEX = re.compile(r"\b(?:\+91[\-\s]?)?[6-9]\d{9}\b|\b0\d{2,4}[\-\s]?\d{6,8}\b")
SYNTHETIC_WHITELIST = {
"27AAPFU0939F1ZV", "27AAPFU0939F1ZW", "AAPFU0939F", "020-00000000", "9999999999"
}
# Patterns indicating coordinate hardcoding (e.g. ymin == 145, box[1] > 840)
HARDCODED_COORDINATE_PATTERNS = [
r"\b(?:box|bbox|ymin|ymax|xmin|xmax)\s*(?:==|>=|<=|>|<)\s*\d{3,4}\b",
r"\[\s*\d{3,4}\s*,\s*\d{3,4}\s*,\s*\d{3,4}\s*,\s*\d{3,4}\s*\]",
r"\b(?:crop|slice)\s*\[\s*\d{3,4}\s*:\s*\d{3,4}\s*\]"
]
@classmethod
def _load_forbidden_hashes(cls) -> Tuple[str, set]:
cfg_path = Path("config/forbidden_hashes.json")
if cfg_path.exists():
try:
with open(cfg_path, "r", encoding="utf-8") as f:
data = json.load(f)
return data.get("salt", ""), set(data.get("hashes", []))
except Exception:
pass
return "", set()
@classmethod
def audit_code_changes(cls, code_or_diff: str) -> Tuple[bool, List[str]]:
"""
Scans code diff or candidate implementation for leakage and memorization.
Returns:
(passed: bool, findings: List[str])
"""
findings = []
lower_code = code_or_diff.lower()
# 1. Check for specific test tokens / sample memorization
for token in cls.SUSPICIOUS_SAMPLE_TOKENS:
if re.search(r"['\"]" + re.escape(token) + r"['\"]", lower_code):
findings.append(
f"DATA LEAKAGE DETECTED: Code contains hardcoded test token '{token}'. "
f"Production heuristics must be generalized, not tailored to specific sample entities."
)
# 1b. Check for literal GSTINs and Indian phone numbers in code
for match in cls.GSTIN_REGEX.findall(code_or_diff):
if match not in cls.SYNTHETIC_WHITELIST:
findings.append(
f"DATA LEAKAGE DETECTED: Code contains hardcoded GSTIN '{match}'."
)
for match in cls.PHONE_REGEX.findall(code_or_diff):
if match not in cls.SYNTHETIC_WHITELIST:
findings.append(
f"DATA LEAKAGE DETECTED: Code contains hardcoded phone number '{match}'."
)
# 1c. Check for salted forbidden entity names
salt, forbidden_hashes = cls._load_forbidden_hashes()
if salt and forbidden_hashes:
tokens = [t.lower().strip(" \t\r\n'\",;:.()[]{}") for t in code_or_diff.split() if len(t.strip()) >= 4]
for token in tokens:
thash = hashlib.sha256((salt + token).encode("utf-8")).hexdigest()
if thash in forbidden_hashes:
findings.append("DATA LEAKAGE DETECTED: Code contains sensitive entity name matching forbidden hash.")
break
# 2. Check for absolute coordinate hardcoding
for pattern in cls.HARDCODED_COORDINATE_PATTERNS:
matches = re.findall(pattern, code_or_diff)
if matches:
findings.append(
f"COORDINATE OVERFITTING WARNING: Found hardcoded pixel coordinates: {matches[:3]}. "
f"Heuristics must use relative ratios (0.0 to 1.0) or dynamic spatial clustering."
)
passed = len(findings) == 0
return passed, findings
@classmethod
def audit_split_generalization(
cls,
calibration_delta: float,
holdout_delta: float,
min_holdout_retention: float = 0.5
) -> Tuple[bool, str]:
"""
Validates that performance gains on the calibration/training set generalize to the holdout set.
Rejects candidates that overfit to calibration data while regressing or stagnating on holdout data.
"""
if holdout_delta < 0.0:
return False, f"GENERALIZATION FAILURE: Candidate regressed on holdout set by {holdout_delta:.2f}% despite gain on calibration set ({calibration_delta:.2f}%)."
if calibration_delta > 2.0 and holdout_delta < (calibration_delta * min_holdout_retention):
return False, (
f"LEAKAGE/OVERFITTING DETECTED: Disproportionate calibration gain (+{calibration_delta:.2f}%) "
f"vs holdout retention (+{holdout_delta:.2f}%). Fails the {min_holdout_retention*100:.0f}% generalization retention threshold."
)
return True, "Split generalization verified."
class PruningAnalyzer:
"""
Identifies redundant, dead, or superseded heuristics in the OCR pipeline.
Recommends removal of clutter to keep pipeline lean, maintainable, and fast.
"""
@staticmethod
def analyze_regex_redundancy(patterns: List[str]) -> List[str]:
"""Detects whether any regex pattern is completely shadowed or duplicated by another."""
recommendations = []
cleaned = [p.strip() for p in patterns if p.strip()]
for i, p1 in enumerate(cleaned):
for j, p2 in enumerate(cleaned):
if i != j and p1 == p2:
recommendations.append(f"PRUNING OPPORTUNITY: Exact duplicate regex pattern '{p1}' found at index {i} and {j}.")
elif i != j and len(p1) < len(p2) and p1 in p2 and p1.startswith(r".*") and p1.endswith(r".*"):
recommendations.append(f"PRUNING OPPORTUNITY: Pattern '{p2}' may be shadowed by broader pattern '{p1}'.")
return list(set(recommendations))
@staticmethod
def audit_keyword_list(keywords: set, sample_occurrences: Dict[str, int]) -> List[str]:
"""Identifies keywords that never activate across any real-world invoice samples."""
recommendations = []
for kw in sorted(keywords):
count = sample_occurrences.get(kw.lower(), 0)
if count == 0:
recommendations.append(f"PRUNING CANDIDATE: Keyword '{kw}' has 0 activations across dataset. Consider deprecating or archiving.")
return recommendations
+237
View File
@@ -0,0 +1,237 @@
# app/rrsi/stats.py
"""
Statistical Utilities for RRSI Evaluation & Selection Gate.
1. Wilson Score Intervals for single proportions (never Wald).
2. Paired Cluster Bootstrap over invoice template groups (10,000 resamples).
3. McNemar Test for paired binary field outcomes.
"""
import math
from typing import Dict, Any, List, Tuple, Union, Optional
import numpy as np
from scipy import stats
def wilson_interval(successes: int, total: int, confidence: float = 0.95) -> Tuple[float, float]:
"""
Computes the Wilson score interval for a binomial proportion.
Never uses Wald (p +/- z*sqrt(p(1-p)/n)), which breaks down near 0/1 and on small sample sizes.
Returns:
(ci_lower, ci_upper) as float in [0.0, 1.0].
"""
if total <= 0:
return 0.0, 0.0
p = successes / total
# Two-sided normal quantile
alpha = 1.0 - confidence
z = stats.norm.ppf(1.0 - alpha / 2.0)
denominator = 1.0 + (z**2) / total
center_adjusted = (p + (z**2) / (2.0 * total)) / denominator
margin = (z / denominator) * math.sqrt((p * (1.0 - p) / total) + (z**2) / (4.0 * (total**2)))
if successes == 0:
ci_lower = 0.0
else:
ci_lower = max(0.0, float(center_adjusted - margin))
if successes == total:
ci_upper = 1.0
else:
ci_upper = min(1.0, float(center_adjusted + margin))
return float(ci_lower), float(ci_upper)
def paired_cluster_bootstrap(
base_per_doc: Union[Dict[str, float], List[float]],
cand_per_doc: Union[Dict[str, float], List[float]],
groups: Union[Dict[str, str], List[str]],
n_resamples: int = 10000,
confidence: float = 0.95,
seed: int = 42
) -> Dict[str, Any]:
"""
Performs a paired cluster bootstrap across document template groups.
Resamples clusters (template groups) with replacement to account for intra-template correlation.
Args:
base_per_doc: Mapping or list of doc_id -> metric score for baseline.
cand_per_doc: Mapping or list of doc_id -> metric score for candidate.
groups: Mapping or list of doc_id -> template group id.
n_resamples: Number of bootstrap iterations (default 10000).
confidence: Confidence level (default 0.95).
seed: Random seed for reproducibility.
Returns:
dict with:
mean_delta: Mean candidate - baseline delta.
ci_lower: Lower bound of bootstrap percentile CI.
ci_upper: Upper bound of bootstrap percentile CI.
std_err: Standard error of the bootstrap deltas.
p_value: Empirical two-sided p-value.
n_clusters: Number of distinct template groups.
n_docs: Number of documents evaluated.
"""
rng = np.random.default_rng(seed)
# Standardize to list of tuples: (doc_id, base_score, cand_score, group_id)
if isinstance(base_per_doc, dict) and isinstance(cand_per_doc, dict):
common_ids = [d for d in base_per_doc if d in cand_per_doc]
if not common_ids:
return {
"mean_delta": 0.0, "ci_lower": 0.0, "ci_upper": 0.0,
"std_err": 0.0, "p_value": 1.0, "n_clusters": 0, "n_docs": 0
}
group_mapping = groups if isinstance(groups, dict) else {d: str(i) for i, d in enumerate(common_ids)}
doc_records = [
(d, float(base_per_doc[d]), float(cand_per_doc[d]), str(group_mapping.get(d, "default_grp")))
for d in common_ids
]
else:
base_list = list(base_per_doc)
cand_list = list(cand_per_doc)
n = min(len(base_list), len(cand_list))
grp_list = list(groups) if groups is not None else [f"grp_{i}" for i in range(n)]
doc_records = [
(str(i), float(base_list[i]), float(cand_list[i]), str(grp_list[i]))
for i in range(n)
]
n_docs = len(doc_records)
if n_docs == 0:
return {
"mean_delta": 0.0, "ci_lower": 0.0, "ci_upper": 0.0,
"std_err": 0.0, "p_value": 1.0, "n_clusters": 0, "n_docs": 0
}
# Group documents by cluster
clusters: Dict[str, List[Tuple[float, float]]] = {}
for _, b_score, c_score, grp in doc_records:
clusters.setdefault(grp, []).append((b_score, c_score))
cluster_keys = list(clusters.keys())
n_clusters = len(cluster_keys)
# Calculate actual observed mean delta
all_b = np.array([r[1] for r in doc_records])
all_c = np.array([r[2] for r in doc_records])
mean_delta = float(np.mean(all_c) - np.mean(all_b))
# Fast path: if candidate and baseline are strictly identical across all documents
if np.allclose(all_b, all_c):
return {
"mean_delta": 0.0,
"ci_lower": 0.0,
"ci_upper": 0.0,
"std_err": 0.0,
"p_value": 1.0,
"n_clusters": n_clusters,
"n_docs": n_docs
}
# Convert clusters into arrays of base & cand sums and sizes
cluster_b_sums = np.array([sum(x[0] for x in clusters[k]) for k in cluster_keys])
cluster_c_sums = np.array([sum(x[1] for x in clusters[k]) for k in cluster_keys])
cluster_sizes = np.array([len(clusters[k]) for k in cluster_keys])
# Sample cluster indices with replacement (n_resamples x n_clusters)
sampled_indices = rng.integers(0, n_clusters, size=(n_resamples, n_clusters))
sample_b_totals = np.take(cluster_b_sums, sampled_indices).sum(axis=1)
sample_c_totals = np.take(cluster_c_sums, sampled_indices).sum(axis=1)
sample_doc_counts = np.take(cluster_sizes, sampled_indices).sum(axis=1)
# Avoid division by zero
valid_mask = sample_doc_counts > 0
bootstrap_deltas = np.zeros(n_resamples, dtype=float)
bootstrap_deltas[valid_mask] = (
(sample_c_totals[valid_mask] - sample_b_totals[valid_mask]) / sample_doc_counts[valid_mask]
)
alpha = 1.0 - confidence
lower_pct = 100.0 * (alpha / 2.0)
upper_pct = 100.0 * (1.0 - alpha / 2.0)
ci_lower = float(np.percentile(bootstrap_deltas, lower_pct))
ci_upper = float(np.percentile(bootstrap_deltas, upper_pct))
std_err = float(np.std(bootstrap_deltas))
# Empirical two-sided p-value
p_leq_0 = np.mean(bootstrap_deltas <= 0.0)
p_geq_0 = np.mean(bootstrap_deltas >= 0.0)
p_value = float(min(1.0, 2.0 * min(p_leq_0, p_geq_0)))
return {
"mean_delta": mean_delta,
"ci_lower": ci_lower,
"ci_upper": ci_upper,
"std_err": std_err,
"p_value": p_value,
"n_clusters": n_clusters,
"n_docs": n_docs
}
def mcnemar_test(
base_outcomes: List[bool],
cand_outcomes: List[bool]
) -> Dict[str, Any]:
"""
Computes McNemar's test for paired nominal / binary outcomes (e.g. per-field exact match).
Uses continuity-corrected chi-square and exact binomial test.
Args:
base_outcomes: List of bool correctness flags for baseline.
cand_outcomes: List of bool correctness flags for candidate.
Returns:
dict with:
b: Baseline correct, candidate incorrect (discordant).
c: Baseline incorrect, candidate correct (discordant).
n_discordant: b + c.
statistic: Continuity-corrected chi-square statistic.
p_value: Two-sided p-value from exact binomial test.
"""
n = min(len(base_outcomes), len(cand_outcomes))
b = 0 # base=1, cand=0
c = 0 # base=0, cand=1
a = 0 # base=1, cand=1
d = 0 # base=0, cand=0
for i in range(n):
b_val = bool(base_outcomes[i])
c_val = bool(cand_outcomes[i])
if b_val and not c_val:
b += 1
elif not b_val and c_val:
c += 1
elif b_val and c_val:
a += 1
else:
d += 1
n_discordant = b + c
if n_discordant == 0:
return {
"a": a, "b": b, "c": c, "d": d,
"n_discordant": 0,
"statistic": 0.0,
"p_value": 1.0
}
# Continuity-corrected chi-square: (|b - c| - 1)^2 / (b + c)
stat = ((abs(b - c) - 1.0) ** 2) / float(n_discordant) if abs(b - c) >= 1 else 0.0
# Exact two-sided binomial test on discordant pairs under H0: p = 0.5
binom_res = stats.binomtest(k=b, n=n_discordant, p=0.5, alternative="two-sided")
p_val = float(binom_res.pvalue)
return {
"a": a, "b": b, "c": c, "d": d,
"n_discordant": n_discordant,
"statistic": float(stat),
"p_value": p_val
}
+366
View File
@@ -0,0 +1,366 @@
# app/rrsi/table_metrics.py
"""
Table & Line-Item Extraction Evaluation Engine.
1. Optimal 1-to-1 bipartite matching using scipy.optimize.linear_sum_assignment.
2. Row-level Precision, Recall, and F1.
3. Cell-level Precision, Recall, and F1 across (description, hsn, qty, unit, rate, amount, tax).
4. Structural error classification: row_merge, row_split, column_shift, missing_row, extra_row.
5. Strict guard preventing None == None from being treated as true matches.
"""
from decimal import Decimal
from enum import Enum
from typing import Dict, Any, List, Optional, Tuple, Set
from dataclasses import dataclass, field
import numpy as np
from scipy.optimize import linear_sum_assignment
from app.rrsi.normalize import (
normalize_vendor_name,
match_amount,
normalize_amount
)
class TableStructureError(str, Enum):
ROW_MERGE = "table_row_merge"
ROW_SPLIT = "table_row_split"
COLUMN_SHIFT = "table_column_shift"
MISSING_ROW = "table_missing_row"
EXTRA_ROW = "table_extra_row"
@dataclass
class TableStructureAnomaly:
error_type: TableStructureError
message: str
exp_idx: Optional[int] = None
pred_idx: Optional[int] = None
details: Dict[str, Any] = field(default_factory=dict)
@dataclass
class TableEvaluationResult:
row_precision: float
row_recall: float
row_f1: float
cell_precision: float
cell_recall: float
cell_f1: float
matched_row_count: int
total_expected_rows: int
total_predicted_rows: int
total_expected_cells: int
correct_cells: int
total_predicted_cells: int
structure_errors: List[TableStructureAnomaly] = field(default_factory=list)
CELL_FIELDS = [
("description", ["description", "item_name", "item_description", "name"]),
("hsn", ["hsn_sac", "hsn", "sac"]),
("qty", ["quantity", "qty"]),
("unit", ["unit", "Pack", "pack", "uom"]),
("rate", ["unit_price", "rate", "price"]),
("amount", ["total_price", "amount", "item_amount"]),
("tax", ["Gst%", "gst_rate", "tax_rate", "GST_AMT", "cgst_amount", "sgst_amount"])
]
def _extract_cell_value(row: Dict[str, Any], canonical_key: str) -> Optional[Any]:
"""Retrieves cell value using canonical aliases."""
for key, aliases in CELL_FIELDS:
if key == canonical_key:
for alias in aliases:
val = row.get(alias)
if val is not None and str(val).strip() != "":
return val
return None
return None
def _compute_row_similarity(exp: Dict[str, Any], pred: Dict[str, Any]) -> float:
"""Computes a normalized similarity [0.0, 1.0] between an expected and predicted row."""
score = 0.0
weights_total = 0.0
# 1. Description (weight: 0.35)
exp_desc = _extract_cell_value(exp, "description")
pred_desc = _extract_cell_value(pred, "description")
if exp_desc and pred_desc:
weights_total += 0.35
n1 = normalize_vendor_name(exp_desc)
n2 = normalize_vendor_name(pred_desc)
t1, t2 = set(n1.split()), set(n2.split())
if t1 and t2:
sim = 2.0 * len(t1 & t2) / (len(t1) + len(t2))
score += 0.35 * sim
# 2. HSN (weight: 0.15)
exp_hsn = _extract_cell_value(exp, "hsn")
pred_hsn = _extract_cell_value(pred, "hsn")
if exp_hsn and pred_hsn:
weights_total += 0.15
if str(exp_hsn).strip().replace(" ", "") == str(pred_hsn).strip().replace(" ", ""):
score += 0.15
# 3. Quantity (weight: 0.15)
exp_qty = _extract_cell_value(exp, "qty")
pred_qty = _extract_cell_value(pred, "qty")
if exp_qty is not None and pred_qty is not None:
weights_total += 0.15
q1, q2 = normalize_amount(exp_qty), normalize_amount(pred_qty)
if q1 is not None and q2 is not None and abs(q1 - q2) <= Decimal("0.05"):
score += 0.15
# 4. Rate (weight: 0.15)
exp_rate = _extract_cell_value(exp, "rate")
pred_rate = _extract_cell_value(pred, "rate")
if exp_rate is not None and pred_rate is not None:
weights_total += 0.15
matched, _ = match_amount(exp_rate, pred_rate, rel_tol=Decimal("0.01"), abs_tol=Decimal("1.00"))
if matched:
score += 0.15
# 5. Amount (weight: 0.20)
exp_amt = _extract_cell_value(exp, "amount")
pred_amt = _extract_cell_value(pred, "amount")
if exp_amt is not None and pred_amt is not None:
weights_total += 0.20
matched, _ = match_amount(exp_amt, pred_amt, rel_tol=Decimal("0.01"), abs_tol=Decimal("1.00"))
if matched:
score += 0.20
if weights_total == 0.0:
return 0.0
# Normalize score by present attributes
return float(score / weights_total)
def _check_cell_match(canonical_key: str, exp_val: Any, pred_val: Any) -> bool:
"""Checks whether two cells match, strictly guarding None == None."""
if exp_val is None or pred_val is None:
return False
s_exp = str(exp_val).strip()
s_pred = str(pred_val).strip()
if not s_exp or not s_pred:
return False
if canonical_key in ("qty", "rate", "amount", "tax"):
matched, _ = match_amount(s_exp, s_pred, rel_tol=Decimal("0.01"), abs_tol=Decimal("1.00"))
return matched
if canonical_key == "description":
n1 = normalize_vendor_name(s_exp)
n2 = normalize_vendor_name(s_pred)
t1, t2 = set(n1.split()), set(n2.split())
return (2.0 * len(t1 & t2) / (len(t1) + len(t2))) >= 0.70 if (t1 and t2) else False
# HSN / Unit
return s_exp.lower().replace(" ", "") == s_pred.lower().replace(" ", "")
def evaluate_table(
expected_rows: List[Dict[str, Any]],
predicted_rows: List[Dict[str, Any]],
similarity_threshold: float = 0.40
) -> TableEvaluationResult:
"""
Evaluates extracted line-items against ground-truth items using optimal 1-to-1 matching.
"""
m = len(expected_rows)
n = len(predicted_rows)
structure_errors: List[TableStructureAnomaly] = []
if m == 0 and n == 0:
return TableEvaluationResult(
row_precision=1.0, row_recall=1.0, row_f1=1.0,
cell_precision=1.0, cell_recall=1.0, cell_f1=1.0,
matched_row_count=0, total_expected_rows=0, total_predicted_rows=0,
total_expected_cells=0, correct_cells=0, total_predicted_cells=0
)
if m == 0 and n > 0:
for j in range(n):
structure_errors.append(TableStructureAnomaly(
error_type=TableStructureError.EXTRA_ROW,
message=f"Extra predicted row {j} when ground truth is empty",
pred_idx=j
))
return TableEvaluationResult(
row_precision=0.0, row_recall=1.0, row_f1=0.0,
cell_precision=0.0, cell_recall=1.0, cell_f1=0.0,
matched_row_count=0, total_expected_rows=0, total_predicted_rows=n,
total_expected_cells=0, correct_cells=0, total_predicted_cells=n * len(CELL_FIELDS),
structure_errors=structure_errors
)
if m > 0 and n == 0:
for i in range(m):
structure_errors.append(TableStructureAnomaly(
error_type=TableStructureError.MISSING_ROW,
message=f"Missing expected row {i}",
exp_idx=i
))
return TableEvaluationResult(
row_precision=1.0, row_recall=0.0, row_f1=0.0,
cell_precision=1.0, cell_recall=0.0, cell_f1=0.0,
matched_row_count=0, total_expected_rows=m, total_predicted_rows=0,
total_expected_cells=m * len(CELL_FIELDS), correct_cells=0, total_predicted_cells=0,
structure_errors=structure_errors
)
# Cost matrix for bipartite matching: cost = 1.0 - similarity
cost_matrix = np.zeros((m, n), dtype=float)
sim_matrix = np.zeros((m, n), dtype=float)
for i in range(m):
for j in range(n):
sim = _compute_row_similarity(expected_rows[i], predicted_rows[j])
sim_matrix[i, j] = sim
cost_matrix[i, j] = 1.0 - sim
row_ind, col_ind = linear_sum_assignment(cost_matrix)
matched_pairs: List[Tuple[int, int]] = []
matched_exp_indices: Set[int] = set()
matched_pred_indices: Set[int] = set()
for r, c in zip(row_ind, col_ind):
if sim_matrix[r, c] >= similarity_threshold:
matched_pairs.append((r, c))
matched_exp_indices.add(r)
matched_pred_indices.add(c)
# Detect unassigned rows
unassigned_exp = set(range(m)) - matched_exp_indices
unassigned_pred = set(range(n)) - matched_pred_indices
# Check for row merge: multiple expected items combined into one predicted item
# e.g. sum of quantities or amounts of two unassigned expected rows matches a predicted row
for p_idx in range(n):
pred_qty = normalize_amount(_extract_cell_value(predicted_rows[p_idx], "qty"))
pred_amt = normalize_amount(_extract_cell_value(predicted_rows[p_idx], "amount"))
if pred_qty and len(unassigned_exp) >= 2:
# Check combinations of two expected rows
exp_list = list(unassigned_exp)
for i1 in range(len(exp_list)):
for i2 in range(i1 + 1, len(exp_list)):
e1_qty = normalize_amount(_extract_cell_value(expected_rows[exp_list[i1]], "qty")) or Decimal("0")
e2_qty = normalize_amount(_extract_cell_value(expected_rows[exp_list[i2]], "qty")) or Decimal("0")
if abs((e1_qty + e2_qty) - pred_qty) <= Decimal("0.05") and (e1_qty > 0 and e2_qty > 0):
structure_errors.append(TableStructureAnomaly(
error_type=TableStructureError.ROW_MERGE,
message=f"Rows {exp_list[i1]} and {exp_list[i2]} merged into predicted row {p_idx}",
pred_idx=p_idx,
details={"merged_exp_indices": [exp_list[i1], exp_list[i2]]}
))
# Check for row split: one expected item split across multiple predicted rows
for e_idx in range(m):
exp_qty = normalize_amount(_extract_cell_value(expected_rows[e_idx], "qty"))
exp_amt = normalize_amount(_extract_cell_value(expected_rows[e_idx], "amount"))
exp_desc = str(_extract_cell_value(expected_rows[e_idx], "description") or "").lower()
# Find predicted rows that share the same description
matching_preds = [
j for j in range(n)
if exp_desc and exp_desc[:8] in str(_extract_cell_value(predicted_rows[j], "description") or "").lower()
]
if len(matching_preds) >= 2:
sum_pred_qty = sum(
(normalize_amount(_extract_cell_value(predicted_rows[j], "qty")) or Decimal("0"))
for j in matching_preds
)
if exp_qty and abs(sum_pred_qty - exp_qty) <= Decimal("0.05"):
structure_errors.append(TableStructureAnomaly(
error_type=TableStructureError.ROW_SPLIT,
message=f"Expected row {e_idx} split into predicted rows {matching_preds}",
exp_idx=e_idx,
details={"split_pred_indices": matching_preds}
))
# Check for column shift: e.g. rate value found in HSN or amount column
for r, c in matched_pairs:
exp_r = expected_rows[r]
pred_c = predicted_rows[c]
exp_rate = _extract_cell_value(exp_r, "rate")
pred_hsn = _extract_cell_value(pred_c, "hsn")
if exp_rate and pred_hsn:
m_shift, _ = match_amount(exp_rate, pred_hsn, rel_tol=Decimal("0.01"), abs_tol=Decimal("0.05"))
if m_shift:
structure_errors.append(TableStructureAnomaly(
error_type=TableStructureError.COLUMN_SHIFT,
message=f"Column shift: Expected rate '{exp_rate}' found in HSN column in row {c}",
exp_idx=r,
pred_idx=c
))
# Missing & extra rows
for r in unassigned_exp:
structure_errors.append(TableStructureAnomaly(
error_type=TableStructureError.MISSING_ROW,
message=f"Expected row {r} not extracted",
exp_idx=r
))
for c in unassigned_pred:
structure_errors.append(TableStructureAnomaly(
error_type=TableStructureError.EXTRA_ROW,
message=f"Extra extracted row {c}",
pred_idx=c
))
# Row metrics
matched_row_count = len(matched_pairs)
row_p = float(matched_row_count / n) if n > 0 else 1.0
row_r = float(matched_row_count / m) if m > 0 else 1.0
row_f1 = float(2.0 * row_p * row_r / (row_p + row_r)) if (row_p + row_r) > 0 else 0.0
# Cell-level evaluation: strictly evaluate non-null expected cells
total_exp_cells = 0
correct_cells = 0
total_pred_cells = 0
# Count predicted cells present
for j in range(n):
for key, _ in CELL_FIELDS:
if _extract_cell_value(predicted_rows[j], key) is not None:
total_pred_cells += 1
# Count expected cells present
for i in range(m):
for key, _ in CELL_FIELDS:
if _extract_cell_value(expected_rows[i], key) is not None:
total_exp_cells += 1
# Count matched cells in assigned pairs
for r, c in matched_pairs:
exp_r = expected_rows[r]
pred_c = predicted_rows[c]
for key, _ in CELL_FIELDS:
e_val = _extract_cell_value(exp_r, key)
p_val = _extract_cell_value(pred_c, key)
if e_val is not None:
if _check_cell_match(key, e_val, p_val):
correct_cells += 1
cell_p = float(correct_cells / total_pred_cells) if total_pred_cells > 0 else (1.0 if total_exp_cells == 0 else 0.0)
cell_r = float(correct_cells / total_exp_cells) if total_exp_cells > 0 else 1.0
cell_f1 = float(2.0 * cell_p * cell_r / (cell_p + cell_r)) if (cell_p + cell_r) > 0 else 0.0
return TableEvaluationResult(
row_precision=round(row_p, 4),
row_recall=round(row_r, 4),
row_f1=round(row_f1, 4),
cell_precision=round(cell_p, 4),
cell_recall=round(cell_r, 4),
cell_f1=round(cell_f1, 4),
matched_row_count=matched_row_count,
total_expected_rows=m,
total_predicted_rows=n,
total_expected_cells=total_exp_cells,
correct_cells=correct_cells,
total_predicted_cells=total_pred_cells,
structure_errors=structure_errors
)
+287
View File
@@ -0,0 +1,287 @@
# app/rrsi/taxonomy.py
"""
RRSI Error Taxonomy and Data Structures.
1. Decoupled Extraction Error Classes (invoice_number_*, date_*, table_*, etc.) from Process Outcomes.
2. Non-double-counting FailureDetail with primary_class + secondary_tags.
3. FieldMetrics with Precision, Recall, F1, Accuracy, and Wilson Score Intervals.
4. Per-document outcome representation for paired statistical testing.
5. Selection Gate decision records and proposal hypotheses.
"""
from enum import Enum
from dataclasses import dataclass, field, asdict
from typing import Dict, Any, List, Optional, Tuple
import time
# =============================================================================
# 1. Extraction Error Classes (Pipeline Performance Taxonomy)
# =============================================================================
class ExtractionErrorClass(str, Enum):
"""Fine-grained error classes for OCR extraction discrepancies."""
# Invoice Number
INVOICE_NUMBER_MISSING = "invoice_number_missing"
INVOICE_NUMBER_MISMATCH = "invoice_number_mismatch"
# Dates
DATE_MISSING = "date_missing"
DATE_MISMATCH = "date_mismatch"
DATE_LOCALE_SWAP = "date_locale_swap"
# Table Structure & Cells
TABLE_ROW_MERGE = "table_row_merge"
TABLE_ROW_SPLIT = "table_row_split"
TABLE_COLUMN_SHIFT = "table_column_shift"
TABLE_MISSING_ROW = "table_missing_row"
TABLE_EXTRA_ROW = "table_extra_row"
TABLE_CELL_MISMATCH = "table_cell_mismatch"
# Currency & Amounts
AMOUNT_PARSE = "amount_parse"
CURRENCY_MISSING = "currency_missing"
# Parties & Legal Identifiers
GSTIN_INVALID = "gstin_invalid"
GSTIN_MISMATCH = "gstin_mismatch"
PARTY_SWAP = "party_swap"
PARTY_NAME_MISMATCH = "party_name_mismatch"
# OCR Engine & Arithmetic
OCR_NOISE = "ocr_noise"
TOTALS_ARITHMETIC = "totals_arithmetic"
TOTALS_ARITHMETIC_ROUNDOFF = "totals_arithmetic_roundoff"
DOCUMENT_INCONSISTENT = "document_inconsistent"
# System & Pipeline
HALLUCINATION = "hallucination"
PIPELINE_ERROR = "pipeline_error"
OTHER = "other"
# Backwards compatibility alias for existing code
ErrorCategory = ExtractionErrorClass
# =============================================================================
# 2. Process Outcomes (Selection Gate Decision Taxonomy - Never mixed with extraction)
# =============================================================================
class ProcessOutcome(str, Enum):
"""Decision outcomes produced by the selection gate."""
ACCEPTED = "accepted"
LEAKAGE = "leakage"
INSIGNIFICANT = "insignificant"
COST_REJECTED = "cost_rejected"
REGRESSION_DETECTED = "regression_detected"
GENERALIZATION_FAILURE = "generalization_failure"
NO_CHANGE = "no_change"
PRUNED = "pruned"
INSUFFICIENT_EVIDENCE = "insufficient_evidence"
class PipelineArea(str, Enum):
"""Subsystem areas of the Invoice OCR pipeline for targeted experimentation and area shifting."""
INPUT_PREPROCESSING = "input_preprocessing"
OCR_ENGINE = "ocr_engine"
ENTITY_EXTRACTION = "entity_extraction"
TABLE_EXTRACTION = "table_extraction"
ARITHMETIC_VERIFIER = "arithmetic_verifier"
DUAL_ENGINE_CONSENSUS = "dual_engine_consensus"
SCHEMA_MAPPING = "schema_mapping"
class ExperimentStatus(str, Enum):
"""Status of an RRSI proposal or experiment."""
PROPOSED = "proposed"
ACCEPTED = "accepted"
REJECTED = "rejected"
STALE = "stale"
PRUNED = "pruned"
# =============================================================================
# 3. Data Structures for Failures & Field Metrics
# =============================================================================
@dataclass
class FailureDetail:
"""
Individual failure record.
Enforces no double-counting: one primary_class, plus optional secondary_tags.
"""
primary_class: ExtractionErrorClass
field_name: str
expected: Any
actual: Any
file_id: str
severity: str = "medium" # "critical", "high", "medium", "low"
secondary_tags: List[str] = field(default_factory=list)
context_message: str = ""
@property
def category(self) -> ExtractionErrorClass:
"""Alias for backward compatibility."""
return self.primary_class
def to_dict(self) -> Dict[str, Any]:
return {
"primary_class": self.primary_class.value,
"category": self.primary_class.value,
"field_name": self.field_name,
"expected": str(self.expected),
"actual": str(self.actual),
"file_id": self.file_id,
"severity": self.severity,
"secondary_tags": self.secondary_tags,
"context_message": self.context_message
}
@dataclass
class FieldMetrics:
"""Detailed statistical metrics for a single extracted field."""
field_name: str
total_expected: int = 0
correct: int = 0
hallucinations: int = 0
precision: float = 1.0
recall: float = 1.0
f1: float = 1.0
accuracy: float = 1.0
wilson_ci: Tuple[float, float] = (0.0, 1.0)
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class DocumentEvaluationResult:
"""Per-document outcomes required for paired bootstrap and McNemar testing."""
doc_id: str
field_outcomes: Dict[str, bool] = field(default_factory=dict)
field_errors: Dict[str, Optional[str]] = field(default_factory=dict)
table_result: Optional[Any] = None
validator_result: Optional[Any] = None
arithmetic_status: str = "consistent"
is_end_to_end_correct: bool = True
failures: List[FailureDetail] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
return {
"doc_id": self.doc_id,
"field_outcomes": self.field_outcomes,
"field_errors": self.field_errors,
"arithmetic_status": self.arithmetic_status,
"is_end_to_end_correct": self.is_end_to_end_correct,
"failures": [f.to_dict() for f in self.failures]
}
@dataclass
class ProposalHypothesis:
"""Candidate change submitted to the RRSI proposal engine."""
proposal_id: str
area: PipelineArea
title: str
description: str
rationale: str
code_diff_summary: str = ""
tags: List[str] = field(default_factory=list)
provenance: str = "real" # "real" or "demo"
timestamp: float = field(default_factory=time.time)
def to_dict(self) -> Dict[str, Any]:
return {
"proposal_id": self.proposal_id,
"area": self.area.value,
"title": self.title,
"description": self.description,
"rationale": self.rationale,
"code_diff_summary": self.code_diff_summary,
"tags": self.tags,
"provenance": self.provenance,
"timestamp": self.timestamp
}
@dataclass
class EvaluationMetrics:
"""Quantitative performance metrics measured on test datasets."""
macro_accuracy: float = 0.0
macro_f1: float = 0.0
per_field_metrics: Dict[str, FieldMetrics] = field(default_factory=dict)
table_row_precision: float = 1.0
table_row_recall: float = 1.0
table_row_f1: float = 1.0
table_cell_precision: float = 1.0
table_cell_recall: float = 1.0
table_cell_f1: float = 1.0
end_to_end_accuracy: float = 0.0
arithmetic_consistency_pct: float = 0.0
document_inconsistent_pct: float = 0.0
total_failures: int = 0
failure_breakdown: Dict[str, int] = field(default_factory=dict)
runtime_median_seconds: float = 0.0
runtime_p95_seconds: float = 0.0
vision_fallback_calls: int = 0
sample_count: int = 0
doc_results: Dict[str, DocumentEvaluationResult] = field(default_factory=dict)
# Backward compatibility properties
@property
def overall_accuracy_pct(self) -> float:
return self.macro_accuracy
@property
def field_accuracy_pct(self) -> float:
return self.macro_accuracy
@property
def table_f1_score(self) -> float:
return self.table_cell_f1
@property
def math_consistency_pct(self) -> float:
return self.arithmetic_consistency_pct
@property
def runtime_seconds(self) -> float:
return self.runtime_median_seconds
def to_dict(self) -> Dict[str, Any]:
res = asdict(self)
res["overall_accuracy_pct"] = self.macro_accuracy
res["field_accuracy_pct"] = self.macro_accuracy
res["table_f1_score"] = self.table_cell_f1
res["math_consistency_pct"] = self.arithmetic_consistency_pct
res["runtime_seconds"] = self.runtime_median_seconds
return res
@dataclass
class DecisionRecord:
"""Final auditable decision record produced by the RRSI Selection Gate."""
proposal_id: str
area: str
status: ExperimentStatus
process_outcome: ProcessOutcome
baseline_accuracy: float
candidate_accuracy: float
delta_accuracy: float
paired_ci_lower: float
paired_ci_upper: float
is_statistically_significant: bool
leakage_screen_passed: bool
leakage_findings: List[str]
cost_aware_accepted: bool
latency_delta_seconds: float
vision_fallback_calls: int
case_regressions: List[str]
rejection_reasons: List[str]
pruning_recommendations: List[str]
failure_deltas: Dict[str, int]
provenance: str = "real"
git_commit_hash: str = ""
git_diff_hash: str = ""
timestamp: float = field(default_factory=time.time)
def to_dict(self) -> Dict[str, Any]:
return asdict(self)