feat: add synthetic generator, benchmark tests, stage cache, and evaluator hardening
CI Pipeline & Git Hygiene / hygiene-and-tests (push) Canceled after 0s

This commit is contained in:
omkarande14
2026-10-06 11:30:38 +05:30
parent 673d181e68
commit 9d37e4f266
30 changed files with 2792 additions and 210 deletions
+143
View File
@@ -0,0 +1,143 @@
# tests/test_data_access_and_manifest.py
"""
Tests for DataAccessGate (Phase 1.4):
- Gating locked_test split with RRSI_FINAL_EVAL=1
- Refusing locked_test when RRSI_FINAL_EVAL is not set
- Manifest integrity validation:
1. Split overlap detection
2. Template straddling detection
3. Contaminated invoice detection in selection/test
4. Copy / page split consistency
- Real repository manifest verification
"""
import os
import json
import pytest
from pathlib import Path
from app.rrsi.data_access import DataAccessGate
class TestDataAccessGate:
@pytest.fixture
def mock_manifest_file(self, tmp_path):
manifest_data = {
"version": "1.0",
"manifest": [
{
"doc_id": "INV_DEV_01",
"template_group": "T01",
"split": "dev",
"contaminated": True,
"files": ["dev_01.png"]
},
{
"doc_id": "INV_SEL_01",
"template_group": "T02",
"split": "selection",
"contaminated": False,
"files": ["sel_01.png"]
},
{
"doc_id": "INV_TEST_01",
"template_group": "T03",
"split": "locked_test",
"contaminated": False,
"files": ["test_01.png"]
}
]
}
man_path = tmp_path / "mock_manifest.json"
with open(man_path, "w", encoding="utf-8") as f:
json.dump(manifest_data, f)
return man_path
def test_locked_test_refused_without_env_var(self, mock_manifest_file, monkeypatch):
monkeypatch.delenv("RRSI_FINAL_EVAL", raising=False)
gate = DataAccessGate(mock_manifest_file)
# dev and selection work normally
dev_invoices = gate.get_invoices_for_split("dev")
assert len(dev_invoices) == 1
assert dev_invoices[0]["doc_id"] == "INV_DEV_01"
sel_invoices = gate.get_invoices_for_split("selection")
assert len(sel_invoices) == 1
assert sel_invoices[0]["doc_id"] == "INV_SEL_01"
# locked_test MUST raise PermissionError
with pytest.raises(PermissionError, match="ACCESS DENIED: 'locked_test' split is locked"):
gate.get_invoices_for_split("locked_test")
def test_locked_test_allowed_with_env_var(self, mock_manifest_file, monkeypatch):
monkeypatch.setenv("RRSI_FINAL_EVAL", "1")
gate = DataAccessGate(mock_manifest_file)
test_invoices = gate.get_invoices_for_split("locked_test")
assert len(test_invoices) == 1
assert test_invoices[0]["doc_id"] == "INV_TEST_01"
def test_template_straddling_detected(self, tmp_path):
bad_manifest = {
"manifest": [
{"doc_id": "INV_1", "template_group": "T01", "split": "dev", "files": ["1.png"]},
{"doc_id": "INV_2", "template_group": "T01", "split": "selection", "files": ["2.png"]}
]
}
p = tmp_path / "straddle.json"
p.write_text(json.dumps(bad_manifest), encoding="utf-8")
gate = DataAccessGate(p)
is_valid, errors = gate.verify_manifest_integrity()
assert not is_valid
assert any("Template straddling" in e for e in errors)
def test_split_overlap_detected(self, tmp_path):
bad_manifest = {
"manifest": [
{"doc_id": "INV_1", "template_group": "T01", "split": "dev", "files": ["1.png"]},
{"doc_id": "INV_1", "template_group": "T01", "split": "selection", "files": ["1.png"]}
]
}
p = tmp_path / "overlap.json"
p.write_text(json.dumps(bad_manifest), encoding="utf-8")
gate = DataAccessGate(p)
is_valid, errors = gate.verify_manifest_integrity()
assert not is_valid
assert any("Split overlap" in e for e in errors)
def test_contaminated_invoice_in_selection_detected(self, tmp_path):
bad_manifest = {
"manifest": [
{
"doc_id": "INV_BAD",
"template_group": "T02",
"split": "selection",
"contaminated": True,
"files": ["bad.png"]
}
]
}
p = tmp_path / "contam.json"
p.write_text(json.dumps(bad_manifest), encoding="utf-8")
gate = DataAccessGate(p)
is_valid, errors = gate.verify_manifest_integrity()
assert not is_valid
assert any("Contaminated invoice" in e for e in errors)
# Also get_invoices_for_split should reject it
with pytest.raises(ValueError, match="INTEGRITY VIOLATION"):
gate.get_invoices_for_split("selection")
def test_real_workspace_manifest_integrity(self):
"""Verifies the actual tracked manifest in the repository."""
manifest_path = Path("data/manifest.json")
if not manifest_path.exists():
pytest.skip("data/manifest.json not found")
gate = DataAccessGate(manifest_path)
is_valid, errors = gate.verify_manifest_integrity()
assert is_valid, f"Repository manifest integrity errors: {errors}"
@@ -0,0 +1,117 @@
# tests/test_replacement_constants_synthetic.py
"""
Synthetic layout tests demonstrating that replacement constants:
- 0.50 (mid_x page width ratio)
- 0.35 (header_y_limit page height ratio)
- 0.20 (missing description gap threshold)
- 0.35 (missing quantity+description gap threshold)
operate invariant to absolute image size, resolution, padding, and aspect ratio.
"""
import pytest
from app.ocr.self_healing import SelfHealingEngine
from app.ocr.table_extractor import TableExtractor
class TestReplacementConstantsSynthetic:
"""Verifies that ratio-based heuristics do not depend on fixed pixel dimensions."""
@pytest.mark.parametrize("width,height,scale_factor", [
(1000.0, 1400.0, 1.0), # Standard 1000x1400
(2500.0, 3500.0, 2.5), # High-resolution 300 DPI scan
(800.0, 2400.0, 0.8), # Narrow aspect voucher
(4000.0, 2500.0, 4.0), # Landscape wide banner
])
def test_self_healing_gstin_scale_invariance(self, width, height, scale_factor):
"""Seller on left (x < 0.5*W) and Buyer on right (x > 0.5*W) or lower (y > 0.35*H)."""
engine = SelfHealingEngine()
# Synthetic OCR tokens placed proportionally across the page
seller_gstin = "27AAPFU0939F1ZV"
buyer_gstin = "27AAPFU0939F1ZW"
seller_box = [[width * 0.1, height * 0.1], [width * 0.3, height * 0.1], [width * 0.3, height * 0.15], [width * 0.1, height * 0.15]]
buyer_box = [[width * 0.6, height * 0.1], [width * 0.85, height * 0.1], [width * 0.85, height * 0.15], [width * 0.6, height * 0.15]]
footer_box = [[width * 0.1, height * 0.95], [width * 0.9, height * 0.95], [width * 0.9, height * 0.98], [width * 0.1, height * 0.98]]
# Case A: Seller top-left, Buyer top-right
ocr_lines_side_by_side = [
{"text": f"GSTIN: {seller_gstin}", "bbox": seller_box},
{"text": f"Customer GST: {buyer_gstin}", "bbox": buyer_box},
{"text": "Authorised Signatory Total", "bbox": footer_box}
]
meta = {"vendor": {}, "buyer": {}}
res_side = engine.heal(meta, {}, [], all_ocr_lines=ocr_lines_side_by_side)
healed_side = res_side["meta"]
assert healed_side["vendor"].get("gstin") == seller_gstin, f"Failed at {width}x{height}: Seller GSTIN not assigned"
assert healed_side["buyer"].get("gstin") == buyer_gstin, f"Failed at {width}x{height}: Buyer GSTIN not assigned"
# Case B: Seller top-left (y < 0.35 * height), Buyer bottom-left (y > 0.35 * height)
buyer_box_stacked = [[width * 0.1, height * 0.40], [width * 0.35, height * 0.40], [width * 0.35, height * 0.45], [width * 0.1, height * 0.45]]
ocr_lines_stacked = [
{"text": f"GSTIN: {seller_gstin}", "bbox": seller_box},
{"text": f"Billed To: {buyer_gstin}", "bbox": buyer_box_stacked},
{"text": "Authorised Signatory Total", "bbox": footer_box}
]
meta_stacked = {"vendor": {}, "buyer": {}}
res_stacked = engine.heal(meta_stacked, {}, [], all_ocr_lines=ocr_lines_stacked)
healed_stacked = res_stacked["meta"]
assert healed_stacked["vendor"].get("gstin") == seller_gstin, f"Stacked layout failed at {width}x{height}"
assert healed_stacked["buyer"].get("gstin") == buyer_gstin, f"Stacked layout failed at {width}x{height}"
@pytest.mark.parametrize("table_width,table_left", [
(600.0, 50.0),
(1200.0, 50.0),
(2400.0, 100.0),
(3600.0, 150.0)
])
def test_table_extractor_gap_ratio_synthetic(self, table_width, table_left):
"""Verifies column inference thresholds: narrow (<0.20), medium (0.20-0.35), wide (>0.35)."""
extractor = TableExtractor()
def make_items(gap_width):
b_min = table_left + gap_width
b_max = b_min + 80.0
a_min = table_left + table_width - 80.0
a_max = table_left + table_width
return [
{
"text": "BATCH",
"box": [[b_min, 300.0], [b_max, 300.0], [b_max, 320.0], [b_min, 320.0]]
},
{
"text": "AMOUNT",
"box": [[a_min, 300.0], [a_max, 300.0], [a_max, 320.0], [a_min, 320.0]]
}
]
# 1. Narrow gap (< 0.20 of table width): No missing columns inferred
narrow_gap = table_width * 0.10
hdr_narrow = extractor._find_table_header(make_items(narrow_gap))
assert hdr_narrow is not None
names_narrow = {c["name"] for c in hdr_narrow["columns"]}
assert "description" not in names_narrow, "Narrow gap should not infer description"
assert "quantity" not in names_narrow, "Narrow gap should not infer quantity"
# 2. Medium gap (0.20 < gap <= 0.35 of table width): Description inferred, quantity omitted
med_gap = table_width * 0.25
hdr_med = extractor._find_table_header(make_items(med_gap))
assert hdr_med is not None
names_med = {c["name"] for c in hdr_med["columns"]}
assert "description" in names_med, "Medium gap must infer description"
assert "quantity" not in names_med, "Medium gap should not infer quantity"
# 3. Wide gap (> 0.35 of table width): Both quantity and description inferred
wide_gap = table_width * 0.45
hdr_wide = extractor._find_table_header(make_items(wide_gap))
assert hdr_wide is not None
names_wide = {c["name"] for c in hdr_wide["columns"]}
assert "description" in names_wide, "Wide gap must infer description"
assert "quantity" in names_wide, "Wide gap must infer quantity"
# Check ordering: quantity must precede description, which must precede batch
ordered_names = [c["name"] for c in hdr_wide["columns"]]
assert ordered_names.index("quantity") < ordered_names.index("description") < ordered_names.index("batch")
+214
View File
@@ -0,0 +1,214 @@
# tests/test_screening_ast.py
"""
Tests for RRSI Leakage Screening (B1, B2, B3, B4, B5):
- Adversarial cases caught:
1. Partial vendor name / 8-gram matching
2. Suffix variation
3. Concatenated literal ('WMP/B/' + '04531')
4. Regex with wildcards / re.compile argument
5. Bare number matching forbidden hash
6. box[1] > 840 coordinate hardcoding
- Benign cases NOT flagged:
1. [255, 255, 255, 255]
2. cv2.resize(img, (1000, 1000))
3. Whitelisted kernel sizes (3, 5, 7)
- B4: Paired-bootstrap dev vs selection gain comparison
- B5: PruningAnalyzer hit counter evidence threshold & ablation evaluation
"""
import pytest
import hashlib
from app.rrsi.screening import LeakageScreening, PruningAnalyzer
class TestScreeningAST:
SALT = "TEST_SALT_2026_"
@pytest.fixture
def forbidden_store(self):
# Synthetic sample ground truth
mock_gt = [{
"invoice_number": "SYNTH-04531",
"seller_name": "ACME INDUSTRIAL SUPPLIES LTD",
"seller_gstin": "27AAPFU0939F1ZV",
"total_amount": "54421.00",
"items": [
{"description": "PRECISION LATHE CHUCK", "amount": "25000.00"}
]
}]
store = LeakageScreening.build_runtime_forbidden_store(mock_gt, salt=self.SALT)
return store
def test_caught_partial_vendor_name_ngram(self, forbidden_store):
"""Adversarial Case 1: 8-gram of vendor name ('acmeindu') caught via char-8-gram hash."""
code = "if 'acmeindu' in raw_text: return True"
passed, findings = LeakageScreening.audit_code_changes(
code,
salt=forbidden_store["salt"],
forbidden_hashes=set(forbidden_store["hashes"]),
forbidden_ngrams=set(forbidden_store["ngrams"])
)
assert not passed
assert any("DATA LEAKAGE DETECTED" in f for f in findings)
def test_caught_concatenated_literal(self, forbidden_store):
"""Adversarial Case 3: Constant-folded concatenation 'SYNTH-' + '04531' caught."""
code = "inv_target = 'SYNTH-' + '04531'"
passed, findings = LeakageScreening.audit_code_changes(
code,
salt=forbidden_store["salt"],
forbidden_hashes=set(forbidden_store["hashes"]),
forbidden_ngrams=set(forbidden_store["ngrams"])
)
assert not passed
assert any("DATA LEAKAGE DETECTED" in f for f in findings)
def test_caught_fstring_part(self, forbidden_store):
"""Adversarial Case: f-string part containing sensitive token."""
code = "pattern = f'SYNTH-04531_{suffix}'"
passed, findings = LeakageScreening.audit_code_changes(
code,
salt=forbidden_store["salt"],
forbidden_hashes=set(forbidden_store["hashes"]),
forbidden_ngrams=set(forbidden_store["ngrams"])
)
assert not passed
assert any("DATA LEAKAGE DETECTED" in f for f in findings)
def test_caught_regex_compile_forbidden(self, forbidden_store):
"""Adversarial Case 4: Regex argument containing sensitive token."""
code = "rgx = re.compile(r'ACME INDUSTRIAL SUPPLIES.*')"
passed, findings = LeakageScreening.audit_code_changes(
code,
salt=forbidden_store["salt"],
forbidden_hashes=set(forbidden_store["hashes"]),
forbidden_ngrams=set(forbidden_store["ngrams"])
)
assert not passed
assert any("DATA LEAKAGE DETECTED" in f for f in findings)
def test_caught_bare_number(self, forbidden_store):
"""Adversarial Case 5: Bare amount number 54421.00 from forbidden set."""
code = "if abs(amt - 54421.00) < 0.01: pass"
passed, findings = LeakageScreening.audit_code_changes(
code,
salt=forbidden_store["salt"],
forbidden_hashes=set(forbidden_store["hashes"]),
forbidden_ngrams=set(forbidden_store["ngrams"])
)
assert not passed
assert any("DATA LEAKAGE DETECTED" in f for f in findings)
def test_caught_box_coordinate_comparison(self):
"""Adversarial Case 6: Missed case 'box[1] > 840' must be caught!"""
code = "if box[1] > 840:\n return 'footer'"
passed, findings = LeakageScreening.audit_code_changes(code)
assert not passed
assert any("COORDINATE OVERFITTING DETECTED" in f for f in findings)
def test_caught_vendor_conditional_branch(self):
"""Vendor-conditional gating on specific string literal >= 6 chars."""
code = "if vendor_name == 'UniqueCustomVendor':\n parse_custom_layout()"
passed, findings = LeakageScreening.audit_code_changes(code)
assert not passed
assert any("VENDOR-CONDITIONAL BRANCH DETECTED" in f for f in findings)
def test_benign_color_mask_not_flagged(self):
"""Benign Case 1: [255, 255, 255, 255] color mask should NOT be flagged."""
code = "mask = [255, 255, 255, 255]"
passed, findings = LeakageScreening.audit_code_changes(code)
assert passed, f"Benign color mask was falsely flagged: {findings}"
def test_benign_cv2_resize_not_flagged(self):
"""Benign Case 2: cv2.resize(img, (1000, 1000)) should NOT be flagged."""
code = "resized = cv2.resize(img, (1000, 1000))"
passed, findings = LeakageScreening.audit_code_changes(code)
assert passed, f"Benign cv2.resize was falsely flagged: {findings}"
def test_benign_relative_coordinates_not_flagged(self):
"""Benign Case: Ratio-based coordinate logic (e.g. ymin > height * 0.35)."""
code = "if ymin > page_height * 0.35:\n return 'lower_band'"
passed, findings = LeakageScreening.audit_code_changes(code)
assert passed, f"Relative ratio was falsely flagged: {findings}"
def test_diff_filtering_scans_only_added_lines(self):
"""Diff parser tests that removed (-) or context lines are not flagged."""
diff = """
diff --git a/app/ocr/pipeline.py b/app/ocr/pipeline.py
--- a/app/ocr/pipeline.py
+++ b/app/ocr/pipeline.py
@@ -10,3 +10,3 @@
-if box[1] > 840:
+if ymin > page_height * 0.5:
return True
"""
passed, findings = LeakageScreening.audit_code_changes(diff)
assert passed, f"Diff added line was clean but flagged: {findings}"
def test_b4_dev_vs_selection_gain_comparison(self):
"""B4: Selection CI lower bound <= 0 or wide gap rejected."""
# Case A: Selection CI lower bound <= 0 -> Reject
passed_a, msg_a = LeakageScreening.compare_dev_vs_selection_gain(
dev_gain=0.04, selection_gain=0.02, selection_ci_lower=-0.005
)
assert not passed_a
assert "CI lower bound" in msg_a
# Case B: Gap > 0.05 -> Reject
passed_b, msg_b = LeakageScreening.compare_dev_vs_selection_gain(
dev_gain=0.10, selection_gain=0.03, selection_ci_lower=0.01, max_gap=0.05
)
assert not passed_b
assert "Dev-selection gap" in msg_b
# Case C: Valid generalization (CI > 0, gap <= 0.05) -> Accept
passed_c, msg_c = LeakageScreening.compare_dev_vs_selection_gain(
dev_gain=0.04, selection_gain=0.03, selection_ci_lower=0.008, max_gap=0.05
)
assert passed_c
def test_b5_pruning_analyzer_insufficient_evidence(self):
"""B5: Below 40 docs or 10 templates, returns INSUFFICIENT_EVIDENCE."""
rule_counts = {"rule_gst_footer": 0, "rule_hsn_prefix": 15}
res = PruningAnalyzer.audit_rule_ablation_candidates(
rule_hit_counts=rule_counts,
corpus_doc_count=25,
corpus_template_count=8,
min_docs=40,
min_templates=10
)
assert res["status"] == "INSUFFICIENT_EVIDENCE"
assert len(res["candidates"]) == 0
def test_b5_pruning_analyzer_candidates_identified(self):
"""B5: When corpus is sufficient, zero-hit rules identified as ablation candidates."""
rule_counts = {"rule_gst_footer": 0, "rule_hsn_prefix": 15}
res = PruningAnalyzer.audit_rule_ablation_candidates(
rule_hit_counts=rule_counts,
corpus_doc_count=45,
corpus_template_count=12,
min_docs=40,
min_templates=10
)
assert res["status"] == "CANDIDATES_IDENTIFIED"
assert res["candidates"] == ["rule_gst_footer"]
def test_b5_ablation_acceptance_evaluation(self):
"""B5: Ablation requires within-noise score change and cost drop."""
# 1. Score dropped beyond noise -> Reject
passed_1, _ = PruningAnalyzer.evaluate_ablation_acceptance(
delta_accuracy=-2.5, noise_sd=0.5, cost_delta=-0.3
)
assert not passed_1
# 2. Cost did not drop -> Reject
passed_2, _ = PruningAnalyzer.evaluate_ablation_acceptance(
delta_accuracy=0.1, noise_sd=0.5, cost_delta=0.0
)
assert not passed_2
# 3. Within noise and cost dropped -> Accept
passed_3, _ = PruningAnalyzer.evaluate_ablation_acceptance(
delta_accuracy=-0.2, noise_sd=0.5, cost_delta=-0.4
)
assert passed_3
+3 -3
View File
@@ -134,7 +134,7 @@ def test_mislabeled_subtotal_grand_total_reconciliation():
# Must be corrected to 1050.0
assert fin["grand_total"] == 1050.0
def test_due_date_inference_from_credit_terms():
def test_due_date_not_synthesized_from_credit_terms():
lines = [
{"text": "Invoice Date: 10/08/2026"},
{"text": "Payment Terms: Credit 20 Days"},
@@ -149,5 +149,5 @@ def test_due_date_inference_from_credit_terms():
)
meta = res["meta"]
# 10/08/2026 + 20 days = 30/08/2026
assert meta["due_date"] == "30/08/2026"
# Due date must NOT be synthesized from credit terms; only reported when explicitly printed
assert meta["due_date"] is None
+68
View File
@@ -0,0 +1,68 @@
# tests/test_stage_cache.py
"""
Unit tests for OCRStageCache (Phase 1.5):
- Cache put and get roundtrip
- Automatic key generation from image sha256 + engine + version + preprocess hash
- Cold vs warm timing measurement
- Cache invalidation / clearing
"""
import time
import pytest
from pathlib import Path
from app.ocr.stage_cache import OCRStageCache
class TestStageCache:
@pytest.fixture
def cache_env(self, tmp_path):
cache_dir = tmp_path / "ocr_cache"
cache = OCRStageCache(cache_dir=cache_dir, enabled=True)
return cache, cache_dir
def test_cache_put_and_get(self, cache_env):
cache, _ = cache_env
img_sha = "abc123def456"
dummy_lines = [
{"text": "INVOICE NO: 1234", "confidence": 0.99, "box": [[10, 10], [100, 10], [100, 30], [10, 30]]},
{"text": "TOTAL: 5000.00", "confidence": 0.98, "box": [[10, 40], [100, 40], [100, 60], [10, 60]]}
]
# Cold get returns None
assert cache.get(img_sha, "PaddleOCR", "v1.0") is None
# Put lines into cache
cache.put(img_sha, "PaddleOCR", "v1.0", dummy_lines)
# Warm get retrieves cached lines
retrieved = cache.get(img_sha, "PaddleOCR", "v1.0")
assert retrieved is not None
assert len(retrieved) == 2
assert retrieved[0]["text"] == "INVOICE NO: 1234"
def test_cache_key_invalidation_on_version_or_engine_change(self, cache_env):
cache, _ = cache_env
img_sha = "same_image_sha_999"
dummy_lines = [{"text": "TEST LINE", "box": []}]
cache.put(img_sha, "PaddleOCR", "v1.0", dummy_lines)
# Changing engine name -> cache miss
assert cache.get(img_sha, "Tesseract", "v1.0") is None
# Changing engine version -> cache miss
assert cache.get(img_sha, "PaddleOCR", "v2.0") is None
# Changing preprocess config -> cache miss
assert cache.get(img_sha, "PaddleOCR", "v1.0", preprocess_config_hash="v2_contrast") is None
def test_cache_clear(self, cache_env):
cache, _ = cache_env
cache.put("sha_1", "PaddleOCR", "v1.0", [{"text": "A"}])
cache.put("sha_2", "PaddleOCR", "v1.0", [{"text": "B"}])
cleared_count = cache.clear()
assert cleared_count == 2
assert cache.get("sha_1", "PaddleOCR", "v1.0") is None
assert cache.get("sha_2", "PaddleOCR", "v1.0") is None
+41
View File
@@ -0,0 +1,41 @@
# tests/test_synthetic_benchmarker.py
"""
Synthetic fixture tests for DualEngineBenchmarker.
Tests key entity extraction and consensus calculation on synthetic generated images.
Uses whitelisted synthetic tokens only.
"""
import pytest
from pathlib import Path
from PIL import Image, ImageDraw
from app.ocr.dual_engine_benchmarker import DualEngineBenchmarker
def test_synthetic_extract_key_entities():
synthetic_text = """
TAX INVOICE
SYNTHETIC SUPPLIERS PVT LTD
GSTIN No.: 27AAPFU0939F1ZV
Invoice No. SYNTH-9876
Invoice Date: 26/08/2026
Total Amount: 14,520.50
"""
entities = DualEngineBenchmarker.extract_key_entities(synthetic_text)
assert "27AAPFU0939F1ZV" in entities["gstin"]
assert any("SYNTH-9876" in inv for inv in entities["invoice_numbers"])
assert any("26/08/2026" in d for d in entities["dates"])
assert "14520.50" in entities["totals"]
def test_synthetic_consensus_scoring_logic(tmp_path):
dummy_img_path = tmp_path / "synthetic_test_invoice.png"
img = Image.new("RGB", (600, 200), color="white")
draw = ImageDraw.Draw(img)
draw.text((20, 20), "Invoice No: SYNTH-999\nGSTIN: 27AAPFU0939F1ZV\nTotal: 500.00", fill="black")
img.save(dummy_img_path)
benchmarker = DualEngineBenchmarker(use_gpu=False)
comp = benchmarker.compare_image(dummy_img_path)
assert "paddle_metrics" in comp
assert "tesseract_metrics" in comp
assert "consensus" in comp
assert 0.0 <= comp["consensus_score"] <= 100.0
@@ -0,0 +1,111 @@
# tests/test_synthetic_dual_copy_and_regressions.py
"""
Synthetic test fixture equivalent for dual-copy detection and pipeline regressions.
Validates date slash normalization, dual-copy segmentation, synthetic parties extraction,
and schema validation using whitelisted synthetic constants.
"""
from pathlib import Path
import pytest
from PIL import Image, ImageDraw, ImageFont
from app.preprocessing.copy_selector import DualCopySelector
from app.ocr.output_formatter import normalize_date_slashes, format_official_output
from app.ocr.schema_mapper import SchemaMapper
from app.ocr.invoice_pipeline import InvoicePipeline
DUMMY_VENDOR_GSTIN = "27AAPFU0939F1ZV"
DUMMY_BUYER_GSTIN = "27AAPFU0939F1ZW"
DUMMY_PAN = "AAPFU0939F"
def test_date_normalization_regressions():
assert normalize_date_slashes("27-Aug-26") == "27/08/2026"
assert normalize_date_slashes("20/08/26") == "20/08/2026"
assert normalize_date_slashes("26/06/2026") == "26/06/2026"
assert normalize_date_slashes("15-Sep-2026") == "15/09/2026"
assert normalize_date_slashes("2/29") == "2/29" # Unaltered 2-part string
def test_synthetic_dual_copy_detection(tmp_path):
"""
Renders an in-memory two-part composite page (Top: Original for Supplier, Bottom: Customer Copy)
and verifies DualCopySelector identifies and segments the boundary.
"""
img = Image.new("L", (1200, 2400), color=255)
draw = ImageDraw.Draw(img)
# Top Copy
draw.text((100, 100), "TAX INVOICE - SUPPLIER COPY", fill=0)
draw.text((100, 200), f"Seller: GLOBAL PHARMA | GSTIN: {DUMMY_VENDOR_GSTIN}", fill=0)
draw.text((100, 300), f"Buyer: ACME HEALTH | GSTIN: {DUMMY_BUYER_GSTIN}", fill=0)
draw.text((100, 500), "Item: Amox 500mg | Qty: 100 | Amount: 1000.00", fill=0)
# Horizontal boundary line
draw.line([(0, 1200), (1200, 1200)], fill=0, width=4)
# Bottom Copy
draw.text((100, 1300), "TAX INVOICE - CUSTOMER COPY", fill=0)
draw.text((100, 1400), f"Seller: GLOBAL PHARMA | GSTIN: {DUMMY_VENDOR_GSTIN}", fill=0)
draw.text((100, 1500), f"Buyer: ACME HEALTH | GSTIN: {DUMMY_BUYER_GSTIN}", fill=0)
draw.text((100, 1700), "Item: Amox 500mg | Qty: 100 | Amount: 1000.00", fill=0)
synth_img_path = tmp_path / "dual_copy_synthetic.png"
img.save(synth_img_path)
selector = DualCopySelector()
res = selector.inspect_and_select(synth_img_path)
assert res is not None
assert hasattr(res, "is_dual_copy")
def test_parties_extraction_synthetic():
"""Validates spatial extraction of seller and buyer entities from synthetic OCR lines."""
lines = [
{"text": "ACME PHARMA DISTRIBUTORS", "box": [[50, 50], [400, 50], [400, 80], [50, 80]]},
{"text": f"GSTIN: {DUMMY_VENDOR_GSTIN}", "box": [[50, 90], [350, 90], [350, 120], [50, 120]]},
{"text": "Customer Name :", "box": [[600, 50], [800, 50], [800, 80], [600, 80]]},
{"text": "CITY GENERAL HOSPITAL", "box": [[600, 90], [950, 90], [950, 120], [600, 120]]},
{"text": f"GSTIN: {DUMMY_BUYER_GSTIN}", "box": [[600, 130], [900, 130], [900, 160], [600, 160]]}
]
parties = InvoicePipeline._extract_parties_metadata(lines)
assert parties["vendor_name"] == "ACME PHARMA DISTRIBUTORS"
assert parties["vendor_gstin"] == DUMMY_VENDOR_GSTIN
assert "CITY GENERAL HOSPITAL" in parties["buyer_name"]
assert parties["buyer_gstin"] == DUMMY_BUYER_GSTIN
def test_official_matches_ground_truth_synthetic():
"""Validates SchemaMapper accuracy report between synthetic GT and synthetic system output."""
gt_json = {
"invoice_number": "INV-SYNTH-100",
"invoice_date": "20/08/2026",
"customer_name": "CITY GENERAL HOSPITAL",
"customer_gstin": DUMMY_BUYER_GSTIN,
"seller_name": "ACME PHARMA DISTRIBUTORS",
"seller_gstin": DUMMY_VENDOR_GSTIN,
"invoice_amount": "1050.00",
"round_off": "0.00",
"total_quantity": 10,
"total_cgst_amount": "25.00",
"total_sgst_amount": "25.00",
"items": [
{
"description": "Synthetic Product A",
"quantity": 10,
"unit_price": "100.00",
"total_price": "1000.00",
"hsn_sac": "30049099"
}
]
}
out_json = dict(gt_json)
mapper = SchemaMapper()
report = mapper.compare(ground_truth=gt_json, system_output=out_json)
metrics = report["metrics"]
assert metrics["overall_accuracy_pct"] == 100.0
assert metrics["header_accuracy_pct"] == 100.0
assert metrics["line_item_accuracy_pct"] == 100.0
+46
View File
@@ -0,0 +1,46 @@
# tests/test_synthetic_generator.py
"""
Unit tests for SyntheticInvoiceGenerator (Phase 1.6):
- Mathematical integrity: Taxable + GST + Freight + RoundOff == Total
- Deterministic reproducibility given seed
- Correct schema attributes
- PIL image rendering and dimensions
"""
import pytest
from decimal import Decimal
from app.rrsi.synthetic_generator import SyntheticInvoiceGenerator
from app.validators import InvoiceArithmeticValidator, ValidationStatus
class TestSyntheticGenerator:
def test_arithmetic_consistency(self):
gen = SyntheticInvoiceGenerator(seed=123)
validator = InvoiceArithmeticValidator()
for i in range(1, 10):
data = gen.generate_invoice_data(invoice_idx=i)
# Reconcile via official validator
val_res = validator.validate(data)
assert val_res.status == ValidationStatus.PASS, f"Synthetic invoice {i} failed arithmetic check: {val_res.error_message}"
assert val_res.is_valid is True
def test_seed_determinism(self):
gen1 = SyntheticInvoiceGenerator(seed=999)
gen2 = SyntheticInvoiceGenerator(seed=999)
d1 = gen1.generate_invoice_data(invoice_idx=1)
d2 = gen2.generate_invoice_data(invoice_idx=1)
assert d1["invoice_number"] == d2["invoice_number"]
assert d1["total_amount"] == d2["total_amount"]
assert len(d1["items"]) == len(d2["items"])
def test_image_rendering(self, tmp_path):
gen = SyntheticInvoiceGenerator(seed=42)
img, data = gen.generate_sample(invoice_idx=5, output_dir=tmp_path, add_noise=True)
assert img.size == (1200, 1600)
assert (tmp_path / "synth_0005.png").exists()
assert (tmp_path / "synth_0005_gt.json").exists()
@@ -0,0 +1,136 @@
# tests/test_synthetic_orientation_corrector.py
"""
Synthetic test fixture equivalent for OrientationCorrector.
Validates OSD detection, 90/180/270 rotation handling, confidence filtering,
and batch folder processing on dynamically rendered synthetic invoices using whitelisted constants.
"""
import shutil
from pathlib import Path
import pytest
from PIL import Image, ImageDraw, ImageFont
import pytesseract
from app.preprocessing.orientation_corrector import (
detect_and_correct_orientation,
process_folder_orientation,
)
DUMMY_VENDOR_GSTIN = "27AAPFU0939F1ZV"
@pytest.fixture
def tesseract_available():
"""Checks whether tesseract binary is installed and operational."""
cmd = shutil.which("tesseract")
if not cmd and not Path(r"C:\Program Files\Tesseract-OCR\tesseract.exe").exists():
pytest.skip("Tesseract OCR binary not found on host environment")
return True
@pytest.fixture
def synthetic_invoice_image():
"""
Generates a realistic invoice-like image with multiple text lines,
numbers, tables, and varied typography suitable for Tesseract OSD.
"""
img = Image.new("L", (1400, 1800), color=255)
draw = ImageDraw.Draw(img)
try:
font_large = ImageFont.truetype("arial.ttf", 36)
font_med = ImageFont.truetype("arial.ttf", 24)
except Exception:
font_large = font_med = ImageFont.load_default()
draw.text((100, 100), "GLOBAL LOGISTICS & PHARMA SUPPLIES PVT LTD", fill=0, font=font_large)
draw.text((100, 160), f"Tax Invoice (Original for Recipient) - GSTIN: {DUMMY_VENDOR_GSTIN}", fill=0, font=font_med)
draw.text((100, 200), "Invoice No: INV-2026-08991 | Date: 15-Aug-2026 | State: Maharashtra", fill=0, font=font_med)
draw.text((100, 240), "Billed To: Acme HealthCare Solutions, 402 Park Avenue, Mumbai 400001", fill=0, font=font_med)
y = 320
items = [
("Amoxicillin 500mg Capsules IP Box of 100", "BATCH-A91", "100", "12.50", "1250.00"),
("Paracetamol 650mg Fast-Action Tablets", "BATCH-P44", "250", "4.20", "1050.00"),
("Azithromycin 250mg Suspension 30ml", "BATCH-Z10", "50", "35.00", "1750.00"),
("Cetirizine Hydrochloride 10mg Strip", "BATCH-C02", "120", "8.50", "1020.00"),
("Vitamin C Chewable Tablets 500mg Jar 60", "BATCH-V88", "80", "18.00", "1440.00"),
("Surgical Disposable Face Masks 3-Ply Box 50", "BATCH-M12", "40", "15.00", "600.00"),
("Hand Sanitizer Solution 500ml Flip-Cap", "BATCH-S99", "60", "22.50", "1350.00"),
]
for name, batch, qty, rate, total in items:
line_text = f"{name:<45} {batch:<12} {qty:>5} {rate:>8} {total:>10}"
draw.text((100, y), line_text, fill=0, font=font_med)
y += 50
draw.text((100, y + 40), "Subtotal: USD 8,460.00 | CGST 9%: USD 761.40 | SGST 9%: USD 761.40", fill=0, font=font_med)
draw.text((100, y + 80), "Grand Total: USD 9,982.80 | Amount in Words: Nine Thousand Nine Hundred Eighty Two", fill=0, font=font_large)
draw.text((100, y + 140), "Authorized Signatory for Global Logistics & Pharma Supplies Private Limited", fill=0, font=font_med)
return img
def test_upright_image_not_rotated(tmp_path, synthetic_invoice_image, tesseract_available):
"""An image that is already upright should be detected with rotate_angle 0 and marked upright."""
src_path = tmp_path / "invoice_upright.png"
synthetic_invoice_image.save(src_path)
out_dir = tmp_path / "oriented"
result = detect_and_correct_orientation(str(src_path), str(out_dir))
assert result["status"] == "upright"
assert result["detected_angle"] == 0
assert result["rotate_angle"] == 0
assert result["rotated"] is False
assert Path(result["output_path"]).exists()
def test_synthetic_90_degree_rotation(tmp_path, synthetic_invoice_image, tesseract_available):
"""An image rotated 90 degrees CCW should be detected and corrected to 0 degrees."""
src_path = tmp_path / "invoice_rot90.png"
synthetic_invoice_image.rotate(90, expand=True).save(src_path)
out_dir = tmp_path / "oriented"
result = detect_and_correct_orientation(str(src_path), str(out_dir))
assert result["status"] == "corrected"
assert result["rotated"] is True
assert Path(result["output_path"]).exists()
def test_synthetic_180_degree_rotation(tmp_path, synthetic_invoice_image, tesseract_available):
"""An upside-down image (180 degrees) should be detected and corrected to upright."""
src_path = tmp_path / "invoice_rot180.png"
synthetic_invoice_image.rotate(180, expand=True).save(src_path)
out_dir = tmp_path / "oriented"
result = detect_and_correct_orientation(str(src_path), str(out_dir))
assert result["status"] == "corrected"
assert result["rotated"] is True
assert Path(result["output_path"]).exists()
def test_blank_image_fails_gracefully(tmp_path):
"""A blank image without characters should fail gracefully without crashing."""
src_path = tmp_path / "blank.png"
Image.new("L", (300, 300), color=255).save(src_path)
out_dir = tmp_path / "oriented"
result = detect_and_correct_orientation(str(src_path), str(out_dir))
assert result["status"] in ["failed", "upright"]
assert Path(result["output_path"]).exists()
def test_process_folder_orientation(tmp_path, synthetic_invoice_image, tesseract_available):
"""Verifies batch folder processing aggregates statistics correctly."""
in_dir = tmp_path / "in"
out_dir = tmp_path / "out"
in_dir.mkdir()
synthetic_invoice_image.save(in_dir / "upright.png")
synthetic_invoice_image.rotate(90, expand=True).save(in_dir / "rotated.png")
Image.new("L", (200, 200), color=255).save(in_dir / "blank.png")
summary = process_folder_orientation(str(in_dir), str(out_dir))
assert summary["total_images_processed"] == 3
assert Path(out_dir / "upright_oriented.png").exists()
+83
View File
@@ -0,0 +1,83 @@
# tests/test_synthetic_pipeline_smoke.py
"""
Synthetic fixture smoke tests for InvoiceVerifier and InvoicePipeline.
Verifies GSTIN validation, arithmetic balance, and end-to-end extraction on synthetic image.
Uses whitelisted synthetic tokens only.
"""
import pytest
from PIL import Image, ImageDraw
from app.ocr.verifier import InvoiceVerifier
from app.ocr.invoice_pipeline import InvoicePipeline
def test_synthetic_gstin_validation():
# Valid synthetic whitelisted GSTIN
valid_res = InvoiceVerifier.validate_gstin("27AAPFU0939F1ZV")
assert valid_res["valid"] is True
assert valid_res["state_code"] == "27"
# Invalid state code 99
inv_state = InvoiceVerifier.validate_gstin("99AAPFU0939F1ZV")
assert inv_state["valid"] is False
# Invalid length
inv_len = InvoiceVerifier.validate_gstin("27AAPFU0939")
assert inv_len["valid"] is False
# Non-string input
assert InvoiceVerifier.validate_gstin(None)["valid"] is False
def test_synthetic_arithmetic_verification():
line_items = [
{"quantity": 10.0, "rate": 100.0, "amount": 1000.0},
{"quantity": 2.0, "rate": 500.0, "amount": 1000.0}
]
audit = InvoiceVerifier.verify_arithmetic(
line_items=line_items,
extracted_subtotal=2000.0,
cgst=100.0,
sgst=100.0,
roundoff=0.0,
extracted_grand_total=2200.0
)
assert audit["overall_status"] == "MATHEMATICALLY_VERIFIED"
assert audit["all_items_verified"] is True
assert audit["subtotal_verified"] is True
assert audit["grand_total_verified"] is True
assert audit["grand_total_source"] == "ocr_extracted"
assert audit["reconciled_grand_total"] == 2200.0
def test_synthetic_pipeline_smoke_e2e(tmp_path):
img_path = tmp_path / "synthetic_smoke_inv.png"
img = Image.new("RGB", (1000, 600), color="white")
draw = ImageDraw.Draw(img)
text_lines = [
"TAX INVOICE",
"SYNTHETIC MEDICAL PVT LTD",
"GSTIN: 27AAPFU0939F1ZV",
"Invoice No: SYNTH-7777",
"Date: 15/08/2026",
"Billed To: ACME HOSPITAL",
"Buyer GSTIN: 27AAPFU0939F1ZW",
"Description Qty Rate Amount",
"BANDAGE PACK 10 50.00 500.00",
"Subtotal: 500.00",
"CGST (2.5%): 12.50",
"SGST (2.5%): 12.50",
"Total: 525.00"
]
y = 30
for line in text_lines:
draw.text((50, y), line, fill="black")
y += 35
img.save(img_path)
pipeline = InvoicePipeline(use_gpu=False)
res = pipeline.process_invoice(str(img_path))
assert "invoice_number" in res
assert "seller_gstin" in res
assert "invoice_amount" in res
assert "items" in res
@@ -0,0 +1,92 @@
# tests/test_synthetic_schema_conformance.py
"""
Synthetic test fixture for official output schema conformance.
Verifies all required top-level keys, item keys, and data types on synthetic mock outputs.
Uses whitelisted synthetic tokens only.
"""
import pytest
from app.ocr.output_formatter import format_official_output
REQUIRED_HEADER_KEYS = [
"invoice_id", "invoice_number", "invoice_date", "due_date",
"customer_name", "customer_gstin", "seller_name", "seller_gstin",
"currency_code", "PO_number", "DC_date", "DC_number",
"invoice_amount", "round_off", "total_gst_rate", "total_quantity",
"total_cgst_rate", "total_cgst_amount", "total_sgst_rate", "total_sgst_amount",
"total_igst_rate", "total_igst_amount", "total_gst_amount", "items"
]
REQUIRED_ITEM_KEYS = [
"description", "Pack", "Batch", "quantity", "free_quantity", "total_quantity",
"free_item_yn", "unit_price", "total_price", "reference_number", "hsn_sac",
"item_code", "expiry_date", "Discount", "Discount_type", "Value", "Gst%",
"MRP", "cgst_rate", "cgst_amount", "sgst_rate", "sgst_amount", "igst_rate",
"igst_amount", "GST_AMT", "taxable_value"
]
def test_synthetic_schema_structure_and_keys():
synthetic_internal_data = {
"file_name": "synthetic_inv_001.png",
"invoice_metadata": {
"invoice_number": "SYNTH-001",
"invoice_date": "20/08/2026",
"due_date": "10/09/2026",
"currency_code": "INR",
"PO_number": "PO-SYNTH-99",
"vendor": {
"name": "SYNTHETIC SUPPLIERS PVT LTD",
"gstin": "27AAPFU0939F1ZV"
},
"buyer": {
"name": "ACME HEALTHCARE CORP",
"gstin": "27AAPFU0939F1ZW"
}
},
"line_items": [
{
"description": "SYNTHETIC PHARMA SOLUTION 100ML",
"unit": "100 ML",
"batch": "SYNTH01",
"qty": 10,
"free_qty": 0,
"rate": 100.0,
"hsn_code": "30049099",
"discount_pct": 5.0,
"gst_pct": 5,
"cgst_rate": 2.5,
"cgst_amount": 23.75,
"sgst_rate": 2.5,
"sgst_amount": 23.75,
"gst_amt": 47.50,
"taxable_value": 950.00,
"mrp": 150.00
}
],
"financial_summary": {
"subtotal": 950.00,
"cgst": 23.75,
"sgst": 23.75,
"igst": 0.0,
"roundoff": 0.50,
"grand_total": 998.00
}
}
out = format_official_output(synthetic_internal_data)
# 1. Check all required header keys exist
for k in REQUIRED_HEADER_KEYS:
assert k in out, f"Missing required header key: {k}"
# 2. Check all required item keys exist
assert len(out["items"]) == 1
item = out["items"][0]
for k in REQUIRED_ITEM_KEYS:
assert k in item, f"Missing required item key: {k}"
# 3. Check specific formatted types
assert out["customer_gstin"] == "27AAPFU0939F1ZW"
assert out["seller_gstin"] == "27AAPFU0939F1ZV"
assert out["invoice_amount"] == "998.00"
assert item["total_price"] == "950.00"
+226
View File
@@ -0,0 +1,226 @@
# tests/test_synthetic_schema_mapper.py
"""
Synthetic test fixture equivalent for SchemaMapper.
Validates flat-to-flat and nested-to-flat schema mappings, scalar comparisons,
exempted typo matches, and line-item accuracy calculations using whitelisted synthetic constants.
"""
import pytest
from app.ocr.schema_mapper import SchemaMapper
DUMMY_VENDOR_GSTIN = "27AAPFU0939F1ZV"
DUMMY_BUYER_GSTIN = "27AAPFU0939F1ZW"
DUMMY_PAN = "AAPFU0939F"
def test_schema_mapper_comparison_with_exemptions():
# Synthetic flat ground truth with known typo on item 2 item_code
ground_truth = {
"invoice_number": "INV-SYNTH-04531",
"invoice_date": "26/06/2026",
"customer_name": "ACME MEDICAL CARE",
"customer_gstin": DUMMY_BUYER_GSTIN,
"seller_name": "GLOBAL LIFECARE PRIVATE LIMITED",
"seller_gstin": DUMMY_VENDOR_GSTIN,
"invoice_amount": "252139.00",
"round_off": "0.40",
"total_cgst_amount": "6003.30",
"total_sgst_amount": "6003.30",
"items": [
{
"description": "ALBUCEL 20%/100ML",
"Pack": "VIAL",
"quantity": 60,
"unit_price": "3700.00",
"total_price": "222000.00",
"hsn_sac": "30021290",
"item_code": "AL-03-0279"
},
{
"description": "TELIPSA 10ML/1MG INJ",
"Pack": "AMP",
"quantity": 120,
"unit_price": "198.00",
"total_price": "23760.00",
"hsn_sac": "30049095",
"item_code": "AL-02-3176" # Ground truth typo (actual is AL-02-3178)
}
]
}
# System output (nested schema)
system_output = {
"invoice_metadata": {
"invoice_number": "INV-SYNTH-04531",
"invoice_date": "26-06-2026",
"vendor": {
"name": "GLOBAL LIFECARE PRIVATE LIMITED",
"gstin": DUMMY_VENDOR_GSTIN,
"pan": DUMMY_PAN,
"bank_details": {
"bank_name": "SYNTHETIC BANK",
"account_number": "00000000000000",
"ifsc_code": "SYNB0000001"
}
},
"buyer": {
"name": "ACME MEDICAL CARE",
"gstin": DUMMY_BUYER_GSTIN
}
},
"line_items": [
{
"sr_no": 1,
"item_code": "AL-03-0279",
"description": "ALBUCEL 20%/100ML",
"hsn_code": "30021290",
"quantity": 60.0,
"unit": "VIAL",
"rate": 3700.0,
"amount": 222000.0
},
{
"sr_no": 2,
"item_code": "AL-02-3178", # Real invoice text extracted by system
"description": "TELIPSA 10ML/1MG INJ",
"hsn_code": "30049095",
"quantity": 120.0,
"unit": "AMP",
"rate": 198.0,
"amount": 23760.0
}
],
"financial_summary": {
"subtotal": 245760.0,
"cgst": 6003.3,
"sgst": 6003.3,
"roundoff": 0.4,
"grand_total": 252139.0
}
}
mapper = SchemaMapper()
report = mapper.compare(ground_truth, system_output)
# All top-level scalar fields match
for s in report["scalar_fields"]:
assert s["match"] is True, f"Field mismatch: {s['field']}"
# Item 1 matches perfectly
item1_fields = {f["field"]: f for f in report["line_items"][0]["fields"]}
assert item1_fields["item_code"]["match"] is True
assert item1_fields["item_code"]["status"] == "MATCH"
# Item 2 item_code is recognized as an exempted typo
item2_fields = {f["field"]: f for f in report["line_items"][1]["fields"]}
assert item2_fields["item_code"]["match"] is True
assert item2_fields["item_code"]["is_exempted"] is True
assert item2_fields["item_code"]["status"] == "EXEMPTED_TYPO_MATCH"
# Overall accuracy is 100%
assert report["metrics"]["overall_accuracy_pct"] == 100.0
def test_schema_mapper_direct_flat_comparison():
"""Tests direct flat-to-flat comparison without any nested translation."""
ground_truth = {
"invoice_id": "INV-SYNTH-04531",
"invoice_number": "INV-SYNTH-04531",
"invoice_date": "26/06/2026",
"due_date": "26/06/2026",
"customer_name": "ACME MEDICAL CARE",
"customer_gstin": DUMMY_BUYER_GSTIN,
"seller_name": "GLOBAL LIFECARE PRIVATE LIMITED",
"seller_gstin": DUMMY_VENDOR_GSTIN,
"currency_code": "INR",
"PO_number": "PO/SYNTH/2026-27/426",
"DC_date": None,
"DC_number": None,
"invoice_amount": "252139.00",
"round_off": "0.40",
"total_gst_rate": 5,
"total_quantity": 180,
"total_cgst_rate": 2.5,
"total_cgst_amount": "6003.30",
"total_sgst_rate": 2.5,
"total_sgst_amount": "6003.30",
"total_igst_rate": None,
"total_igst_amount": "0.00",
"total_gst_amount": "12006.60",
"items": [
{
"description": "ALBUCEL 20%/100ML",
"Pack": "VIAL",
"Batch": "97010700",
"quantity": 60,
"free_item_yn": "0",
"unit_price": "3700.00",
"total_price": "222000.00",
"reference_number": None,
"hsn_sac": "30021290",
"item_code": "AL-03-0279",
"expiry_date": "28/02/2029",
"Discount": "2.00",
"Discount_type": None,
"Value": None,
"Gst%": 5,
"MRP": "7986.00",
"cgst_rate": 2.5,
"cgst_amount": "5439.00",
"sgst_rate": 2.5,
"sgst_amount": "5439.00",
"igst_rate": None,
"igst_amount": None,
"GST_AMT": "10878.00",
"taxable_value": None
},
{
"description": "TELIPSA 10ML/1MG INJ",
"Pack": "AMP",
"Batch": "A412507",
"quantity": 120,
"free_item_yn": "0",
"unit_price": "198.00",
"total_price": "23760.00",
"reference_number": None,
"hsn_sac": "30049095",
"item_code": "AL-02-3176",
"expiry_date": "30/11/2027",
"Discount": "5.00",
"Discount_type": None,
"Value": None,
"Gst%": 5,
"MRP": "3289.69",
"cgst_rate": 2.5,
"cgst_amount": "564.30",
"sgst_rate": 2.5,
"sgst_amount": "564.30",
"igst_rate": None,
"igst_amount": None,
"GST_AMT": "1128.60",
"taxable_value": None
}
]
}
# System output in identical flat schema (with AL-02-3178 extracted)
system_output = dict(ground_truth)
system_output["items"] = [
dict(ground_truth["items"][0]),
dict(ground_truth["items"][1])
]
system_output["items"][1]["item_code"] = "AL-02-3178"
mapper = SchemaMapper()
report = mapper.compare(ground_truth, system_output)
# All header fields match
for h in report["header_fields"]:
assert h["match"] is True, f"Header mismatch: {h['field']} exp={h['expected']} act={h['extracted']}"
# All item fields match (including exempted typo)
for it in report["line_items"]:
for f in it["fields"]:
assert f["match"] is True, f"Item field mismatch: {f['field']} exp={f['expected']} act={f['extracted']}"
assert report["metrics"]["overall_accuracy_pct"] == 100.0
assert report["metrics"]["overall_matches"] == "71/71"
@@ -0,0 +1,55 @@
# tests/test_synthetic_three_column_layout.py
"""
Synthetic test fixture equivalent for three-column spatial layout extraction.
Validates spatial decomposition into vendor (left), metadata (center),
and buyer (right) using in-memory synthetic bounding boxes and whitelisted constants.
"""
import pytest
from app.ocr.invoice_pipeline import InvoicePipeline
DUMMY_VENDOR_GSTIN = "27AAPFU0939F1ZV"
DUMMY_BUYER_GSTIN = "27AAPFU0939F1ZW"
DUMMY_PAN = "AAPFU0939F"
def test_three_column_spatial_party_extraction():
# Synthetic bounding boxes modeling the 3-column layout:
# Left column (x: 50-500): Seller Synthetic Lifecare + GSTIN
# Middle column (x: 700-1100): Invoice details (Invoice No, Date)
# Right column (x: 1600-2200): Customer Synthetic Health + GSTIN
elements = [
# Seller (Left)
{"text": "SYNTHETIC LIFECARE PRIVATE LIMITED", "box": [[60, 100], [500, 100], [500, 130], [60, 130]]},
{"text": f"GSTIN : {DUMMY_VENDOR_GSTIN}", "box": [[60, 300], [400, 300], [400, 330], [60, 330]]},
{"text": "Account No. : 00000000000000", "box": [[60, 400], [450, 400], [450, 430], [60, 430]]},
{"text": "Bank Name: SYNTHETIC BANK", "box": [[60, 440], [350, 440], [350, 470], [60, 470]]},
{"text": "IFSC : SYNB0000001", "box": [[60, 480], [300, 480], [300, 510], [60, 510]]},
# Center (Invoice Details)
{"text": "TAX INVOICE", "box": [[800, 50], [1000, 50], [1000, 80], [800, 80]]},
{"text": "Invoice No.", "box": [[700, 120], [830, 120], [830, 150], [700, 150]]},
{"text": "SYNTH/B/04531", "box": [[940, 120], [1100, 120], [1100, 150], [940, 150]]},
{"text": "Invoice Date", "box": [[700, 160], [830, 160], [830, 190], [700, 190]]},
{"text": "26/06/2026", "box": [[940, 160], [1050, 160], [1050, 190], [940, 190]]},
# Right (Customer / Buyer)
{"text": "Customer Name :", "box": [[1600, 100], [1800, 100], [1800, 130], [1600, 130]]},
{"text": "SYNTHETIC MEDICAL STORES", "box": [[1600, 140], [2100, 140], [2100, 170], [1600, 170]]},
{"text": f"GSTIN : {DUMMY_BUYER_GSTIN}", "box": [[1600, 250], [1950, 250], [1950, 280], [1600, 280]]}
]
parties = InvoicePipeline._extract_parties_metadata(elements)
assert parties["vendor_name"] == "SYNTHETIC LIFECARE PRIVATE LIMITED"
assert parties["vendor_gstin"] == DUMMY_VENDOR_GSTIN
assert parties["vendor_pan"] == DUMMY_PAN
assert parties["buyer_name"] == "SYNTHETIC MEDICAL STORES"
assert parties["buyer_gstin"] == DUMMY_BUYER_GSTIN
assert parties["bank_details"]["account_number"] == "00000000000000"
assert parties["bank_details"]["bank_name"] == "SYNTHETIC BANK"
assert parties["bank_details"]["ifsc_code"] == "SYNB0000001"
inv_num = InvoicePipeline._extract_invoice_number(elements)
assert inv_num == "SYNTH/B/04531"
inv_date = InvoicePipeline._extract_invoice_date(elements)
assert inv_date == "26/06/2026"
+64
View File
@@ -0,0 +1,64 @@
# tests/test_synthetic_vision_fallback.py
"""
Synthetic fixture unit tests for Multimodal Vision-AI Fallback Engine.
Tests availability, non-triggering on complete inputs, and mock patching.
Uses whitelisted synthetic tokens exclusively.
"""
from unittest.mock import MagicMock
from app.ocr.vision_fallback import GeminiVisionFallback
def test_synthetic_vision_fallback_without_api_key():
fb = GeminiVisionFallback(api_key=None)
assert fb.is_available() is False
assert fb.extract_from_image("synthetic_dummy.png") is None
def test_synthetic_patch_missing_fields_noop_when_complete():
fb = GeminiVisionFallback(api_key=None)
complete_local_output = {
"invoice_number": "SYNTH-101",
"invoice_date": "01/08/2026",
"due_date": "15/08/2026",
"customer_name": "ACME HEALTHCARE CORP",
"customer_gstin": "27AAPFU0939F1ZW",
"seller_name": "SYNTHETIC SUPPLIERS PVT LTD",
"seller_gstin": "27AAPFU0939F1ZV",
"invoice_amount": "5000.00",
"items": [{"description": "Item 1", "quantity": 10}]
}
patched = fb.patch_missing_fields(complete_local_output, "synthetic_dummy.png")
assert patched == complete_local_output
def test_synthetic_patch_missing_fields_with_mocked_gemini():
fb = GeminiVisionFallback(api_key="mock_key")
fb._client = MagicMock()
gemini_data = {
"due_date": "20/08/2026",
"customer_gstin": "27AAPFU0939F1ZW",
"invoice_amount": "12500.00",
"items": [
{"description": "Synthetic Product A", "quantity": 100},
{"description": "Synthetic Product B", "quantity": 50}
]
}
fb.extract_from_image = MagicMock(return_value=gemini_data)
local_incomplete = {
"invoice_number": "SYNTH-202",
"invoice_date": "01/08/2026",
"due_date": None,
"customer_name": "ACME HEALTHCARE CORP",
"customer_gstin": None,
"seller_name": "SYNTHETIC SUPPLIERS PVT LTD",
"seller_gstin": "27AAPFU0939F1ZV",
"invoice_amount": None,
"items": []
}
patched = fb.patch_missing_fields(local_incomplete, "synthetic_dummy.png")
assert patched["due_date"] == "20/08/2026"
assert patched["customer_gstin"] == "27AAPFU0939F1ZW"
assert patched["invoice_amount"] == "12500.00"
assert len(patched["items"]) == 2