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
+3 -15
View File
@@ -154,22 +154,10 @@ class SelfHealingEngine:
healing_log.append(f"Reconciled mislabeled Grand Total: changed {ext_grand_total} (was subtotal) to {calculated_grand_total}") healing_log.append(f"Reconciled mislabeled Grand Total: changed {ext_grand_total} (was subtotal) to {calculated_grand_total}")
# --------------------------------------------------------------------- # ---------------------------------------------------------------------
# 3. Due Date Inference from Credit Terms # 3. Due Date: Strict OCR Fidelity (Only report printed dates)
# Payment terms are preserved in metadata if needed, but not synthesized
# into due_date to prevent hallucinating unprinted dates.
# --------------------------------------------------------------------- # ---------------------------------------------------------------------
if not meta_repaired.get("due_date") and all_ocr_lines:
inv_date_str = meta_repaired.get("invoice_date")
if inv_date_str:
parsed_inv_date = cls._parse_date(inv_date_str)
if parsed_inv_date:
# Scan text lines for credit days terms
for line in all_ocr_lines:
txt = line.get("text", "")
credit_days = parse_credit_terms_days(txt)
if credit_days:
due_dt = parsed_inv_date + timedelta(days=credit_days)
meta_repaired["due_date"] = due_dt.strftime("%d/%m/%Y")
healing_log.append(f"Inferred due date '{meta_repaired['due_date']}' from credit terms: {credit_days} days")
break
# --------------------------------------------------------------------- # ---------------------------------------------------------------------
# 4. GSTIN Recovery from Unassigned Tokens # 4. GSTIN Recovery from Unassigned Tokens
+119
View File
@@ -0,0 +1,119 @@
# app/ocr/stage_cache.py
"""
Persistent Stage Cache for Raw OCR Engine Outputs (Phase 1.5).
Caches raw OCR line outputs keyed by:
(image_sha256, engine_name, engine_version, preprocess_config_hash)
Automatically invalidates when any component changes.
Enables downstream stages (extraction, table parsing, self-healing, verification)
to re-run in milliseconds rather than ~25s per invoice.
"""
import os
import json
import hashlib
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
class OCRStageCache:
"""Persistent on-disk cache for raw OCR output tokens and bounding boxes."""
DEFAULT_CACHE_DIR = Path("data_private/stage_cache")
def __init__(self, cache_dir: Optional[Path] = None, enabled: bool = True):
self.cache_dir = cache_dir or self.DEFAULT_CACHE_DIR
self.enabled = enabled
if self.enabled:
self.cache_dir.mkdir(parents=True, exist_ok=True)
@staticmethod
def compute_image_sha256(image_path_or_bytes: Any) -> str:
"""Computes SHA-256 of image bytes."""
if isinstance(image_path_or_bytes, (str, Path)):
p = Path(image_path_or_bytes)
if not p.exists():
raise FileNotFoundError(f"Image not found: {p}")
return hashlib.sha256(p.read_bytes()).hexdigest()
elif isinstance(image_path_or_bytes, bytes):
return hashlib.sha256(image_path_or_bytes).hexdigest()
elif hasattr(image_path_or_bytes, "tobytes"): # numpy array
return hashlib.sha256(image_path_or_bytes.tobytes()).hexdigest()
else:
return hashlib.sha256(str(image_path_or_bytes).encode("utf-8")).hexdigest()
def get_cache_key(
self,
image_sha256: str,
engine_name: str,
engine_version: str,
preprocess_config_hash: str
) -> str:
payload = f"{image_sha256}:{engine_name}:{engine_version}:{preprocess_config_hash}"
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def get(
self,
image_sha256: str,
engine_name: str,
engine_version: str,
preprocess_config_hash: str = "v1_default"
) -> Optional[List[Dict[str, Any]]]:
"""Retrieves cached OCR lines if present."""
if not self.enabled:
return None
key = self.get_cache_key(image_sha256, engine_name, engine_version, preprocess_config_hash)
cache_file = self.cache_dir / f"{key}.json"
if not cache_file.exists():
return None
try:
with open(cache_file, "r", encoding="utf-8") as f:
data = json.load(f)
return data.get("ocr_lines")
except Exception:
return None
def put(
self,
image_sha256: str,
engine_name: str,
engine_version: str,
ocr_lines: List[Dict[str, Any]],
preprocess_config_hash: str = "v1_default"
) -> None:
"""Stores raw OCR lines into persistent cache."""
if not self.enabled:
return
key = self.get_cache_key(image_sha256, engine_name, engine_version, preprocess_config_hash)
cache_file = self.cache_dir / f"{key}.json"
payload = {
"key": key,
"image_sha256": image_sha256,
"engine_name": engine_name,
"engine_version": engine_version,
"preprocess_config_hash": preprocess_config_hash,
"line_count": len(ocr_lines),
"ocr_lines": ocr_lines
}
try:
tmp_file = self.cache_dir / f"{key}.tmp"
with open(tmp_file, "w", encoding="utf-8") as f:
json.dump(payload, f, default=str)
tmp_file.replace(cache_file)
except Exception:
pass
def clear(self) -> int:
"""Clears all entries in the cache directory."""
count = 0
if self.cache_dir.exists():
for f in self.cache_dir.glob("*.json"):
try:
f.unlink()
count += 1
except Exception:
pass
return count
+174
View File
@@ -0,0 +1,174 @@
# app/rrsi/data_access.py
"""
Data Access Control and Manifest Integrity Verification (Phase 1.4).
Policy:
- app/rrsi/data_access.py is the authoritative gate for dataset reads in RRSI.
- Refuses 'locked_test' split access unless environment variable RRSI_FINAL_EVAL=1 is set.
- Convention & CI Check: This is a software convention enforced in Python and tested in CI,
not an OS-level hardware security guarantee.
- Enforces manifest integrity:
1. No split overlap across doc_ids.
2. No template straddling across splits.
3. No copy/page split divergence.
4. No contaminated invoices in selection or locked_test splits.
5. SHA-256 hash consistency.
"""
import os
import json
import hashlib
from pathlib import Path
from typing import Dict, Any, List, Tuple, Optional, Set
class DataAccessGate:
"""Controls read access to invoice datasets and validates partition integrity."""
DEFAULT_MANIFEST_PATHS = [
Path("data/manifest.json"),
Path("data_private/manifest_private.json")
]
def __init__(self, manifest_path: Optional[Path] = None):
self.manifest_path = manifest_path or self._resolve_manifest_path()
self._manifest_cache: Optional[Dict[str, Any]] = None
def _resolve_manifest_path(self) -> Path:
for p in self.DEFAULT_MANIFEST_PATHS:
if p.exists():
return p
return Path("data/manifest.json")
def load_manifest(self, force_reload: bool = False) -> Dict[str, Any]:
"""Loads and returns the manifest dictionary."""
if self._manifest_cache is not None and not force_reload:
return self._manifest_cache
if not self.manifest_path.exists():
raise FileNotFoundError(f"Manifest not found at {self.manifest_path}")
with open(self.manifest_path, "r", encoding="utf-8") as f:
data = json.load(f)
self._manifest_cache = data
return data
def get_invoices_for_split(
self,
split_name: str,
allow_contaminated: bool = False
) -> List[Dict[str, Any]]:
"""
Retrieves all invoice metadata records assigned to a specific split.
Refuses 'locked_test' unless RRSI_FINAL_EVAL=1 is present in the environment.
"""
normalized_split = split_name.strip().lower()
# Gate 'locked_test'
if normalized_split in ("locked_test", "test"):
final_eval_env = os.environ.get("RRSI_FINAL_EVAL", "").strip()
if final_eval_env != "1":
raise PermissionError(
"ACCESS DENIED: 'locked_test' split is locked against premature evaluation. "
"Access is only permitted when environment variable RRSI_FINAL_EVAL=1 is explicitly set."
)
manifest_data = self.load_manifest()
raw_manifest = manifest_data.get("manifest", [])
# Support both list of dicts and dict of dicts
items: List[Dict[str, Any]] = []
if isinstance(raw_manifest, list):
items = raw_manifest
elif isinstance(raw_manifest, dict):
items = list(raw_manifest.values())
selected: List[Dict[str, Any]] = []
for inv in items:
inv_split = str(inv.get("split", "")).strip().lower()
if inv_split == normalized_split:
is_contaminated = bool(inv.get("contaminated", False))
if is_contaminated and normalized_split in ("selection", "locked_test") and not allow_contaminated:
raise ValueError(
f"INTEGRITY VIOLATION: Contaminated invoice '{inv.get('doc_id')}' found in '{normalized_split}' split!"
)
selected.append(inv)
return selected
def verify_manifest_integrity(
self,
check_disk_hashes: bool = False,
images_dir: Optional[Path] = None
) -> Tuple[bool, List[str]]:
"""
Comprehensive manifest validation:
1. Split overlap: no doc_id appears in multiple splits.
2. Template straddling: no template_group straddles across splits.
3. Copy integrity: copies belonging to the same invoice share the same split.
4. Contamination: no contaminated invoices in selection or locked_test.
5. Hash validation (optional): file sha256 matches manifest.
"""
errors: List[str] = []
manifest_data = self.load_manifest()
raw_manifest = manifest_data.get("manifest", [])
items: List[Dict[str, Any]] = []
if isinstance(raw_manifest, list):
items = raw_manifest
elif isinstance(raw_manifest, dict):
items = list(raw_manifest.values())
doc_splits: Dict[str, str] = {}
template_splits: Dict[str, Set[str]] = {}
file_to_doc: Dict[str, str] = {}
for inv in items:
doc_id = inv.get("doc_id")
split = str(inv.get("split", "")).strip().lower()
tmpl = inv.get("template_group")
contaminated = bool(inv.get("contaminated", False))
files = inv.get("files", [])
if not doc_id:
errors.append("Manifest entry missing 'doc_id'")
continue
# 1. Split overlap
if doc_id in doc_splits and doc_splits[doc_id] != split:
errors.append(f"Split overlap: doc_id '{doc_id}' in both '{doc_splits[doc_id]}' and '{split}'")
doc_splits[doc_id] = split
# 2. Template straddling
if tmpl:
template_splits.setdefault(tmpl, set()).add(split)
# 3. Contamination guard
if contaminated and split in ("selection", "locked_test"):
errors.append(f"Contaminated invoice '{doc_id}' found in forbidden split '{split}'")
# 4. File-to-doc mapping for copies
for fname in files:
if fname in file_to_doc and file_to_doc[fname] != doc_id:
errors.append(f"File '{fname}' assigned to multiple doc_ids: '{file_to_doc[fname]}' and '{doc_id}'")
file_to_doc[fname] = doc_id
# 5. Check SHA-256 on disk if requested
if check_disk_hashes and images_dir and images_dir.exists():
file_hashes = inv.get("file_hashes", {})
for fname in files:
expected_sha = file_hashes.get(fname)
img_file = images_dir / fname
if img_file.exists() and expected_sha:
actual_sha = hashlib.sha256(img_file.read_bytes()).hexdigest()
if actual_sha != expected_sha:
errors.append(f"SHA-256 mismatch on '{fname}': expected {expected_sha[:10]}, got {actual_sha[:10]}")
# Check template straddling
for tmpl, splits in template_splits.items():
if len(splits) > 1:
errors.append(f"Template straddling: template_group '{tmpl}' straddles multiple splits: {sorted(list(splits))}")
is_valid = (len(errors) == 0)
return is_valid, errors
+11 -5
View File
@@ -158,19 +158,25 @@ class StatisticalEvaluator:
exp_val = gt.get(f) exp_val = gt.get(f)
act_val = pred.get(f) act_val = pred.get(f)
# Hallucination check: expected is null, actual is non-null # UNANNOTATED ground truth: field has not been reviewed by human annotator; skip scoring
if exp_val is None or str(exp_val).strip() == "": if str(exp_val).strip() in ("UNANNOTATED", "__UNANNOTATED__"):
if act_val is not None and str(act_val).strip() != "": continue
# ABSENT ground truth: verified by human annotator to be physically absent from source document
is_absent = (exp_val is None or str(exp_val).strip() in ("", "None", "ABSENT", "__ABSENT__"))
if is_absent:
# If pipeline extracted a non-empty, non-absent value, flag hallucination
if act_val is not None and str(act_val).strip() not in ("", "None", "ABSENT"):
field_stats[f]["hallucinations"] += 1 field_stats[f]["hallucinations"] += 1
failure_counts[ExtractionErrorClass.HALLUCINATION.value] += 1 failure_counts[ExtractionErrorClass.HALLUCINATION.value] += 1
fail_rec = FailureDetail( fail_rec = FailureDetail(
primary_class=ExtractionErrorClass.HALLUCINATION, primary_class=ExtractionErrorClass.HALLUCINATION,
field_name=f, field_name=f,
expected=None, expected="ABSENT",
actual=act_val, actual=act_val,
file_id=doc_id, file_id=doc_id,
severity="low", severity="low",
context_message=f"Hallucination on '{f}': expected null, extracted '{act_val}'" context_message=f"Hallucination on '{f}': field is ABSENT from document, but pipeline extracted '{act_val}'"
) )
failures.append(fail_rec) failures.append(fail_rec)
doc_failures.append(fail_rec) doc_failures.append(fail_rec)
+1 -1
View File
@@ -135,7 +135,7 @@ class ExperimentLedger:
f"- **Candidate Accuracy**: `{c_acc}`", f"- **Candidate Accuracy**: `{c_acc}`",
f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO'}`", f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO'}`",
f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED'}`", f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED'}`",
f"- **Cost-Aware Acceptance**: `{'PASSED' if decision.cost_aware_accepted else 'FAILED'}` (dt: {dt_str})", f"- **Cost-Aware Acceptance**: `{'N/A' if decision.cost_aware_accepted is None else ('PASSED' if decision.cost_aware_accepted else 'FAILED')}` (dt: {dt_str})",
"" ""
] ]
+52
View File
@@ -235,3 +235,55 @@ def mcnemar_test(
"statistic": float(stat), "statistic": float(stat),
"p_value": p_val "p_value": p_val
} }
def cluster_bootstrap_mean(
scores_per_cluster: Union[Dict[str, float], List[float]],
n_resamples: int = 10000,
confidence: float = 0.95,
seed: int = 42
) -> Dict[str, Any]:
"""
Performs cluster bootstrap for an aggregate metric grouped by cluster (e.g. invoice_id).
Resamples clusters with replacement to properly account for correlated within-invoice field outcomes.
Returns:
dict with:
mean: Observed sample mean
ci_lower: Lower bound of bootstrap percentile CI
ci_upper: Upper bound of bootstrap percentile CI
std_err: Standard error of bootstrap means
n_clusters: Number of clusters (invoices)
"""
rng = np.random.default_rng(seed)
if isinstance(scores_per_cluster, dict):
vals = np.array(list(scores_per_cluster.values()), dtype=float)
else:
vals = np.array(scores_per_cluster, dtype=float)
n = len(vals)
if n == 0:
return {"mean": 0.0, "ci_lower": 0.0, "ci_upper": 0.0, "std_err": 0.0, "n_clusters": 0}
if n == 1:
return {"mean": float(vals[0]), "ci_lower": float(vals[0]), "ci_upper": float(vals[0]), "std_err": 0.0, "n_clusters": 1}
mean_val = float(np.mean(vals))
sample_indices = rng.integers(0, n, size=(n_resamples, n))
resampled_means = np.take(vals, sample_indices).mean(axis=1)
alpha = 1.0 - confidence
lower_pct = 100.0 * (alpha / 2.0)
upper_pct = 100.0 * (1.0 - alpha / 2.0)
ci_lower = float(np.percentile(resampled_means, lower_pct))
ci_upper = float(np.percentile(resampled_means, upper_pct))
std_err = float(np.std(resampled_means))
return {
"mean": mean_val,
"ci_lower": ci_lower,
"ci_upper": ci_upper,
"std_err": std_err,
"n_clusters": n
}
+260
View File
@@ -0,0 +1,260 @@
# app/rrsi/synthetic_generator.py
"""
Seeded Synthetic Invoice & Programmatic Ground Truth Generator (Phase 1.6).
Generates synthetic invoice images and matching ground truth JSON:
- Seeded & deterministic (reproducible)
- Varied layouts: tabular, box-header, column-split, minimalist
- Varied date formats: DD/MM/YYYY, YYYY-MM-DD, DD-Mon-YYYY, DD.MM.YYYY
- Diverse GST slabs: 0%, 5%, 12%, 18%, 28%
- Line items with discounts, HSN codes, freight, round-off
- Visual augmentations: optional rotation, blur, resolution scaling
- Strictly for dev diagnosis, unit tests, and stress tests (never in selection or test).
"""
import random
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
from typing import Dict, Any, List, Tuple, Optional
from PIL import Image, ImageDraw, ImageFont, ImageFilter
class SyntheticInvoiceGenerator:
"""Generates synthetic invoice image and strict ground truth pairs."""
VENDORS = [
("NEXUS ENGINEERING SOLUTIONS PVT LTD", "27AAPFU0939F1ZV"),
("APEX HEALTHCARE SUPPLIES LLP", "27AAPFU0939F1ZV"),
("DYNAMIC PHARMA DISTRIBUTION CO", "27AAPFU0939F1ZV"),
("ZENITH SURGICAL INSTRUMENTS", "27AAPFU0939F1ZV"),
("BHARAT PRECISION TOOLS", "27AAPFU0939F1ZV")
]
BUYERS = [
("METROPOLITAN HOSPITAL TRUST", "27AAPFU0939F1ZW"),
("HORIZON MEDICARE FOUNDATION", "27AAPFU0939F1ZW"),
("CITY SURGICAL CLINIC & RESEARCH", "27AAPFU0939F1ZW"),
("ROYAL DIAGNOSTICS LABS", "27AAPFU0939F1ZW")
]
ITEMS_CATALOG = [
("DISPOSABLE SURGICAL GLOVES (BOX OF 100)", "4015", Decimal("350.00"), "BOX"),
("STAINLESS STEEL SCALPEL BLADES #10", "8203", Decimal("120.00"), "PKT"),
("N95 PARTICULATE RESPIRATOR MASKS", "6307", Decimal("45.00"), "PCS"),
("DIGITAL INFRARED THERMOMETER", "9025", Decimal("1850.00"), "NOS"),
("SURGICAL SUTURE VICRYL 3-0", "3006", Decimal("420.00"), "BOX"),
("STERILE GAUZE SWABS 10CM X 10CM", "3005", Decimal("85.00"), "PKT"),
("PULSE OXIMETER FINGERTIP SENSOR", "9018", Decimal("1250.00"), "NOS")
]
def __init__(self, seed: int = 42):
self.seed = seed
self.rng = random.Random(seed)
def _round(self, val: Decimal) -> Decimal:
return val.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def generate_invoice_data(self, invoice_idx: int = 1) -> Dict[str, Any]:
"""Generates programmatic ground-truth data with exact cross-field math."""
vendor_name, vendor_gstin = self.rng.choice(self.VENDORS)
buyer_name, buyer_gstin = self.rng.choice(self.BUYERS)
inv_num = f"SYNTH/{self.rng.randint(2026, 2027)}/{invoice_idx:04d}"
d_day = self.rng.randint(1, 28)
d_month = self.rng.randint(1, 12)
inv_date = f"{d_day:02d}/{d_month:02d}/2026"
due_date = f"{(d_day + 15) % 28 + 1:02d}/{(d_month % 12) + 1:02d}/2026"
po_num = f"PO-SYN-{self.rng.randint(1000, 9999)}"
num_items = self.rng.randint(2, 5)
chosen_items = self.rng.sample(self.ITEMS_CATALOG, num_items)
items_gt = []
gross_sum = Decimal("0.00")
total_discount = Decimal("0.00")
taxable_sum = Decimal("0.00")
total_gst = Decimal("0.00")
gst_rate = Decimal(str(self.rng.choice([5, 12, 18])))
for item_desc, hsn, rate, unit in chosen_items:
qty = Decimal(str(self.rng.randint(5, 50)))
gross = self._round(qty * rate)
gross_sum += gross
disc_pct = Decimal(str(self.rng.choice([0, 2, 5, 10])))
discount = self._round(gross * (disc_pct / Decimal("100")))
total_discount += discount
taxable = gross - discount
taxable_sum += taxable
tax = self._round(taxable * (gst_rate / Decimal("100")))
total_gst += tax
items_gt.append({
"description": item_desc,
"hsn": hsn,
"quantity": float(qty),
"unit": unit,
"rate": str(rate),
"discount": str(discount),
"tax_rate": float(gst_rate),
"total_price": str(taxable),
"tax_amount": str(tax)
})
freight = self._round(Decimal(str(self.rng.choice([0, 250, 500]))))
cgst = self._round(total_gst / Decimal("2"))
sgst = total_gst - cgst
subtotal_before_round = taxable_sum + total_gst + freight
total_rounded = self._round(Decimal(round(float(subtotal_before_round))))
round_off = self._round(total_rounded - subtotal_before_round)
return {
"invoice_number": inv_num,
"invoice_id": inv_num,
"invoice_date": inv_date,
"due_date": due_date,
"PO_number": po_num,
"seller_name": vendor_name,
"seller_gstin": vendor_gstin,
"customer_name": buyer_name,
"customer_gstin": buyer_gstin,
"taxable_amount": str(taxable_sum),
"cgst_amount": str(cgst),
"sgst_amount": str(sgst),
"igst_amount": "0.00",
"total_gst_amount": str(total_gst),
"freight_amount": str(freight),
"round_off": str(round_off),
"total_amount": str(total_rounded),
"invoice_amount": str(total_rounded),
"items": items_gt
}
def render_invoice_image(
self,
data: Dict[str, Any],
width: int = 1200,
height: int = 1600,
add_noise: bool = False
) -> Image.Image:
"""Renders an invoice data dictionary into a clean high-resolution PIL Image."""
img = Image.new("RGB", (width, height), color=(255, 255, 255))
draw = ImageDraw.Draw(img)
# Draw border
draw.rectangle([(30, 30), (width - 30, height - 30)], outline=(0, 0, 0), width=2)
# Header: Tax Invoice Title
draw.text((width // 2 - 100, 50), "TAX INVOICE", fill=(0, 0, 0))
draw.line([(30, 90), (width - 30, 90)], fill=(0, 0, 0), width=2)
# Seller Section (Left)
draw.text((50, 110), f"SELLER / SUPPLIER:", fill=(0, 0, 0))
draw.text((50, 135), f"{data['seller_name']}", fill=(0, 0, 0))
draw.text((50, 160), f"GSTIN: {data['seller_gstin']}", fill=(0, 0, 0))
draw.text((50, 185), f"State: Maharashtra (Code: 27)", fill=(0, 0, 0))
# Invoice Metadata (Right)
mid_x = width // 2 + 50
draw.text((mid_x, 110), f"Invoice No : {data['invoice_number']}", fill=(0, 0, 0))
draw.text((mid_x, 135), f"Invoice Date: {data['invoice_date']}", fill=(0, 0, 0))
draw.text((mid_x, 160), f"Due Date : {data['due_date']}", fill=(0, 0, 0))
draw.text((mid_x, 185), f"PO Number : {data['PO_number']}", fill=(0, 0, 0))
draw.line([(30, 220), (width - 30, 220)], fill=(0, 0, 0), width=2)
# Buyer Section
draw.text((50, 235), f"BILLED TO / CUSTOMER:", fill=(0, 0, 0))
draw.text((50, 260), f"{data['customer_name']}", fill=(0, 0, 0))
draw.text((50, 285), f"Customer GSTIN: {data['customer_gstin']}", fill=(0, 0, 0))
draw.line([(30, 320), (width - 30, 320)], fill=(0, 0, 0), width=2)
# Table Header
table_top = 340
draw.rectangle([(40, table_top), (width - 40, table_top + 35)], fill=(240, 240, 240), outline=(0, 0, 0), width=1)
draw.text((50, table_top + 10), "Sr", fill=(0, 0, 0))
draw.text((100, table_top + 10), "Description of Goods", fill=(0, 0, 0))
draw.text((520, table_top + 10), "HSN", fill=(0, 0, 0))
draw.text((620, table_top + 10), "Qty", fill=(0, 0, 0))
draw.text((720, table_top + 10), "Rate", fill=(0, 0, 0))
draw.text((840, table_top + 10), "Disc", fill=(0, 0, 0))
draw.text((960, table_top + 10), "Amount", fill=(0, 0, 0))
row_y = table_top + 45
for i, item in enumerate(data["items"], 1):
draw.text((50, row_y), str(i), fill=(0, 0, 0))
draw.text((100, row_y), item["description"][:38], fill=(0, 0, 0))
draw.text((520, row_y), item["hsn"], fill=(0, 0, 0))
draw.text((620, row_y), str(int(item["quantity"])), fill=(0, 0, 0))
draw.text((720, row_y), str(item["rate"]), fill=(0, 0, 0))
draw.text((840, row_y), str(item["discount"]), fill=(0, 0, 0))
draw.text((960, row_y), str(item["total_price"]), fill=(0, 0, 0))
row_y += 35
draw.line([(40, row_y + 10), (width - 40, row_y + 10)], fill=(0, 0, 0), width=1)
# Totals Section (Right Aligned)
tot_y = row_y + 30
draw.text((720, tot_y), f"Taxable Value :", fill=(0, 0, 0))
draw.text((960, tot_y), data["taxable_amount"], fill=(0, 0, 0))
tot_y += 28
draw.text((720, tot_y), f"CGST Amount :", fill=(0, 0, 0))
draw.text((960, tot_y), data["cgst_amount"], fill=(0, 0, 0))
tot_y += 28
draw.text((720, tot_y), f"SGST Amount :", fill=(0, 0, 0))
draw.text((960, tot_y), data["sgst_amount"], fill=(0, 0, 0))
if Decimal(data["freight_amount"]) > 0:
tot_y += 28
draw.text((720, tot_y), f"Freight / P&F :", fill=(0, 0, 0))
draw.text((960, tot_y), data["freight_amount"], fill=(0, 0, 0))
tot_y += 28
draw.text((720, tot_y), f"Round Off :", fill=(0, 0, 0))
draw.text((960, tot_y), data["round_off"], fill=(0, 0, 0))
tot_y += 35
draw.rectangle([(700, tot_y - 5), (width - 40, tot_y + 30)], fill=(230, 230, 230), outline=(0, 0, 0), width=1)
draw.text((720, tot_y + 5), f"TOTAL AMOUNT : INR {data['total_amount']}", fill=(0, 0, 0))
# Footer Signatory
draw.text((800, height - 120), "For " + data["seller_name"][:25], fill=(0, 0, 0))
draw.text((800, height - 60), "Authorised Signatory", fill=(0, 0, 0))
# Optional visual augmentations
if add_noise:
angle = self.rng.uniform(-1.5, 1.5)
img = img.rotate(angle, resample=Image.BICUBIC, fillcolor=(255, 255, 255))
if self.rng.random() > 0.5:
img = img.filter(ImageFilter.GaussianBlur(radius=0.5))
return img
def generate_sample(
self,
invoice_idx: int = 1,
output_dir: Optional[Path] = None,
add_noise: bool = False
) -> Tuple[Image.Image, Dict[str, Any]]:
"""Generates image + ground truth pair and optionally saves to disk."""
data = self.generate_invoice_data(invoice_idx=invoice_idx)
img = self.render_invoice_image(data, add_noise=add_noise)
if output_dir:
out_path = Path(output_dir)
out_path.mkdir(parents=True, exist_ok=True)
doc_id = f"synth_{invoice_idx:04d}"
data["doc_id"] = doc_id
img.save(out_path / f"{doc_id}.png")
import json
with open(out_path / f"{doc_id}_gt.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
return img, data
+2 -2
View File
@@ -273,10 +273,10 @@ class DecisionRecord:
is_statistically_significant: bool = False is_statistically_significant: bool = False
leakage_screen_passed: bool = True leakage_screen_passed: bool = True
leakage_findings: List[str] = field(default_factory=list) leakage_findings: List[str] = field(default_factory=list)
cost_aware_accepted: bool = False cost_aware_accepted: Optional[bool] = None
latency_delta_seconds: Optional[float] = None latency_delta_seconds: Optional[float] = None
vision_fallback_calls: int = 0 vision_fallback_calls: int = 0
case_regressions: List[str] = field(default_factory=list) case_regressions: List[Any] = field(default_factory=list)
rejection_reasons: List[str] = field(default_factory=list) rejection_reasons: List[str] = field(default_factory=list)
pruning_recommendations: List[str] = field(default_factory=list) pruning_recommendations: List[str] = field(default_factory=list)
failure_deltas: Dict[str, int] = field(default_factory=dict) failure_deltas: Dict[str, int] = field(default_factory=dict)
+261 -143
View File
@@ -1,4 +1,69 @@
{ {
"version": "1.0.0",
"description": "Git-safe anonymized benchmark manifest with template-isolated split partitioning",
"total_documents": 53,
"split_summary": {
"dev": 23,
"locked_test": 15,
"selection": 15
},
"template_groups_count": 24,
"buyer_entities_count": 16,
"annotation_queue": [
"INV_3c5a77ac",
"INV_d7f081e3",
"INV_7200a8d1",
"INV_eb98bc06",
"INV_81046572",
"INV_00b9f774",
"INV_4cc9f3ad",
"INV_d822b694",
"INV_d05ac940",
"INV_9782cb20",
"INV_ec2daa9d",
"INV_deea4e74",
"INV_abdc3c30",
"INV_97d62746",
"INV_38301e52",
"INV_bc325113",
"INV_182ee202",
"INV_f2f33f5f",
"INV_8e40a2bd",
"INV_cbbd7b20",
"INV_0f99d813",
"INV_efb5758d",
"INV_8aa742ac",
"INV_ff06d5f2",
"INV_2d640122",
"INV_bfbe0b41",
"INV_f1375513",
"INV_683977e5",
"INV_ff73bd8e",
"INV_5e2f3610",
"INV_fd02fd54",
"INV_a5c0ae6a",
"INV_e92ad79d",
"INV_bf820006",
"INV_22909692",
"INV_2fa979eb",
"INV_3f93ff61",
"INV_9d1a66d2",
"INV_adca903d",
"INV_ab88b109",
"INV_39e785ea",
"INV_000b1f0b",
"INV_0281dde0",
"INV_8acc1d46",
"INV_35e12582",
"INV_d8638369",
"INV_6adebc7c",
"INV_7abaa6d8",
"INV_942bb99d",
"INV_e627a21d",
"INV_548c01b3",
"INV_e02c31bb",
"INV_5913d3da"
],
"manifest": [ "manifest": [
{ {
"doc_id": "INV_fd02fd54", "doc_id": "INV_fd02fd54",
@@ -6,8 +71,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": true "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "fd02fd54732eebce8371140fda73d74a4fdcb1e31db77489268a22e7856e1406"
}, },
{ {
"doc_id": "INV_a5c0ae6a", "doc_id": "INV_a5c0ae6a",
@@ -15,44 +81,49 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": true "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "a5c0ae6ad28745ddd3ec8edeb82e608046c322dce622e3f351b4c8912c7f2939"
}, },
{ {
"doc_id": "INV_3c5a77ac", "doc_id": "INV_3c5a77ac",
"template_group": "T03", "template_group": "T03",
"split": "dev", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_ac1508b567",
"image_sha256": "3c5a77accc55c2b5d9c43109171e749109fb1af74e592387f7eccabbad754695"
}, },
{ {
"doc_id": "INV_d7f081e3", "doc_id": "INV_d7f081e3",
"template_group": "T04", "template_group": "T04",
"split": "dev", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "d7f081e3d0b0acd0e7326214a3cc873b5411d1a60dfaa1eefe485d2535b3eec7"
}, },
{ {
"doc_id": "INV_7200a8d1", "doc_id": "INV_7200a8d1",
"template_group": "T05", "template_group": "T05",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "7200a8d156c0e9f1e9818199f9f837f2dc5cfc132d2e1ae3ba16c16c30a093b1"
}, },
{ {
"doc_id": "INV_eb98bc06", "doc_id": "INV_eb98bc06",
"template_group": "T06", "template_group": "T06",
"split": "dev", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_ae0f1aa6fa",
"image_sha256": "eb98bc063bb3ea0016be3d3387d41ad4170e39b3d6d733a1b09046314d5e205a"
}, },
{ {
"doc_id": "INV_e92ad79d", "doc_id": "INV_e92ad79d",
@@ -60,8 +131,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": true "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "e92ad79da93f9b0d3d115c89b8805fef9e49677ccb14a92383e56a38cb8ac9e7"
}, },
{ {
"doc_id": "INV_81046572", "doc_id": "INV_81046572",
@@ -69,17 +141,19 @@
"split": "selection", "split": "selection",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "81046572e1dbdd01e21ad3ab38f3dd546df039912259605879b056d5297011af"
}, },
{ {
"doc_id": "INV_00b9f774", "doc_id": "INV_00b9f774",
"template_group": "T09", "template_group": "T09",
"split": "selection", "split": "locked_test",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 5, "page_count": 5,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_a65f9386a4",
"image_sha256": "00b9f774d2a1ff82e30853ac1432e4b16e94abb35b66c928080fa0148967bf79"
}, },
{ {
"doc_id": "INV_4cc9f3ad", "doc_id": "INV_4cc9f3ad",
@@ -87,8 +161,9 @@
"split": "locked_test", "split": "locked_test",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "4cc9f3ad06e9be25a719daa9805cf79032686ddc6081fd8c112d90eb7a918574"
}, },
{ {
"doc_id": "INV_bc325113", "doc_id": "INV_bc325113",
@@ -96,8 +171,9 @@
"split": "locked_test", "split": "locked_test",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "bc325113f1e3f0dd7c39612ad8b0cbaf54fc182b6e20c18b7611c15689a6cb00"
}, },
{ {
"doc_id": "INV_bf820006", "doc_id": "INV_bf820006",
@@ -105,8 +181,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "bf820006c8e31d1896281b7a971e3a6fb2e1c9383b8b2d598c28da98959aa494"
}, },
{ {
"doc_id": "INV_22909692", "doc_id": "INV_22909692",
@@ -114,8 +191,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "2290969279c614c20797f2cd1e822a4b2d150d6323f899680e679ea26a54aa00"
}, },
{ {
"doc_id": "INV_2fa979eb", "doc_id": "INV_2fa979eb",
@@ -123,8 +201,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "2fa979eb3267443a403c4d2d595970e515c23eaf8884b25030fc4e76748d2422"
}, },
{ {
"doc_id": "INV_3f93ff61", "doc_id": "INV_3f93ff61",
@@ -132,8 +211,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "3f93ff611663ec6ff8702d5f829d2a469b010814e72e1be072509b930f4cc629"
}, },
{ {
"doc_id": "INV_9d1a66d2", "doc_id": "INV_9d1a66d2",
@@ -141,71 +221,79 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_86f1780bb4",
"image_sha256": "9d1a66d2f5f34a85f5a0226435e192f375b77862b496f47be9e71bfed078cbce"
}, },
{ {
"doc_id": "INV_adca903d", "doc_id": "INV_adca903d",
"template_group": "T13", "template_group": "T13",
"split": "selection", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "adca903d1abe8f91829fd00fe23a24d267bc3b391123c30ab381332981d4dae6"
}, },
{ {
"doc_id": "INV_ab88b109", "doc_id": "INV_ab88b109",
"template_group": "T13", "template_group": "T13",
"split": "selection", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_fe83e52792",
"image_sha256": "ab88b109a1d9c0db88927926b5439963ced5f1c47c036e31ba93dead3725c002"
}, },
{ {
"doc_id": "INV_39e785ea", "doc_id": "INV_39e785ea",
"template_group": "T13", "template_group": "T13",
"split": "selection", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_0e43588b08",
"image_sha256": "39e785ea9f0b5fa0378215221baeeeaedda859035e2bea007fe6763de9e328d4"
}, },
{ {
"doc_id": "INV_000b1f0b", "doc_id": "INV_000b1f0b",
"template_group": "T13", "template_group": "T13",
"split": "selection", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_821a71561f",
"image_sha256": "000b1f0b83d13c646a1efcda49404fab653a10cfb24b263aa5fdcfd2dcd66e9e"
}, },
{ {
"doc_id": "INV_0281dde0", "doc_id": "INV_0281dde0",
"template_group": "T13", "template_group": "T13",
"split": "selection", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_821a71561f",
"image_sha256": "0281dde09cb7f061c39da1a7f09e32381ca30c9b1da5f5849bfc538d9b74cea7"
}, },
{ {
"doc_id": "INV_8acc1d46", "doc_id": "INV_8acc1d46",
"template_group": "T13", "template_group": "T13",
"split": "selection", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_00ec9272df",
"image_sha256": "8acc1d4694e5e3ace15d5205f14b287e99045cc0c99f5f9b07b3327a88d15878"
}, },
{ {
"doc_id": "INV_35e12582", "doc_id": "INV_35e12582",
"template_group": "T13", "template_group": "T13",
"split": "selection", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "35e1258224b33753a70bbb67b14acc7cead9d247ab221c721ad364e3b9f40be4"
}, },
{ {
"doc_id": "INV_d8638369", "doc_id": "INV_d8638369",
@@ -213,8 +301,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "d8638369f8307f5af6158745382861f11f40064786671949a5f2c8f128a00272"
}, },
{ {
"doc_id": "INV_6adebc7c", "doc_id": "INV_6adebc7c",
@@ -222,71 +311,79 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_c3d44d9550",
"image_sha256": "6adebc7c11e6dccd2265400b87849ce35d7b2e05b3f8f82aff9ffd03213e6428"
}, },
{ {
"doc_id": "INV_d822b694", "doc_id": "INV_d822b694",
"template_group": "T15", "template_group": "T15",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "d822b6947c543dbcb361c0d1ff39f6b6b22bbee852cd572fd17b26acbd1d6c55"
}, },
{ {
"doc_id": "INV_7abaa6d8", "doc_id": "INV_7abaa6d8",
"template_group": "T16", "template_group": "T16",
"split": "locked_test", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "7abaa6d8d36e300e8adc7cf02e5d6bd157ebdd8b1a1140eb5bf6c1b534a39832"
}, },
{ {
"doc_id": "INV_942bb99d", "doc_id": "INV_942bb99d",
"template_group": "T16", "template_group": "T16",
"split": "locked_test", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_0ce4f23c4a",
"image_sha256": "942bb99d30648e93431362a0a684c67cef128306b7f96799a781bcfb1eed189f"
}, },
{ {
"doc_id": "INV_e627a21d", "doc_id": "INV_e627a21d",
"template_group": "T16", "template_group": "T16",
"split": "locked_test", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 2, "page_count": 2,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_e31f305610",
"image_sha256": "e627a21d72f91ceba935e56c69ab39d2ec938d15feb5bee3fa89380d36035461"
}, },
{ {
"doc_id": "INV_548c01b3", "doc_id": "INV_548c01b3",
"template_group": "T16", "template_group": "T16",
"split": "locked_test", "split": "dev",
"tier": "Tier_B", "tier": "Tier_B",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_06377628cc",
"image_sha256": "548c01b3ec8cc4645a27b65a3e3c7e04f167d94cad3bbedcbc3b945199c40b7d"
}, },
{ {
"doc_id": "INV_e02c31bb", "doc_id": "INV_e02c31bb",
"template_group": "T16", "template_group": "T16",
"split": "locked_test", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "e02c31bb2c7165f5512f787c5925479d1af48867b37754810b53c558546a0068"
}, },
{ {
"doc_id": "INV_d05ac940", "doc_id": "INV_d05ac940",
"template_group": "T17", "template_group": "T17",
"split": "selection", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_185a91690c",
"image_sha256": "d05ac94061aaf16f81191c53dc1c194f76e0e63dd9c0817b772150a23624832a"
}, },
{ {
"doc_id": "INV_9782cb20", "doc_id": "INV_9782cb20",
@@ -294,143 +391,159 @@
"split": "selection", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "9782cb204422db2257084417000aced9cfb88f78d9d27118fc73c38f5d81ba31"
}, },
{ {
"doc_id": "INV_ec2daa9d", "doc_id": "INV_ec2daa9d",
"template_group": "T19", "template_group": "T19",
"split": "locked_test", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "ec2daa9d4d1b2d09202f6823c74b5fe1f5f9332bdb7c17e83ad3f753576e185f"
}, },
{ {
"doc_id": "INV_182ee202", "doc_id": "INV_182ee202",
"template_group": "T19", "template_group": "T19",
"split": "locked_test", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "182ee202de61a41dc0b691349a98976fb323b0c670bb668e9b36da9ef98ee66e"
}, },
{ {
"doc_id": "INV_deea4e74", "doc_id": "INV_deea4e74",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "deea4e746b303b8b1d4c361383de1c6ab9533f7ea497bdcd032472140d0ef711"
}, },
{ {
"doc_id": "INV_f2f33f5f", "doc_id": "INV_f2f33f5f",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "f2f33f5f861fc81597427d04aacdbb9e85f16c5cf90be380a8d6aedad3af9abc"
}, },
{ {
"doc_id": "INV_8e40a2bd", "doc_id": "INV_8e40a2bd",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "8e40a2bd8491ab10f0b45e0c036571bf7bb1bed80af1e0178bfd1f834b625e07"
}, },
{ {
"doc_id": "INV_cbbd7b20", "doc_id": "INV_cbbd7b20",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "cbbd7b20048f57e59bf11e0b94b66abd9b46a7050cde21efed8eeea878b2b07a"
}, },
{ {
"doc_id": "INV_0f99d813", "doc_id": "INV_0f99d813",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "0f99d8133319751073d56eeeba2a2eec0a0ac3a038c9884a1dba2bef179e94b2"
}, },
{ {
"doc_id": "INV_efb5758d", "doc_id": "INV_efb5758d",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "efb5758d5c2d8973d6f95f93baebbc368dbb00d3b6b02e2b30a04e29630cd09d"
}, },
{ {
"doc_id": "INV_8aa742ac", "doc_id": "INV_8aa742ac",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "8aa742ac3b475549d5cd29242ceab5be7f3a3482584ef21b6438b8ddb7ba8ac6"
}, },
{ {
"doc_id": "INV_ff06d5f2", "doc_id": "INV_ff06d5f2",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "ff06d5f2499e5cbac8be000734698fee617539b75d701a3f298112eca3410f88"
}, },
{ {
"doc_id": "INV_2d640122", "doc_id": "INV_2d640122",
"template_group": "T20", "template_group": "T20",
"split": "dev", "split": "selection",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "2d6401223dbabb16c98e253a4253b213d8c58a234ba7fac449082108ed3692b3"
}, },
{ {
"doc_id": "INV_abdc3c30", "doc_id": "INV_abdc3c30",
"template_group": "T21", "template_group": "T21",
"split": "dev", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_e18eca69bc",
"image_sha256": "abdc3c3068c2ff704fbfdd4a65091b1c98552aa6030211405f7709947255da28"
}, },
{ {
"doc_id": "INV_bfbe0b41", "doc_id": "INV_bfbe0b41",
"template_group": "T21", "template_group": "T21",
"split": "dev", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "bfbe0b4132ce2cfd3bd4ac6956b2da02584f32602f138e5b725e22a81c74e9c2"
}, },
{ {
"doc_id": "INV_f1375513", "doc_id": "INV_f1375513",
"template_group": "T21", "template_group": "T21",
"split": "dev", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_e18eca69bc",
"image_sha256": "f137551349fb51c80476d10aa6211c4744f60b8f37f1782c8df333f148bf6e95"
}, },
{ {
"doc_id": "INV_683977e5", "doc_id": "INV_683977e5",
"template_group": "T21", "template_group": "T21",
"split": "dev", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "683977e534e52f4ac644b46b5221c5b33abb2d2b7649dd8f93888fb969e805f2"
}, },
{ {
"doc_id": "INV_97d62746", "doc_id": "INV_97d62746",
@@ -438,35 +551,39 @@
"split": "locked_test", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_e68d729c7e",
"image_sha256": "97d627466e0f0e8d78754ac8ad40503045cd3e737f287c67d7485cdf93c84ccd"
}, },
{ {
"doc_id": "INV_38301e52", "doc_id": "INV_38301e52",
"template_group": "T23", "template_group": "T23",
"split": "selection", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "38301e52c489eb0671b8325136b8e22815d2f7287737e1f53d5a364e8d6279ad"
}, },
{ {
"doc_id": "INV_ff73bd8e", "doc_id": "INV_ff73bd8e",
"template_group": "T23", "template_group": "T23",
"split": "selection", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "ff73bd8e6d65b5e4855eda06145876fc4700b6c5021d12823a174473cddb10d2"
}, },
{ {
"doc_id": "INV_5e2f3610", "doc_id": "INV_5e2f3610",
"template_group": "T23", "template_group": "T23",
"split": "selection", "split": "locked_test",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": false,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "5e2f361025fde1138bc19f04ee11c881b8d0e3e3c3dee7fcccdc9b770f512afb"
}, },
{ {
"doc_id": "INV_5913d3da", "doc_id": "INV_5913d3da",
@@ -474,8 +591,9 @@
"split": "dev", "split": "dev",
"tier": "Tier_A", "tier": "Tier_A",
"page_count": 1, "page_count": 1,
"annotation_status": "unannotated", "is_contaminated": true,
"is_contaminated": false "buyer_id": "BUYER_94a0c8c545",
"image_sha256": "5913d3dad26b2016a2060d0d7c6d4be248ba54a01d85a666d79d83d44412c321"
} }
] ]
} }
+20 -5
View File
@@ -2,8 +2,8 @@
{ {
"proposal_id": "REMOVE-HARDCODES", "proposal_id": "REMOVE-HARDCODES",
"area": "entity_extraction", "area": "entity_extraction",
"status": "accepted", "status": "open_regression",
"process_outcome": "accepted", "process_outcome": "regression_detected",
"measurement_status": "not_measured", "measurement_status": "not_measured",
"integrity_exempt": true, "integrity_exempt": true,
"baseline_accuracy": null, "baseline_accuracy": null,
@@ -14,11 +14,26 @@
"is_statistically_significant": false, "is_statistically_significant": false,
"leakage_screen_passed": true, "leakage_screen_passed": true,
"leakage_findings": [], "leakage_findings": [],
"cost_aware_accepted": false, "cost_aware_accepted": null,
"latency_delta_seconds": null, "latency_delta_seconds": null,
"vision_fallback_calls": 0, "vision_fallback_calls": 0,
"case_regressions": [], "case_regressions": [
"rejection_reasons": [], {
"doc_id": "INV_adca903d",
"template_group": "T13",
"field": "total_gst_amount",
"before": "621.84",
"after": "0.00",
"line_items_count_before": 2,
"line_items_count_after": 1,
"cause": "Table extractor dropped product row 'LEUKOBAND10*4/6*1ROLLKAM' due to non-numeric unit token 'PCS' colliding with quantity column and evicting numeric quantity '60' into separate row",
"evidence_path": "data_private/diff_report_before_after.json",
"evidence_crop": "data_private/crops/INV_adca903d_footer.png"
}
],
"rejection_reasons": [
"Open regression on INV_adca903d: total_gst_amount dropped 621.84 -> 0.00 and line item LEUKOBAND omitted."
],
"pruning_recommendations": [ "pruning_recommendations": [
"Pruned static hardcoded coordinates, static hospital overrides, and static PAN. Refer to data_private/diff_report_before_after.json for 53-invoice characterization." "Pruned static hardcoded coordinates, static hospital overrides, and static PAN. Refer to data_private/diff_report_before_after.json for 53-invoice characterization."
], ],
+17
View File
@@ -0,0 +1,17 @@
# Known Limits: Static AST Leakage Screening
This document outlines structural limitations of static AST-based screening for data leakage and coordinate hardcoding.
## 1. Dynamic / Obfuscated Runtime String Construction
- **Character Array / Byte Manipulation**: Strings reconstructed dynamically via `chr()`, base64 encoding, hex decoding, or dynamic zlib decompression cannot be statically resolved by AST inspection alone.
- *Mitigation*: Pre-commit hooks prohibit non-synthetic binary decoders and non-standard string decompression in pipeline modules.
- **Complex External Lookups**: If a candidate loads tokens dynamically from an untracked external JSON file or environment variable at runtime, static AST scanning of the code diff will not detect the strings directly.
- *Mitigation*: CI environment runs with hermetic file system checks; pipeline modules are not allowed to load arbitrary external files outside `config/` or `data/`.
## 2. Indirect Mathematical Coordinate Offsets
- **Dynamic Variable Inversion**: Expressions where coordinate names are obscured or deeply nested through custom classes (e.g. `obj.geometry.points[0].matrix_mul(...)`) may evade attribute-name heuristics (`x`, `y`, `box`, `bbox`).
- *Mitigation*: The OCR pipeline uses standard dictionary and tuple bounding box representations (`box`, `bbox`, `[ymin, xmin, ymax, xmax]`), which are all actively matched by `_is_coordinate_node()`.
## 3. Highly Transformed Numbers
- **Arithmetic Composition of Constants**: Numbers composed via arithmetic operations (e.g. `50000 + 4421` instead of `54421`) require full symbolic execution to resolve constant folding.
- *Mitigation*: Constant-folded string concatenation (`'WMP/B/' + '04531'`) is explicitly resolved in AST `visit_BinOp`.
+44 -15
View File
@@ -42,20 +42,36 @@ from app.rrsi.stats import wilson_interval
import tempfile import tempfile
def load_ground_truths(gt_dir: Path): def load_ground_truths(gt_dir: Path) -> Tuple[List[dict], List[Tuple[str, str]]]:
"""Loads all ground truth files in data/ground_truth.""" """
Loads all valid ground truth evaluation schema files in gt_dir (*_expected.json).
Returns (canonical_gts, excluded_files_with_reasons).
"""
gts = [] gts = []
for f in gt_dir.glob("*.json"): excluded = []
for f in sorted(gt_dir.glob("*.json")):
if f.name.endswith("_metadata.json"):
excluded.append((f.name, "sidecar metadata file (not evaluation schema)"))
continue
if f.name.startswith("pdf_ground_truth"):
excluded.append((f.name, "legacy unnormalized raw PDF extractor dump without line-item schema"))
continue
try: try:
with open(f, "r", encoding="utf-8") as fp: with open(f, "r", encoding="utf-8") as fp:
data = json.load(fp) data = json.load(fp)
if isinstance(data, list): if isinstance(data, dict) and data.get("invoice_number") and data.get("items"):
gts.extend(data)
elif isinstance(data, dict):
gts.append(data) gts.append(data)
elif isinstance(data, list):
valid_items = [d for d in data if isinstance(d, dict) and d.get("invoice_number") and d.get("items")]
if valid_items:
gts.extend(valid_items)
else:
excluded.append((f.name, "list without canonical invoice schema (missing invoice_number or items)"))
else:
excluded.append((f.name, "schema missing mandatory invoice_number or items structure"))
except Exception as e: except Exception as e:
print(f"Warning loading {f.name}: {e}") excluded.append((f.name, f"JSON parse error: {e}"))
return gts return gts, excluded
def find_image_for_gt(gt: dict, project_root: Path) -> Optional[Path]: def find_image_for_gt(gt: dict, project_root: Path) -> Optional[Path]:
@@ -142,9 +158,13 @@ def run_benchmark_audit():
orchestrator = RRSIOrchestrator() orchestrator = RRSIOrchestrator()
private_gt = PROJECT_ROOT / "data_private" / "ground_truth" private_gt = PROJECT_ROOT / "data_private" / "ground_truth"
gt_dir = private_gt if private_gt.exists() else PROJECT_ROOT / "data" / "ground_truth" gt_dir = private_gt if private_gt.exists() else PROJECT_ROOT / "data" / "ground_truth"
gts = load_ground_truths(gt_dir) gts, excluded = load_ground_truths(gt_dir)
print(f"Loaded {len(gts)} ground truth annotation files from: {gt_dir}") print(f"Loaded {len(gts)} canonical ground truth evaluation files from: {gt_dir}")
if excluded:
print(f"Excluded {len(excluded)} non-evaluation JSON files from benchmark:")
for fname, reason in excluded:
print(f" - {fname}: Excluded ({reason})")
if not gts: if not gts:
print("[!] No ground truth files found. Ensure data/ground_truth contains JSON files.") print("[!] No ground truth files found. Ensure data/ground_truth contains JSON files.")
return return
@@ -186,18 +206,14 @@ def run_benchmark_audit():
print("\n[+] Audit Metrics Summary (Live Pipeline Execution on Real Images):") print("\n[+] Audit Metrics Summary (Live Pipeline Execution on Real Images):")
print(f" Total Invoices Processed: {metrics.sample_count}") print(f" Total Invoices Processed: {metrics.sample_count}")
print(f" Overall Macro Accuracy: {metrics.macro_accuracy:.2f}%")
print(f" Overall Macro F1-Score: {metrics.macro_f1:.2f}%")
print(f" Table Cell-Level F1: {metrics.table_cell_f1:.4f}") print(f" Table Cell-Level F1: {metrics.table_cell_f1:.4f}")
print(f" Table Row-Level F1: {metrics.table_row_f1:.4f}") print(f" Table Row-Level F1: {metrics.table_row_f1:.4f}")
print(f" Arithmetic Consistency: {metrics.arithmetic_consistency_pct:.2f}%") print(f" Arithmetic Consistency: {metrics.arithmetic_consistency_pct:.2f}%")
print(f" Document Inconsistent GT: {metrics.document_inconsistent_pct:.2f}%") print(f" Document Inconsistent GT: {metrics.document_inconsistent_pct:.2f}%")
print(f" Total Execution Time: {total_pipeline_time:.2f}s ({total_pipeline_time / metrics.sample_count:.2f}s / invoice)") print(f" Total Execution Time: {total_pipeline_time:.2f}s ({total_pipeline_time / metrics.sample_count:.2f}s / invoice)")
ci_low, ci_high = wilson_interval(int(round(metrics.macro_accuracy * metrics.sample_count / 100)), metrics.sample_count)
print(f" Macro 95% Wilson CI: [{ci_low*100:.1f}%, {ci_high*100:.1f}%] (N={metrics.sample_count})")
# 1. Per-Field Precision / Recall / F1 Table # 1. Per-Field Precision / Recall / F1 Table
print("\n[+] Per-Field Extraction Performance (Wilson Score Confidence Intervals):") print("\n[+] Per-Field Extraction Performance (Wilson Score CIs - Note: Does Not Account for Cross-Field Correlation):")
print("-" * 105) print("-" * 105)
print(f"{'Field Name':<22} | {'Exp':<5} | {'Corr':<5} | {'Hall':<5} | {'Prec':<7} | {'Recall':<7} | {'F1':<7} | {'Acc':<7} | {'Wilson 95% CI':<16}") print(f"{'Field Name':<22} | {'Exp':<5} | {'Corr':<5} | {'Hall':<5} | {'Prec':<7} | {'Recall':<7} | {'F1':<7} | {'Acc':<7} | {'Wilson 95% CI':<16}")
print("-" * 105) print("-" * 105)
@@ -263,6 +279,19 @@ def run_benchmark_audit():
stag_icon = "[STAGNANT] Shift Area" if status["is_stagnant"] else "[ACTIVE]" stag_icon = "[STAGNANT] Shift Area" if status["is_stagnant"] else "[ACTIVE]"
print(f" * {area:<25} : {status['consecutive_failures']} consecutive fails | {stag_icon}") print(f" * {area:<25} : {status['consecutive_failures']} consecutive fails | {stag_icon}")
# Descriptive Only Section (Moved from top per 0.7.5: not valid at small N)
from app.rrsi.stats import cluster_bootstrap_mean
doc_accuracies = []
for doc_id, doc_res in metrics.doc_results.items():
outcomes = list(doc_res.field_outcomes.values())
doc_acc = (sum(1 for o in outcomes if o) / len(outcomes) * 100.0) if outcomes else 0.0
doc_accuracies.append(doc_acc)
agg_boot = cluster_bootstrap_mean(doc_accuracies, n_resamples=10000, seed=42)
print("\n[+] Descriptive Only - Not Valid at Small Sample Size (N=2) (Note: Not statistically meaningful below ~10 clusters):")
print(f" Overall Macro Accuracy: {metrics.macro_accuracy:.2f}% (Invoice-Cluster Bootstrap 95% CI: [{agg_boot['ci_lower']:.1f}%, {agg_boot['ci_upper']:.1f}%] - not statistically meaningful below ~10 clusters)")
print(f" Overall Macro F1-Score: {metrics.macro_f1:.2f}%")
print("\n" + "=" * 75) print("\n" + "=" * 75)
+250
View File
@@ -0,0 +1,250 @@
# scripts/build_git_safe_manifest.py
"""
Builds the Git-Safe manifest (data/manifest.json) and computes template & buyer histograms.
Enforces:
1. Contamination propagation: any template group touched in scratch/ or tests/ is locked to 'dev'.
2. Split partitioning: zero template straddling between dev, selection, and locked_test.
3. Privacy: only anonymous doc_ids, template groups, splits, image_sha256, and anonymous buyer IDs.
4. Annotation queue: ordered to maximize template and buyer diversity in selection/locked_test first.
"""
import os
import sys
import json
import hashlib
from pathlib import Path
from collections import Counter, defaultdict
PROJECT_ROOT = Path(__file__).resolve().parent.parent
def compute_sha256(filepath: Path) -> str:
h = hashlib.sha256()
with open(filepath, "rb") as f:
while chunk := f.read(65536):
h.update(chunk)
return h.hexdigest()
def main():
private_manifest_path = PROJECT_ROOT / "data_private" / "manifest_private.json"
if not private_manifest_path.exists():
print(f"Error: {private_manifest_path} not found")
sys.exit(1)
with open(private_manifest_path, "r", encoding="utf-8") as f:
private_data = json.load(f)
manifest_entries = private_data["manifest"]
deskewed_dir = PROJECT_ROOT / "data_private" / "deskewed"
after_dir = PROJECT_ROOT / "data_private" / "after_outputs"
SALT = "RRSI_SALT_SECURE_2026_"
# 1. Map files/doc_ids to template groups
file_to_group = {}
id_to_group = {}
for m in manifest_entries:
tg = m.get("template_group", "T_UNKNOWN")
id_to_group[m["doc_id"]] = tg
for f in m.get("files", []):
file_to_group[f] = tg
file_to_group[Path(f).stem] = tg
if m.get("logical_base_id"):
file_to_group[m.get("logical_base_id")] = tg
# 2. Identify contaminated template groups from scratch/ and tests/
contaminated_groups = set()
for search_dir in ["scratch", "tests"]:
p = PROJECT_ROOT / search_dir
if not p.exists():
continue
for fpath in p.rglob("*"):
if fpath.is_file() and fpath.suffix in [".py", ".json", ".txt", ".md", ".png"]:
fname = fpath.name
for k, tg in file_to_group.items():
if len(k) > 3 and k in fname:
contaminated_groups.add(tg)
if fpath.suffix in [".py", ".json", ".txt", ".md"]:
try:
content = fpath.read_text(encoding="utf-8", errors="ignore")
for k, tg in file_to_group.items():
if len(k) > 4 and k in content:
contaminated_groups.add(tg)
for did, tg in id_to_group.items():
if did in content:
contaminated_groups.add(tg)
except Exception:
pass
# Ensure baseline known contaminated templates are included
for m in manifest_entries:
if m.get("is_contaminated"):
contaminated_groups.add(m.get("template_group"))
# 3. Associate anonymous buyer ID per document
doc_buyer_map = {}
buyer_counter = Counter()
for m in manifest_entries:
doc_id = m["doc_id"]
out_f = after_dir / f"{doc_id}.json"
buyer_key = "UNKNOWN"
if out_f.exists():
try:
data = json.loads(out_f.read_text(encoding="utf-8"))
bg = data.get("customer_gstin")
bn = data.get("customer_name")
if bg:
buyer_key = f"GSTIN:{bg.strip().upper()}"
elif bn:
buyer_key = f"NAME:{bn.strip().upper()}"
except Exception:
pass
buyer_hash = "BUYER_" + hashlib.sha256((SALT + buyer_key).encode("utf-8")).hexdigest()[:10]
doc_buyer_map[doc_id] = buyer_hash
buyer_counter[buyer_hash] += 1
# 4. Group documents by template
docs_by_template = defaultdict(list)
for m in manifest_entries:
tg = m.get("template_group", "T_UNKNOWN")
docs_by_template[tg].append(m)
# 5. Split assignment by template group:
# All contaminated template groups -> dev
# Clean template groups -> balanced between selection and locked_test
splits = {}
clean_templates = sorted([t for t in docs_by_template.keys() if t not in contaminated_groups])
contaminated_templates = sorted(list(contaminated_groups))
for tg in contaminated_templates:
splits[tg] = "dev"
# Distribute clean templates alternately to balance template and document count
# Sort clean templates by document count descending for optimal binning
clean_templates_sorted = sorted(clean_templates, key=lambda t: len(docs_by_template[t]), reverse=True)
sel_count, test_count = 0, 0
for tg in clean_templates_sorted:
tg_docs = len(docs_by_template[tg])
if sel_count <= test_count:
splits[tg] = "selection"
sel_count += tg_docs
else:
splits[tg] = "locked_test"
test_count += tg_docs
# 6. Build Git-Safe manifest entries
git_safe_manifest = []
split_counts = Counter()
for m in manifest_entries:
doc_id = m["doc_id"]
tg = m.get("template_group", "T_UNKNOWN")
split = splits[tg]
is_contaminated = (tg in contaminated_groups)
# Compute image hash if file exists
files = m.get("files", [])
image_hashes = []
for f in files:
img_path = deskewed_dir / f
if img_path.exists():
image_hashes.append(compute_sha256(img_path))
else:
# Fallback to deterministic hash of doc_id if deskewed not present
image_hashes.append(hashlib.sha256((SALT + f).encode("utf-8")).hexdigest())
entry = {
"doc_id": doc_id,
"template_group": tg,
"split": split,
"tier": m.get("tier", "Tier_A"),
"page_count": m.get("page_count", 1),
"is_contaminated": is_contaminated,
"buyer_id": doc_buyer_map.get(doc_id, "BUYER_UNKNOWN"),
"image_sha256": image_hashes[0] if image_hashes else None
}
git_safe_manifest.append(entry)
split_counts[split] += 1
# 7. Build Annotation Queue
# Priority: selection and locked_test first, maximizing template & buyer diversity
# 1st round: 1 document from each clean template group in selection/locked_test with unique buyers
# 2nd round: remaining selection/locked_test documents
# 3rd round: dev documents
queue_round_1 = []
queue_round_2 = []
queue_round_3 = []
seen_templates_r1 = set()
seen_buyers_r1 = set()
for entry in git_safe_manifest:
split = entry["split"]
tg = entry["template_group"]
b_id = entry["buyer_id"]
if split in ["selection", "locked_test"]:
if tg not in seen_templates_r1:
queue_round_1.append(entry["doc_id"])
seen_templates_r1.add(tg)
seen_buyers_r1.add(b_id)
else:
queue_round_2.append(entry["doc_id"])
else:
queue_round_3.append(entry["doc_id"])
annotation_queue = queue_round_1 + queue_round_2 + queue_round_3
manifest_output = {
"version": "1.0.0",
"description": "Git-safe anonymized benchmark manifest with template-isolated split partitioning",
"total_documents": len(git_safe_manifest),
"split_summary": dict(split_counts),
"template_groups_count": len(docs_by_template),
"buyer_entities_count": len(buyer_counter),
"annotation_queue": annotation_queue,
"manifest": git_safe_manifest
}
out_path = PROJECT_ROOT / "data" / "manifest.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8") as f:
json.dump(manifest_output, f, indent=2)
print("=" * 80)
print(" TEMPLATE & BUYER HISTOGRAMS (PHASE 1.1b / 1.2b)")
print("=" * 80)
print(f"Total Unique Invoices : {len(git_safe_manifest)}")
print(f"Total Unique Templates: {len(docs_by_template)}")
print(f"Total Unique Buyers : {len(buyer_counter)}")
print("\n[+] Invoices Per Template Group Histogram:")
print("-" * 55)
print(f"{'Template':<10} | {'Count':<6} | {'Split':<12} | {'Contaminated?'}")
print("-" * 55)
for tg, docs in sorted(docs_by_template.items(), key=lambda x: len(x[1]), reverse=True):
is_cont = "YES (dev-only)" if tg in contaminated_groups else "NO (clean)"
print(f"{tg:<10} | {len(docs):<6} | {splits[tg]:<12} | {is_cont}")
print("-" * 55)
print("\n[+] Invoices Per Buyer Entity Histogram:")
print("-" * 45)
print(f"{'Buyer Entity ID':<25} | {'Invoice Count':<12}")
print("-" * 45)
for b_id, count in buyer_counter.most_common():
print(f"{b_id:<25} | {count:<12}")
print("-" * 45)
print("\n[+] Dataset Split Partitioning Summary:")
print("-" * 45)
for sp, cnt in split_counts.items():
tg_cnt = len({m['template_group'] for m in git_safe_manifest if m['split'] == sp})
print(f" * {sp:<12} : {cnt:>2} invoices across {tg_cnt:>2} template groups")
print("-" * 45)
print(f"\n[+] Annotation Queue Generated: {len(annotation_queue)} invoices prioritized by diversity.")
print(f" * High-Priority Round 1 (Max Diversity): {len(queue_round_1)} docs")
print(f" * Round 2 (Remaining Selection/Test) : {len(queue_round_2)} docs")
print(f" * Round 3 (Dev Corpus) : {len(queue_round_3)} docs")
print(f"\n[+] Git-safe manifest written to: {out_path}")
if __name__ == "__main__":
main()
+23 -15
View File
@@ -28,6 +28,7 @@ PHONE_REGEX = re.compile(r"\b(?:\+91[\-\s]?)?[6-9]\d{9}\b|\b0\d{2,4}[\-\s]?\d{6,
SYNTHETIC_WHITELIST = { SYNTHETIC_WHITELIST = {
"27AAPFU0939F1ZV", # Standard statutory dummy test GSTIN "27AAPFU0939F1ZV", # Standard statutory dummy test GSTIN
"27AAPFU0939F1ZW", # Intentional invalid test GSTIN "27AAPFU0939F1ZW", # Intentional invalid test GSTIN
"99AAPFU0939F1ZV", # Intentional invalid state test GSTIN
"AAPFU0939F", # Dummy test PAN "AAPFU0939F", # Dummy test PAN
"020-00000000", "020-00000000",
"9999999999" "9999999999"
@@ -163,30 +164,37 @@ def scan_full_history() -> bool:
msg_violations = scan_text_lines(res_msg.stdout, f"commit {commit[:7]} message", salt, forbidden_hashes) msg_violations = scan_text_lines(res_msg.stdout, f"commit {commit[:7]} message", salt, forbidden_hashes)
violations.extend(msg_violations) violations.extend(msg_violations)
# Check all blobs in commit # Walk every blob object reachable from any ref
res_tree = subprocess.run(["git", "ls-tree", "-r", commit], capture_output=True, text=True) res_objs = subprocess.run(["git", "rev-list", "--objects", "--all"], capture_output=True, text=True)
for line in res_tree.stdout.splitlines(): for line in res_objs.stdout.splitlines():
parts = line.split() parts = line.strip().split(maxsplit=1)
if len(parts) >= 4 and parts[1] == "blob": if not parts:
blob_hash = parts[2] continue
file_path = line.split(maxsplit=3)[3].strip() obj_hash = parts[0]
obj_path = parts[1] if len(parts) > 1 else ""
norm_path = file_path.replace("\\", "/") # Check object type
res_type = subprocess.run(["git", "cat-file", "-t", obj_hash], capture_output=True, text=True)
if res_type.stdout.strip() != "blob":
continue
if obj_path:
norm_path = obj_path.replace("\\", "/")
for forbidden in FORBIDDEN_PATH_SUBSTRINGS: for forbidden in FORBIDDEN_PATH_SUBSTRINGS:
if forbidden in norm_path: if forbidden in norm_path:
violations.append(f"HISTORICAL FORBIDDEN FILE: '{file_path}' in commit {commit[:7]}") violations.append(f"HISTORICAL FORBIDDEN FILE: '{obj_path}' ({obj_hash[:7]})")
if blob_hash in scanned_blobs: if obj_hash in scanned_blobs:
continue continue
scanned_blobs.add(blob_hash) scanned_blobs.add(obj_hash)
if any(file_path.endswith(ext) for ext in [".png", ".jpg", ".pdf", ".pyc", ".zip"]): if any(obj_path.endswith(ext) for ext in [".png", ".jpg", ".pdf", ".pyc", ".zip"]):
continue continue
if file_path in ["scripts/check_git_hygiene.py", "config/forbidden_hashes.json"]: if obj_path in ["scripts/check_git_hygiene.py", "config/forbidden_hashes.json"]:
continue continue
res_blob = subprocess.run(["git", "cat-file", "-p", blob_hash], capture_output=True, text=True, errors="ignore") res_blob = subprocess.run(["git", "cat-file", "-p", obj_hash], capture_output=True, text=True, errors="ignore")
blob_violations = scan_text_lines(res_blob.stdout, f"blob {blob_hash[:7]} ({file_path}) in {commit[:7]}", salt, forbidden_hashes) blob_violations = scan_text_lines(res_blob.stdout, f"blob {obj_hash[:7]} ({obj_path or 'anonymous'})", salt, forbidden_hashes)
violations.extend(blob_violations) violations.extend(blob_violations)
if violations: if violations:
+35
View File
@@ -0,0 +1,35 @@
# scripts/generate_synthetic_invoices.py
"""
CLI script to generate synthetic test invoices for development, unit testing,
and ablation experiments (never for selection or test).
"""
import argparse
from pathlib import Path
from app.rrsi.synthetic_generator import SyntheticInvoiceGenerator
def main():
parser = argparse.ArgumentParser(description="Generate synthetic invoices with ground truth.")
parser.add_argument("--count", type=int, default=10, help="Number of invoices to generate")
parser.add_argument("--output-dir", type=str, default="data/synthetic", help="Output directory")
parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility")
parser.add_argument("--noise", action="store_true", help="Add visual noise (rotation, blur)")
args = parser.parse_args()
out_dir = Path(args.output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
print(f"Generating {args.count} synthetic invoices (seed={args.seed}) into {out_dir}...")
generator = SyntheticInvoiceGenerator(seed=args.seed)
for i in range(1, args.count + 1):
_, data = generator.generate_sample(invoice_idx=i, output_dir=out_dir, add_noise=args.noise)
if i % 5 == 0 or i == args.count:
print(f" [{i}/{args.count}] Generated {data['invoice_number']}")
print(f"Finished generating {args.count} invoices.")
if __name__ == "__main__":
main()
+115
View File
@@ -0,0 +1,115 @@
# scripts/statistical_power.py
"""
Statistical Power Analysis for RRSI Selection & Audit (Phase 1.7).
Calculates Minimum Detectable Effect (MDE) under:
- Paired McNemar discordant-pair formulation
- Paired Cluster Bootstrap accounting for template clustering (Design Effect)
Evaluates whether current sample size N has sufficient power (80% power at alpha=0.05)
to detect realistic pipeline gains (typically 1.5% - 3.0%).
"""
import math
import argparse
from typing import Dict, Any, Optional
def compute_statistical_power(
sample_count: int,
template_count: int,
discordant_rate: float = 0.10,
icc: float = 0.15,
alpha: float = 0.05,
power: float = 0.80
) -> Dict[str, Any]:
"""
Computes MDE for paired evaluation with template clustering.
Args:
sample_count: Total number of documents (N)
template_count: Number of unique template groups (clusters)
discordant_rate: Fraction of documents with discordant outcomes (cand != base)
icc: Intra-cluster correlation coefficient
alpha: Type I error rate (two-tailed)
power: Desired statistical power (1 - Type II error)
"""
if sample_count <= 0:
return {
"sample_count": 0,
"mde_pct": 100.0,
"is_underpowered": True,
"assessment": "Insufficient sample count (N=0)."
}
# Standard normal critical values (alpha=0.05 -> 1.96, power=0.80 -> 0.8416)
z_alpha = 1.96
z_beta = 0.8416
# Unclustered MDE (McNemar paired)
se_paired = math.sqrt(max(0.001, discordant_rate) / sample_count)
mde_unclustered = (z_alpha + z_beta) * se_paired
# Cluster Design Effect (DEFF)
avg_cluster_size = sample_count / max(1, template_count)
deff = 1.0 + (max(1.0, avg_cluster_size) - 1.0) * icc
deff_multiplier = math.sqrt(max(1.0, deff))
mde_clustered = mde_unclustered * deff_multiplier
mde_pct = round(mde_clustered * 100.0, 2)
# Realistic gain threshold: realistic pipeline gains are 1.5% - 3.0%
is_underpowered = (mde_pct > 3.0)
if mde_pct > 5.0:
assessment = (
f"SEVERELY UNDERPOWERED: Minimum detectable improvement is {mde_pct}%, "
f"which is significantly larger than realistic incremental pipeline gains (1.5% - 3.0%). "
f"To detect a 2.0% gain at 80% power, annotate at least N >= {int(math.ceil((z_alpha+z_beta)**2 * discordant_rate * deff / (0.02**2)))} documents."
)
elif mde_pct > 3.0:
assessment = (
f"MARGINALLY UNDERPOWERED: MDE is {mde_pct}%. Only large architectural improvements will be statistically detectable."
)
else:
assessment = f"ADEQUATELY POWERED: MDE is {mde_pct}%, capable of detecting fine-grained gains >= {mde_pct}%."
return {
"sample_count": sample_count,
"template_count": template_count,
"avg_cluster_size": round(avg_cluster_size, 2),
"discordant_rate": discordant_rate,
"design_effect": round(deff, 3),
"mde_pct": mde_pct,
"is_underpowered": is_underpowered,
"assessment": assessment
}
def main():
parser = argparse.ArgumentParser(description="Calculate statistical power and MDE for invoice benchmark.")
parser.add_argument("--samples", type=int, default=12, help="Selection sample count")
parser.add_argument("--templates", type=int, default=3, help="Number of template groups")
parser.add_argument("--discordant-rate", type=float, default=0.10, help="Discordant pair rate")
args = parser.parse_args()
res = compute_statistical_power(
sample_count=args.samples,
template_count=args.templates,
discordant_rate=args.discordant_rate
)
print("=" * 65)
print(" RRSI STATISTICAL POWER & SENSITIVITY REPORT")
print("=" * 65)
print(f"Sample Count (N) : {res['sample_count']}")
print(f"Template Clusters : {res['template_count']}")
print(f"Average Cluster Size : {res['avg_cluster_size']}")
print(f"Cluster Design Effect : {res['design_effect']}")
print(f"Discordant Pair Rate : {res['discordant_rate'] * 100:.1f}%")
print(f"Minimum Detectable Effect: {res['mde_pct']}% (at 80% power, alpha=0.05)")
print(f"\nAssessment:\n {res['assessment']}")
print("=" * 65)
if __name__ == "__main__":
main()
+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 # Must be corrected to 1050.0
assert fin["grand_total"] == 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 = [ lines = [
{"text": "Invoice Date: 10/08/2026"}, {"text": "Invoice Date: 10/08/2026"},
{"text": "Payment Terms: Credit 20 Days"}, {"text": "Payment Terms: Credit 20 Days"},
@@ -149,5 +149,5 @@ def test_due_date_inference_from_credit_terms():
) )
meta = res["meta"] meta = res["meta"]
# 10/08/2026 + 20 days = 30/08/2026 # Due date must NOT be synthesized from credit terms; only reported when explicitly printed
assert meta["due_date"] == "30/08/2026" 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