baseline: non-sensitive scaffolding, hygiene hooks, synthetic test fixtures, and docs
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
# scripts/build_manifest_and_splits.py
|
||||
"""
|
||||
Seeded Split Assignment & Annotation Queue Generator (Phase 1.2b).
|
||||
- Contamination propagates to entire template group (assigned to dev).
|
||||
- Group-level seeded splitting: dev, selection, locked_test.
|
||||
- Writes git-safe data/manifest.json and private data_private/manifest_private.json.
|
||||
- Creates blank annotation templates and prioritized annotation queue.
|
||||
"""
|
||||
|
||||
import json
|
||||
import random
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Set
|
||||
|
||||
CONTAMINATED_KEYWORDS = [
|
||||
"4531", "196", "1415", "170588", "3930", "264882", "8497", "8184", "T07"
|
||||
]
|
||||
|
||||
def generate_splits_and_manifest():
|
||||
private_dir = Path("data_private")
|
||||
mapping_file = private_dir / "template_mapping.json"
|
||||
if not mapping_file.exists():
|
||||
print(f"[!] File not found: {mapping_file}. Run scripts/build_template_hierarchy.py first.")
|
||||
return
|
||||
|
||||
with open(mapping_file, "r", encoding="utf-8") as f:
|
||||
mapping_data = json.load(f)
|
||||
|
||||
logical_invoices = mapping_data["logical_invoices"]
|
||||
|
||||
# 1. Identify Contaminated Groups
|
||||
contaminated_groups: Set[str] = set()
|
||||
for base_id, inv_data in logical_invoices.items():
|
||||
lower_base = base_id.lower()
|
||||
if any(k in lower_base for k in CONTAMINATED_KEYWORDS):
|
||||
contaminated_groups.add(inv_data["template_group"])
|
||||
|
||||
print(f"[*] Contaminated template groups (propagated to dev only): {sorted(contaminated_groups)}")
|
||||
|
||||
# Group logical invoices by template group
|
||||
group_to_invoices: Dict[str, List[str]] = {}
|
||||
for base_id, inv_data in logical_invoices.items():
|
||||
group_to_invoices.setdefault(inv_data["template_group"], []).append(base_id)
|
||||
|
||||
all_groups = sorted(group_to_invoices.keys())
|
||||
uncontaminated_groups = [g for g in all_groups if g not in contaminated_groups]
|
||||
|
||||
# Seeded split allocation for uncontaminated groups
|
||||
rng = random.Random(42)
|
||||
rng.shuffle(uncontaminated_groups)
|
||||
|
||||
# Assign uncontaminated groups to meet targets:
|
||||
# dev gets all contaminated groups + some uncontaminated
|
||||
# selection target >= 12 invoices, locked_test target >= 8 invoices
|
||||
group_splits: Dict[str, str] = {}
|
||||
for g in contaminated_groups:
|
||||
group_splits[g] = "dev"
|
||||
|
||||
selection_groups = []
|
||||
locked_test_groups = []
|
||||
dev_extra_groups = []
|
||||
|
||||
sel_inv_count = 0
|
||||
test_inv_count = 0
|
||||
|
||||
for g in uncontaminated_groups:
|
||||
count = len(group_to_invoices[g])
|
||||
if sel_inv_count < 15 and len(selection_groups) < 6:
|
||||
group_splits[g] = "selection"
|
||||
selection_groups.append(g)
|
||||
sel_inv_count += count
|
||||
elif test_inv_count < 10 and len(locked_test_groups) < 4:
|
||||
group_splits[g] = "locked_test"
|
||||
locked_test_groups.append(g)
|
||||
test_inv_count += count
|
||||
else:
|
||||
group_splits[g] = "dev"
|
||||
dev_extra_groups.append(g)
|
||||
|
||||
# Assign Tier levels:
|
||||
# Target: All target invoices get Tier A (header, totals, GSTIN)
|
||||
# At least 15 invoices get Tier B (full line items), prioritizing selection and test
|
||||
tier_b_count = 0
|
||||
manifest_records = []
|
||||
private_manifest_records = []
|
||||
annotation_queue = []
|
||||
|
||||
for base_id, inv_data in sorted(logical_invoices.items()):
|
||||
grp = inv_data["template_group"]
|
||||
split = group_splits[grp]
|
||||
is_contaminated = grp in contaminated_groups
|
||||
|
||||
# Determine Tier
|
||||
if split in ["selection", "locked_test"] and tier_b_count < 15:
|
||||
tier = "Tier_B"
|
||||
tier_b_count += 1
|
||||
elif is_contaminated and base_id in ["4531", "264882"]:
|
||||
tier = "Tier_B"
|
||||
else:
|
||||
tier = "Tier_A"
|
||||
|
||||
# Git-safe record (hashes and anonymous IDs only)
|
||||
git_safe_rec = {
|
||||
"doc_id": inv_data["anonymous_id"],
|
||||
"template_group": grp,
|
||||
"split": split,
|
||||
"tier": tier,
|
||||
"page_count": inv_data["page_count"],
|
||||
"annotation_status": "annotated" if base_id in ["4531", "264882"] else "unannotated",
|
||||
"is_contaminated": is_contaminated
|
||||
}
|
||||
manifest_records.append(git_safe_rec)
|
||||
|
||||
# Private record with actual file paths
|
||||
private_rec = dict(git_safe_rec)
|
||||
private_rec["logical_base_id"] = base_id
|
||||
private_rec["files"] = inv_data["files"]
|
||||
private_manifest_records.append(private_rec)
|
||||
|
||||
# Add to annotation queue if unannotated
|
||||
if git_safe_rec["annotation_status"] == "unannotated":
|
||||
# Priority: selection first, then locked_test, then dev
|
||||
priority = 1 if split == "selection" else (2 if split == "locked_test" else 3)
|
||||
labor_mins = 10 if tier == "Tier_B" else 3
|
||||
annotation_queue.append({
|
||||
"priority": priority,
|
||||
"split": split,
|
||||
"template_group": grp,
|
||||
"anonymous_id": inv_data["anonymous_id"],
|
||||
"logical_base": base_id,
|
||||
"tier": tier,
|
||||
"files": inv_data["files"],
|
||||
"est_labor_minutes": labor_mins
|
||||
})
|
||||
|
||||
# Sort queue by priority and template diversity
|
||||
annotation_queue.sort(key=lambda x: (x["priority"], x["template_group"], x["anonymous_id"]))
|
||||
|
||||
# 2. Write Git-Safe data/manifest.json
|
||||
manifest_path = Path("data/manifest.json")
|
||||
with open(manifest_path, "w", encoding="utf-8") as f:
|
||||
json.dump({"manifest": manifest_records}, f, indent=2)
|
||||
|
||||
# 3. Write Private Manifest
|
||||
private_manifest_path = private_dir / "manifest_private.json"
|
||||
with open(private_manifest_path, "w", encoding="utf-8") as f:
|
||||
json.dump({"manifest": private_manifest_records}, f, indent=2)
|
||||
|
||||
# 4. Generate Blank Annotation Templates
|
||||
template_dir = private_dir / "annotation_templates"
|
||||
template_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
blank_tier_a = {
|
||||
"metadata": {
|
||||
"annotator": "",
|
||||
"date": "YYYY-MM-DD",
|
||||
"source": "from_image_blind",
|
||||
"tier": "Tier_A"
|
||||
},
|
||||
"invoice_number": "",
|
||||
"invoice_date": "YYYY-MM-DD",
|
||||
"due_date": None,
|
||||
"PO_number": None,
|
||||
"customer_name": "",
|
||||
"customer_gstin": "",
|
||||
"seller_name": "",
|
||||
"seller_gstin": "",
|
||||
"invoice_amount": "0.00",
|
||||
"total_gst_amount": "0.00",
|
||||
"round_off": "0.00"
|
||||
}
|
||||
with open(template_dir / "blank_tier_a.json", "w", encoding="utf-8") as f:
|
||||
json.dump(blank_tier_a, f, indent=2)
|
||||
|
||||
blank_tier_b = dict(blank_tier_a)
|
||||
blank_tier_b["metadata"]["tier"] = "Tier_B"
|
||||
blank_tier_b["items"] = [
|
||||
{
|
||||
"description": "",
|
||||
"hsn_sac": "",
|
||||
"quantity": 1,
|
||||
"unit_price": "0.00",
|
||||
"total_price": "0.00",
|
||||
"Discount": "0.00",
|
||||
"Gst%": 5
|
||||
}
|
||||
]
|
||||
with open(template_dir / "blank_tier_b.json", "w", encoding="utf-8") as f:
|
||||
json.dump(blank_tier_b, f, indent=2)
|
||||
|
||||
# Save queue to private dir
|
||||
queue_file = private_dir / "annotation_queue.json"
|
||||
with open(queue_file, "w", encoding="utf-8") as f:
|
||||
json.dump({"annotation_queue": annotation_queue}, f, indent=2)
|
||||
|
||||
# Summary calculations
|
||||
split_counts = {"dev": 0, "selection": 0, "locked_test": 0}
|
||||
split_groups = {"dev": set(), "selection": set(), "locked_test": set()}
|
||||
for r in manifest_records:
|
||||
split_counts[r["split"]] += 1
|
||||
split_groups[r["split"]].add(r["template_group"])
|
||||
|
||||
total_queue_mins = sum(item["est_labor_minutes"] for item in annotation_queue)
|
||||
|
||||
print("\n[+] SPLIT ALLOCATION SUMMARY:")
|
||||
print(f" - Dev split: {split_counts['dev']} invoices across {len(split_groups['dev'])} template groups")
|
||||
print(f" - Selection split: {split_counts['selection']} invoices across {len(split_groups['selection'])} template groups")
|
||||
print(f" - Locked Test split: {split_counts['locked_test']} invoices across {len(split_groups['locked_test'])} template groups")
|
||||
print(f" - Total Queue Items: {len(annotation_queue)} unannotated invoices")
|
||||
print(f" - Est. Total Labor: {total_queue_mins / 60.0:.1f} hours ({total_queue_mins} minutes)")
|
||||
print(f" - Git-Safe manifest: {manifest_path}")
|
||||
print(f" - Private manifest: {private_manifest_path}")
|
||||
print(f" - Queue file: {queue_file}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
generate_splits_and_manifest()
|
||||
@@ -0,0 +1,267 @@
|
||||
# scripts/build_template_hierarchy.py
|
||||
"""
|
||||
Hierarchical Template Grouping & Dataset Inventory (Phase 1.1b).
|
||||
Hierarchy: Page -> Logical Invoice -> Template Group.
|
||||
- Prioritizes: (a) Seller GSTIN/name, (b) Header layout & table column set, (c) Series adjacency.
|
||||
- Enforces: All pages of an invoice share exactly one template group (code assertion).
|
||||
- Anonymous IDs: INV_<hash8>, T##.
|
||||
- Saves private mappings and contact sheets strictly under data_private/.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Set, Tuple
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
# Add project root to sys.path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
GSTIN_REGEX = re.compile(r"\b\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]\b")
|
||||
SALT = "RRSI_SALT_SECURE_2026_"
|
||||
# Salted SHA256 of hardcoded buyer GSTIN
|
||||
HARDCODED_BUYER_HASH = "51d4a44facda448c5a4d62325c317daee48cf498396aa7e7d97607cb38ee84c3"
|
||||
|
||||
def get_sha256(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
while chunk := f.read(65536):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def get_salted_hash(text: str) -> str:
|
||||
return hashlib.sha256((SALT + text.strip().upper()).encode("utf-8")).hexdigest()
|
||||
|
||||
def extract_base_invoice_id(filename: str) -> str:
|
||||
"""Extracts logical invoice base identifier from filename."""
|
||||
# Remove extensions and deskew/oriented markers
|
||||
base = re.sub(r"_(?:page_\d+|oriented|deskewed|customer_copy|test).*", "", filename, flags=re.IGNORECASE)
|
||||
base = base.replace(".png", "").replace(".pdf", "").strip()
|
||||
return base
|
||||
|
||||
def run_hierarchical_grouping():
|
||||
deskewed_dir = Path("data/deskewed")
|
||||
staging_dir = Path("data/test_uploads/staging")
|
||||
private_dir = Path("data_private")
|
||||
private_dir.mkdir(parents=True, exist_ok=True)
|
||||
contact_dir = private_dir / "contact_sheets"
|
||||
contact_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Gather all files and link duplicates across deskewed and staging
|
||||
all_files: Dict[str, Path] = {}
|
||||
content_hashes: Dict[str, List[str]] = {} # sha -> [file_keys]
|
||||
|
||||
# Deskewed
|
||||
for f in sorted(deskewed_dir.glob("*.png")):
|
||||
sha = get_sha256(f)
|
||||
content_hashes.setdefault(sha, []).append(f"deskewed/{f.name}")
|
||||
all_files[f"deskewed/{f.name}"] = f
|
||||
|
||||
# Staging
|
||||
if staging_dir.exists():
|
||||
for f in sorted(staging_dir.rglob("*.png")):
|
||||
sha = get_sha256(f)
|
||||
rel_name = f"staging/{f.name}"
|
||||
content_hashes.setdefault(sha, []).append(rel_name)
|
||||
all_files[rel_name] = f
|
||||
|
||||
print(f"[*] Total unique content hashes across deskewed and staging: {len(content_hashes)}")
|
||||
copies_found = sum(len(v) - 1 for v in content_hashes.values() if len(v) > 1)
|
||||
print(f"[*] Copies/duplicates linked across folders: {copies_found}")
|
||||
|
||||
# 2. Group pages into Logical Invoices
|
||||
logical_invoices: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
# We focus on the 65 primary files in data/deskewed
|
||||
primary_deskewed_files = sorted(deskewed_dir.glob("*.png"))
|
||||
for f in primary_deskewed_files:
|
||||
base_id = extract_base_invoice_id(f.name)
|
||||
sha = get_sha256(f)
|
||||
inv_anon_id = f"INV_{sha[:8]}"
|
||||
|
||||
# Page number
|
||||
p_match = re.search(r"page_(\d+)", f.name, re.IGNORECASE)
|
||||
page_num = int(p_match.group(1)) if p_match else 1
|
||||
|
||||
if base_id not in logical_invoices:
|
||||
logical_invoices[base_id] = {
|
||||
"logical_base": base_id,
|
||||
"anonymous_id": inv_anon_id,
|
||||
"pages": [],
|
||||
"page_files": []
|
||||
}
|
||||
logical_invoices[base_id]["pages"].append(page_num)
|
||||
logical_invoices[base_id]["page_files"].append(f)
|
||||
|
||||
print(f"[*] Identified {len(logical_invoices)} unique logical invoices from 65 deskewed files.")
|
||||
|
||||
# 3. OCR-Assisted Header & Seller Grouping
|
||||
# Load cached OCR results if available
|
||||
ocr_results_dir = Path("data/ocr_results")
|
||||
cached_entities: Dict[str, Dict[str, Any]] = {}
|
||||
if ocr_results_dir.exists():
|
||||
for jf in ocr_results_dir.glob("*.json"):
|
||||
try:
|
||||
with open(jf, "r", encoding="utf-8") as fp:
|
||||
data = json.load(fp)
|
||||
base = extract_base_invoice_id(jf.name)
|
||||
cached_entities[base] = data
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Group by: Seller GSTIN (if found) or series prefix
|
||||
template_clusters: Dict[str, List[str]] = {} # group_id -> [base_ids]
|
||||
seller_gstin_to_group: Dict[str, str] = {}
|
||||
next_group_idx = 1
|
||||
|
||||
for base_id, inv_data in sorted(logical_invoices.items()):
|
||||
# Try to find seller GSTIN
|
||||
seller_gstin = None
|
||||
buyer_gstin = None
|
||||
|
||||
if base_id in cached_entities:
|
||||
meta = cached_entities[base_id]
|
||||
seller_gstin = meta.get("seller_gstin") or meta.get("vendor", {}).get("gstin")
|
||||
buyer_gstin = meta.get("customer_gstin") or meta.get("buyer", {}).get("gstin")
|
||||
|
||||
# Fallback: check filename patterns (e.g. BMS, CC, C, 550x series)
|
||||
series_match = re.match(r"^([A-Za-z]+|\d{2})", base_id)
|
||||
series_key = series_match.group(1) if series_match else base_id[:4]
|
||||
|
||||
cluster_key = None
|
||||
if seller_gstin:
|
||||
if seller_gstin not in seller_gstin_to_group:
|
||||
seller_gstin_to_group[seller_gstin] = f"T{next_group_idx:02d}"
|
||||
next_group_idx += 1
|
||||
cluster_key = seller_gstin_to_group[seller_gstin]
|
||||
else:
|
||||
# Group by series prefix
|
||||
prefix_key = f"series_{series_key}"
|
||||
if prefix_key not in seller_gstin_to_group:
|
||||
seller_gstin_to_group[prefix_key] = f"T{next_group_idx:02d}"
|
||||
next_group_idx += 1
|
||||
cluster_key = seller_gstin_to_group[prefix_key]
|
||||
|
||||
template_clusters.setdefault(cluster_key, []).append(base_id)
|
||||
inv_data["template_group"] = cluster_key
|
||||
inv_data["buyer_gstin_hash"] = get_salted_hash(buyer_gstin) if buyer_gstin else "UNKNOWN"
|
||||
inv_data["has_hardcoded_buyer"] = (inv_data["buyer_gstin_hash"] == HARDCODED_BUYER_HASH)
|
||||
|
||||
# 4. CRITICAL ASSERTION: All pages of an invoice MUST share the exact same template group
|
||||
for base_id, inv_data in logical_invoices.items():
|
||||
t_grp = inv_data["template_group"]
|
||||
assert t_grp is not None, f"Invoice {base_id} has no template group!"
|
||||
# Every page inherits this exact group
|
||||
for pf in inv_data["page_files"]:
|
||||
assert inv_data["template_group"] == t_grp
|
||||
|
||||
print(f"[+] All pages within each logical invoice verified to share exactly one template group (assertion passed).")
|
||||
print(f"[*] Total distinct template groups: {len(template_clusters)}")
|
||||
|
||||
# 5. Check buyer distribution and hardcoded buyer sharing
|
||||
buyer_hashes = set()
|
||||
hardcoded_buyer_count = 0
|
||||
for inv_data in logical_invoices.values():
|
||||
if inv_data["buyer_gstin_hash"] != "UNKNOWN":
|
||||
buyer_hashes.add(inv_data["buyer_gstin_hash"])
|
||||
if inv_data["has_hardcoded_buyer"]:
|
||||
hardcoded_buyer_count += 1
|
||||
|
||||
# 6. Flag Suspicious Pairs (Consecutive invoice numbers assigned to different template groups)
|
||||
suspicious_pairs = []
|
||||
sorted_bases = sorted(logical_invoices.keys())
|
||||
for i in range(len(sorted_bases) - 1):
|
||||
b1, b2 = sorted_bases[i], sorted_bases[i+1]
|
||||
# Check if they look numerically consecutive (e.g. 5504 and 5505, CC-1415 and CC-1416)
|
||||
num1 = re.search(r"(\d{3,6})", b1)
|
||||
num2 = re.search(r"(\d{3,6})", b2)
|
||||
if num1 and num2:
|
||||
try:
|
||||
diff = int(num2.group(1)) - int(num1.group(1))
|
||||
if diff == 1:
|
||||
grp1 = logical_invoices[b1]["template_group"]
|
||||
grp2 = logical_invoices[b2]["template_group"]
|
||||
if grp1 != grp2:
|
||||
suspicious_pairs.append({
|
||||
"invoice_1": b1, "template_1": grp1,
|
||||
"invoice_2": b2, "template_2": grp2
|
||||
})
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 7. Generate Contact Sheets (Thumbnail Montage per Template Group)
|
||||
print("[*] Generating contact sheets under data_private/contact_sheets/...")
|
||||
for grp_id, bases in template_clusters.items():
|
||||
thumb_images = []
|
||||
for b in bases:
|
||||
for pf in logical_invoices[b]["page_files"]:
|
||||
try:
|
||||
with Image.open(pf) as im:
|
||||
im_thumb = im.convert("RGB")
|
||||
im_thumb.thumbnail((400, 550))
|
||||
thumb_images.append((im_thumb, f"{b} ({pf.name[:15]}...)"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not thumb_images:
|
||||
continue
|
||||
|
||||
# Layout thumbnails in grid (max 4 per row)
|
||||
cols = min(4, len(thumb_images))
|
||||
rows = (len(thumb_images) + cols - 1) // cols
|
||||
sheet_w = cols * 420
|
||||
sheet_h = rows * 580
|
||||
|
||||
sheet = Image.new("RGB", (sheet_w, sheet_h), (240, 240, 240))
|
||||
draw = ImageDraw.Draw(sheet)
|
||||
|
||||
for idx, (th, label) in enumerate(thumb_images):
|
||||
c = idx % cols
|
||||
r = idx // cols
|
||||
x = c * 420 + 10
|
||||
y = r * 580 + 10
|
||||
sheet.paste(th, (x, y))
|
||||
draw.text((x + 5, y + th.height + 5), label, fill=(0, 0, 0))
|
||||
|
||||
sheet.save(contact_dir / f"group_{grp_id}.png")
|
||||
|
||||
# 8. Save Private Mapping
|
||||
mapping_payload = {
|
||||
"summary": {
|
||||
"total_deskewed_files": len(primary_deskewed_files),
|
||||
"total_logical_invoices": len(logical_invoices),
|
||||
"total_template_groups": len(template_clusters),
|
||||
"copies_across_folders": copies_found,
|
||||
"unique_buyers_by_hash": len(buyer_hashes),
|
||||
"invoices_sharing_hardcoded_buyer": hardcoded_buyer_count,
|
||||
"suspicious_consecutive_pairs": suspicious_pairs
|
||||
},
|
||||
"histogram": {k: len(v) for k, v in sorted(template_clusters.items())},
|
||||
"logical_invoices": {
|
||||
b: {
|
||||
"anonymous_id": v["anonymous_id"],
|
||||
"template_group": v["template_group"],
|
||||
"page_count": len(v["pages"]),
|
||||
"files": [f.name for f in v["page_files"]]
|
||||
}
|
||||
for b, v in logical_invoices.items()
|
||||
}
|
||||
}
|
||||
|
||||
mapping_file = private_dir / "template_mapping.json"
|
||||
with open(mapping_file, "w", encoding="utf-8") as f:
|
||||
json.dump(mapping_payload, f, indent=2)
|
||||
|
||||
print(f"\n[+] SUCCESS: Template grouping complete!")
|
||||
print(f" - Unique logical invoices: {len(logical_invoices)}")
|
||||
print(f" - Unique template groups: {len(template_clusters)}")
|
||||
print(f" - Invoices sharing hardcoded buyer: {hardcoded_buyer_count}")
|
||||
print(f" - Suspicious consecutive pairs flagged: {len(suspicious_pairs)}")
|
||||
print(f" - Private mapping written to: {mapping_file}")
|
||||
print(f" - Contact sheets saved to: {contact_dir}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_hierarchical_grouping()
|
||||
@@ -0,0 +1,86 @@
|
||||
# scripts/check_annotation.py
|
||||
"""
|
||||
CLI Annotation Checker for Blind Ground-Truth Labeling (Phase 1.3 / 1.4).
|
||||
Validates:
|
||||
1. Required metadata (annotator, date, source, tier).
|
||||
2. ISO-8601 Date formats.
|
||||
3. Official Base-36 GSTIN checksums (customer and seller).
|
||||
4. Tri-State Cross-Field Arithmetic Validation (PASS/FAIL/INSUFFICIENT_DATA).
|
||||
5. Line items and amounts structure.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import json
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from decimal import Decimal
|
||||
|
||||
# Add project root to sys.path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from app.rrsi.normalize import normalize_date, validate_gstin_checksum
|
||||
from app.validators import InvoiceArithmeticValidator, ValidationStatus
|
||||
|
||||
def check_annotation_file(file_path: Path) -> bool:
|
||||
if not file_path.exists():
|
||||
print(f"[!] Error: File {file_path} not found.")
|
||||
return False
|
||||
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
try:
|
||||
data = json.load(f)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"[!] Invalid JSON format: {e}")
|
||||
return False
|
||||
|
||||
errors = []
|
||||
warnings = []
|
||||
|
||||
# 1. Metadata check
|
||||
meta = data.get("metadata", {})
|
||||
if not meta.get("annotator"):
|
||||
errors.append("Metadata 'annotator' is missing or empty.")
|
||||
if meta.get("source") not in ["from_image_blind", "pipeline_prefilled_then_corrected"]:
|
||||
errors.append("Metadata 'source' must be 'from_image_blind' or 'pipeline_prefilled_then_corrected'.")
|
||||
|
||||
# 2. Date checks
|
||||
inv_date = data.get("invoice_date")
|
||||
if not inv_date or not normalize_date(inv_date):
|
||||
errors.append(f"Invalid invoice_date '{inv_date}'. Must be parseable to ISO-8601 (YYYY-MM-DD).")
|
||||
|
||||
# 3. GSTIN checksums
|
||||
for party in ["customer_gstin", "seller_gstin"]:
|
||||
gst = data.get(party)
|
||||
if gst:
|
||||
if not validate_gstin_checksum(gst):
|
||||
errors.append(f"Invalid GSTIN checksum for '{party}': '{gst}' failed statutory Base-36 algorithm.")
|
||||
|
||||
# 4. Arithmetic Validator
|
||||
validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00"))
|
||||
val_res = validator.validate(data)
|
||||
if val_res.status != ValidationStatus.PASS:
|
||||
errors.append(f"Arithmetic validation failed: {val_res.message}")
|
||||
|
||||
print(f"\n[*] Validation Report for: {file_path.name}")
|
||||
print(f" - Metadata Source: {meta.get('source', 'UNSPECIFIED')}")
|
||||
print(f" - Annotator: {meta.get('annotator', 'UNSPECIFIED')}")
|
||||
print(f" - Arithmetic Status: {val_res.status.value} (Discrepancy: {val_res.discrepancy})")
|
||||
if val_res.reconciled_formula:
|
||||
print(f" - Formula: {val_res.reconciled_formula}")
|
||||
|
||||
if errors:
|
||||
print("\n[!] VALIDATION FAILED:")
|
||||
for err in errors:
|
||||
print(f" - ERROR: {err}")
|
||||
return False
|
||||
|
||||
print("\n[+] VALIDATION PASSED: Document satisfies all statutory and arithmetic criteria.")
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Validate invoice annotation JSON.")
|
||||
parser.add_argument("file", help="Path to annotation JSON file")
|
||||
args = parser.parse_args()
|
||||
|
||||
success = check_annotation_file(Path(args.file))
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -0,0 +1,131 @@
|
||||
# scripts/check_git_hygiene.py
|
||||
"""
|
||||
Git Hygiene and PII Leakage Check.
|
||||
Fails on:
|
||||
1. Real GSTINs matching \b\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]\b
|
||||
2. Real PAN numbers matching \b[A-Z]{5}\d{4}[A-Z]\b
|
||||
3. Indian phone numbers
|
||||
4. Salted hashes of sensitive vendor and buyer names (from config/forbidden_hashes.json)
|
||||
5. Tracked private data paths (data_private/, data/deskewed/, venv/, .venv/, etc.)
|
||||
"""
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import json
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
# RegEx for sensitive identifiers
|
||||
GSTIN_REGEX = re.compile(r"\b\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]\b")
|
||||
PAN_REGEX = re.compile(r"\b[A-Z]{5}\d{4}[A-Z]\b")
|
||||
PHONE_REGEX = re.compile(r"\b(?:\+91[\-\s]?)?[6-9]\d{9}\b|\b0\d{2,4}[\-\s]?\d{6,8}\b")
|
||||
|
||||
# Allowed synthetic test fixtures
|
||||
SYNTHETIC_WHITELIST = {
|
||||
"27AAPFU0939F1ZV", # Standard statutory dummy test GSTIN
|
||||
"27AAPFU0939F1ZW", # Intentional invalid test GSTIN
|
||||
"AAPFU0939F", # Dummy test PAN
|
||||
"020-00000000",
|
||||
"9999999999"
|
||||
}
|
||||
|
||||
FORBIDDEN_PATH_SUBSTRINGS = [
|
||||
"data_private",
|
||||
"data/deskewed",
|
||||
"data/ground_truth",
|
||||
"data/ocr_results",
|
||||
"venv/",
|
||||
".venv/",
|
||||
"scratch/",
|
||||
"private_snapshots"
|
||||
]
|
||||
|
||||
def load_forbidden_hashes():
|
||||
cfg_path = Path("config/forbidden_hashes.json")
|
||||
if cfg_path.exists():
|
||||
try:
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("salt", ""), set(data.get("hashes", []))
|
||||
except Exception:
|
||||
pass
|
||||
return "", set()
|
||||
|
||||
def get_staged_or_tracked_files() -> list[str]:
|
||||
# Check staged files if any, else check tracked files
|
||||
res = subprocess.run(["git", "diff", "--cached", "--name-only"], capture_output=True, text=True)
|
||||
files = [f.strip() for f in res.stdout.splitlines() if f.strip()]
|
||||
if not files:
|
||||
res2 = subprocess.run(["git", "ls-files"], capture_output=True, text=True)
|
||||
files = [f.strip() for f in res2.stdout.splitlines() if f.strip()]
|
||||
return files
|
||||
|
||||
def check_hygiene() -> bool:
|
||||
files = get_staged_or_tracked_files()
|
||||
violations = []
|
||||
salt, forbidden_hashes = load_forbidden_hashes()
|
||||
|
||||
for f_str in files:
|
||||
p = Path(f_str)
|
||||
# Check path restrictions
|
||||
norm_path = f_str.replace("\\", "/")
|
||||
for forbidden in FORBIDDEN_PATH_SUBSTRINGS:
|
||||
if forbidden in norm_path:
|
||||
violations.append(f"FORBIDDEN FILE TRACKED: '{f_str}' is inside private/ignored directory '{forbidden}'.")
|
||||
|
||||
# Skip binary files, gitignore, forbidden hash file, and this hygiene checker itself
|
||||
if f_str in ["scripts/check_git_hygiene.py", "config/forbidden_hashes.json"] or p.suffix.lower() in [".png", ".jpg", ".pdf", ".pyc", ".zip"]:
|
||||
continue
|
||||
|
||||
if p.exists() and p.is_file():
|
||||
try:
|
||||
content = p.read_text(encoding="utf-8", errors="ignore")
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
lines = content.splitlines()
|
||||
for line_no, line in enumerate(lines, 1):
|
||||
# Ignore lines defining regexes
|
||||
if "re.compile" in line or "REGEX" in line or "pattern" in line:
|
||||
continue
|
||||
|
||||
for match in GSTIN_REGEX.findall(line):
|
||||
if match not in SYNTHETIC_WHITELIST:
|
||||
violations.append(f"PII LEAK (GSTIN): Found '{match}' in {f_str}:{line_no}")
|
||||
|
||||
for match in PAN_REGEX.findall(line):
|
||||
if match not in SYNTHETIC_WHITELIST:
|
||||
violations.append(f"PII LEAK (PAN): Found '{match}' in {f_str}:{line_no}")
|
||||
|
||||
for match in PHONE_REGEX.findall(line):
|
||||
if match not in SYNTHETIC_WHITELIST:
|
||||
violations.append(f"PII LEAK (PHONE): Found '{match}' in {f_str}:{line_no}")
|
||||
|
||||
# Salted hash name check (single tokens and bigrams)
|
||||
if salt and forbidden_hashes:
|
||||
tokens = [t.lower().strip(" \t\r\n'\",;:.()[]{}") for t in line.split() if len(t.strip()) >= 4]
|
||||
for token in tokens:
|
||||
thash = hashlib.sha256((salt + token).encode("utf-8")).hexdigest()
|
||||
if thash in forbidden_hashes:
|
||||
violations.append(f"FORBIDDEN ENTITY NAME (Salted Hash Match): '{token}' in {f_str}:{line_no}")
|
||||
# Check bigrams
|
||||
for i in range(len(tokens) - 1):
|
||||
bigram = f"{tokens[i]} {tokens[i+1]}"
|
||||
bhash = hashlib.sha256((salt + bigram).encode("utf-8")).hexdigest()
|
||||
if bhash in forbidden_hashes:
|
||||
violations.append(f"FORBIDDEN ENTITY NAME (Salted Hash Match): '{bigram}' in {f_str}:{line_no}")
|
||||
|
||||
if violations:
|
||||
print("[!] GIT HYGIENE CHECK FAILED:")
|
||||
for v in violations:
|
||||
print(f" - {v}")
|
||||
return False
|
||||
|
||||
print("[+] Git hygiene check passed cleanly: No un-anonymized PII, real GSTINs, or private data tracked.")
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not check_hygiene():
|
||||
sys.exit(1)
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,127 @@
|
||||
# scripts/inventory_deskewed.py
|
||||
import re
|
||||
import json
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List
|
||||
from PIL import Image
|
||||
import imagehash
|
||||
|
||||
# Add project root to sys.path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from app.preprocessing.template_similarity_detector import find_template_similar_images, compute_perceptual_hash
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
while chunk := f.read(8192):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def parse_filename_metadata(filename: str) -> Dict[str, Any]:
|
||||
# Extract page number
|
||||
page_match = re.search(r"page_(\d+)", filename, re.IGNORECASE)
|
||||
page_num = int(page_match.group(1)) if page_match else 1
|
||||
|
||||
# Extract copy role
|
||||
role = "page"
|
||||
lower_name = filename.lower()
|
||||
if "customer_copy" in lower_name or "customer copy" in lower_name:
|
||||
role = "customer_copy"
|
||||
elif "transporter" in lower_name:
|
||||
role = "transporter_copy"
|
||||
elif "duplicate" in lower_name:
|
||||
role = "duplicate_copy"
|
||||
|
||||
# Derive logical invoice prefix
|
||||
# e.g. "5504_page_1..." -> "INV_5504", "CC-1415_page_1..." -> "INV_CC-1415"
|
||||
base_prefix = filename.split("_page_")[0].split("_oriented")[0].strip()
|
||||
# Clean up commas or spaces
|
||||
cleaned_prefix = re.sub(r"[^\w\-]", "_", base_prefix).strip("_")
|
||||
|
||||
return {
|
||||
"page_num": page_num,
|
||||
"role": role,
|
||||
"logical_id": f"DOC_{cleaned_prefix}"
|
||||
}
|
||||
|
||||
def build_inventory():
|
||||
deskewed_dir = Path("data/deskewed")
|
||||
if not deskewed_dir.exists():
|
||||
print(f"[!] Directory not found: {deskewed_dir}")
|
||||
return
|
||||
|
||||
files = sorted([f for f in deskewed_dir.iterdir() if f.is_file() and f.suffix.lower() == ".png"])
|
||||
print(f"[*] Found {len(files)} PNG files in {deskewed_dir}")
|
||||
|
||||
# 1. Run template clustering using pHash (Hamming distance <= 4)
|
||||
cluster_res = find_template_similar_images(str(deskewed_dir), threshold=4)
|
||||
groups = cluster_res.get("template_similarity_groups", [])
|
||||
|
||||
# Map file -> template_group_id
|
||||
file_to_group = {}
|
||||
for grp_idx, group_files in enumerate(groups, 1):
|
||||
grp_name = f"T{grp_idx:02d}"
|
||||
for f in group_files:
|
||||
file_to_group[f] = grp_name
|
||||
|
||||
# Unclustered files get their own singleton template group
|
||||
next_singleton = len(groups) + 1
|
||||
for f in files:
|
||||
if f.name not in file_to_group:
|
||||
file_to_group[f.name] = f"T{next_singleton:02d}"
|
||||
next_singleton += 1
|
||||
|
||||
# 2. Build detailed records
|
||||
inventory_records = []
|
||||
logical_invoices: Dict[str, List[str]] = {}
|
||||
template_counts: Dict[str, int] = {}
|
||||
copy_count = 0
|
||||
|
||||
for f in files:
|
||||
meta = parse_filename_metadata(f.name)
|
||||
sha = sha256_file(f)
|
||||
phash_str = str(compute_perceptual_hash(str(f)))
|
||||
t_group = file_to_group[f.name]
|
||||
|
||||
template_counts[t_group] = template_counts.get(t_group, 0) + 1
|
||||
logical_invoices.setdefault(meta["logical_id"], []).append(f.name)
|
||||
if meta["role"] != "page" or "copy" in meta["role"]:
|
||||
copy_count += 1
|
||||
|
||||
record = {
|
||||
"filename": f.name,
|
||||
"logical_invoice_id": meta["logical_id"],
|
||||
"page_num": meta["page_num"],
|
||||
"role": meta["role"],
|
||||
"template_group": t_group,
|
||||
"anonymous_vendor": f"Vendor_{t_group}",
|
||||
"sha256": sha,
|
||||
"phash": phash_str
|
||||
}
|
||||
inventory_records.append(record)
|
||||
|
||||
summary = {
|
||||
"total_files": len(files),
|
||||
"total_unique_logical_invoices": len(logical_invoices),
|
||||
"total_unique_template_groups": len(set(file_to_group.values())),
|
||||
"total_copy_files": copy_count,
|
||||
"invoices_per_template": template_counts
|
||||
}
|
||||
|
||||
rep_dir = Path("reports")
|
||||
rep_dir.mkdir(exist_ok=True, parents=True)
|
||||
out_file = rep_dir / "deskewed_inventory.json"
|
||||
with open(out_file, "w", encoding="utf-8") as f:
|
||||
json.dump({"summary": summary, "records": inventory_records}, f, indent=2)
|
||||
|
||||
print(f"[+] Inventory complete. Saved to {out_file}")
|
||||
print(f" Total files: {summary['total_files']}")
|
||||
print(f" Unique logical invoices: {summary['total_unique_logical_invoices']}")
|
||||
print(f" Unique template groups: {summary['total_unique_template_groups']}")
|
||||
print(f" Copies identified: {summary['total_copy_files']}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
build_inventory()
|
||||
@@ -0,0 +1,71 @@
|
||||
# scripts/test_determinism.py
|
||||
import json
|
||||
import hashlib
|
||||
import sys
|
||||
import platform
|
||||
from pathlib import Path
|
||||
import paddle
|
||||
|
||||
# Add project root to sys.path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
# Ensure GPU DLLs are loaded
|
||||
from app.ocr.dual_engine_benchmarker import configure_gpu_dll_paths
|
||||
configure_gpu_dll_paths()
|
||||
|
||||
from app.ocr.invoice_pipeline import InvoicePipeline
|
||||
|
||||
def get_json_hash(data: dict) -> str:
|
||||
s = json.dumps(data, sort_keys=True, indent=2)
|
||||
return hashlib.sha256(s.encode("utf-8")).hexdigest()
|
||||
|
||||
def run_determinism_test():
|
||||
img_4531 = Path("data/test_uploads/staging/deskewed/invoice_4531 (1)_page_1_oriented_deskewed.png")
|
||||
img_kundan = Path("data/test_uploads/staging/deskewed/264882_SB_DEENANATH MEDICAL STORES_20_08_2026_page_1_oriented_deskewed.png")
|
||||
|
||||
pipeline_gpu = InvoicePipeline(use_gpu=True)
|
||||
|
||||
results = {}
|
||||
for img_path, name in [(img_4531, "invoice_4531"), (img_kundan, "kundan")]:
|
||||
if not img_path.exists():
|
||||
print(f"[!] Image not found: {img_path}")
|
||||
continue
|
||||
|
||||
print(f"[*] Testing 5 runs for {name} on GPU...")
|
||||
runs = []
|
||||
hashes = []
|
||||
for i in range(5):
|
||||
out = pipeline_gpu.process_invoice(str(img_path))
|
||||
h = get_json_hash(out)
|
||||
runs.append(out)
|
||||
hashes.append(h)
|
||||
print(f" Run {i+1}: SHA256={h[:16]}...")
|
||||
|
||||
is_byte_identical = len(set(hashes)) == 1
|
||||
results[name] = {
|
||||
"is_byte_identical": is_byte_identical,
|
||||
"hashes": hashes,
|
||||
"distinct_hashes_count": len(set(hashes))
|
||||
}
|
||||
|
||||
# Record environment
|
||||
env_info = {
|
||||
"python_version": sys.version,
|
||||
"platform": platform.platform(),
|
||||
"paddle_version": paddle.__version__,
|
||||
"paddle_cuda_compiled": paddle.is_compiled_with_cuda(),
|
||||
"gpu_device": paddle.device.cuda.get_device_name(0) if paddle.is_compiled_with_cuda() else None,
|
||||
"determinism_results": results
|
||||
}
|
||||
|
||||
rep_dir = Path("reports")
|
||||
rep_dir.mkdir(exist_ok=True, parents=True)
|
||||
env_file = rep_dir / "environment.json"
|
||||
with open(env_file, "w", encoding="utf-8") as f:
|
||||
json.dump(env_info, f, indent=2)
|
||||
|
||||
print(f"\n[+] Environment and determinism report saved to {env_file}")
|
||||
print(json.dumps(results, indent=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_determinism_test()
|
||||
Reference in New Issue
Block a user