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}")
# ---------------------------------------------------------------------
# 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
+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)
act_val = pred.get(f)
# Hallucination check: expected is null, actual is non-null
if exp_val is None or str(exp_val).strip() == "":
if act_val is not None and str(act_val).strip() != "":
# UNANNOTATED ground truth: field has not been reviewed by human annotator; skip scoring
if str(exp_val).strip() in ("UNANNOTATED", "__UNANNOTATED__"):
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
failure_counts[ExtractionErrorClass.HALLUCINATION.value] += 1
fail_rec = FailureDetail(
primary_class=ExtractionErrorClass.HALLUCINATION,
field_name=f,
expected=None,
expected="ABSENT",
actual=act_val,
file_id=doc_id,
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)
doc_failures.append(fail_rec)
+1 -1
View File
@@ -135,7 +135,7 @@ class ExperimentLedger:
f"- **Candidate Accuracy**: `{c_acc}`",
f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO'}`",
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),
"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
leakage_screen_passed: bool = True
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
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)
pruning_recommendations: List[str] = field(default_factory=list)
failure_deltas: Dict[str, int] = field(default_factory=dict)