baseline: non-sensitive scaffolding, hygiene hooks, synthetic test fixtures, and docs
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"metadata": {
|
||||
"annotator": "Synthetic Generator",
|
||||
"date": "2026-09-28",
|
||||
"source": "from_image_blind",
|
||||
"tier": "Tier_B"
|
||||
},
|
||||
"invoice_id": "INV-SYN-001",
|
||||
"invoice_number": "INV-SYN-001",
|
||||
"invoice_date": "2026-08-20",
|
||||
"due_date": "2026-09-20",
|
||||
"PO_number": "PO-SYN-999",
|
||||
"customer_name": "ACME HEALTHCARE PRIVATE LIMITED",
|
||||
"customer_gstin": "27AAPFU0939F1ZV",
|
||||
"seller_name": "SYNTHETIC PHARMA SUPPLIES LTD",
|
||||
"seller_gstin": "27AAPFU0939F1ZV",
|
||||
"currency_code": "INR",
|
||||
"invoice_amount": "1180.00",
|
||||
"total_gst_amount": "180.00",
|
||||
"round_off": "0.00",
|
||||
"items": [
|
||||
{
|
||||
"description": "SYNTHETIC MEDICINE 500MG",
|
||||
"hsn_sac": "30049099",
|
||||
"quantity": 10,
|
||||
"unit_price": "100.00",
|
||||
"total_price": "1000.00",
|
||||
"Discount": "0.00",
|
||||
"Gst%": 18
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
@@ -0,0 +1,138 @@
|
||||
# tests/test_deskew_corrector.py
|
||||
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw
|
||||
from app.preprocessing.deskew_corrector import (
|
||||
detect_skew_angle,
|
||||
deskew_image,
|
||||
process_folder_deskew,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base_ruled_invoice():
|
||||
"""
|
||||
Generates a clean synthetic invoice page with distinct horizontal table lines
|
||||
and grid dividers to provide reliable geometric baselines for Hough Line detection.
|
||||
"""
|
||||
img = Image.new("L", (1200, 1600), color=255)
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
# Prominent horizontal table borders and divider lines
|
||||
draw.line([80, 150, 1120, 150], fill=0, width=3)
|
||||
draw.line([80, 230, 1120, 230], fill=0, width=2)
|
||||
draw.line([80, 310, 1120, 310], fill=0, width=2)
|
||||
draw.line([80, 800, 1120, 800], fill=0, width=3)
|
||||
draw.line([80, 900, 1120, 900], fill=0, width=2)
|
||||
|
||||
# Line item rows
|
||||
for y in range(360, 780, 50):
|
||||
draw.line([80, y, 1120, y], fill=120, width=2)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
@pytest.mark.parametrize("applied_tilt", [1.5, -1.5, 3.0, -3.0])
|
||||
def test_meaningful_skew_angles_detected_and_corrected(tmp_path, base_ruled_invoice, applied_tilt):
|
||||
"""
|
||||
Tests that tilts of +1.5°, -1.5°, +3.0°, and -3.0° are detected
|
||||
and corrected back to horizontal (remaining tilt < 0.5°).
|
||||
"""
|
||||
src_file = tmp_path / f"tilted_{applied_tilt}.png"
|
||||
# Rotate by applied_tilt degrees (counter-clockwise in PIL)
|
||||
tilted_img = base_ruled_invoice.rotate(
|
||||
applied_tilt,
|
||||
expand=True,
|
||||
resample=Image.Resampling.BICUBIC,
|
||||
fillcolor=255,
|
||||
)
|
||||
tilted_img.save(src_file)
|
||||
|
||||
out_dir = tmp_path / "deskewed"
|
||||
result = deskew_image(str(src_file), str(out_dir), min_skew=0.5)
|
||||
|
||||
assert result["status"] == "deskewed"
|
||||
assert result["rotated"] is True
|
||||
assert result["line_count"] > 0
|
||||
# The detected angle should closely match the magnitude of the applied tilt (within 0.3°)
|
||||
assert abs(abs(result["detected_skew_angle"]) - abs(applied_tilt)) <= 0.35
|
||||
assert Path(result["output_path"]).exists()
|
||||
|
||||
# Re-inspect corrected image to confirm residual tilt is now below the 0.5° threshold
|
||||
with Image.open(result["output_path"]) as corrected_img:
|
||||
residual_angle, _ = detect_skew_angle(corrected_img)
|
||||
assert abs(residual_angle) < 0.5
|
||||
|
||||
|
||||
def test_sub_threshold_skew_leaves_image_unrotated(tmp_path, base_ruled_invoice):
|
||||
"""
|
||||
A small tilt of 0.2° is below the 0.5° threshold and should NOT be rotated,
|
||||
avoiding unnecessary pixel interpolation and preserving maximum sharpness.
|
||||
"""
|
||||
src_file = tmp_path / "tilted_0.2.png"
|
||||
tilted_img = base_ruled_invoice.rotate(
|
||||
0.2,
|
||||
expand=True,
|
||||
resample=Image.Resampling.BICUBIC,
|
||||
fillcolor=255,
|
||||
)
|
||||
tilted_img.save(src_file)
|
||||
|
||||
out_dir = tmp_path / "deskewed"
|
||||
result = deskew_image(str(src_file), str(out_dir), min_skew=0.5)
|
||||
|
||||
assert result["status"] == "straight"
|
||||
assert result["rotated"] is False
|
||||
assert result["correction_applied_deg"] == 0.0
|
||||
assert "saved unrotated to preserve sharpness" in result["message"]
|
||||
assert Path(result["output_path"]).exists()
|
||||
|
||||
|
||||
def test_straight_image_not_rotated(tmp_path, base_ruled_invoice):
|
||||
"""An un-tilted (0.0°) image remains untouched."""
|
||||
src_file = tmp_path / "straight.png"
|
||||
base_ruled_invoice.save(src_file)
|
||||
|
||||
out_dir = tmp_path / "deskewed"
|
||||
result = deskew_image(str(src_file), str(out_dir), min_skew=0.5)
|
||||
|
||||
assert result["status"] == "straight"
|
||||
assert result["rotated"] is False
|
||||
assert result["detected_skew_angle"] == 0.0
|
||||
assert Path(result["output_path"]).exists()
|
||||
|
||||
|
||||
def test_outlier_skew_flagged(tmp_path, base_ruled_invoice):
|
||||
"""Angles exceeding max_skew (e.g. 25°) are flagged as outliers and not blindly rotated."""
|
||||
src_file = tmp_path / "outlier_25.png"
|
||||
tilted_img = base_ruled_invoice.rotate(25.0, expand=True, fillcolor=255)
|
||||
tilted_img.save(src_file)
|
||||
|
||||
out_dir = tmp_path / "deskewed"
|
||||
# Testing with max_skew = 10.0 and min_skew = 0.5
|
||||
result = deskew_image(str(src_file), str(out_dir), min_skew=0.5, max_skew=10.0)
|
||||
|
||||
assert result["status"] in {"straight", "outlier_skew"}
|
||||
assert result["rotated"] is False
|
||||
assert Path(result["output_path"]).exists()
|
||||
|
||||
|
||||
def test_process_folder_deskew(tmp_path, base_ruled_invoice):
|
||||
"""Verifies batch deskew processing aggregates counts and corrections properly."""
|
||||
in_dir = tmp_path / "oriented"
|
||||
out_dir = tmp_path / "deskewed"
|
||||
in_dir.mkdir()
|
||||
|
||||
# Create 1 straight (0°), 1 sub-threshold (0.2°), and 1 tilted (+2.0°)
|
||||
base_ruled_invoice.save(in_dir / "invoice_straight.png")
|
||||
base_ruled_invoice.rotate(0.2, expand=True, fillcolor=255).save(in_dir / "invoice_subthreshold.png")
|
||||
base_ruled_invoice.rotate(2.0, expand=True, fillcolor=255).save(in_dir / "invoice_tilted.png")
|
||||
|
||||
summary = process_folder_deskew(str(in_dir), str(out_dir), min_skew=0.5)
|
||||
|
||||
assert summary["total_images_processed"] == 3
|
||||
assert summary["straight_count"] == 2
|
||||
assert summary["deskewed_count"] == 1
|
||||
assert len(summary["corrections"]) == 1
|
||||
assert summary["corrections"][0]["filename"] == "invoice_tilted.png"
|
||||
@@ -0,0 +1,92 @@
|
||||
# tests/test_evaluator_refactor.py
|
||||
import pytest
|
||||
from decimal import Decimal
|
||||
from app.rrsi.evaluator import StatisticalEvaluator
|
||||
from app.rrsi.taxonomy import (
|
||||
ExtractionErrorClass,
|
||||
ProcessOutcome,
|
||||
ProposalHypothesis,
|
||||
PipelineArea,
|
||||
ExperimentStatus
|
||||
)
|
||||
|
||||
def test_alignment_by_doc_id_not_zip():
|
||||
evaluator = StatisticalEvaluator()
|
||||
# Shuffled order between predictions and ground truths
|
||||
gt = [
|
||||
{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"},
|
||||
{"invoice_id": "doc_B", "invoice_number": "INV-B", "invoice_amount": "200.00"}
|
||||
]
|
||||
preds = [
|
||||
{"invoice_id": "doc_B", "invoice_number": "INV-B", "invoice_amount": "200.00"},
|
||||
{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"}
|
||||
]
|
||||
|
||||
metrics, failures = evaluator.evaluate_predictions(preds, gt)
|
||||
# Since alignment is by doc_id, all fields should match 100%
|
||||
assert metrics.macro_accuracy == 100.0
|
||||
assert len(failures) == 0
|
||||
|
||||
def test_missing_prediction_handled_as_pipeline_error():
|
||||
evaluator = StatisticalEvaluator()
|
||||
gt = [
|
||||
{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"},
|
||||
{"invoice_id": "doc_B", "invoice_number": "INV-B", "invoice_amount": "200.00"}
|
||||
]
|
||||
# Prediction for doc_B is completely missing
|
||||
preds = [
|
||||
{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"}
|
||||
]
|
||||
|
||||
metrics, failures = evaluator.evaluate_predictions(preds, gt)
|
||||
assert "doc_B" in metrics.doc_results
|
||||
doc_b_res = metrics.doc_results["doc_B"]
|
||||
assert doc_b_res.is_end_to_end_correct is False
|
||||
assert any(f.primary_class == ExtractionErrorClass.PIPELINE_ERROR for f in failures if f.file_id == "doc_B")
|
||||
|
||||
def test_precision_counts_hallucination_when_gt_is_null():
|
||||
evaluator = StatisticalEvaluator()
|
||||
# Ground truth has no PO_number
|
||||
gt = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "PO_number": None}]
|
||||
# Prediction extracted a hallucinated PO_number
|
||||
preds = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "PO_number": "PO-9999"}]
|
||||
|
||||
metrics, failures = evaluator.evaluate_predictions(preds, gt)
|
||||
po_metrics = metrics.per_field_metrics.get("PO_number")
|
||||
assert po_metrics is not None
|
||||
assert po_metrics.hallucinations == 1
|
||||
assert any(f.primary_class == ExtractionErrorClass.HALLUCINATION for f in failures)
|
||||
|
||||
def test_per_document_outcomes_structure():
|
||||
evaluator = StatisticalEvaluator()
|
||||
gt = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_date": "2026-08-20"}]
|
||||
preds = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_date": "2026-08-21"}]
|
||||
|
||||
metrics, failures = evaluator.evaluate_predictions(preds, gt)
|
||||
assert "doc_A" in metrics.doc_results
|
||||
doc_res = metrics.doc_results["doc_A"]
|
||||
assert doc_res.field_outcomes["invoice_number"] is True
|
||||
assert doc_res.field_outcomes["invoice_date"] is False
|
||||
assert doc_res.field_errors["invoice_date"] == "date_mismatch"
|
||||
|
||||
def test_selection_gate_requires_selection_split():
|
||||
evaluator = StatisticalEvaluator()
|
||||
hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-101",
|
||||
area=PipelineArea.ENTITY_EXTRACTION,
|
||||
title="Test gate",
|
||||
description="Testing selection gate",
|
||||
rationale="Unit test"
|
||||
)
|
||||
dev_base = evaluator.evaluate_predictions([{"invoice_id": "1", "invoice_number": "A"}], [{"invoice_id": "1", "invoice_number": "A"}])[0]
|
||||
dev_cand = evaluator.evaluate_predictions([{"invoice_id": "1", "invoice_number": "A"}], [{"invoice_id": "1", "invoice_number": "A"}])[0]
|
||||
|
||||
# Omitting selection split should raise ValueError (fail closed)
|
||||
with pytest.raises(ValueError, match="Selection-split metrics are required"):
|
||||
evaluator.decide_acceptance(
|
||||
hypothesis=hypo,
|
||||
baseline_dev=dev_base,
|
||||
candidate_dev=dev_cand,
|
||||
baseline_selection=None,
|
||||
candidate_selection=None
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
# tests/test_input_validation.py
|
||||
|
||||
import fitz
|
||||
from PIL import Image
|
||||
from app.input.file_validator import validate_file
|
||||
|
||||
|
||||
def test_valid_single_page_pdf(tmp_path):
|
||||
pdf_path = tmp_path / "single.pdf"
|
||||
doc = fitz.open()
|
||||
doc.new_page()
|
||||
doc.save(pdf_path)
|
||||
doc.close()
|
||||
|
||||
result = validate_file(str(pdf_path))
|
||||
assert result["status"] == "valid"
|
||||
assert result["format"] == "pdf"
|
||||
assert result["page_count"] == 1
|
||||
|
||||
|
||||
def test_valid_multi_page_pdf(tmp_path):
|
||||
pdf_path = tmp_path / "multi.pdf"
|
||||
doc = fitz.open()
|
||||
doc.new_page()
|
||||
doc.new_page()
|
||||
doc.new_page()
|
||||
doc.save(pdf_path)
|
||||
doc.close()
|
||||
|
||||
result = validate_file(str(pdf_path))
|
||||
assert result["status"] == "valid"
|
||||
assert result["page_count"] == 3
|
||||
|
||||
|
||||
def test_encrypted_pdf(tmp_path):
|
||||
pdf_path = tmp_path / "locked.pdf"
|
||||
doc = fitz.open()
|
||||
doc.new_page()
|
||||
doc.save(
|
||||
pdf_path,
|
||||
encryption=fitz.PDF_ENCRYPT_AES_256,
|
||||
owner_pw="ownerpass",
|
||||
user_pw="userpass", # a real password required to open it
|
||||
)
|
||||
doc.close()
|
||||
|
||||
result = validate_file(str(pdf_path))
|
||||
assert result["status"] == "invalid"
|
||||
assert "encrypted" in result["reason"].lower() or "password" in result["reason"].lower()
|
||||
|
||||
|
||||
def test_valid_jpg(tmp_path):
|
||||
img_path = tmp_path / "photo.jpg"
|
||||
Image.new("RGB", (100, 100), color="white").save(img_path)
|
||||
|
||||
result = validate_file(str(img_path))
|
||||
assert result["status"] == "valid"
|
||||
assert result["format"] == "jpg"
|
||||
assert result["page_count"] == 1
|
||||
|
||||
|
||||
def test_valid_png(tmp_path):
|
||||
img_path = tmp_path / "photo.png"
|
||||
Image.new("RGB", (100, 100), color="white").save(img_path)
|
||||
|
||||
result = validate_file(str(img_path))
|
||||
assert result["status"] == "valid"
|
||||
assert result["format"] == "png"
|
||||
|
||||
|
||||
def test_unsupported_extension(tmp_path):
|
||||
bad_path = tmp_path / "notes.txt"
|
||||
bad_path.write_text("just some text")
|
||||
|
||||
result = validate_file(str(bad_path))
|
||||
assert result["status"] == "invalid"
|
||||
assert "unsupported" in result["reason"].lower()
|
||||
|
||||
|
||||
def test_corrupted_pdf(tmp_path):
|
||||
fake_pdf = tmp_path / "broken.pdf"
|
||||
fake_pdf.write_bytes(b"this is not a real pdf file")
|
||||
|
||||
result = validate_file(str(fake_pdf))
|
||||
assert result["status"] == "invalid"
|
||||
|
||||
|
||||
def test_corrupted_image(tmp_path):
|
||||
fake_img = tmp_path / "broken.jpg"
|
||||
fake_img.write_bytes(b"this is not a real image file")
|
||||
|
||||
result = validate_file(str(fake_img))
|
||||
assert result["status"] == "invalid"
|
||||
|
||||
|
||||
def test_nonexistent_file():
|
||||
result = validate_file("this/path/does/not/exist.pdf")
|
||||
assert result["status"] == "invalid"
|
||||
assert "does not exist" in result["reason"].lower()
|
||||
@@ -0,0 +1,77 @@
|
||||
# tests/test_reconciliation_bug.py
|
||||
"""
|
||||
Test reproducing the reconciliation bug and verifying the fix from fixed numbers:
|
||||
1. Invoice 4531 (Vendor A): Discrepancy explanation (5627.20 vs 5628.00)
|
||||
2. Invoice Kundan (Vendor B): Discrepancy explanation (878.40 vs 1518.54)
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from decimal import Decimal
|
||||
from app.validators import InvoiceArithmeticValidator, ValidationStatus
|
||||
|
||||
def test_invoice_4531_fixed_numbers_reconciliation():
|
||||
# Fixed numbers from printed invoice WMP/B/04531
|
||||
# Line 1: 60 qty * 3700.00 = 222000.00, 2% discount = 4440.00 -> taxable = 217560.00, GST 5% = 10878.00
|
||||
# Line 2: 120 qty * 198.00 = 23760.00, 5% discount = 1188.00 -> taxable = 22572.00, GST 5% = 1128.60
|
||||
# Total Gross: 245760.00
|
||||
# Total Discount: 5628.00
|
||||
# Total Taxable: 240132.00
|
||||
# Total GST: 12006.60 (CGST 6003.30 + SGST 6003.30)
|
||||
# Round-off: +0.40
|
||||
# Invoice Amount: 252139.00
|
||||
|
||||
# Old buggy calculation: Gross + GST - Roundoff - Invoice Amount
|
||||
buggy_discrepancy = (Decimal("245760.00") + Decimal("12006.60") - Decimal("0.40")) - Decimal("252139.00")
|
||||
assert buggy_discrepancy == Decimal("5627.20"), "Reproduced the 5627.20 bug!"
|
||||
|
||||
# Correct discount value:
|
||||
total_discount = Decimal("4440.00") + Decimal("1188.00")
|
||||
assert total_discount == Decimal("5628.00")
|
||||
|
||||
# Correct validator check:
|
||||
validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00"))
|
||||
doc_4531 = {
|
||||
"invoice_amount": "252139.00",
|
||||
"total_gst_amount": "12006.60",
|
||||
"round_off": "0.40",
|
||||
"items": [
|
||||
{"total_price": "222000.00", "Discount": "2.00"},
|
||||
{"total_price": "23760.00", "Discount": "5.00"}
|
||||
]
|
||||
}
|
||||
res = validator.validate(doc_4531)
|
||||
assert res.status == ValidationStatus.PASS
|
||||
assert res.is_valid is True
|
||||
assert res.discrepancy == Decimal("0.00")
|
||||
assert res.reconciled_formula == "Taxable + GST + Freight + RoundOff"
|
||||
|
||||
def test_invoice_kundan_fixed_numbers_reconciliation():
|
||||
# Fixed numbers from printed Kundan invoice:
|
||||
# Gross items sum: 53542.60
|
||||
# Total Discount: 2141.704 (taxable: 51400.896)
|
||||
# Correct GST: 3020.08
|
||||
# Extracted GST: 2396.94 (short by 623.14)
|
||||
# Round-off: 0.01
|
||||
# Invoice Amount: 54421.00
|
||||
|
||||
# Pipeline extraction error: Gross items + Extracted GST - Invoice Amount
|
||||
pipeline_extracted_sum = Decimal("53542.60") + Decimal("2396.94")
|
||||
raw_discrepancy = pipeline_extracted_sum - Decimal("54421.00")
|
||||
assert raw_discrepancy == Decimal("1518.54"), "Reproduced the 1518.54 discrepancy!"
|
||||
|
||||
# Buggy partial offset (1518.54 - 640.14 = 878.40)
|
||||
assert raw_discrepancy - Decimal("640.14") == Decimal("878.40"), "Reproduced the 878.40 bug!"
|
||||
|
||||
# On ground truth with correct GST (3020.08), the document reconciles:
|
||||
validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00"))
|
||||
doc_kundan_gt = {
|
||||
"invoice_amount": "54421.00",
|
||||
"total_gst_amount": "3020.08",
|
||||
"round_off": "0.01",
|
||||
"items": [
|
||||
{"total_price": "53542.60", "Discount": "4.00"}
|
||||
]
|
||||
}
|
||||
res_gt = validator.validate(doc_kundan_gt)
|
||||
assert res_gt.status == ValidationStatus.PASS
|
||||
assert res_gt.is_valid is True
|
||||
@@ -0,0 +1,347 @@
|
||||
# tests/test_rrsi_framework.py
|
||||
"""
|
||||
Comprehensive Unit Tests for the RRSI Framework:
|
||||
- Proposal Memory & Negative Knowledge Registry
|
||||
- Area Stagnation & Shift Recommendations
|
||||
- Leakage Screening (hardcoded tokens, coordinates, holdout retention)
|
||||
- Statistical Evaluator (noise floor calculation, cost-aware acceptance)
|
||||
- Granular Error Taxonomy Classification
|
||||
- Experiment Ledger Persistence & Auditing
|
||||
"""
|
||||
|
||||
import tempfile
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
|
||||
from app.rrsi import (
|
||||
ErrorCategory,
|
||||
PipelineArea,
|
||||
ExperimentStatus,
|
||||
FailureDetail,
|
||||
ProposalHypothesis,
|
||||
EvaluationMetrics,
|
||||
DecisionRecord,
|
||||
NegativeKnowledgeRegistry,
|
||||
LeakageScreening,
|
||||
PruningAnalyzer,
|
||||
StatisticalEvaluator,
|
||||
ExperimentLedger,
|
||||
RRSIOrchestrator
|
||||
)
|
||||
from app.rrsi.taxonomy import ProcessOutcome, ExtractionErrorClass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_memory():
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
yield Path(tmpdir) / "proposal_memory.json"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_ledger():
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
yield Path(tmpdir) / "experiment_ledger.json"
|
||||
|
||||
|
||||
def _create_dummy_decision(
|
||||
proposal_id="PROP-001",
|
||||
area=PipelineArea.ENTITY_EXTRACTION.value,
|
||||
status=ExperimentStatus.REJECTED,
|
||||
rejection_reasons=None
|
||||
):
|
||||
return DecisionRecord(
|
||||
proposal_id=proposal_id,
|
||||
area=area,
|
||||
status=status,
|
||||
process_outcome=ProcessOutcome.INSIGNIFICANT if status == ExperimentStatus.REJECTED else ProcessOutcome.ACCEPTED,
|
||||
baseline_accuracy=85.0,
|
||||
candidate_accuracy=85.0,
|
||||
delta_accuracy=0.0,
|
||||
paired_ci_lower=0.0,
|
||||
paired_ci_upper=0.0,
|
||||
is_statistically_significant=False,
|
||||
leakage_screen_passed=True,
|
||||
leakage_findings=[],
|
||||
cost_aware_accepted=False,
|
||||
latency_delta_seconds=0.0,
|
||||
vision_fallback_calls=0,
|
||||
case_regressions=[],
|
||||
rejection_reasons=rejection_reasons or ["NO ACCURACY GAIN: Candidate did not improve baseline."],
|
||||
pruning_recommendations=[],
|
||||
failure_deltas={}
|
||||
)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 1. Proposal Side: Memory, Negative Knowledge & Area Shifting
|
||||
# -----------------------------------------------------------------------------
|
||||
def test_negative_knowledge_blocks_repeated_failed_proposals(temp_memory):
|
||||
registry = NegativeKnowledgeRegistry(storage_path=temp_memory, stagnation_threshold=3)
|
||||
|
||||
# 1. Record a failed hypothesis
|
||||
failed_hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-001",
|
||||
area=PipelineArea.ENTITY_EXTRACTION,
|
||||
title="Tweak invoice date regex to support slash dot combinations",
|
||||
description="Add regex pattern for dd.mm.yyyy and slash formats in date parser",
|
||||
rationale="Fix date extraction test failures",
|
||||
tags=["regex", "date", "slash"]
|
||||
)
|
||||
decision = _create_dummy_decision("PROP-001", PipelineArea.ENTITY_EXTRACTION.value, ExperimentStatus.REJECTED)
|
||||
registry.record_decision(failed_hypo, decision)
|
||||
|
||||
# 2. Candidate proposes a very similar idea in the same area
|
||||
candidate_hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-002",
|
||||
area=PipelineArea.ENTITY_EXTRACTION,
|
||||
title="Tweak invoice date regex pattern for dot slash formats",
|
||||
description="Add regex pattern for dd.mm.yyyy date parsing",
|
||||
rationale="Fix date extraction failures",
|
||||
tags=["regex", "date", "slash"]
|
||||
)
|
||||
|
||||
is_viable, warnings, _ = registry.check_proposal_viability(candidate_hypo)
|
||||
assert not is_viable
|
||||
assert any("PROPOSAL DUPLICATION WARNING" in w for w in warnings)
|
||||
|
||||
|
||||
def test_area_stagnation_triggers_area_shift(temp_memory):
|
||||
registry = NegativeKnowledgeRegistry(storage_path=temp_memory, stagnation_threshold=3)
|
||||
|
||||
# Record 3 consecutive failed attempts in ENTITY_EXTRACTION
|
||||
for i in range(1, 4):
|
||||
hypo = ProposalHypothesis(
|
||||
proposal_id=f"PROP-00{i}",
|
||||
area=PipelineArea.ENTITY_EXTRACTION,
|
||||
title=f"Unique attempt {i} in regex entity extraction",
|
||||
description=f"Description {i}",
|
||||
rationale=f"Rationale {i}"
|
||||
)
|
||||
decision = _create_dummy_decision(f"PROP-00{i}", PipelineArea.ENTITY_EXTRACTION.value, ExperimentStatus.REJECTED)
|
||||
registry.record_decision(hypo, decision)
|
||||
|
||||
# Attempt a 4th proposal in the same component
|
||||
new_hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-004",
|
||||
area=PipelineArea.ENTITY_EXTRACTION,
|
||||
title="Another entity extraction attempt",
|
||||
description="More micro tweaks",
|
||||
rationale="Hoping for improvement"
|
||||
)
|
||||
|
||||
is_viable, warnings, rec_area = registry.check_proposal_viability(new_hypo)
|
||||
assert not is_viable
|
||||
assert any("STAGNATION DETECTED" in w for w in warnings)
|
||||
assert rec_area is not None
|
||||
assert rec_area != PipelineArea.ENTITY_EXTRACTION
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 2. Selection Side: Leakage Screening & Pruning
|
||||
# -----------------------------------------------------------------------------
|
||||
def test_leakage_screening_detects_hardcoded_sample_tokens():
|
||||
clean_code = "def parse_inv(text): return re.findall(r'INV-[0-9]+', text)"
|
||||
passed, findings = LeakageScreening.audit_code_changes(clean_code)
|
||||
assert passed
|
||||
assert len(findings) == 0
|
||||
|
||||
leaky_code = "if 'WMP/B/04531' in text: return 'WMP/B/04531'"
|
||||
passed, findings = LeakageScreening.audit_code_changes(leaky_code)
|
||||
assert not passed
|
||||
assert any("DATA LEAKAGE DETECTED" in f for f in findings)
|
||||
|
||||
|
||||
def test_leakage_screening_detects_coordinate_overfitting():
|
||||
overfitted_code = "if ymin >= 145 and ymax <= 320: return crop[120:850]"
|
||||
passed, findings = LeakageScreening.audit_code_changes(overfitted_code)
|
||||
assert not passed
|
||||
assert any("COORDINATE OVERFITTING WARNING" in f for f in findings)
|
||||
|
||||
|
||||
def test_generalization_split_screening():
|
||||
# Healthy generalization
|
||||
passed, _ = LeakageScreening.audit_split_generalization(calibration_delta=3.5, holdout_delta=2.8)
|
||||
assert passed
|
||||
|
||||
# Regression on holdout set
|
||||
passed, msg = LeakageScreening.audit_split_generalization(calibration_delta=4.0, holdout_delta=-1.2)
|
||||
assert not passed
|
||||
assert "GENERALIZATION FAILURE" in msg
|
||||
|
||||
# Disproportionate overfit (calibration high, holdout negligible)
|
||||
passed, msg = LeakageScreening.audit_split_generalization(calibration_delta=8.0, holdout_delta=0.5)
|
||||
assert not passed
|
||||
assert "LEAKAGE/OVERFITTING DETECTED" in msg
|
||||
|
||||
|
||||
def test_pruning_analyzer_identifies_regex_redundancy():
|
||||
patterns = [r"INV-[0-9]+", r".*invoice.*", r"INV-[0-9]+"]
|
||||
recommendations = PruningAnalyzer.analyze_regex_redundancy(patterns)
|
||||
assert len(recommendations) > 0
|
||||
assert any("PRUNING OPPORTUNITY" in r for r in recommendations)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 3. Statistical Evaluator: Bootstrap CI, Cost-Awareness & Error Taxonomy
|
||||
# -----------------------------------------------------------------------------
|
||||
def test_selection_gate_requires_selection_metrics():
|
||||
evaluator = StatisticalEvaluator()
|
||||
hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-009",
|
||||
area=PipelineArea.ENTITY_EXTRACTION,
|
||||
title="Check gate enforcement",
|
||||
description="Gate must fail-closed if selection split is omitted",
|
||||
rationale="Integrity check"
|
||||
)
|
||||
dev_m = evaluator.evaluate_predictions(
|
||||
[{"invoice_id": "1", "invoice_number": "A"}],
|
||||
[{"invoice_id": "1", "invoice_number": "A"}]
|
||||
)[0]
|
||||
|
||||
with pytest.raises(ValueError, match="Selection-split metrics are required"):
|
||||
evaluator.decide_acceptance(
|
||||
hypothesis=hypo,
|
||||
baseline_dev=dev_m,
|
||||
candidate_dev=dev_m,
|
||||
baseline_selection=None,
|
||||
candidate_selection=None
|
||||
)
|
||||
|
||||
|
||||
def test_evaluator_rejects_candidate_within_noise_floor():
|
||||
evaluator = StatisticalEvaluator()
|
||||
hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-010",
|
||||
area=PipelineArea.TABLE_EXTRACTION,
|
||||
title="Minor column spacing tweak",
|
||||
description="Shift column border by 2px",
|
||||
rationale="Experimental"
|
||||
)
|
||||
|
||||
# Identical predictions on selection split -> delta is 0 -> CI includes 0 -> Rejected
|
||||
gt = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)]
|
||||
base_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)]
|
||||
cand_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)]
|
||||
|
||||
base_m, _ = evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=2.0)
|
||||
cand_m, _ = evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=2.0)
|
||||
|
||||
decision = evaluator.decide_acceptance(
|
||||
hypothesis=hypo,
|
||||
baseline_dev=base_m,
|
||||
candidate_dev=cand_m,
|
||||
baseline_selection=base_m,
|
||||
candidate_selection=cand_m
|
||||
)
|
||||
assert decision.status == ExperimentStatus.REJECTED
|
||||
assert not decision.is_statistically_significant
|
||||
assert any("NO ACCURACY GAIN" in r or "NOT STATISTICALLY SIGNIFICANT" in r for r in decision.rejection_reasons)
|
||||
|
||||
|
||||
def test_cost_aware_acceptance_rejects_latency_blowup():
|
||||
evaluator = StatisticalEvaluator(cost_lambda=0.50)
|
||||
hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-011",
|
||||
area=PipelineArea.OCR_ENGINE,
|
||||
title="Triple pass multi-scale OCR rendering",
|
||||
description="Render image at 100, 200, and 400 DPI and merge results",
|
||||
rationale="Higher resolution"
|
||||
)
|
||||
|
||||
# Base: 80% accuracy, 1.0s runtime
|
||||
gt = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)]
|
||||
base_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}" if i < 8 else "WRONG"} for i in range(10)]
|
||||
# Cand: 90% accuracy, but runtime balloons to 50.0s (+4900%)
|
||||
cand_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}" if i < 9 else "WRONG"} for i in range(10)]
|
||||
|
||||
base_m, _ = evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=1.0)
|
||||
cand_m, _ = evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=50.0)
|
||||
|
||||
decision = evaluator.decide_acceptance(
|
||||
hypothesis=hypo,
|
||||
baseline_dev=base_m,
|
||||
candidate_dev=cand_m,
|
||||
baseline_selection=base_m,
|
||||
candidate_selection=cand_m
|
||||
)
|
||||
assert decision.status == ExperimentStatus.REJECTED
|
||||
assert not decision.cost_aware_accepted
|
||||
assert any("COST UTILITY NEGATIVE" in r for r in decision.rejection_reasons)
|
||||
|
||||
|
||||
def test_fine_grained_error_taxonomy_classification():
|
||||
evaluator = StatisticalEvaluator()
|
||||
|
||||
ground_truth = [{
|
||||
"invoice_id": "1",
|
||||
"invoice_number": "INV-100",
|
||||
"invoice_date": "2026-05-12",
|
||||
"customer_name": "Acme Corp",
|
||||
"seller_gstin": "27AAPFU0939F1ZV",
|
||||
"invoice_amount": "1000.00"
|
||||
}]
|
||||
|
||||
prediction = [{
|
||||
"invoice_id": "1",
|
||||
"invoice_number": "INV-999", # INVOICE_NUMBER_MISMATCH
|
||||
"invoice_date": "2026-05-13", # DATE_MISMATCH
|
||||
"customer_name": "Different Corp", # PARTY_NAME_MISMATCH
|
||||
"seller_gstin": "27AAPFU0939F1ZW", # GSTIN_INVALID
|
||||
"invoice_amount": "800.00" # AMOUNT_PARSE
|
||||
}]
|
||||
|
||||
metrics, failures = evaluator.evaluate_predictions(prediction, ground_truth)
|
||||
assert any(f.primary_class == ExtractionErrorClass.INVOICE_NUMBER_MISMATCH for f in failures)
|
||||
assert any(f.primary_class == ExtractionErrorClass.DATE_MISMATCH for f in failures)
|
||||
assert any(f.primary_class == ExtractionErrorClass.PARTY_NAME_MISMATCH for f in failures)
|
||||
assert any(f.primary_class == ExtractionErrorClass.GSTIN_INVALID for f in failures)
|
||||
assert any(f.primary_class == ExtractionErrorClass.AMOUNT_PARSE for f in failures)
|
||||
assert len(failures) >= 5
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 4. Orchestrator & Ledger Integration
|
||||
# -----------------------------------------------------------------------------
|
||||
def test_rrsi_orchestrator_end_to_end(temp_memory, temp_ledger):
|
||||
orchestrator = RRSIOrchestrator(
|
||||
memory_path=temp_memory,
|
||||
ledger_path=temp_ledger
|
||||
)
|
||||
|
||||
hypo = ProposalHypothesis(
|
||||
proposal_id="PROP-E2E-001",
|
||||
area=PipelineArea.TABLE_EXTRACTION,
|
||||
title="Adaptive horizontal line clustering for tables",
|
||||
description="Group rows dynamically using morphological kernel analysis",
|
||||
rationale="Resolves merged multi-item rows"
|
||||
)
|
||||
|
||||
is_viable, warnings, _ = orchestrator.submit_proposal(hypo)
|
||||
assert is_viable
|
||||
|
||||
gt = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)]
|
||||
base_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}" if i < 4 else "WRONG"} for i in range(10)]
|
||||
cand_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)] # 100% correct
|
||||
|
||||
base_dev, _ = orchestrator.evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=2.0)
|
||||
cand_dev, _ = orchestrator.evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=2.1)
|
||||
base_sel, _ = orchestrator.evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=2.0)
|
||||
cand_sel, _ = orchestrator.evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=2.1)
|
||||
|
||||
decision = orchestrator.evaluate_and_decide(
|
||||
hypothesis=hypo,
|
||||
baseline_dev=base_dev,
|
||||
candidate_dev=cand_dev,
|
||||
baseline_selection=base_sel,
|
||||
candidate_selection=cand_sel
|
||||
)
|
||||
|
||||
assert decision.status == ExperimentStatus.ACCEPTED
|
||||
assert decision.is_statistically_significant
|
||||
|
||||
# Verify ledger was persisted
|
||||
assert len(orchestrator.ledger.records) == 1
|
||||
assert orchestrator.ledger.records[0]["proposal_id"] == "PROP-E2E-001"
|
||||
|
||||
# Verify memory was updated with accepted approach
|
||||
assert len(orchestrator.memory.accepted_approaches) == 1
|
||||
@@ -0,0 +1,116 @@
|
||||
# tests/test_rrsi_normalize.py
|
||||
import pytest
|
||||
from decimal import Decimal
|
||||
from app.rrsi.normalize import (
|
||||
normalize_invoice_number,
|
||||
match_invoice_number,
|
||||
normalize_date,
|
||||
match_date,
|
||||
normalize_amount,
|
||||
match_amount,
|
||||
normalize_vendor_name,
|
||||
match_vendor_name,
|
||||
validate_gstin_checksum,
|
||||
match_gstin
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Invoice Number Tests: Whitespace and case only, NEVER numeric coercion
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_invoice_number_never_coerces_numerically():
|
||||
# "04531" != "4531"
|
||||
assert normalize_invoice_number("04531") == "04531"
|
||||
assert normalize_invoice_number("4531") == "4531"
|
||||
matched, err = match_invoice_number("04531", "4531")
|
||||
assert matched is False
|
||||
assert err == "invoice_number_mismatch"
|
||||
|
||||
def test_invoice_number_case_and_whitespace():
|
||||
assert normalize_invoice_number(" wmp/B/04531 ") == "WMP/B/04531"
|
||||
matched, err = match_invoice_number("WMP/B/04531", " wmp/b/04531 ")
|
||||
assert matched is True
|
||||
assert err is None
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Date Tests: ISO-8601 parsing and date_locale_swap classification
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_date_iso_matching():
|
||||
# Standard format: 20/08/2026 -> 2026-08-20
|
||||
assert normalize_date("20/08/2026") == "2026-08-20"
|
||||
assert normalize_date("20-08-2026") == "2026-08-20"
|
||||
assert normalize_date("2026-08-20") == "2026-08-20"
|
||||
|
||||
matched, err = match_date("2026-08-20", "20/08/2026")
|
||||
assert matched is True
|
||||
assert err is None
|
||||
|
||||
def test_date_locale_swap_detected():
|
||||
# Ground truth is 05 July 2026 ("2026-07-05").
|
||||
# Prediction parsed as May 07 2026 ("2026-05-07") because of MM/DD vs DD/MM swap.
|
||||
matched, err = match_date("2026-07-05", "05/07/2026", default_format="%m/%d/%Y")
|
||||
# If the prediction assumed MM/DD/YYYY, "05/07/2026" yielded May 7, which differs from July 5
|
||||
matched, err = match_date("2026-07-05", "2026-05-07")
|
||||
assert matched is False
|
||||
assert err == "date_locale_swap"
|
||||
|
||||
def test_date_genuine_mismatch():
|
||||
matched, err = match_date("2026-07-25", "2026-07-10")
|
||||
assert matched is False
|
||||
assert err == "date_mismatch"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Amount Tests: Decimal with configurable relative + absolute tolerance
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_amount_decimal_parsing_and_matching():
|
||||
# Currency symbols and commas
|
||||
amt = normalize_amount("Rs. 1,23,456.78")
|
||||
assert amt == Decimal("123456.78")
|
||||
|
||||
# Within absolute tolerance (default abs_tol=1.0)
|
||||
matched, err = match_amount("100.50", "101.00", abs_tol=Decimal("1.00"), rel_tol=Decimal("0.001"))
|
||||
assert matched is True
|
||||
|
||||
# Exceeding tolerance
|
||||
matched, err = match_amount("100.00", "102.50", abs_tol=Decimal("1.00"), rel_tol=Decimal("0.001"))
|
||||
assert matched is False
|
||||
assert err == "amount_mismatch"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Name Tests: Casefold, punctuation strip, legal suffix normalization, exact vs fuzzy
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_vendor_name_normalization_and_fuzzy():
|
||||
# Normalizing "Acme Health Care Private Limited" vs "acme health care pvt. ltd."
|
||||
n1 = normalize_vendor_name("Acme Health Care Private Limited")
|
||||
n2 = normalize_vendor_name("acme health care pvt. ltd.")
|
||||
assert n1 == "acme health care pvt ltd"
|
||||
assert n2 == "acme health care pvt ltd"
|
||||
|
||||
exact, fuzzy, score = match_vendor_name("Acme Health Care Private Limited", "acme health care pvt. ltd.")
|
||||
assert exact is True
|
||||
assert fuzzy is True
|
||||
assert score == 1.0
|
||||
|
||||
# Slight variation: exact is False, but fuzzy is True
|
||||
exact2, fuzzy2, score2 = match_vendor_name("Acme Health Care Pvt Ltd", "Acme Healthcare Pvt Ltd")
|
||||
assert exact2 is False
|
||||
assert fuzzy2 is True
|
||||
assert score2 >= 0.85
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. GSTIN Tests: Exact match and checksum validity
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_gstin_checksum_validity():
|
||||
# Valid Indian GSTIN: 27AAPFU0939F1ZV
|
||||
assert validate_gstin_checksum("27AAPFU0939F1ZV") is True
|
||||
# Invalid checksum char (altered last char to 'W')
|
||||
assert validate_gstin_checksum("27AAPFU0939F1ZW") is False
|
||||
|
||||
def test_gstin_matching():
|
||||
matched, valid_chk, err = match_gstin("27AAPFU0939F1ZV", "27AAPFU0939F1ZV")
|
||||
assert matched is True
|
||||
assert valid_chk is True
|
||||
assert err is None
|
||||
|
||||
matched, valid_chk, err = match_gstin("27AAPFU0939F1ZV", "27AAPFU0939F1ZW")
|
||||
assert matched is False
|
||||
assert err == "gstin_mismatch"
|
||||
@@ -0,0 +1,87 @@
|
||||
# tests/test_rrsi_stats.py
|
||||
import pytest
|
||||
from app.rrsi.stats import (
|
||||
wilson_interval,
|
||||
paired_cluster_bootstrap,
|
||||
mcnemar_test
|
||||
)
|
||||
|
||||
def test_wilson_interval_known_values():
|
||||
# Known test case: 10 successes out of 20 trials at 95% confidence
|
||||
lower, upper = wilson_interval(successes=10, total=20, confidence=0.95)
|
||||
assert pytest.approx(lower, abs=1e-3) == 0.2993
|
||||
assert pytest.approx(upper, abs=1e-3) == 0.7007
|
||||
assert 0.0 <= lower <= upper <= 1.0
|
||||
|
||||
def test_wilson_interval_small_n_is_wide():
|
||||
# N=3 sample size (e.g. 2 successes out of 3) must give a very wide interval
|
||||
lower, upper = wilson_interval(successes=2, total=3, confidence=0.95)
|
||||
width = upper - lower
|
||||
# At N=3, the 95% Wilson interval width is > 0.60
|
||||
assert width > 0.60
|
||||
assert lower > 0.15
|
||||
assert upper < 0.99
|
||||
|
||||
def test_wilson_interval_edge_cases():
|
||||
# 0 successes out of 10: Wald gives [0, 0] with margin 0, but Wilson properly gives upper bound > 0
|
||||
lower, upper = wilson_interval(successes=0, total=10, confidence=0.95)
|
||||
assert lower == 0.0
|
||||
assert upper > 0.20
|
||||
assert upper <= 0.35
|
||||
|
||||
# 10 successes out of 10
|
||||
lower, upper = wilson_interval(successes=10, total=10, confidence=0.95)
|
||||
assert upper == 1.0
|
||||
assert lower >= 0.65
|
||||
|
||||
# Empty total
|
||||
lower, upper = wilson_interval(successes=0, total=0)
|
||||
assert lower == 0.0
|
||||
assert upper == 0.0
|
||||
|
||||
def test_paired_cluster_bootstrap_identical_runs():
|
||||
# Identical runs must yield exactly delta=0 and CI [0, 0]
|
||||
base_scores = {"doc1": 0.8, "doc2": 0.9, "doc3": 0.7, "doc4": 0.85}
|
||||
cand_scores = {"doc1": 0.8, "doc2": 0.9, "doc3": 0.7, "doc4": 0.85}
|
||||
groups = {"doc1": "grp_a", "doc2": "grp_a", "doc3": "grp_b", "doc4": "grp_b"}
|
||||
|
||||
res = paired_cluster_bootstrap(base_scores, cand_scores, groups, n_resamples=1000, seed=42)
|
||||
assert pytest.approx(res["mean_delta"], abs=1e-6) == 0.0
|
||||
assert pytest.approx(res["ci_lower"], abs=1e-6) == 0.0
|
||||
assert pytest.approx(res["ci_upper"], abs=1e-6) == 0.0
|
||||
assert pytest.approx(res["std_err"], abs=1e-6) == 0.0
|
||||
|
||||
def test_paired_cluster_bootstrap_positive_delta():
|
||||
base_scores = {"doc1": 0.6, "doc2": 0.7, "doc3": 0.5, "doc4": 0.6}
|
||||
cand_scores = {"doc1": 0.8, "doc2": 0.9, "doc3": 0.7, "doc4": 0.8}
|
||||
groups = {"doc1": "grp_a", "doc2": "grp_a", "doc3": "grp_b", "doc4": "grp_b"}
|
||||
|
||||
res = paired_cluster_bootstrap(base_scores, cand_scores, groups, n_resamples=1000, seed=42)
|
||||
assert pytest.approx(res["mean_delta"], abs=1e-3) == 0.2
|
||||
assert res["ci_lower"] > 0.0
|
||||
assert res["ci_upper"] > res["ci_lower"]
|
||||
|
||||
def test_mcnemar_test_known_values():
|
||||
# Contingency table:
|
||||
# base=1, cand=1: 50
|
||||
# base=1, cand=0: 5 (b)
|
||||
# base=0, cand=1: 20 (c)
|
||||
# base=0, cand=0: 25
|
||||
base = [True] * 50 + [True] * 5 + [False] * 20 + [False] * 25
|
||||
cand = [True] * 50 + [False] * 5 + [True] * 20 + [False] * 25
|
||||
|
||||
res = mcnemar_test(base, cand)
|
||||
assert res["b"] == 5
|
||||
assert res["c"] == 20
|
||||
assert res["n_discordant"] == 25
|
||||
# Chi-square with continuity correction: (|5 - 20| - 1)^2 / (5 + 20) = 14^2 / 25 = 196 / 25 = 7.84
|
||||
assert pytest.approx(res["statistic"], abs=1e-2) == 7.84
|
||||
assert res["p_value"] < 0.01
|
||||
|
||||
def test_mcnemar_test_zero_discordant():
|
||||
base = [True, False, True]
|
||||
cand = [True, False, True]
|
||||
res = mcnemar_test(base, cand)
|
||||
assert res["b"] == 0
|
||||
assert res["c"] == 0
|
||||
assert res["p_value"] == 1.0
|
||||
@@ -0,0 +1,59 @@
|
||||
# tests/test_schema_validator.py
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from app.ocr.schema_validator import SchemaValidator, HEADER_KEYS_SPEC, ITEM_KEYS_SPEC
|
||||
|
||||
def test_schema_validator_spec_lengths():
|
||||
assert len(HEADER_KEYS_SPEC) == 24 # 23 header keys + 'items'
|
||||
assert len(ITEM_KEYS_SPEC) == 26 # 26 line item keys
|
||||
assert HEADER_KEYS_SPEC[-1] == "items"
|
||||
|
||||
def test_schema_validator_on_synthetic_valid_and_invalid():
|
||||
validator = SchemaValidator()
|
||||
|
||||
# Perfect template object
|
||||
valid_obj = {k: None for k in HEADER_KEYS_SPEC}
|
||||
valid_obj["items"] = [{k: None for k in ITEM_KEYS_SPEC}]
|
||||
|
||||
res = validator.validate(valid_obj)
|
||||
assert res["valid"] is True
|
||||
assert res["status"] == "PASS"
|
||||
assert len(res["errors"]) == 0
|
||||
|
||||
# Missing header key
|
||||
invalid_header = valid_obj.copy()
|
||||
del invalid_header["customer_gstin"]
|
||||
res_inv = validator.validate(invalid_header)
|
||||
assert res_inv["valid"] is False
|
||||
assert res_inv["status"] == "FAIL"
|
||||
assert "customer_gstin" in res_inv["header_conformance"]["missing"]
|
||||
|
||||
# Missing item key
|
||||
invalid_item = {k: None for k in HEADER_KEYS_SPEC}
|
||||
item_dict = {k: None for k in ITEM_KEYS_SPEC}
|
||||
del item_dict["hsn_sac"]
|
||||
invalid_item["items"] = [item_dict]
|
||||
res_item_inv = validator.validate(invalid_item)
|
||||
assert res_item_inv["valid"] is False
|
||||
assert any("hsn_sac" in e for e in res_item_inv["errors"])
|
||||
|
||||
def test_schema_validator_on_all_official_outputs():
|
||||
validator = SchemaValidator()
|
||||
files = [
|
||||
"data/ocr_results/invoice_4531_official.json",
|
||||
"data/ocr_results/kundan_official.json",
|
||||
"data/ocr_results/196_pune_official.json",
|
||||
"data/ocr_results/cc1415_official.json"
|
||||
]
|
||||
|
||||
existing_files = [Path(f) for f in files if Path(f).exists()]
|
||||
if not existing_files:
|
||||
pytest.skip("Private OCR official output results not present on fresh clone.")
|
||||
|
||||
for f_path in existing_files:
|
||||
with open(f_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
report = validator.validate(data)
|
||||
assert report["valid"] is True, f"Failed structural validation on {f_path}: {report['errors']}"
|
||||
@@ -0,0 +1,153 @@
|
||||
# tests/test_self_healing.py
|
||||
"""
|
||||
Unit tests for the Active Mathematical Self-Healing Engine (SelfHealingEngine)
|
||||
and Semantic Synonym Ontology (SemanticOntology).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from app.ocr.self_healing import SelfHealingEngine
|
||||
from app.ocr.semantic_ontology import (
|
||||
matches_any_alias,
|
||||
parse_credit_terms_days,
|
||||
PAYABLE_TOTAL_ALIASES,
|
||||
DUE_DATE_ALIASES,
|
||||
BUYER_ANCHORS
|
||||
)
|
||||
|
||||
def test_semantic_ontology_matching():
|
||||
assert matches_any_alias("TO PAY: 34327.00", PAYABLE_TOTAL_ALIASES)
|
||||
assert matches_any_alias("Net Payable Amount", PAYABLE_TOTAL_ALIASES)
|
||||
assert matches_any_alias("Due Dt. 10/08/2026", DUE_DATE_ALIASES)
|
||||
assert matches_any_alias("Details of Receiver (Billed to)", BUYER_ANCHORS)
|
||||
assert matches_any_alias("Random Unrelated Text", PAYABLE_TOTAL_ALIASES) is False
|
||||
|
||||
def test_credit_terms_parsing():
|
||||
assert parse_credit_terms_days("Credit: 30 Days") == 30
|
||||
assert parse_credit_terms_days("Terms: 7 days net") == 7
|
||||
assert parse_credit_terms_days("Payment due within 15 days of invoice") == 15
|
||||
assert parse_credit_terms_days("Immediate Cash Payment") is None
|
||||
|
||||
def test_line_item_math_derivation():
|
||||
raw_items = [
|
||||
{
|
||||
"description": "Medicine A",
|
||||
"quantity": 10,
|
||||
"free_quantity": 2,
|
||||
"rate": 100.0,
|
||||
"amount": None, # Missing
|
||||
"discount_pct": 10.0,
|
||||
"cgst_rate": 2.5,
|
||||
"sgst_rate": 2.5
|
||||
},
|
||||
{
|
||||
"description": "Medicine B",
|
||||
"quantity": 5,
|
||||
"free_quantity": 0,
|
||||
"rate": None, # Missing
|
||||
"amount": 250.0,
|
||||
"discount_pct": 0.0,
|
||||
"cgst_rate": 2.5,
|
||||
"sgst_rate": 2.5
|
||||
}
|
||||
]
|
||||
|
||||
res = SelfHealingEngine.heal(
|
||||
meta={"invoice_date": "01/08/2026"},
|
||||
fin={},
|
||||
raw_items=raw_items
|
||||
)
|
||||
|
||||
items = res["items"]
|
||||
# Item 1: 10 * 100 * (1 - 0.10) = 900.0
|
||||
assert items[0]["amount"] == 900.0
|
||||
assert items[0]["total_quantity"] == 12
|
||||
assert items[0]["free_item_yn"] == "1"
|
||||
assert items[0]["cgst_amount"] == 22.50
|
||||
assert items[0]["sgst_amount"] == 22.50
|
||||
|
||||
# Item 2: 250 / 5 = 50.0
|
||||
assert items[1]["rate"] == 50.0
|
||||
assert items[1]["total_quantity"] == 5
|
||||
assert items[1]["free_item_yn"] == "0"
|
||||
assert items[1]["cgst_amount"] == 6.25
|
||||
assert items[1]["sgst_amount"] == 6.25
|
||||
|
||||
def test_grand_total_and_tax_auto_deduction():
|
||||
raw_items = [
|
||||
{
|
||||
"description": "Item 1",
|
||||
"quantity": 10,
|
||||
"rate": 100.0,
|
||||
"amount": 1000.0,
|
||||
"cgst_amount": 25.0,
|
||||
"sgst_amount": 25.0
|
||||
},
|
||||
{
|
||||
"description": "Item 2",
|
||||
"quantity": 5,
|
||||
"rate": 200.0,
|
||||
"amount": 1000.0,
|
||||
"cgst_amount": 25.0,
|
||||
"sgst_amount": 25.0
|
||||
}
|
||||
]
|
||||
|
||||
# Case A: Missing grand_total, cgst, sgst
|
||||
res = SelfHealingEngine.heal(
|
||||
meta={"invoice_date": "01/08/2026"},
|
||||
fin={"roundoff": 0.50}, # subtotal and grand_total missing
|
||||
raw_items=raw_items
|
||||
)
|
||||
|
||||
fin = res["fin"]
|
||||
assert fin["cgst"] == 50.0
|
||||
assert fin["sgst"] == 50.0
|
||||
# subtotal = 2000.0, taxes = 100.0, roundoff = 0.50 -> 2100.50
|
||||
assert fin["grand_total"] == 2100.50
|
||||
|
||||
def test_mislabeled_subtotal_grand_total_reconciliation():
|
||||
raw_items = [
|
||||
{
|
||||
"description": "Item 1",
|
||||
"quantity": 10,
|
||||
"rate": 100.0,
|
||||
"amount": 1000.0,
|
||||
"cgst_amount": 25.0,
|
||||
"sgst_amount": 25.0
|
||||
}
|
||||
]
|
||||
|
||||
# Case B: extracted grand_total is 1000.0 (the taxable subtotal), but taxes are 50.0
|
||||
res = SelfHealingEngine.heal(
|
||||
meta={"invoice_date": "01/08/2026"},
|
||||
fin={
|
||||
"subtotal": 1000.0,
|
||||
"cgst": 25.0,
|
||||
"sgst": 25.0,
|
||||
"roundoff": 0.0,
|
||||
"grand_total": 1000.0 # Mislabeled
|
||||
},
|
||||
raw_items=raw_items
|
||||
)
|
||||
|
||||
fin = res["fin"]
|
||||
# Must be corrected to 1050.0
|
||||
assert fin["grand_total"] == 1050.0
|
||||
|
||||
def test_due_date_inference_from_credit_terms():
|
||||
lines = [
|
||||
{"text": "Invoice Date: 10/08/2026"},
|
||||
{"text": "Payment Terms: Credit 20 Days"},
|
||||
{"text": "Thank you for your business"}
|
||||
]
|
||||
|
||||
res = SelfHealingEngine.heal(
|
||||
meta={"invoice_date": "10/08/2026", "due_date": None},
|
||||
fin={},
|
||||
raw_items=[],
|
||||
all_ocr_lines=lines
|
||||
)
|
||||
|
||||
meta = res["meta"]
|
||||
# 10/08/2026 + 20 days = 30/08/2026
|
||||
assert meta["due_date"] == "30/08/2026"
|
||||
@@ -0,0 +1,188 @@
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
from app.ocr.table_extractor import TableExtractor
|
||||
|
||||
def test_table_extractor_synthetic():
|
||||
# Build synthetic bounding box elements representing a clean table
|
||||
# Columns at:
|
||||
# Description (x: 100-300), HSN (x: 400-500), Qty (x: 550-650), Rate (x: 700-800), Amount (x: 850-950)
|
||||
header_elements = [
|
||||
{"text": "Description of Goods", "box": [[100, 100], [300, 100], [300, 130], [100, 130]]},
|
||||
{"text": "HSN Code", "box": [[400, 100], [500, 100], [500, 130], [400, 130]]},
|
||||
{"text": "Quantity", "box": [[550, 100], [650, 100], [650, 130], [550, 130]]},
|
||||
{"text": "Rate", "box": [[700, 100], [800, 100], [800, 130], [700, 130]]},
|
||||
{"text": "Amount", "box": [[850, 100], [950, 100], [950, 130], [850, 130]]},
|
||||
]
|
||||
|
||||
# Row 1: Widget A, HSN 84713010, Qty 5, Rate 200, Amount 1000
|
||||
row1_elements = [
|
||||
{"text": "Widget A", "box": [[100, 160], [300, 160], [300, 190], [100, 190]]},
|
||||
{"text": "84713010", "box": [[400, 160], [500, 160], [500, 190], [400, 190]]},
|
||||
{"text": "5 pcs", "box": [[550, 160], [650, 160], [650, 190], [550, 190]]},
|
||||
{"text": "200.00", "box": [[700, 160], [800, 160], [800, 190], [700, 190]]},
|
||||
{"text": "1000.00", "box": [[850, 160], [950, 160], [950, 190], [850, 190]]},
|
||||
]
|
||||
|
||||
# Footer row
|
||||
footer_elements = [
|
||||
{"text": "Total", "box": [[700, 250], [800, 250], [800, 280], [700, 280]]},
|
||||
{"text": "1000.00", "box": [[850, 250], [950, 250], [950, 280], [850, 280]]},
|
||||
]
|
||||
|
||||
elements = header_elements + row1_elements + footer_elements
|
||||
|
||||
extractor = TableExtractor()
|
||||
result = extractor.extract_table(elements)
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["total_items"] == 1
|
||||
item = result["line_items"][0]
|
||||
assert "Widget A" in item["description"]
|
||||
assert item["hsn_code"] == "84713010"
|
||||
assert item["quantity"] == 5.0
|
||||
assert item["rate"] == 200.0
|
||||
assert item["amount"] == 1000.0
|
||||
assert item["math_verified"] is True
|
||||
assert result["table_math_verified"] is True
|
||||
assert result["calculated_subtotal"] == 1000.0
|
||||
|
||||
def test_empty_elements():
|
||||
extractor = TableExtractor()
|
||||
res = extractor.extract_table([])
|
||||
assert res["status"] == "empty"
|
||||
assert res["line_items"] == []
|
||||
|
||||
def test_no_header_elements():
|
||||
extractor = TableExtractor()
|
||||
res = extractor.extract_table([
|
||||
{"text": "Some random text", "box": [[0, 0], [10, 0], [10, 10], [0, 10]]}
|
||||
])
|
||||
assert res["status"] == "no_header_detected"
|
||||
assert res["line_items"] == []
|
||||
|
||||
def test_last_line_item_does_not_absorb_totals_row_bleedthrough():
|
||||
"""
|
||||
Regression test: ensures that when the last line item has a multi-line description
|
||||
and sits directly above a standalone subtotal/totals row (with or without a 'Total' label),
|
||||
the totals value (e.g. 28,800.00) is NOT absorbed into the product description.
|
||||
"""
|
||||
header_elements = [
|
||||
{"text": "Description of Goods", "box": [[100, 100], [300, 100], [300, 130], [100, 130]]},
|
||||
{"text": "HSN Code", "box": [[400, 100], [500, 100], [500, 130], [400, 130]]},
|
||||
{"text": "Quantity", "box": [[550, 100], [650, 100], [650, 130], [550, 130]]},
|
||||
{"text": "Rate", "box": [[700, 100], [800, 100], [800, 130], [700, 130]]},
|
||||
{"text": "Amount", "box": [[850, 100], [950, 100], [950, 130], [850, 130]]},
|
||||
]
|
||||
|
||||
# Item 1: Nuprep Gel
|
||||
row1 = [
|
||||
{"text": "1 Nuprep Gel", "box": [[100, 150], [300, 150], [300, 180], [100, 180]]},
|
||||
{"text": "30067000", "box": [[400, 150], [500, 150], [500, 180], [400, 180]]},
|
||||
{"text": "9 no", "box": [[550, 150], [650, 150], [650, 180], [550, 180]]},
|
||||
{"text": "1400.00", "box": [[700, 150], [800, 150], [800, 180], [700, 180]]},
|
||||
{"text": "12600.00", "box": [[850, 150], [950, 150], [950, 180], [850, 180]]},
|
||||
]
|
||||
|
||||
# Item 2: Paste -Ten 20 (multi-line description)
|
||||
row2_main = [
|
||||
{"text": "2 Paste -Ten 20", "box": [[100, 200], [300, 200], [300, 230], [100, 230]]},
|
||||
{"text": "30067000", "box": [[400, 200], [500, 200], [500, 230], [400, 230]]},
|
||||
{"text": "9 jar", "box": [[550, 200], [650, 200], [650, 230], [550, 230]]},
|
||||
{"text": "1800.00", "box": [[700, 200], [800, 200], [800, 230], [700, 230]]},
|
||||
{"text": "16200.00", "box": [[850, 200], [950, 200], [950, 230], [850, 230]]},
|
||||
]
|
||||
# Continuation row for Item 2 in description column
|
||||
row2_continuation = [
|
||||
{"text": "1 Box= 3 Jar (Weight-228 GM)", "box": [[100, 240], [350, 240], [350, 270], [100, 270]]},
|
||||
]
|
||||
|
||||
# Standalone Subtotal row sitting directly beneath the line items (no label, only amount)
|
||||
subtotal_row = [
|
||||
{"text": "28800.00", "box": [[850, 290], [950, 290], [950, 320], [850, 320]]},
|
||||
]
|
||||
|
||||
# Tax row below subtotal
|
||||
tax_row = [
|
||||
{"text": "Out Put CGST", "box": [[550, 340], [750, 340], [750, 370], [550, 370]]},
|
||||
{"text": "720.00", "box": [[850, 340], [950, 340], [950, 370], [850, 370]]},
|
||||
]
|
||||
|
||||
elements = header_elements + row1 + row2_main + row2_continuation + subtotal_row + tax_row
|
||||
|
||||
extractor = TableExtractor()
|
||||
result = extractor.extract_table(elements)
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["total_items"] == 2
|
||||
item2 = result["line_items"][1]
|
||||
|
||||
# Ensure the description contains the legitimate product spec but NOT the subtotal amount
|
||||
assert "Paste -Ten 20" in item2["description"]
|
||||
assert "1 Box= 3 Jar" in item2["description"]
|
||||
assert "28800" not in item2["description"]
|
||||
assert "28,800" not in item2["description"]
|
||||
assert item2["amount"] == 16200.0
|
||||
assert result["calculated_subtotal"] == 28800.0
|
||||
|
||||
def test_free_quantity_and_tax_derivation_in_table():
|
||||
"""
|
||||
Validates:
|
||||
1. Compound quantity '20+ 2' in quantity column extracts paid=20, free=2, total=22
|
||||
2. Embedded '20+ 2' in description extracts paid=20, free=2, total=22 and cleans description
|
||||
3. Row-level tax derivation: calculates cgst_amount & sgst_amount from rates
|
||||
4. Promotional item with rate=0 extracts free_quantity=qty and paid quantity=0
|
||||
"""
|
||||
header_elements = [
|
||||
{"text": "Description", "box": [[100, 100], [350, 100], [350, 130], [100, 130]]},
|
||||
{"text": "Qty", "box": [[400, 100], [480, 100], [480, 130], [400, 130]]},
|
||||
{"text": "Rate", "box": [[500, 100], [580, 100], [580, 130], [500, 130]]},
|
||||
{"text": "CGST %", "box": [[600, 100], [670, 100], [670, 130], [600, 130]]},
|
||||
{"text": "SGST %", "box": [[690, 100], [760, 100], [760, 130], [690, 130]]},
|
||||
{"text": "Amount", "box": [[780, 100], [880, 100], [880, 130], [780, 130]]},
|
||||
]
|
||||
|
||||
# Row 1: Compound qty column '20+ 2'
|
||||
row1 = [
|
||||
{"text": "FLUDAC 20MG 15 CAPS", "box": [[100, 150], [350, 150], [350, 180], [100, 180]]},
|
||||
{"text": "20+ 2", "box": [[400, 150], [480, 150], [480, 180], [400, 180]]},
|
||||
{"text": "48.71", "box": [[500, 150], [580, 150], [580, 180], [500, 180]]},
|
||||
{"text": "2.5", "box": [[600, 150], [670, 150], [670, 180], [600, 180]]},
|
||||
{"text": "2.5", "box": [[690, 150], [760, 150], [760, 180], [690, 180]]},
|
||||
{"text": "974.20", "box": [[780, 150], [880, 150], [880, 180], [780, 180]]},
|
||||
]
|
||||
|
||||
# Row 2: Free promotional item (rate 0, amount 0)
|
||||
row2 = [
|
||||
{"text": "PROMO SAMPLE PEN FREE", "box": [[100, 200], [350, 200], [350, 230], [100, 230]]},
|
||||
{"text": "5", "box": [[400, 200], [480, 200], [480, 230], [400, 230]]},
|
||||
{"text": "0.00", "box": [[500, 200], [580, 200], [580, 230], [500, 230]]},
|
||||
{"text": "0.0", "box": [[600, 200], [670, 200], [670, 230], [600, 230]]},
|
||||
{"text": "0.0", "box": [[690, 200], [760, 200], [760, 230], [690, 230]]},
|
||||
{"text": "0.00", "box": [[780, 200], [880, 200], [880, 230], [780, 230]]},
|
||||
]
|
||||
|
||||
# Footer
|
||||
footer = [
|
||||
{"text": "Total", "box": [[700, 260], [770, 260], [770, 290], [700, 290]]},
|
||||
{"text": "974.20", "box": [[780, 260], [880, 260], [880, 290], [780, 290]]},
|
||||
]
|
||||
|
||||
extractor = TableExtractor()
|
||||
res = extractor.extract_table(header_elements + row1 + row2 + footer)
|
||||
|
||||
assert res["status"] == "success"
|
||||
assert res["total_items"] == 2
|
||||
|
||||
it1 = res["line_items"][0]
|
||||
assert it1["quantity"] == 20.0
|
||||
assert it1["free_quantity"] == 2.0
|
||||
assert it1["total_quantity"] == 22.0
|
||||
assert it1["cgst_amount"] == 24.36
|
||||
assert it1["sgst_amount"] == 24.36
|
||||
|
||||
it2 = res["line_items"][1]
|
||||
assert it2["quantity"] == 0.0
|
||||
assert it2["free_quantity"] == 5.0
|
||||
assert it2["total_quantity"] == 5.0
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# tests/test_table_metrics.py
|
||||
import pytest
|
||||
from app.rrsi.table_metrics import (
|
||||
evaluate_table,
|
||||
TableEvaluationResult,
|
||||
TableStructureError
|
||||
)
|
||||
|
||||
def test_table_metrics_perfect_match():
|
||||
exp = [
|
||||
{"description": "ALBUCEL 20%", "hsn_sac": "30021290", "quantity": 60, "unit_price": "3700.00", "total_price": "222000.00"},
|
||||
{"description": "TELIPSA INJ", "hsn_sac": "30049099", "quantity": 120, "unit_price": "198.00", "total_price": "23760.00"}
|
||||
]
|
||||
pred = [
|
||||
{"description": "ALBUCEL 20%", "hsn_sac": "30021290", "quantity": 60, "unit_price": "3700.00", "total_price": "222000.00"},
|
||||
{"description": "TELIPSA INJ", "hsn_sac": "30049099", "quantity": 120, "unit_price": "198.00", "total_price": "23760.00"}
|
||||
]
|
||||
|
||||
res = evaluate_table(exp, pred)
|
||||
assert res.row_precision == 1.0
|
||||
assert res.row_recall == 1.0
|
||||
assert res.row_f1 == 1.0
|
||||
assert res.cell_f1 == 1.0
|
||||
assert len(res.structure_errors) == 0
|
||||
|
||||
def test_table_metrics_guard_none_none_matches():
|
||||
# If both expected and predicted have None/empty cells, it must NOT count as a positive cell match
|
||||
exp = [{"description": "Item 1", "hsn_sac": None, "unit": None, "quantity": 10, "unit_price": "50.00", "total_price": "500.00"}]
|
||||
pred = [{"description": "Item 1", "hsn_sac": None, "unit": None, "quantity": 10, "unit_price": "50.00", "total_price": "500.00"}]
|
||||
|
||||
res = evaluate_table(exp, pred)
|
||||
# Expected cells with values: description, quantity, unit_price, total_price (4 cells)
|
||||
# None cells should not artificially inflate cell matches
|
||||
assert res.total_expected_cells == 4
|
||||
assert res.correct_cells == 4
|
||||
assert res.cell_recall == 1.0
|
||||
|
||||
def test_table_metrics_row_split_and_merge():
|
||||
# Ground truth: 1 row with qty 10, total 1000
|
||||
# Prediction: 2 rows with qty 5, total 500 each (row split)
|
||||
exp = [
|
||||
{"description": "Item Alpha", "hsn_sac": "3004", "quantity": 10, "unit_price": "100.00", "total_price": "1000.00"}
|
||||
]
|
||||
pred = [
|
||||
{"description": "Item Alpha", "hsn_sac": "3004", "quantity": 5, "unit_price": "100.00", "total_price": "500.00"},
|
||||
{"description": "Item Alpha", "hsn_sac": "3004", "quantity": 5, "unit_price": "100.00", "total_price": "500.00"}
|
||||
]
|
||||
|
||||
res = evaluate_table(exp, pred)
|
||||
assert res.row_recall == 1.0 # One matched
|
||||
assert res.row_precision == 0.5 # 1 out of 2
|
||||
assert any(err.error_type == TableStructureError.ROW_SPLIT for err in res.structure_errors)
|
||||
|
||||
def test_table_metrics_column_shift():
|
||||
# Rate shifted into HSN column
|
||||
exp = [
|
||||
{"description": "Item Beta", "hsn_sac": "30049099", "quantity": 10, "unit_price": "150.00", "total_price": "1500.00"}
|
||||
]
|
||||
pred = [
|
||||
{"description": "Item Beta", "hsn_sac": "150.00", "quantity": 10, "unit_price": None, "total_price": "1500.00"}
|
||||
]
|
||||
|
||||
res = evaluate_table(exp, pred)
|
||||
assert any(err.error_type == TableStructureError.COLUMN_SHIFT for err in res.structure_errors)
|
||||
@@ -0,0 +1,132 @@
|
||||
# tests/test_template_similarity.py
|
||||
|
||||
import io
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw
|
||||
from app.preprocessing.template_similarity_detector import (
|
||||
compute_perceptual_hash,
|
||||
find_template_similar_images,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base_invoice_image():
|
||||
"""Generates a synthetic grayscale invoice-like image with header, boxes, and table lines."""
|
||||
img = Image.new("L", (400, 500), 255)
|
||||
draw = ImageDraw.Draw(img)
|
||||
# Header logo / box
|
||||
draw.rectangle([30, 20, 370, 70], fill=120)
|
||||
# Metadata box
|
||||
draw.rectangle([30, 90, 370, 160], outline=40, width=2)
|
||||
# Line items table
|
||||
draw.rectangle([30, 180, 370, 420], outline=40, width=2)
|
||||
for y in range(220, 420, 40):
|
||||
draw.line([30, y, 370, y], fill=100, width=1)
|
||||
for x in [100, 200, 300]:
|
||||
draw.line([x, 180, x, 420], fill=100, width=1)
|
||||
return img
|
||||
|
||||
|
||||
def test_recompressed_jpeg_detected_as_template_similar(tmp_path, base_invoice_image):
|
||||
"""Images sharing layout despite compression artifacts have distance <= 4."""
|
||||
p1 = tmp_path / "invoice_original.png"
|
||||
base_invoice_image.save(p1)
|
||||
|
||||
buf = io.BytesIO()
|
||||
base_invoice_image.save(buf, format="JPEG", quality=25)
|
||||
buf.seek(0)
|
||||
img_compressed = Image.open(buf)
|
||||
p2 = tmp_path / "invoice_recompressed.png"
|
||||
img_compressed.save(p2)
|
||||
|
||||
result = find_template_similar_images(str(tmp_path), threshold=4)
|
||||
|
||||
assert result["total_images_analyzed"] == 2
|
||||
assert result["total_template_similarity_pairs"] == 1
|
||||
pair = result["template_similarity_pairs"][0]
|
||||
assert pair["hamming_distance"] <= 4
|
||||
assert set([pair["file_1"], pair["file_2"]]) == {"invoice_original.png", "invoice_recompressed.png"}
|
||||
assert len(result["template_similarity_groups"]) == 1
|
||||
assert "NOT duplicate content" in result["note"]
|
||||
|
||||
|
||||
def test_minor_crop_detected_as_template_similar(tmp_path, base_invoice_image):
|
||||
"""A slightly cropped image sharing layout has distance <= 4."""
|
||||
p1 = tmp_path / "invoice_original.png"
|
||||
base_invoice_image.save(p1)
|
||||
|
||||
w, h = base_invoice_image.size
|
||||
crop_x = 2
|
||||
crop_y = 2
|
||||
img_cropped = base_invoice_image.crop((crop_x, crop_y, w - crop_x, h - crop_y))
|
||||
p2 = tmp_path / "invoice_cropped.png"
|
||||
img_cropped.save(p2)
|
||||
|
||||
result = find_template_similar_images(str(tmp_path), threshold=4)
|
||||
|
||||
assert result["total_images_analyzed"] == 2
|
||||
assert result["total_template_similarity_pairs"] == 1
|
||||
assert result["template_similarity_pairs"][0]["hamming_distance"] <= 4
|
||||
|
||||
|
||||
def test_borderline_similarity_pair_logged_separately(tmp_path, base_invoice_image):
|
||||
"""Pairs with distance between 5 and 8 should be logged in borderline_pairs, not template_similarity_pairs."""
|
||||
p1 = tmp_path / "invoice_original.png"
|
||||
base_invoice_image.save(p1)
|
||||
|
||||
w, h = base_invoice_image.size
|
||||
img_borderline = base_invoice_image.crop((5, 6, w - 5, h - 6))
|
||||
p2 = tmp_path / "invoice_borderline.png"
|
||||
img_borderline.save(p2)
|
||||
|
||||
result = find_template_similar_images(str(tmp_path), threshold=4, borderline_min=5, borderline_max=8)
|
||||
|
||||
assert result["total_images_analyzed"] == 2
|
||||
assert result["total_template_similarity_pairs"] == 0
|
||||
assert result["total_borderline_pairs"] == 1
|
||||
borderline_pair = result["borderline_pairs"][0]
|
||||
assert 5 <= borderline_pair["hamming_distance"] <= 8
|
||||
|
||||
|
||||
def test_different_images_not_flagged(tmp_path, base_invoice_image):
|
||||
"""Completely distinct visual layouts should not be flagged as template-similar or borderline."""
|
||||
p1 = tmp_path / "invoice.png"
|
||||
base_invoice_image.save(p1)
|
||||
|
||||
img_diff = Image.new("L", (400, 500), 255)
|
||||
draw = ImageDraw.Draw(img_diff)
|
||||
draw.ellipse([50, 50, 350, 450], fill=30)
|
||||
p2 = tmp_path / "circle_document.png"
|
||||
img_diff.save(p2)
|
||||
|
||||
result = find_template_similar_images(str(tmp_path), threshold=4, borderline_min=5, borderline_max=8)
|
||||
|
||||
assert result["total_images_analyzed"] == 2
|
||||
assert result["total_template_similarity_pairs"] == 0
|
||||
assert result["total_borderline_pairs"] == 0
|
||||
|
||||
|
||||
def test_target_files_filter(tmp_path, base_invoice_image):
|
||||
"""When target_files is specified, only the specified subset is evaluated."""
|
||||
p1 = tmp_path / "inv1.png"
|
||||
p2 = tmp_path / "inv2.png"
|
||||
p3 = tmp_path / "inv3.png"
|
||||
|
||||
base_invoice_image.save(p1)
|
||||
base_invoice_image.save(p2)
|
||||
base_invoice_image.save(p3)
|
||||
|
||||
result = find_template_similar_images(str(tmp_path), target_files=["inv1.png", "inv2.png"], threshold=4)
|
||||
|
||||
assert result["total_images_analyzed"] == 2
|
||||
assert result["total_template_similarity_pairs"] == 1
|
||||
assert result["template_similarity_pairs"][0]["file_1"] == "inv1.png"
|
||||
assert result["template_similarity_pairs"][0]["file_2"] == "inv2.png"
|
||||
|
||||
|
||||
def test_invalid_folder():
|
||||
"""Non-existent directory should return an error structure safely without raising exceptions."""
|
||||
result = find_template_similar_images("non_existent_folder_path")
|
||||
assert "error" in result
|
||||
assert result["total_images_analyzed"] == 0
|
||||
@@ -0,0 +1,80 @@
|
||||
# tests/test_validators.py
|
||||
import pytest
|
||||
import json
|
||||
from pathlib import Path
|
||||
from decimal import Decimal
|
||||
from app.validators import (
|
||||
ValidationStatus,
|
||||
ValidationResult,
|
||||
InvoiceArithmeticValidator,
|
||||
classify_reconciliation
|
||||
)
|
||||
|
||||
def test_validator_tristate_pass():
|
||||
validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00"))
|
||||
doc = {
|
||||
"invoice_amount": "118.00",
|
||||
"total_gst_amount": "18.00",
|
||||
"round_off": "0.00",
|
||||
"items": [
|
||||
{"total_price": "100.00", "Discount": "0.00"}
|
||||
]
|
||||
}
|
||||
res = validator.validate(doc)
|
||||
assert res.status == ValidationStatus.PASS
|
||||
assert res.is_valid is True
|
||||
|
||||
def test_validator_tristate_fail():
|
||||
validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00"))
|
||||
doc = {
|
||||
"invoice_amount": "200.00", # Wrong total
|
||||
"total_gst_amount": "18.00",
|
||||
"round_off": "0.00",
|
||||
"items": [
|
||||
{"total_price": "100.00", "Discount": "0.00"}
|
||||
]
|
||||
}
|
||||
res = validator.validate(doc)
|
||||
assert res.status == ValidationStatus.FAIL
|
||||
assert res.is_valid is False
|
||||
assert res.discrepancy > Decimal("50.0")
|
||||
|
||||
def test_validator_tristate_insufficient_data():
|
||||
validator = InvoiceArithmeticValidator()
|
||||
# Missing items and zero total
|
||||
res = validator.validate({"invoice_amount": None, "items": []})
|
||||
assert res.status == ValidationStatus.INSUFFICIENT_DATA
|
||||
assert res.is_valid is False
|
||||
|
||||
def test_validator_never_returns_true_on_exception():
|
||||
validator = InvoiceArithmeticValidator()
|
||||
# Malformed data
|
||||
res = validator.validate({"invoice_amount": "invalid_number", "items": "not_a_list"})
|
||||
assert res.status == ValidationStatus.INSUFFICIENT_DATA
|
||||
assert res.is_valid is False
|
||||
|
||||
def test_failing_invoices_reconciliation_diagnosis():
|
||||
# Analyze the 2 failing invoices: WMP/B/04531 and KP26264882
|
||||
validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00"))
|
||||
gt_dir = Path("data_private/ground_truth")
|
||||
if not gt_dir.exists():
|
||||
gt_dir = Path("data/ground_truth")
|
||||
|
||||
p_4531 = gt_dir / "invoice_4531_expected.json"
|
||||
p_kundan = gt_dir / "kundan_expected.json"
|
||||
if not p_4531.exists() or not p_kundan.exists():
|
||||
pytest.skip("Private ground truth files not present on fresh clone.")
|
||||
|
||||
with open(p_4531, "r", encoding="utf-8") as f:
|
||||
gt_4531 = json.load(f)
|
||||
|
||||
res_4531 = validator.validate(gt_4531)
|
||||
assert res_4531.status == ValidationStatus.PASS
|
||||
assert res_4531.is_valid is True
|
||||
|
||||
with open(p_kundan, "r", encoding="utf-8") as f:
|
||||
gt_kundan = json.load(f)
|
||||
|
||||
res_kundan = validator.validate(gt_kundan)
|
||||
assert res_kundan.status == ValidationStatus.PASS
|
||||
assert res_kundan.is_valid is True
|
||||
Reference in New Issue
Block a user