commit 6f3831ecdb5dcaaa14241e9514317b95d9a62819 Author: omkarande14 <284905859+omkarande14@users.noreply.github.com> Date: Mon Sep 28 17:13:23 2026 +0530 baseline: non-sensitive scaffolding, hygiene hooks, synthetic test fixtures, and docs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d073316 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +name: CI Pipeline & Git Hygiene + +on: + push: + branches: [ master, main, 'rrsi/**' ] + pull_request: + branches: [ master, main ] + +jobs: + hygiene-and-tests: + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install Test Dependencies + run: | + python -m pip install --upgrade pip + pip install pytest scipy numpy pydantic pyyaml pillow imagehash + + - name: Run Git Hygiene & PII Leak Check + run: | + python scripts/check_git_hygiene.py + + - name: Run Unit & Statistical Tests + run: | + pytest tests/test_rrsi_stats.py tests/test_rrsi_normalize.py tests/test_validators.py tests/test_table_metrics.py tests/test_reconciliation_bug.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b5e19a6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +# Environments +.venv/ +venv/ +ENV/ +env/ + +# Python cache +__pycache__/ +*.py[cod] +*$py.class +*.pytest_cache/ +.pytest_cache/ + +# Test output, dump logs, artifacts +*.log +*.txt +!requirements.txt +test_output.txt +test_run_output.txt +full_test_output.txt + +# Scratch and debug files +scratch/ + +# Private and Unanonymized Production Data (Strictly Gitignored) +data_private/ +data/input/ +data/oriented/ +data/deskewed/ +data/processed/ +data/validation/ +data/test_uploads/ +data/benchmarks/ +data/ground_truth/ +data/ocr_results/ +tests_private/ + +# Reports and temporary artifacts +reports/*.json +!reports/.gitkeep + +# Snapshots of unredacted state +private_snapshots/ + diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..fc5895e --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,11 @@ +# .pre-commit-config.yaml +# Versioned pre-commit hook configuration for Git Hygiene and PII leak prevention +repos: + - repo: local + hooks: + - id: check-git-hygiene + name: Check Git Hygiene and PII Leakage + entry: python scripts/check_git_hygiene.py + language: system + stages: [commit] + always_run: true diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb8ec56 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# Invoice OCR System + +An automated Invoice Processing and OCR pipeline designed for high-accuracy data extraction from real-world invoice PDFs and scanned images. + +--- + +## 1. Architecture & Pipeline Stages + +1. **Input Validation (Milestone 1)** (`app/input/`): + - Validates existence, formats (`.pdf`, `.jpg`, `.jpeg`, `.png`), corruption, PDF encryption, and page counts. +2. **Image Conversion (Milestone 2)** (`app/preprocessing/image_converter.py`): + - Renders valid PDF pages and images into standard 200 DPI grayscale PNG files (`_page_.png`). +3. **Exact Visual Duplicate Detection (Milestone 3a)** (`app/preprocessing/duplicate_detector.py`): + - Computes SHA-256 hashes of decoded pixel data (`img.tobytes()`). + - The **only reliable duplicate signal** prior to OCR. Identifies redundant exact copies without modifying original input. +4. **Template Similarity Detection (Milestone 3b)** (`app/preprocessing/template_similarity_detector.py`): + - Uses perceptual hashing (`pHash`) to cluster images sharing visual layouts/templates. + - **Critical Architectural Decision:** Evaluated and confirmed that perceptual hashing detects *shared vendor template layouts*, NOT duplicate document content. Different invoices from the same vendor share near-identical layouts (pHash distance 0–4) despite having different invoice numbers, line items, and amounts. + - **Non-destructive:** Results are strictly informational for downstream template-aware extraction (Milestones 4–6) and must **never** be used to skip or delete files. True duplicate detection for different scans of the same document is deferred until post-OCR content comparison. +5. **Orientation Correction (Milestone 3c)** (`app/preprocessing/orientation_corrector.py`): + - Uses Tesseract OSD to detect orientation (0°, 90°, 180°, 270°) and restores all images to standard 0° upright in `data/oriented/`. +6. **Deskew Correction (Milestone 3d)** (`app/preprocessing/deskew_corrector.py`): + - Uses OpenCV Hough Line Transform to detect and correct small tilts ($0.5^\circ$ to $15.0^\circ$) into `data/deskewed/`, preserving pristine sharpness for straight files ($< 0.5^\circ$). +7. **Normalization Evaluation (Milestone 3e)**: + - Empirically audited contrast/sharpness across the dataset; speculative binarization safely deferred to protect thin character strokes. +8. **OCR Engine Selection & GPU Acceleration (Milestone 4a)** (`app/ocr/`): + - GPU-accelerated PaddleOCR configured with CUDA 12 and cuDNN v8 targeting NVIDIA GeForce RTX 3050 (6GB VRAM). + - Massive real-world speedup: high-resolution camera scans (4096 × 3072) dropped from 275s on CPU to ~16s on GPU; standard 200 DPI PDF invoices run in ~3–5 seconds. +9. **Dual-Engine Benchmarking & Consensus Strategy (Milestone 4b)** (`app/ocr/dual_engine_benchmarker.py`): + - Evaluated PaddleOCR (deep-learning layout/table focus) against Tesseract (independent patch validation) across 3 diverse invoice types. + - Achieved 100% consensus agreement on clean invoices; PaddleOCR successfully extracted critical data (94% confidence) on mobile camera scans where Tesseract degraded to 67%. +10. **Table & Line-Item Extraction (Milestone 4c)** (`app/ocr/table_extractor.py`): + - Spatial geometric column mapping and adaptive vertical row clustering. + - Accurately parses Item Description, HSN/SAC Code, Quantity, Unit, Rate, and Taxable Amount. + - Automatic row-level arithmetic validation ($\text{Quantity} \times \text{Rate} = \text{Amount}$). +11. **Arithmetic Verifier & End-to-End Pipeline (Milestone 4d)** (`app/ocr/verifier.py`, `app/ocr/invoice_pipeline.py`): + - Multi-stage mathematical reconciliation: + - Row Item Check: $\text{Qty} \times \text{Rate} = \text{Amount}$ + - Line Item Sum: $\sum \text{Line Items} = \text{Subtotal}$ + - Tax Reconciliation: $\text{Subtotal} + \text{CGST} + \text{SGST} + \text{IGST} \pm \text{Roundoff} = \text{Grand Total}$ + - 15-character Indian GSTIN format and state code verification. + - Cross-engine consensus scoring and automated JSON export into `data/ocr_results/`. +12. **Reflective Recursive Self-Improvement (RRSI Framework)** (`app/rrsi/`): + - **Proposal Side**: Negative Knowledge Registry (`proposal_memory.json`) prevents repeating failed approaches; Area Stagnation monitors consecutive failures and enforces pivoting to orthogonal pipeline areas. + - **Selection Side**: Leakage Screening audits candidate code for sample memorization and coordinate overfitting; Noise Floor Guard ($\pm \text{SE}$) eliminates lucky fluctuations; Cost-Aware Acceptance rejects latency blowups. + - **Error Taxonomy & Ledger**: Tracks fine-grained failures (`table_data_mismatch`, `date_extraction_mismatch`, `invoice_number_error`, `party_mismatch`, `totals_arithmetic_error`) in an auditable ledger (`experiment_ledger.json`). + +--- + +## 2. Running the System + +```bash +# Run all automated tests (including RRSI unit tests) +python -m pytest tests/ -v + +# Run RRSI Baseline Error Taxonomy Audit +python run_rrsi_evaluation.py --audit + +# Run RRSI Proposal & Selection Demonstration +python run_rrsi_evaluation.py --demo + +# Run Streamlit Web Workbench (Testing & Verification UI) +streamlit run app/ui/workbench.py + +# Run complete end-to-end OCR and verification pipeline +python run_invoice_pipeline.py +``` + diff --git a/config/selection.yaml b/config/selection.yaml new file mode 100644 index 0000000..1d9da7c --- /dev/null +++ b/config/selection.yaml @@ -0,0 +1,47 @@ +# config/selection.yaml +# Selection Gate Configuration for RRSI Self-Improvement Loop (Fail-Closed) + +gate: + min_macro_gain_ci_lower: 0.0 # Lower bound of 95% paired bootstrap CI on macro gain must be > 0 + noise_multiplier: 2.0 # Mean macro gain must exceed 2x measured noise standard deviation + allow_field_regression: false # No individual field can regress by more than its noise SD + max_dev_selection_gap: 0.05 # Widening gap between dev and selection gain indicates overfitting + bonferroni_correction: true # Adjust alpha when testing k candidates simultaneously + +macro_weights: + # Written justification: + # - invoice_number (0.20): Core unique identifier for document matching and deduplication + # - invoice_date (0.15): Critical for payment terms, GST tax period, and cash discounts + # - invoice_amount (0.20): Primary financial liability and ledger posting value + # - party_gstin (0.15): Legal GST compliance, E-Way bill reconciliation, and ITC eligibility + # - party_name (0.10): Vendor master lookup and entity disambiguation + # - table_cells (0.20): Line-item reconciliation, HSN verification, and rate auditing + invoice_number: 0.20 + invoice_date: 0.15 + invoice_amount: 0.20 + party_gstin: 0.15 + party_name: 0.10 + table_cells: 0.20 + +cost: + cost_lambda: 0.05 # Utility penalty per second of median latency increase + max_allowed_latency_s: 45.0 # Max acceptable runtime per invoice + max_cost_per_invoice_inr: 2.0 # Maximum allowable vision/LLM fallback cost per document + num_warmup_runs: 5 # Number of warmup runs for reliable median & p95 latency + max_vision_fallback_calls: 0 # Disallow LLM/vision fallback unless explicitly justified + +pruning: + min_corpus_docs: 40 # Minimum annotated documents required before rule pruning + min_corpus_templates: 10 # Minimum distinct template groups required + allow_zero_hit_ablation: true # Zero-hit rules eligible only as ablation candidates + +whitelist: + # Known benign numeric constants (kernel sizes, image boundaries, color masks) + allowed_numeric_literals: + - 255 + - 1000 + - 3 + - 5 + - 7 + - 0 + - 1 diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..5334305 --- /dev/null +++ b/conftest.py @@ -0,0 +1,6 @@ +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) diff --git a/data/manifest.json b/data/manifest.json new file mode 100644 index 0000000..c23593d --- /dev/null +++ b/data/manifest.json @@ -0,0 +1,481 @@ +{ + "manifest": [ + { + "doc_id": "INV_fd02fd54", + "template_group": "T01", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": true + }, + { + "doc_id": "INV_a5c0ae6a", + "template_group": "T02", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": true + }, + { + "doc_id": "INV_3c5a77ac", + "template_group": "T03", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_d7f081e3", + "template_group": "T04", + "split": "dev", + "tier": "Tier_A", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_7200a8d1", + "template_group": "T05", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_eb98bc06", + "template_group": "T06", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_e92ad79d", + "template_group": "T07", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": true + }, + { + "doc_id": "INV_81046572", + "template_group": "T08", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_00b9f774", + "template_group": "T09", + "split": "selection", + "tier": "Tier_B", + "page_count": 5, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_4cc9f3ad", + "template_group": "T10", + "split": "locked_test", + "tier": "Tier_B", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_bc325113", + "template_group": "T10", + "split": "locked_test", + "tier": "Tier_B", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_bf820006", + "template_group": "T11", + "split": "dev", + "tier": "Tier_A", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_22909692", + "template_group": "T12", + "split": "dev", + "tier": "Tier_A", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_2fa979eb", + "template_group": "T12", + "split": "dev", + "tier": "Tier_A", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_3f93ff61", + "template_group": "T12", + "split": "dev", + "tier": "Tier_A", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_9d1a66d2", + "template_group": "T12", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_adca903d", + "template_group": "T13", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_ab88b109", + "template_group": "T13", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_39e785ea", + "template_group": "T13", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_000b1f0b", + "template_group": "T13", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_0281dde0", + "template_group": "T13", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_8acc1d46", + "template_group": "T13", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_35e12582", + "template_group": "T13", + "split": "selection", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_d8638369", + "template_group": "T14", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_6adebc7c", + "template_group": "T14", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_d822b694", + "template_group": "T15", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_7abaa6d8", + "template_group": "T16", + "split": "locked_test", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_942bb99d", + "template_group": "T16", + "split": "locked_test", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_e627a21d", + "template_group": "T16", + "split": "locked_test", + "tier": "Tier_B", + "page_count": 2, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_548c01b3", + "template_group": "T16", + "split": "locked_test", + "tier": "Tier_B", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_e02c31bb", + "template_group": "T16", + "split": "locked_test", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_d05ac940", + "template_group": "T17", + "split": "selection", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_9782cb20", + "template_group": "T18", + "split": "selection", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_ec2daa9d", + "template_group": "T19", + "split": "locked_test", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_182ee202", + "template_group": "T19", + "split": "locked_test", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_deea4e74", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_f2f33f5f", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_8e40a2bd", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_cbbd7b20", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_0f99d813", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_efb5758d", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_8aa742ac", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_ff06d5f2", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_2d640122", + "template_group": "T20", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_abdc3c30", + "template_group": "T21", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_bfbe0b41", + "template_group": "T21", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_f1375513", + "template_group": "T21", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_683977e5", + "template_group": "T21", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_97d62746", + "template_group": "T22", + "split": "locked_test", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_38301e52", + "template_group": "T23", + "split": "selection", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_ff73bd8e", + "template_group": "T23", + "split": "selection", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_5e2f3610", + "template_group": "T23", + "split": "selection", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + }, + { + "doc_id": "INV_5913d3da", + "template_group": "T24", + "split": "dev", + "tier": "Tier_A", + "page_count": 1, + "annotation_status": "unannotated", + "is_contaminated": false + } + ] +} \ No newline at end of file diff --git a/docs/RRSI_AUDIT.md b/docs/RRSI_AUDIT.md new file mode 100644 index 0000000..de1ab66 --- /dev/null +++ b/docs/RRSI_AUDIT.md @@ -0,0 +1,150 @@ +# RRSI Phase 0 Technical Audit & Verification Report + +**Date**: 2026-09-28 +**Component**: Reflective Recursive Self-Improvement (RRSI) Framework +**Status**: PHASE 0 COMPLETE — GATE AUDITED + +--- + +## 1. Audit Target 0.1 — Live Pipeline Execution vs. Synthetic Static Comparison + +### The Issue Identified +Prior to this audit, `run_rrsi_evaluation.py --audit` did **not** execute the real extraction pipeline on source images. Instead, it: +1. Attempted to read pre-baked, static JSON files located in `data/ocr_results/`. +2. If no pre-baked file was found, it fell back to: + ```python + if not matched: + predictions.append(gt) # Evaluated Ground Truth against itself! + ``` +3. Loaded `data/ground_truth/pdf_ground_truth_4531.json`, which was a duplicate schema representation with non-standard keys (`vendor`, `buyer`, `line_items`), causing silent evaluation misses. + +### Deconstruction of the "86.67%" Overall Accuracy +The previously reported **86.67%** was an arithmetic illusion resulting from: +$$\text{Overall Accuracy} = 0.40 \times \text{Field Accuracy} + 0.40 \times (\text{Table F1} \times 100) + 0.20 \times \text{Math Accuracy}$$ + +Because ground-truth files were compared against static outputs or themselves: +- Field Accuracy = $100.00\%$ +- Table F1-Score = $1.000$ ($100.00\%$) +- Math Accuracy = $33.33\%$ (1 of 3 files passed the naive equation) +$$\text{Overall Accuracy} = 0.40(100) + 0.40(100) + 0.20(33.33) = 40 + 40 + 6.67 = 86.67\%$$ + +### The Fix +`run_rrsi_evaluation.py` has been refactored so that `--audit`: +1. Maps each canonical ground truth annotation to its real source image: + - `invoice_4531_expected.json` $\rightarrow$ `data/test_uploads/staging/deskewed/invoice_4531 (1)_page_1_oriented_deskewed.png` + - `kundan_expected.json` $\rightarrow$ `data/test_uploads/staging/deskewed/264882_SB_DEENANATH MEDICAL STORES_20_08_2026_page_1_oriented_deskewed_customer_copy.png` +2. Instantiates `InvoicePipeline(use_gpu=False)` and executes `pipeline.process_invoice(img_path)` live on each raw image. +3. Evaluates fresh predictions directly against ground-truth annotations and records true execution latency. + +### Live Baseline Results (Real Pipeline on Real Source Images) +```text +Total Invoices Processed: 2 +Overall Accuracy Score: 72.56% +Field Accuracy: 94.74% +Table F1-Score: 0.867 +Arithmetic Consistency: 0.00% +Total Execution Time: 48.18s (24.09s / invoice on CPU) +Calculated Noise Floor: +/-30.92% (due to small N=2 sample size) +``` + +The true baseline accuracy is **72.56%**, not 86.67%. The live run immediately exposed real pipeline extraction errors that were previously masked. + +--- + +## 2. Audit Target 0.2 — Diagnosis of `totals_arithmetic_error` Cases + +In the initial audit, 2 out of 3 invoices failed arithmetic checks. Both cases were investigated mathematically to classify whether the failure was an **evaluator flaw**, a **pipeline extraction error**, or a **source-document inconsistency**. + +### Case 1: `invoice_4531` (`WMP/B/04531`) +* **Physical Invoice Data**: + - Item 1 (ALBUCEL): Qty 60 @ Rs. 3,700.00 = Gross Rs. 222,000.00. Trade discount 2% (-Rs. 4,440.00) $\rightarrow$ Taxable Rs. 217,560.00. GST 5% = Rs. 10,878.00. + - Item 2 (TELIPSA): Qty 120 @ Rs. 198.00 = Gross Rs. 23,760.00. Trade discount 5% (-Rs. 1,188.00) $\rightarrow$ Taxable Rs. 22,572.00. GST 5% = Rs. 1,128.60. + - Total Taxable Value: $\text{Rs. } 217,560.00 + \text{Rs. } 22,572.00 = \text{Rs. } 240,132.00$ + - Total GST: $\text{Rs. } 10,878.00 + \text{Rs. } 1,128.60 = \text{Rs. } 12,006.60$ + - Subtotal + GST: $\text{Rs. } 240,132.00 + \text{Rs. } 12,006.60 = \text{Rs. } 252,138.60$ + - Round-Off: $+\text{Rs. } 0.40$ + - Invoice Grand Total: $\mathbf{\text{Rs. } 252,139.00}$ +* **Diagnosis**: + - The source invoice is **100% mathematically consistent**. + - The evaluator failed because it naively checked $\sum \text{Gross Items} + \text{GST} = \text{Total}$ ($\text{Rs. } 245,760.00 + \text{Rs. } 12,006.60 = \text{Rs. } 257,766.60 \neq \text{Rs. } 252,139.00$), ignoring line-item discounts and round-off. +* **Classification**: **Evaluator Defect (Missing Discount & Round-Off Handling)**. + +### Case 2: `kundan` (`KP26264882`) +* **Physical Invoice Data**: + - 14 Line items, each with individual trade discounts (e.g. 4.00%). + - Gross line items sum: Rs. 53,542.60. + - Taxable discounted sum: Rs. 51,400.90. + - Total GST: Rs. 3,020.08. + - Taxable + GST: $\text{Rs. } 51,400.90 + \text{Rs. } 3,020.08 = \text{Rs. } 54,420.98$. + - Round-Off: $+\text{Rs. } 0.02$. + - Invoice Grand Total: $\mathbf{\text{Rs. } 54,421.00}$. +* **Pipeline Extraction Output**: + - Pipeline extracted `total_gst_amount = 2396.94` (missed GST tax buckets on CPU line extraction) instead of `3020.08`. + - Pipeline missed 1 table line item (`ATOCOR 40 (15 TAB)`). +* **Diagnosis**: + - The source invoice is **100% mathematically consistent**. + - The pipeline produced a **real extraction error** on GST amount (Rs. 2,396.94 vs Rs. 3,020.08) and missed a line item. + - The evaluator also lacked round-off and discount awareness. +* **Classification**: **Pipeline Extraction Error + Evaluator Missing Discount Handling**. + +### Evaluator Mathematical Hardening +`StatisticalEvaluator` in `app/rrsi/evaluator.py` has been updated with: +1. **Configurable Tolerance** (`tolerance: float = 1.0`, adjustable per currency/precision). +2. **Round-Off Awareness**: Checks both $\text{Taxable} + \text{GST} + \text{Roundoff}$ and $\text{Taxable} + \text{GST} - \text{Roundoff}$ against Grand Total. +3. **Item Discount & Taxable Value Derivation**: Derives line-item taxable values using `total_price * (1 - Discount/100)`. +4. **Error Decoupling**: + - `document_inconsistent`: Triggered when ground-truth arithmetic itself fails (printed document numbers do not add up). + - `totals_arithmetic_error`: Triggered when the pipeline extracts values that do not reconcile, while the ground truth is consistent. + +--- + +## 3. Audit Target 0.3 — Environment Isolation & Provenance Tracking + +### The Contamination Identified +Running `python run_rrsi_evaluation.py --demo` previously wrote directly to: +- `data/rrsi/proposal_memory.json` +- `data/rrsi/experiment_ledger.json` + +This injected a fake proposal (`PROP-2026-001`) into the production registry and caused false stagnation counters in `entity_extraction` and `table_extraction`. + +### Remediations Applied +1. **Ledger & Memory Purge**: + `data/rrsi/proposal_memory.json` and `data/rrsi/experiment_ledger.json` were reset to clean, empty states. +2. **Demo Isolation via Tempfile**: + `run_rrsi_evaluation.py --demo` now executes inside a `tempfile.TemporaryDirectory()`, instantiating isolated registry and ledger instances that are discarded after the demonstration. `data/rrsi/` is never modified during demo runs or tests. +3. **Provenance Tracking**: + Added a mandatory `provenance` field (`"real"` vs `"demo"`) across: + - `ProposalHypothesis` (`app/rrsi/taxonomy.py`) + - `DecisionRecord` (`app/rrsi/taxonomy.py`) + - Ledger entries (`app/rrsi/ledger.py`) + - Proposal memory records (`app/rrsi/memory.py`) + +--- + +## 4. Audit Target 0.4 — Inventory of Hardcoded Heuristics, Coordinates & Vendor Strings in `app/` + +A comprehensive static audit was performed across all source files in `app/` to inventory hardcoded constants, vendor names, and coordinate checks. + +| Location | Hardcoded Value / Pattern | Context / Risk | Generalization Hazard | +| :--- | :--- | :--- | :--- | +| `app/ocr/invoice_pipeline.py:1001` | `"[REDACTED_BUYER_PAN]" in buyer_gstin` | Hardcoded PAN of specific buyer | Fails when entity is seller or on any other entity | +| `app/ocr/invoice_pipeline.py:1010` | `parties["buyer_name"] = "[REDACTED_BUYER_NAME]"` | Static override of buyer name when prefix detected | Hardcodes specific buyer entity into generic OCR pipeline | +| `app/ocr/invoice_pipeline.py:1011` | `buyer_gstin == "[REDACTED_BUYER_GSTIN]"` | Hardcoded 15-char GSTIN string | Overfits to single buyer entity | +| `app/ocr/self_healing.py:198` | `xmin > 550 or ymin > 300` | Fixed pixel coordinate thresholds for buyer GSTIN recovery | Breaks on 300 DPI, mobile scans (4096px), or varying layouts | +| `app/ocr/self_healing.py:201` | `xmin <= 550` | Fixed pixel coordinate threshold for seller GSTIN recovery | Fails on left-aligned buyer layouts or multi-column invoices | +| `app/ocr/self_healing.py:207` | `"[REDACTED_BUYER_PAN]" in buyer["gstin"]` | Hardcoded PAN check to disambiguate identical buyer/seller GSTIN | Fails on any customer other than hardcoded entity | +| `app/ocr/table_extractor.py:64-66` | `"[REDACTED_VENDOR]", "strives for", "strives", "custgihe", "po/phrmcy"` | Hardcoded vendor slogans and customer tags in `TABLE_STOP_KEYWORDS` | Fragile heuristic: vendor-specific slogans used as table boundary stops | +| `app/ocr/table_extractor.py:234-246` | `first_col_xmin > 220.0`, `first_col_xmin > 350.0`, `xmin: 50.0, xmin: 220.0` | Fixed pixel constants to synthesize missing description columns | Hardcoded to specific template geometry; breaks on other dimensions | +| `app/ocr/invoice_pipeline.py:105, 153, 188, 255` | `o_xmin - xmax <= 400`, `<= 350`, `<= 300`, `o_ymin - ymax <= 60` | Fixed pixel proximity thresholds for spatial key-value association | Fails on high-resolution camera captures where word spacing exceeds 400px | +| `app/ui/workbench.py:282` | `if "4531" in selected_file_path.name` | Hardcoded filename match for workbench ground-truth comparison | UI demo cheat that must not exist in production extraction | + +--- + +## 5. Phase 0 Gate Conclusion + +1. **Comparison Authenticity**: Confirmed that prior 86.67% was an artifact of static JSON self-comparison. The live pipeline execution baseline on real images has been established at **72.56% Overall Accuracy** (94.74% Field Accuracy, 0.867 Table F1, 0.0% Math Consistency). +2. **Arithmetic Diagnosis**: Concluded both test invoices (`invoice_4531` and `kundan`) are internally consistent. Failures were caused by naive evaluator discount/roundoff omissions, compounded by a live pipeline GST extraction error on Kundan. Configurable tolerance and round-off logic have been implemented. +3. **Isolation Enforced**: Demo and test runs are strictly sandboxed via `tempfile`, persistent registries have been purged, and `provenance` metadata is enforced. +4. **Hardcoding Documented**: Complete inventory of 10 hardcoded points cataloged above, serving as targets for Phase 5 leakage elimination and Phase 7 refactoring. + +**Ready for Phase 1 (Dataset Manifest, Template Grouping & Anonymization).** diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..d78bfbc --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +testpaths = tests +norecursedirs = venv .venv build dist scratch data diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5ca953b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,15 @@ +pymupdf +Pillow +pytest +imagehash +pytesseract +opencv-python +streamlit +protobuf==3.20.2 +google-genai + +# GPU-accelerated OCR stack for NVIDIA RTX 3050 (CUDA 12 + cuDNN v8) +--extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu120/ +paddlepaddle-gpu==2.6.2.post120 +paddleocr==2.9.1 +nvidia-cudnn-cu12==8.9.7.29 \ No newline at end of file diff --git a/scripts/build_manifest_and_splits.py b/scripts/build_manifest_and_splits.py new file mode 100644 index 0000000..608a719 --- /dev/null +++ b/scripts/build_manifest_and_splits.py @@ -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() diff --git a/scripts/build_template_hierarchy.py b/scripts/build_template_hierarchy.py new file mode 100644 index 0000000..a46a19c --- /dev/null +++ b/scripts/build_template_hierarchy.py @@ -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_, 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() diff --git a/scripts/check_annotation.py b/scripts/check_annotation.py new file mode 100644 index 0000000..fc73394 --- /dev/null +++ b/scripts/check_annotation.py @@ -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) diff --git a/scripts/check_git_hygiene.py b/scripts/check_git_hygiene.py new file mode 100644 index 0000000..329dc3c --- /dev/null +++ b/scripts/check_git_hygiene.py @@ -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) diff --git a/scripts/inventory_deskewed.py b/scripts/inventory_deskewed.py new file mode 100644 index 0000000..6ede53e --- /dev/null +++ b/scripts/inventory_deskewed.py @@ -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() diff --git a/scripts/test_determinism.py b/scripts/test_determinism.py new file mode 100644 index 0000000..bd39283 --- /dev/null +++ b/scripts/test_determinism.py @@ -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() diff --git a/start.bat b/start.bat new file mode 100644 index 0000000..286cacb --- /dev/null +++ b/start.bat @@ -0,0 +1,88 @@ +@echo off +setlocal +cd /d "%~dp0" + +:: Set console code page to UTF-8 for unicode support (emojis, symbols) +chcp 65001 >nul +set PYTHONUTF8=1 +set PYTHONIOENCODING=utf-8 + +echo ========================================================== +echo Invoice OCR - Streamlit Workbench Launcher +echo ========================================================== +echo Project Directory: %CD% +echo. + +:: Detect Python in virtual environment (.venv or venv) +set "PYTHON_EXE=" + +:: 1. Check if .venv has Streamlit +if exist "%~dp0.venv\Scripts\python.exe" ( + "%~dp0.venv\Scripts\python.exe" -c "import streamlit" >nul 2>&1 + if not errorlevel 1 ( + set "PYTHON_EXE=%~dp0.venv\Scripts\python.exe" + ) +) + +:: 2. Check if venv has Streamlit (Python 3.11 with full GPU OCR stack) +if not defined PYTHON_EXE ( + if exist "%~dp0venv\Scripts\python.exe" ( + "%~dp0venv\Scripts\python.exe" -c "import streamlit" >nul 2>&1 + if not errorlevel 1 ( + set "PYTHON_EXE=%~dp0venv\Scripts\python.exe" + ) + ) +) + +:: 3. Fallback: use whichever python.exe exists +if not defined PYTHON_EXE ( + if exist "%~dp0.venv\Scripts\python.exe" ( + set "PYTHON_EXE=%~dp0.venv\Scripts\python.exe" + ) else if exist "%~dp0venv\Scripts\python.exe" ( + set "PYTHON_EXE=%~dp0venv\Scripts\python.exe" + ) +) + +:: Error handling: No Python found +if not defined PYTHON_EXE ( + echo [ERROR] Virtual environment Python executable not found! + echo Looked for: + echo - "%~dp0.venv\Scripts\python.exe" + echo - "%~dp0venv\Scripts\python.exe" + echo. + echo Please make sure the virtual environment exists. + echo. + pause + exit /b 1 +) + +:: Error handling: Entry point missing +set "APP_ENTRY=%~dp0app\ui\workbench.py" +if not exist "%APP_ENTRY%" ( + echo [ERROR] Streamlit entry point not found: + echo "%APP_ENTRY%" + echo. + pause + exit /b 1 +) + +echo Python Runtime : %PYTHON_EXE% +echo UI Entry Point : %APP_ENTRY% +echo. +echo Starting Streamlit application... +echo (The browser will open automatically. Keep this window open.) +echo ========================================================== +echo. + +"%PYTHON_EXE%" -m streamlit run "%APP_ENTRY%" + +if errorlevel 1 ( + echo. + echo ========================================================== + echo [ERROR] Streamlit exited with error code %errorlevel%. + echo Review the error log above to diagnose. + echo ========================================================== +) + +echo. +pause \ No newline at end of file diff --git a/start.ps1 b/start.ps1 new file mode 100644 index 0000000..0271a60 --- /dev/null +++ b/start.ps1 @@ -0,0 +1,86 @@ +# start.ps1 - Invoice OCR Streamlit Workbench Launcher +$ErrorActionPreference = "Continue" + +# Resolve project root from script directory +$ProjectRoot = $PSScriptRoot +Set-Location -LiteralPath $ProjectRoot + +# Set UTF-8 encoding for console output +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 +$OutputEncoding = [System.Text.Encoding]::UTF8 +$env:PYTHONUTF8 = "1" +$env:PYTHONIOENCODING = "utf-8" + +Write-Host "==========================================================" -ForegroundColor Cyan +Write-Host " Invoice OCR - Streamlit Workbench Launcher" -ForegroundColor Cyan +Write-Host "==========================================================" -ForegroundColor Cyan +Write-Host "Project Directory: $ProjectRoot" +Write-Host "" + +# Detect Python in virtual environment +$PythonExe = $null + +# 1. Check if .venv has Streamlit +$dotVenvPython = Join-Path $ProjectRoot ".venv\Scripts\python.exe" +if (Test-Path -LiteralPath $dotVenvPython) { + & $dotVenvPython -c "import streamlit" 2>$null + if ($LASTEXITCODE -eq 0) { + $PythonExe = $dotVenvPython + } +} + +# 2. Check if venv has Streamlit (Python 3.11 with full GPU OCR stack) +if (-not $PythonExe) { + $venvPython = Join-Path $ProjectRoot "venv\Scripts\python.exe" + if (Test-Path -LiteralPath $venvPython) { + & $venvPython -c "import streamlit" 2>$null + if ($LASTEXITCODE -eq 0) { + $PythonExe = $venvPython + } + } +} + +# 3. Fallback +if (-not $PythonExe) { + if (Test-Path -LiteralPath $dotVenvPython) { + $PythonExe = $dotVenvPython + } elseif (Test-Path -LiteralPath $venvPython) { + $PythonExe = $venvPython + } +} + +if (-not $PythonExe) { + Write-Host "[ERROR] Virtual environment Python executable not found!" -ForegroundColor Red + Write-Host "Looked for:" -ForegroundColor Red + Write-Host " - $dotVenvPython" -ForegroundColor Red + Write-Host " - $venvPython" -ForegroundColor Red + Read-Host "Press Enter to exit..." + exit 1 +} + +$AppEntry = Join-Path $ProjectRoot "app\ui\workbench.py" +if (-not (Test-Path -LiteralPath $AppEntry)) { + Write-Host "[ERROR] Streamlit entry point not found: $AppEntry" -ForegroundColor Red + Read-Host "Press Enter to exit..." + exit 1 +} + +Write-Host "Python Runtime : $PythonExe" -ForegroundColor Green +Write-Host "UI Entry Point : $AppEntry" -ForegroundColor Green +Write-Host "" +Write-Host "Starting Streamlit application..." -ForegroundColor Yellow +Write-Host "(The browser will open automatically. Keep this window open.)" -ForegroundColor Yellow +Write-Host "==========================================================" -ForegroundColor Cyan +Write-Host "" + +& $PythonExe -m streamlit run $AppEntry + +if ($LASTEXITCODE -ne 0) { + Write-Host "" + Write-Host "==========================================================" -ForegroundColor Red + Write-Host "[ERROR] Streamlit exited with code $LASTEXITCODE." -ForegroundColor Red + Write-Host "==========================================================" -ForegroundColor Red +} + +Write-Host "" +Read-Host "Press Enter to exit..." diff --git a/tests/fixtures/synthetic_invoice.json b/tests/fixtures/synthetic_invoice.json new file mode 100644 index 0000000..9c44fed --- /dev/null +++ b/tests/fixtures/synthetic_invoice.json @@ -0,0 +1,32 @@ +{ + "metadata": { + "annotator": "Synthetic Generator", + "date": "2026-09-28", + "source": "from_image_blind", + "tier": "Tier_B" + }, + "invoice_id": "INV-SYN-001", + "invoice_number": "INV-SYN-001", + "invoice_date": "2026-08-20", + "due_date": "2026-09-20", + "PO_number": "PO-SYN-999", + "customer_name": "ACME HEALTHCARE PRIVATE LIMITED", + "customer_gstin": "27AAPFU0939F1ZV", + "seller_name": "SYNTHETIC PHARMA SUPPLIES LTD", + "seller_gstin": "27AAPFU0939F1ZV", + "currency_code": "INR", + "invoice_amount": "1180.00", + "total_gst_amount": "180.00", + "round_off": "0.00", + "items": [ + { + "description": "SYNTHETIC MEDICINE 500MG", + "hsn_sac": "30049099", + "quantity": 10, + "unit_price": "100.00", + "total_price": "1000.00", + "Discount": "0.00", + "Gst%": 18 + } + ] +} \ No newline at end of file diff --git a/tests/fixtures/synthetic_invoice.png b/tests/fixtures/synthetic_invoice.png new file mode 100644 index 0000000..030d5da Binary files /dev/null and b/tests/fixtures/synthetic_invoice.png differ diff --git a/tests/test_deskew_corrector.py b/tests/test_deskew_corrector.py new file mode 100644 index 0000000..7947abb --- /dev/null +++ b/tests/test_deskew_corrector.py @@ -0,0 +1,138 @@ +# tests/test_deskew_corrector.py + +from pathlib import Path +import pytest +from PIL import Image, ImageDraw +from app.preprocessing.deskew_corrector import ( + detect_skew_angle, + deskew_image, + process_folder_deskew, +) + + +@pytest.fixture +def base_ruled_invoice(): + """ + Generates a clean synthetic invoice page with distinct horizontal table lines + and grid dividers to provide reliable geometric baselines for Hough Line detection. + """ + img = Image.new("L", (1200, 1600), color=255) + draw = ImageDraw.Draw(img) + + # Prominent horizontal table borders and divider lines + draw.line([80, 150, 1120, 150], fill=0, width=3) + draw.line([80, 230, 1120, 230], fill=0, width=2) + draw.line([80, 310, 1120, 310], fill=0, width=2) + draw.line([80, 800, 1120, 800], fill=0, width=3) + draw.line([80, 900, 1120, 900], fill=0, width=2) + + # Line item rows + for y in range(360, 780, 50): + draw.line([80, y, 1120, y], fill=120, width=2) + + return img + + +@pytest.mark.parametrize("applied_tilt", [1.5, -1.5, 3.0, -3.0]) +def test_meaningful_skew_angles_detected_and_corrected(tmp_path, base_ruled_invoice, applied_tilt): + """ + Tests that tilts of +1.5°, -1.5°, +3.0°, and -3.0° are detected + and corrected back to horizontal (remaining tilt < 0.5°). + """ + src_file = tmp_path / f"tilted_{applied_tilt}.png" + # Rotate by applied_tilt degrees (counter-clockwise in PIL) + tilted_img = base_ruled_invoice.rotate( + applied_tilt, + expand=True, + resample=Image.Resampling.BICUBIC, + fillcolor=255, + ) + tilted_img.save(src_file) + + out_dir = tmp_path / "deskewed" + result = deskew_image(str(src_file), str(out_dir), min_skew=0.5) + + assert result["status"] == "deskewed" + assert result["rotated"] is True + assert result["line_count"] > 0 + # The detected angle should closely match the magnitude of the applied tilt (within 0.3°) + assert abs(abs(result["detected_skew_angle"]) - abs(applied_tilt)) <= 0.35 + assert Path(result["output_path"]).exists() + + # Re-inspect corrected image to confirm residual tilt is now below the 0.5° threshold + with Image.open(result["output_path"]) as corrected_img: + residual_angle, _ = detect_skew_angle(corrected_img) + assert abs(residual_angle) < 0.5 + + +def test_sub_threshold_skew_leaves_image_unrotated(tmp_path, base_ruled_invoice): + """ + A small tilt of 0.2° is below the 0.5° threshold and should NOT be rotated, + avoiding unnecessary pixel interpolation and preserving maximum sharpness. + """ + src_file = tmp_path / "tilted_0.2.png" + tilted_img = base_ruled_invoice.rotate( + 0.2, + expand=True, + resample=Image.Resampling.BICUBIC, + fillcolor=255, + ) + tilted_img.save(src_file) + + out_dir = tmp_path / "deskewed" + result = deskew_image(str(src_file), str(out_dir), min_skew=0.5) + + assert result["status"] == "straight" + assert result["rotated"] is False + assert result["correction_applied_deg"] == 0.0 + assert "saved unrotated to preserve sharpness" in result["message"] + assert Path(result["output_path"]).exists() + + +def test_straight_image_not_rotated(tmp_path, base_ruled_invoice): + """An un-tilted (0.0°) image remains untouched.""" + src_file = tmp_path / "straight.png" + base_ruled_invoice.save(src_file) + + out_dir = tmp_path / "deskewed" + result = deskew_image(str(src_file), str(out_dir), min_skew=0.5) + + assert result["status"] == "straight" + assert result["rotated"] is False + assert result["detected_skew_angle"] == 0.0 + assert Path(result["output_path"]).exists() + + +def test_outlier_skew_flagged(tmp_path, base_ruled_invoice): + """Angles exceeding max_skew (e.g. 25°) are flagged as outliers and not blindly rotated.""" + src_file = tmp_path / "outlier_25.png" + tilted_img = base_ruled_invoice.rotate(25.0, expand=True, fillcolor=255) + tilted_img.save(src_file) + + out_dir = tmp_path / "deskewed" + # Testing with max_skew = 10.0 and min_skew = 0.5 + result = deskew_image(str(src_file), str(out_dir), min_skew=0.5, max_skew=10.0) + + assert result["status"] in {"straight", "outlier_skew"} + assert result["rotated"] is False + assert Path(result["output_path"]).exists() + + +def test_process_folder_deskew(tmp_path, base_ruled_invoice): + """Verifies batch deskew processing aggregates counts and corrections properly.""" + in_dir = tmp_path / "oriented" + out_dir = tmp_path / "deskewed" + in_dir.mkdir() + + # Create 1 straight (0°), 1 sub-threshold (0.2°), and 1 tilted (+2.0°) + base_ruled_invoice.save(in_dir / "invoice_straight.png") + base_ruled_invoice.rotate(0.2, expand=True, fillcolor=255).save(in_dir / "invoice_subthreshold.png") + base_ruled_invoice.rotate(2.0, expand=True, fillcolor=255).save(in_dir / "invoice_tilted.png") + + summary = process_folder_deskew(str(in_dir), str(out_dir), min_skew=0.5) + + assert summary["total_images_processed"] == 3 + assert summary["straight_count"] == 2 + assert summary["deskewed_count"] == 1 + assert len(summary["corrections"]) == 1 + assert summary["corrections"][0]["filename"] == "invoice_tilted.png" diff --git a/tests/test_evaluator_refactor.py b/tests/test_evaluator_refactor.py new file mode 100644 index 0000000..2a1a11b --- /dev/null +++ b/tests/test_evaluator_refactor.py @@ -0,0 +1,92 @@ +# tests/test_evaluator_refactor.py +import pytest +from decimal import Decimal +from app.rrsi.evaluator import StatisticalEvaluator +from app.rrsi.taxonomy import ( + ExtractionErrorClass, + ProcessOutcome, + ProposalHypothesis, + PipelineArea, + ExperimentStatus +) + +def test_alignment_by_doc_id_not_zip(): + evaluator = StatisticalEvaluator() + # Shuffled order between predictions and ground truths + gt = [ + {"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"}, + {"invoice_id": "doc_B", "invoice_number": "INV-B", "invoice_amount": "200.00"} + ] + preds = [ + {"invoice_id": "doc_B", "invoice_number": "INV-B", "invoice_amount": "200.00"}, + {"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"} + ] + + metrics, failures = evaluator.evaluate_predictions(preds, gt) + # Since alignment is by doc_id, all fields should match 100% + assert metrics.macro_accuracy == 100.0 + assert len(failures) == 0 + +def test_missing_prediction_handled_as_pipeline_error(): + evaluator = StatisticalEvaluator() + gt = [ + {"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"}, + {"invoice_id": "doc_B", "invoice_number": "INV-B", "invoice_amount": "200.00"} + ] + # Prediction for doc_B is completely missing + preds = [ + {"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_amount": "100.00"} + ] + + metrics, failures = evaluator.evaluate_predictions(preds, gt) + assert "doc_B" in metrics.doc_results + doc_b_res = metrics.doc_results["doc_B"] + assert doc_b_res.is_end_to_end_correct is False + assert any(f.primary_class == ExtractionErrorClass.PIPELINE_ERROR for f in failures if f.file_id == "doc_B") + +def test_precision_counts_hallucination_when_gt_is_null(): + evaluator = StatisticalEvaluator() + # Ground truth has no PO_number + gt = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "PO_number": None}] + # Prediction extracted a hallucinated PO_number + preds = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "PO_number": "PO-9999"}] + + metrics, failures = evaluator.evaluate_predictions(preds, gt) + po_metrics = metrics.per_field_metrics.get("PO_number") + assert po_metrics is not None + assert po_metrics.hallucinations == 1 + assert any(f.primary_class == ExtractionErrorClass.HALLUCINATION for f in failures) + +def test_per_document_outcomes_structure(): + evaluator = StatisticalEvaluator() + gt = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_date": "2026-08-20"}] + preds = [{"invoice_id": "doc_A", "invoice_number": "INV-A", "invoice_date": "2026-08-21"}] + + metrics, failures = evaluator.evaluate_predictions(preds, gt) + assert "doc_A" in metrics.doc_results + doc_res = metrics.doc_results["doc_A"] + assert doc_res.field_outcomes["invoice_number"] is True + assert doc_res.field_outcomes["invoice_date"] is False + assert doc_res.field_errors["invoice_date"] == "date_mismatch" + +def test_selection_gate_requires_selection_split(): + evaluator = StatisticalEvaluator() + hypo = ProposalHypothesis( + proposal_id="PROP-101", + area=PipelineArea.ENTITY_EXTRACTION, + title="Test gate", + description="Testing selection gate", + rationale="Unit test" + ) + dev_base = evaluator.evaluate_predictions([{"invoice_id": "1", "invoice_number": "A"}], [{"invoice_id": "1", "invoice_number": "A"}])[0] + dev_cand = evaluator.evaluate_predictions([{"invoice_id": "1", "invoice_number": "A"}], [{"invoice_id": "1", "invoice_number": "A"}])[0] + + # Omitting selection split should raise ValueError (fail closed) + with pytest.raises(ValueError, match="Selection-split metrics are required"): + evaluator.decide_acceptance( + hypothesis=hypo, + baseline_dev=dev_base, + candidate_dev=dev_cand, + baseline_selection=None, + candidate_selection=None + ) diff --git a/tests/test_input_validation.py b/tests/test_input_validation.py new file mode 100644 index 0000000..b149176 --- /dev/null +++ b/tests/test_input_validation.py @@ -0,0 +1,99 @@ +# tests/test_input_validation.py + +import fitz +from PIL import Image +from app.input.file_validator import validate_file + + +def test_valid_single_page_pdf(tmp_path): + pdf_path = tmp_path / "single.pdf" + doc = fitz.open() + doc.new_page() + doc.save(pdf_path) + doc.close() + + result = validate_file(str(pdf_path)) + assert result["status"] == "valid" + assert result["format"] == "pdf" + assert result["page_count"] == 1 + + +def test_valid_multi_page_pdf(tmp_path): + pdf_path = tmp_path / "multi.pdf" + doc = fitz.open() + doc.new_page() + doc.new_page() + doc.new_page() + doc.save(pdf_path) + doc.close() + + result = validate_file(str(pdf_path)) + assert result["status"] == "valid" + assert result["page_count"] == 3 + + +def test_encrypted_pdf(tmp_path): + pdf_path = tmp_path / "locked.pdf" + doc = fitz.open() + doc.new_page() + doc.save( + pdf_path, + encryption=fitz.PDF_ENCRYPT_AES_256, + owner_pw="ownerpass", + user_pw="userpass", # a real password required to open it + ) + doc.close() + + result = validate_file(str(pdf_path)) + assert result["status"] == "invalid" + assert "encrypted" in result["reason"].lower() or "password" in result["reason"].lower() + + +def test_valid_jpg(tmp_path): + img_path = tmp_path / "photo.jpg" + Image.new("RGB", (100, 100), color="white").save(img_path) + + result = validate_file(str(img_path)) + assert result["status"] == "valid" + assert result["format"] == "jpg" + assert result["page_count"] == 1 + + +def test_valid_png(tmp_path): + img_path = tmp_path / "photo.png" + Image.new("RGB", (100, 100), color="white").save(img_path) + + result = validate_file(str(img_path)) + assert result["status"] == "valid" + assert result["format"] == "png" + + +def test_unsupported_extension(tmp_path): + bad_path = tmp_path / "notes.txt" + bad_path.write_text("just some text") + + result = validate_file(str(bad_path)) + assert result["status"] == "invalid" + assert "unsupported" in result["reason"].lower() + + +def test_corrupted_pdf(tmp_path): + fake_pdf = tmp_path / "broken.pdf" + fake_pdf.write_bytes(b"this is not a real pdf file") + + result = validate_file(str(fake_pdf)) + assert result["status"] == "invalid" + + +def test_corrupted_image(tmp_path): + fake_img = tmp_path / "broken.jpg" + fake_img.write_bytes(b"this is not a real image file") + + result = validate_file(str(fake_img)) + assert result["status"] == "invalid" + + +def test_nonexistent_file(): + result = validate_file("this/path/does/not/exist.pdf") + assert result["status"] == "invalid" + assert "does not exist" in result["reason"].lower() \ No newline at end of file diff --git a/tests/test_reconciliation_bug.py b/tests/test_reconciliation_bug.py new file mode 100644 index 0000000..f314574 --- /dev/null +++ b/tests/test_reconciliation_bug.py @@ -0,0 +1,77 @@ +# tests/test_reconciliation_bug.py +""" +Test reproducing the reconciliation bug and verifying the fix from fixed numbers: +1. Invoice 4531 (Vendor A): Discrepancy explanation (5627.20 vs 5628.00) +2. Invoice Kundan (Vendor B): Discrepancy explanation (878.40 vs 1518.54) +""" + +import pytest +from decimal import Decimal +from app.validators import InvoiceArithmeticValidator, ValidationStatus + +def test_invoice_4531_fixed_numbers_reconciliation(): + # Fixed numbers from printed invoice WMP/B/04531 + # Line 1: 60 qty * 3700.00 = 222000.00, 2% discount = 4440.00 -> taxable = 217560.00, GST 5% = 10878.00 + # Line 2: 120 qty * 198.00 = 23760.00, 5% discount = 1188.00 -> taxable = 22572.00, GST 5% = 1128.60 + # Total Gross: 245760.00 + # Total Discount: 5628.00 + # Total Taxable: 240132.00 + # Total GST: 12006.60 (CGST 6003.30 + SGST 6003.30) + # Round-off: +0.40 + # Invoice Amount: 252139.00 + + # Old buggy calculation: Gross + GST - Roundoff - Invoice Amount + buggy_discrepancy = (Decimal("245760.00") + Decimal("12006.60") - Decimal("0.40")) - Decimal("252139.00") + assert buggy_discrepancy == Decimal("5627.20"), "Reproduced the 5627.20 bug!" + + # Correct discount value: + total_discount = Decimal("4440.00") + Decimal("1188.00") + assert total_discount == Decimal("5628.00") + + # Correct validator check: + validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00")) + doc_4531 = { + "invoice_amount": "252139.00", + "total_gst_amount": "12006.60", + "round_off": "0.40", + "items": [ + {"total_price": "222000.00", "Discount": "2.00"}, + {"total_price": "23760.00", "Discount": "5.00"} + ] + } + res = validator.validate(doc_4531) + assert res.status == ValidationStatus.PASS + assert res.is_valid is True + assert res.discrepancy == Decimal("0.00") + assert res.reconciled_formula == "Taxable + GST + Freight + RoundOff" + +def test_invoice_kundan_fixed_numbers_reconciliation(): + # Fixed numbers from printed Kundan invoice: + # Gross items sum: 53542.60 + # Total Discount: 2141.704 (taxable: 51400.896) + # Correct GST: 3020.08 + # Extracted GST: 2396.94 (short by 623.14) + # Round-off: 0.01 + # Invoice Amount: 54421.00 + + # Pipeline extraction error: Gross items + Extracted GST - Invoice Amount + pipeline_extracted_sum = Decimal("53542.60") + Decimal("2396.94") + raw_discrepancy = pipeline_extracted_sum - Decimal("54421.00") + assert raw_discrepancy == Decimal("1518.54"), "Reproduced the 1518.54 discrepancy!" + + # Buggy partial offset (1518.54 - 640.14 = 878.40) + assert raw_discrepancy - Decimal("640.14") == Decimal("878.40"), "Reproduced the 878.40 bug!" + + # On ground truth with correct GST (3020.08), the document reconciles: + validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00")) + doc_kundan_gt = { + "invoice_amount": "54421.00", + "total_gst_amount": "3020.08", + "round_off": "0.01", + "items": [ + {"total_price": "53542.60", "Discount": "4.00"} + ] + } + res_gt = validator.validate(doc_kundan_gt) + assert res_gt.status == ValidationStatus.PASS + assert res_gt.is_valid is True diff --git a/tests/test_rrsi_framework.py b/tests/test_rrsi_framework.py new file mode 100644 index 0000000..1b91d15 --- /dev/null +++ b/tests/test_rrsi_framework.py @@ -0,0 +1,347 @@ +# tests/test_rrsi_framework.py +""" +Comprehensive Unit Tests for the RRSI Framework: +- Proposal Memory & Negative Knowledge Registry +- Area Stagnation & Shift Recommendations +- Leakage Screening (hardcoded tokens, coordinates, holdout retention) +- Statistical Evaluator (noise floor calculation, cost-aware acceptance) +- Granular Error Taxonomy Classification +- Experiment Ledger Persistence & Auditing +""" + +import tempfile +import pytest +from pathlib import Path + +from app.rrsi import ( + ErrorCategory, + PipelineArea, + ExperimentStatus, + FailureDetail, + ProposalHypothesis, + EvaluationMetrics, + DecisionRecord, + NegativeKnowledgeRegistry, + LeakageScreening, + PruningAnalyzer, + StatisticalEvaluator, + ExperimentLedger, + RRSIOrchestrator +) +from app.rrsi.taxonomy import ProcessOutcome, ExtractionErrorClass + + +@pytest.fixture +def temp_memory(): + with tempfile.TemporaryDirectory() as tmpdir: + yield Path(tmpdir) / "proposal_memory.json" + + +@pytest.fixture +def temp_ledger(): + with tempfile.TemporaryDirectory() as tmpdir: + yield Path(tmpdir) / "experiment_ledger.json" + + +def _create_dummy_decision( + proposal_id="PROP-001", + area=PipelineArea.ENTITY_EXTRACTION.value, + status=ExperimentStatus.REJECTED, + rejection_reasons=None +): + return DecisionRecord( + proposal_id=proposal_id, + area=area, + status=status, + process_outcome=ProcessOutcome.INSIGNIFICANT if status == ExperimentStatus.REJECTED else ProcessOutcome.ACCEPTED, + baseline_accuracy=85.0, + candidate_accuracy=85.0, + delta_accuracy=0.0, + paired_ci_lower=0.0, + paired_ci_upper=0.0, + is_statistically_significant=False, + leakage_screen_passed=True, + leakage_findings=[], + cost_aware_accepted=False, + latency_delta_seconds=0.0, + vision_fallback_calls=0, + case_regressions=[], + rejection_reasons=rejection_reasons or ["NO ACCURACY GAIN: Candidate did not improve baseline."], + pruning_recommendations=[], + failure_deltas={} + ) + + +# ----------------------------------------------------------------------------- +# 1. Proposal Side: Memory, Negative Knowledge & Area Shifting +# ----------------------------------------------------------------------------- +def test_negative_knowledge_blocks_repeated_failed_proposals(temp_memory): + registry = NegativeKnowledgeRegistry(storage_path=temp_memory, stagnation_threshold=3) + + # 1. Record a failed hypothesis + failed_hypo = ProposalHypothesis( + proposal_id="PROP-001", + area=PipelineArea.ENTITY_EXTRACTION, + title="Tweak invoice date regex to support slash dot combinations", + description="Add regex pattern for dd.mm.yyyy and slash formats in date parser", + rationale="Fix date extraction test failures", + tags=["regex", "date", "slash"] + ) + decision = _create_dummy_decision("PROP-001", PipelineArea.ENTITY_EXTRACTION.value, ExperimentStatus.REJECTED) + registry.record_decision(failed_hypo, decision) + + # 2. Candidate proposes a very similar idea in the same area + candidate_hypo = ProposalHypothesis( + proposal_id="PROP-002", + area=PipelineArea.ENTITY_EXTRACTION, + title="Tweak invoice date regex pattern for dot slash formats", + description="Add regex pattern for dd.mm.yyyy date parsing", + rationale="Fix date extraction failures", + tags=["regex", "date", "slash"] + ) + + is_viable, warnings, _ = registry.check_proposal_viability(candidate_hypo) + assert not is_viable + assert any("PROPOSAL DUPLICATION WARNING" in w for w in warnings) + + +def test_area_stagnation_triggers_area_shift(temp_memory): + registry = NegativeKnowledgeRegistry(storage_path=temp_memory, stagnation_threshold=3) + + # Record 3 consecutive failed attempts in ENTITY_EXTRACTION + for i in range(1, 4): + hypo = ProposalHypothesis( + proposal_id=f"PROP-00{i}", + area=PipelineArea.ENTITY_EXTRACTION, + title=f"Unique attempt {i} in regex entity extraction", + description=f"Description {i}", + rationale=f"Rationale {i}" + ) + decision = _create_dummy_decision(f"PROP-00{i}", PipelineArea.ENTITY_EXTRACTION.value, ExperimentStatus.REJECTED) + registry.record_decision(hypo, decision) + + # Attempt a 4th proposal in the same component + new_hypo = ProposalHypothesis( + proposal_id="PROP-004", + area=PipelineArea.ENTITY_EXTRACTION, + title="Another entity extraction attempt", + description="More micro tweaks", + rationale="Hoping for improvement" + ) + + is_viable, warnings, rec_area = registry.check_proposal_viability(new_hypo) + assert not is_viable + assert any("STAGNATION DETECTED" in w for w in warnings) + assert rec_area is not None + assert rec_area != PipelineArea.ENTITY_EXTRACTION + + +# ----------------------------------------------------------------------------- +# 2. Selection Side: Leakage Screening & Pruning +# ----------------------------------------------------------------------------- +def test_leakage_screening_detects_hardcoded_sample_tokens(): + clean_code = "def parse_inv(text): return re.findall(r'INV-[0-9]+', text)" + passed, findings = LeakageScreening.audit_code_changes(clean_code) + assert passed + assert len(findings) == 0 + + leaky_code = "if 'WMP/B/04531' in text: return 'WMP/B/04531'" + passed, findings = LeakageScreening.audit_code_changes(leaky_code) + assert not passed + assert any("DATA LEAKAGE DETECTED" in f for f in findings) + + +def test_leakage_screening_detects_coordinate_overfitting(): + overfitted_code = "if ymin >= 145 and ymax <= 320: return crop[120:850]" + passed, findings = LeakageScreening.audit_code_changes(overfitted_code) + assert not passed + assert any("COORDINATE OVERFITTING WARNING" in f for f in findings) + + +def test_generalization_split_screening(): + # Healthy generalization + passed, _ = LeakageScreening.audit_split_generalization(calibration_delta=3.5, holdout_delta=2.8) + assert passed + + # Regression on holdout set + passed, msg = LeakageScreening.audit_split_generalization(calibration_delta=4.0, holdout_delta=-1.2) + assert not passed + assert "GENERALIZATION FAILURE" in msg + + # Disproportionate overfit (calibration high, holdout negligible) + passed, msg = LeakageScreening.audit_split_generalization(calibration_delta=8.0, holdout_delta=0.5) + assert not passed + assert "LEAKAGE/OVERFITTING DETECTED" in msg + + +def test_pruning_analyzer_identifies_regex_redundancy(): + patterns = [r"INV-[0-9]+", r".*invoice.*", r"INV-[0-9]+"] + recommendations = PruningAnalyzer.analyze_regex_redundancy(patterns) + assert len(recommendations) > 0 + assert any("PRUNING OPPORTUNITY" in r for r in recommendations) + + +# ----------------------------------------------------------------------------- +# 3. Statistical Evaluator: Bootstrap CI, Cost-Awareness & Error Taxonomy +# ----------------------------------------------------------------------------- +def test_selection_gate_requires_selection_metrics(): + evaluator = StatisticalEvaluator() + hypo = ProposalHypothesis( + proposal_id="PROP-009", + area=PipelineArea.ENTITY_EXTRACTION, + title="Check gate enforcement", + description="Gate must fail-closed if selection split is omitted", + rationale="Integrity check" + ) + dev_m = evaluator.evaluate_predictions( + [{"invoice_id": "1", "invoice_number": "A"}], + [{"invoice_id": "1", "invoice_number": "A"}] + )[0] + + with pytest.raises(ValueError, match="Selection-split metrics are required"): + evaluator.decide_acceptance( + hypothesis=hypo, + baseline_dev=dev_m, + candidate_dev=dev_m, + baseline_selection=None, + candidate_selection=None + ) + + +def test_evaluator_rejects_candidate_within_noise_floor(): + evaluator = StatisticalEvaluator() + hypo = ProposalHypothesis( + proposal_id="PROP-010", + area=PipelineArea.TABLE_EXTRACTION, + title="Minor column spacing tweak", + description="Shift column border by 2px", + rationale="Experimental" + ) + + # Identical predictions on selection split -> delta is 0 -> CI includes 0 -> Rejected + gt = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)] + base_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)] + cand_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)] + + base_m, _ = evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=2.0) + cand_m, _ = evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=2.0) + + decision = evaluator.decide_acceptance( + hypothesis=hypo, + baseline_dev=base_m, + candidate_dev=cand_m, + baseline_selection=base_m, + candidate_selection=cand_m + ) + assert decision.status == ExperimentStatus.REJECTED + assert not decision.is_statistically_significant + assert any("NO ACCURACY GAIN" in r or "NOT STATISTICALLY SIGNIFICANT" in r for r in decision.rejection_reasons) + + +def test_cost_aware_acceptance_rejects_latency_blowup(): + evaluator = StatisticalEvaluator(cost_lambda=0.50) + hypo = ProposalHypothesis( + proposal_id="PROP-011", + area=PipelineArea.OCR_ENGINE, + title="Triple pass multi-scale OCR rendering", + description="Render image at 100, 200, and 400 DPI and merge results", + rationale="Higher resolution" + ) + + # Base: 80% accuracy, 1.0s runtime + gt = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)] + base_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}" if i < 8 else "WRONG"} for i in range(10)] + # Cand: 90% accuracy, but runtime balloons to 50.0s (+4900%) + cand_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}" if i < 9 else "WRONG"} for i in range(10)] + + base_m, _ = evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=1.0) + cand_m, _ = evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=50.0) + + decision = evaluator.decide_acceptance( + hypothesis=hypo, + baseline_dev=base_m, + candidate_dev=cand_m, + baseline_selection=base_m, + candidate_selection=cand_m + ) + assert decision.status == ExperimentStatus.REJECTED + assert not decision.cost_aware_accepted + assert any("COST UTILITY NEGATIVE" in r for r in decision.rejection_reasons) + + +def test_fine_grained_error_taxonomy_classification(): + evaluator = StatisticalEvaluator() + + ground_truth = [{ + "invoice_id": "1", + "invoice_number": "INV-100", + "invoice_date": "2026-05-12", + "customer_name": "Acme Corp", + "seller_gstin": "27AAPFU0939F1ZV", + "invoice_amount": "1000.00" + }] + + prediction = [{ + "invoice_id": "1", + "invoice_number": "INV-999", # INVOICE_NUMBER_MISMATCH + "invoice_date": "2026-05-13", # DATE_MISMATCH + "customer_name": "Different Corp", # PARTY_NAME_MISMATCH + "seller_gstin": "27AAPFU0939F1ZW", # GSTIN_INVALID + "invoice_amount": "800.00" # AMOUNT_PARSE + }] + + metrics, failures = evaluator.evaluate_predictions(prediction, ground_truth) + assert any(f.primary_class == ExtractionErrorClass.INVOICE_NUMBER_MISMATCH for f in failures) + assert any(f.primary_class == ExtractionErrorClass.DATE_MISMATCH for f in failures) + assert any(f.primary_class == ExtractionErrorClass.PARTY_NAME_MISMATCH for f in failures) + assert any(f.primary_class == ExtractionErrorClass.GSTIN_INVALID for f in failures) + assert any(f.primary_class == ExtractionErrorClass.AMOUNT_PARSE for f in failures) + assert len(failures) >= 5 + + +# ----------------------------------------------------------------------------- +# 4. Orchestrator & Ledger Integration +# ----------------------------------------------------------------------------- +def test_rrsi_orchestrator_end_to_end(temp_memory, temp_ledger): + orchestrator = RRSIOrchestrator( + memory_path=temp_memory, + ledger_path=temp_ledger + ) + + hypo = ProposalHypothesis( + proposal_id="PROP-E2E-001", + area=PipelineArea.TABLE_EXTRACTION, + title="Adaptive horizontal line clustering for tables", + description="Group rows dynamically using morphological kernel analysis", + rationale="Resolves merged multi-item rows" + ) + + is_viable, warnings, _ = orchestrator.submit_proposal(hypo) + assert is_viable + + gt = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)] + base_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}" if i < 4 else "WRONG"} for i in range(10)] + cand_preds = [{"invoice_id": str(i), "invoice_number": f"INV-{i}"} for i in range(10)] # 100% correct + + base_dev, _ = orchestrator.evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=2.0) + cand_dev, _ = orchestrator.evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=2.1) + base_sel, _ = orchestrator.evaluator.evaluate_predictions(base_preds, gt, runtime_seconds=2.0) + cand_sel, _ = orchestrator.evaluator.evaluate_predictions(cand_preds, gt, runtime_seconds=2.1) + + decision = orchestrator.evaluate_and_decide( + hypothesis=hypo, + baseline_dev=base_dev, + candidate_dev=cand_dev, + baseline_selection=base_sel, + candidate_selection=cand_sel + ) + + assert decision.status == ExperimentStatus.ACCEPTED + assert decision.is_statistically_significant + + # Verify ledger was persisted + assert len(orchestrator.ledger.records) == 1 + assert orchestrator.ledger.records[0]["proposal_id"] == "PROP-E2E-001" + + # Verify memory was updated with accepted approach + assert len(orchestrator.memory.accepted_approaches) == 1 diff --git a/tests/test_rrsi_normalize.py b/tests/test_rrsi_normalize.py new file mode 100644 index 0000000..bcf5a12 --- /dev/null +++ b/tests/test_rrsi_normalize.py @@ -0,0 +1,116 @@ +# tests/test_rrsi_normalize.py +import pytest +from decimal import Decimal +from app.rrsi.normalize import ( + normalize_invoice_number, + match_invoice_number, + normalize_date, + match_date, + normalize_amount, + match_amount, + normalize_vendor_name, + match_vendor_name, + validate_gstin_checksum, + match_gstin +) + +# --------------------------------------------------------------------------- +# 1. Invoice Number Tests: Whitespace and case only, NEVER numeric coercion +# --------------------------------------------------------------------------- +def test_invoice_number_never_coerces_numerically(): + # "04531" != "4531" + assert normalize_invoice_number("04531") == "04531" + assert normalize_invoice_number("4531") == "4531" + matched, err = match_invoice_number("04531", "4531") + assert matched is False + assert err == "invoice_number_mismatch" + +def test_invoice_number_case_and_whitespace(): + assert normalize_invoice_number(" wmp/B/04531 ") == "WMP/B/04531" + matched, err = match_invoice_number("WMP/B/04531", " wmp/b/04531 ") + assert matched is True + assert err is None + +# --------------------------------------------------------------------------- +# 2. Date Tests: ISO-8601 parsing and date_locale_swap classification +# --------------------------------------------------------------------------- +def test_date_iso_matching(): + # Standard format: 20/08/2026 -> 2026-08-20 + assert normalize_date("20/08/2026") == "2026-08-20" + assert normalize_date("20-08-2026") == "2026-08-20" + assert normalize_date("2026-08-20") == "2026-08-20" + + matched, err = match_date("2026-08-20", "20/08/2026") + assert matched is True + assert err is None + +def test_date_locale_swap_detected(): + # Ground truth is 05 July 2026 ("2026-07-05"). + # Prediction parsed as May 07 2026 ("2026-05-07") because of MM/DD vs DD/MM swap. + matched, err = match_date("2026-07-05", "05/07/2026", default_format="%m/%d/%Y") + # If the prediction assumed MM/DD/YYYY, "05/07/2026" yielded May 7, which differs from July 5 + matched, err = match_date("2026-07-05", "2026-05-07") + assert matched is False + assert err == "date_locale_swap" + +def test_date_genuine_mismatch(): + matched, err = match_date("2026-07-25", "2026-07-10") + assert matched is False + assert err == "date_mismatch" + +# --------------------------------------------------------------------------- +# 3. Amount Tests: Decimal with configurable relative + absolute tolerance +# --------------------------------------------------------------------------- +def test_amount_decimal_parsing_and_matching(): + # Currency symbols and commas + amt = normalize_amount("Rs. 1,23,456.78") + assert amt == Decimal("123456.78") + + # Within absolute tolerance (default abs_tol=1.0) + matched, err = match_amount("100.50", "101.00", abs_tol=Decimal("1.00"), rel_tol=Decimal("0.001")) + assert matched is True + + # Exceeding tolerance + matched, err = match_amount("100.00", "102.50", abs_tol=Decimal("1.00"), rel_tol=Decimal("0.001")) + assert matched is False + assert err == "amount_mismatch" + +# --------------------------------------------------------------------------- +# 4. Name Tests: Casefold, punctuation strip, legal suffix normalization, exact vs fuzzy +# --------------------------------------------------------------------------- +def test_vendor_name_normalization_and_fuzzy(): + # Normalizing "Acme Health Care Private Limited" vs "acme health care pvt. ltd." + n1 = normalize_vendor_name("Acme Health Care Private Limited") + n2 = normalize_vendor_name("acme health care pvt. ltd.") + assert n1 == "acme health care pvt ltd" + assert n2 == "acme health care pvt ltd" + + exact, fuzzy, score = match_vendor_name("Acme Health Care Private Limited", "acme health care pvt. ltd.") + assert exact is True + assert fuzzy is True + assert score == 1.0 + + # Slight variation: exact is False, but fuzzy is True + exact2, fuzzy2, score2 = match_vendor_name("Acme Health Care Pvt Ltd", "Acme Healthcare Pvt Ltd") + assert exact2 is False + assert fuzzy2 is True + assert score2 >= 0.85 + +# --------------------------------------------------------------------------- +# 5. GSTIN Tests: Exact match and checksum validity +# --------------------------------------------------------------------------- +def test_gstin_checksum_validity(): + # Valid Indian GSTIN: 27AAPFU0939F1ZV + assert validate_gstin_checksum("27AAPFU0939F1ZV") is True + # Invalid checksum char (altered last char to 'W') + assert validate_gstin_checksum("27AAPFU0939F1ZW") is False + +def test_gstin_matching(): + matched, valid_chk, err = match_gstin("27AAPFU0939F1ZV", "27AAPFU0939F1ZV") + assert matched is True + assert valid_chk is True + assert err is None + + matched, valid_chk, err = match_gstin("27AAPFU0939F1ZV", "27AAPFU0939F1ZW") + assert matched is False + assert err == "gstin_mismatch" diff --git a/tests/test_rrsi_stats.py b/tests/test_rrsi_stats.py new file mode 100644 index 0000000..959b44c --- /dev/null +++ b/tests/test_rrsi_stats.py @@ -0,0 +1,87 @@ +# tests/test_rrsi_stats.py +import pytest +from app.rrsi.stats import ( + wilson_interval, + paired_cluster_bootstrap, + mcnemar_test +) + +def test_wilson_interval_known_values(): + # Known test case: 10 successes out of 20 trials at 95% confidence + lower, upper = wilson_interval(successes=10, total=20, confidence=0.95) + assert pytest.approx(lower, abs=1e-3) == 0.2993 + assert pytest.approx(upper, abs=1e-3) == 0.7007 + assert 0.0 <= lower <= upper <= 1.0 + +def test_wilson_interval_small_n_is_wide(): + # N=3 sample size (e.g. 2 successes out of 3) must give a very wide interval + lower, upper = wilson_interval(successes=2, total=3, confidence=0.95) + width = upper - lower + # At N=3, the 95% Wilson interval width is > 0.60 + assert width > 0.60 + assert lower > 0.15 + assert upper < 0.99 + +def test_wilson_interval_edge_cases(): + # 0 successes out of 10: Wald gives [0, 0] with margin 0, but Wilson properly gives upper bound > 0 + lower, upper = wilson_interval(successes=0, total=10, confidence=0.95) + assert lower == 0.0 + assert upper > 0.20 + assert upper <= 0.35 + + # 10 successes out of 10 + lower, upper = wilson_interval(successes=10, total=10, confidence=0.95) + assert upper == 1.0 + assert lower >= 0.65 + + # Empty total + lower, upper = wilson_interval(successes=0, total=0) + assert lower == 0.0 + assert upper == 0.0 + +def test_paired_cluster_bootstrap_identical_runs(): + # Identical runs must yield exactly delta=0 and CI [0, 0] + base_scores = {"doc1": 0.8, "doc2": 0.9, "doc3": 0.7, "doc4": 0.85} + cand_scores = {"doc1": 0.8, "doc2": 0.9, "doc3": 0.7, "doc4": 0.85} + groups = {"doc1": "grp_a", "doc2": "grp_a", "doc3": "grp_b", "doc4": "grp_b"} + + res = paired_cluster_bootstrap(base_scores, cand_scores, groups, n_resamples=1000, seed=42) + assert pytest.approx(res["mean_delta"], abs=1e-6) == 0.0 + assert pytest.approx(res["ci_lower"], abs=1e-6) == 0.0 + assert pytest.approx(res["ci_upper"], abs=1e-6) == 0.0 + assert pytest.approx(res["std_err"], abs=1e-6) == 0.0 + +def test_paired_cluster_bootstrap_positive_delta(): + base_scores = {"doc1": 0.6, "doc2": 0.7, "doc3": 0.5, "doc4": 0.6} + cand_scores = {"doc1": 0.8, "doc2": 0.9, "doc3": 0.7, "doc4": 0.8} + groups = {"doc1": "grp_a", "doc2": "grp_a", "doc3": "grp_b", "doc4": "grp_b"} + + res = paired_cluster_bootstrap(base_scores, cand_scores, groups, n_resamples=1000, seed=42) + assert pytest.approx(res["mean_delta"], abs=1e-3) == 0.2 + assert res["ci_lower"] > 0.0 + assert res["ci_upper"] > res["ci_lower"] + +def test_mcnemar_test_known_values(): + # Contingency table: + # base=1, cand=1: 50 + # base=1, cand=0: 5 (b) + # base=0, cand=1: 20 (c) + # base=0, cand=0: 25 + base = [True] * 50 + [True] * 5 + [False] * 20 + [False] * 25 + cand = [True] * 50 + [False] * 5 + [True] * 20 + [False] * 25 + + res = mcnemar_test(base, cand) + assert res["b"] == 5 + assert res["c"] == 20 + assert res["n_discordant"] == 25 + # Chi-square with continuity correction: (|5 - 20| - 1)^2 / (5 + 20) = 14^2 / 25 = 196 / 25 = 7.84 + assert pytest.approx(res["statistic"], abs=1e-2) == 7.84 + assert res["p_value"] < 0.01 + +def test_mcnemar_test_zero_discordant(): + base = [True, False, True] + cand = [True, False, True] + res = mcnemar_test(base, cand) + assert res["b"] == 0 + assert res["c"] == 0 + assert res["p_value"] == 1.0 diff --git a/tests/test_schema_validator.py b/tests/test_schema_validator.py new file mode 100644 index 0000000..b2ed5b8 --- /dev/null +++ b/tests/test_schema_validator.py @@ -0,0 +1,59 @@ +# tests/test_schema_validator.py + +import json +from pathlib import Path +import pytest +from app.ocr.schema_validator import SchemaValidator, HEADER_KEYS_SPEC, ITEM_KEYS_SPEC + +def test_schema_validator_spec_lengths(): + assert len(HEADER_KEYS_SPEC) == 24 # 23 header keys + 'items' + assert len(ITEM_KEYS_SPEC) == 26 # 26 line item keys + assert HEADER_KEYS_SPEC[-1] == "items" + +def test_schema_validator_on_synthetic_valid_and_invalid(): + validator = SchemaValidator() + + # Perfect template object + valid_obj = {k: None for k in HEADER_KEYS_SPEC} + valid_obj["items"] = [{k: None for k in ITEM_KEYS_SPEC}] + + res = validator.validate(valid_obj) + assert res["valid"] is True + assert res["status"] == "PASS" + assert len(res["errors"]) == 0 + + # Missing header key + invalid_header = valid_obj.copy() + del invalid_header["customer_gstin"] + res_inv = validator.validate(invalid_header) + assert res_inv["valid"] is False + assert res_inv["status"] == "FAIL" + assert "customer_gstin" in res_inv["header_conformance"]["missing"] + + # Missing item key + invalid_item = {k: None for k in HEADER_KEYS_SPEC} + item_dict = {k: None for k in ITEM_KEYS_SPEC} + del item_dict["hsn_sac"] + invalid_item["items"] = [item_dict] + res_item_inv = validator.validate(invalid_item) + assert res_item_inv["valid"] is False + assert any("hsn_sac" in e for e in res_item_inv["errors"]) + +def test_schema_validator_on_all_official_outputs(): + validator = SchemaValidator() + files = [ + "data/ocr_results/invoice_4531_official.json", + "data/ocr_results/kundan_official.json", + "data/ocr_results/196_pune_official.json", + "data/ocr_results/cc1415_official.json" + ] + + existing_files = [Path(f) for f in files if Path(f).exists()] + if not existing_files: + pytest.skip("Private OCR official output results not present on fresh clone.") + + for f_path in existing_files: + with open(f_path, "r", encoding="utf-8") as f: + data = json.load(f) + report = validator.validate(data) + assert report["valid"] is True, f"Failed structural validation on {f_path}: {report['errors']}" diff --git a/tests/test_self_healing.py b/tests/test_self_healing.py new file mode 100644 index 0000000..81758f9 --- /dev/null +++ b/tests/test_self_healing.py @@ -0,0 +1,153 @@ +# tests/test_self_healing.py +""" +Unit tests for the Active Mathematical Self-Healing Engine (SelfHealingEngine) +and Semantic Synonym Ontology (SemanticOntology). +""" + +import pytest +from app.ocr.self_healing import SelfHealingEngine +from app.ocr.semantic_ontology import ( + matches_any_alias, + parse_credit_terms_days, + PAYABLE_TOTAL_ALIASES, + DUE_DATE_ALIASES, + BUYER_ANCHORS +) + +def test_semantic_ontology_matching(): + assert matches_any_alias("TO PAY: 34327.00", PAYABLE_TOTAL_ALIASES) + assert matches_any_alias("Net Payable Amount", PAYABLE_TOTAL_ALIASES) + assert matches_any_alias("Due Dt. 10/08/2026", DUE_DATE_ALIASES) + assert matches_any_alias("Details of Receiver (Billed to)", BUYER_ANCHORS) + assert matches_any_alias("Random Unrelated Text", PAYABLE_TOTAL_ALIASES) is False + +def test_credit_terms_parsing(): + assert parse_credit_terms_days("Credit: 30 Days") == 30 + assert parse_credit_terms_days("Terms: 7 days net") == 7 + assert parse_credit_terms_days("Payment due within 15 days of invoice") == 15 + assert parse_credit_terms_days("Immediate Cash Payment") is None + +def test_line_item_math_derivation(): + raw_items = [ + { + "description": "Medicine A", + "quantity": 10, + "free_quantity": 2, + "rate": 100.0, + "amount": None, # Missing + "discount_pct": 10.0, + "cgst_rate": 2.5, + "sgst_rate": 2.5 + }, + { + "description": "Medicine B", + "quantity": 5, + "free_quantity": 0, + "rate": None, # Missing + "amount": 250.0, + "discount_pct": 0.0, + "cgst_rate": 2.5, + "sgst_rate": 2.5 + } + ] + + res = SelfHealingEngine.heal( + meta={"invoice_date": "01/08/2026"}, + fin={}, + raw_items=raw_items + ) + + items = res["items"] + # Item 1: 10 * 100 * (1 - 0.10) = 900.0 + assert items[0]["amount"] == 900.0 + assert items[0]["total_quantity"] == 12 + assert items[0]["free_item_yn"] == "1" + assert items[0]["cgst_amount"] == 22.50 + assert items[0]["sgst_amount"] == 22.50 + + # Item 2: 250 / 5 = 50.0 + assert items[1]["rate"] == 50.0 + assert items[1]["total_quantity"] == 5 + assert items[1]["free_item_yn"] == "0" + assert items[1]["cgst_amount"] == 6.25 + assert items[1]["sgst_amount"] == 6.25 + +def test_grand_total_and_tax_auto_deduction(): + raw_items = [ + { + "description": "Item 1", + "quantity": 10, + "rate": 100.0, + "amount": 1000.0, + "cgst_amount": 25.0, + "sgst_amount": 25.0 + }, + { + "description": "Item 2", + "quantity": 5, + "rate": 200.0, + "amount": 1000.0, + "cgst_amount": 25.0, + "sgst_amount": 25.0 + } + ] + + # Case A: Missing grand_total, cgst, sgst + res = SelfHealingEngine.heal( + meta={"invoice_date": "01/08/2026"}, + fin={"roundoff": 0.50}, # subtotal and grand_total missing + raw_items=raw_items + ) + + fin = res["fin"] + assert fin["cgst"] == 50.0 + assert fin["sgst"] == 50.0 + # subtotal = 2000.0, taxes = 100.0, roundoff = 0.50 -> 2100.50 + assert fin["grand_total"] == 2100.50 + +def test_mislabeled_subtotal_grand_total_reconciliation(): + raw_items = [ + { + "description": "Item 1", + "quantity": 10, + "rate": 100.0, + "amount": 1000.0, + "cgst_amount": 25.0, + "sgst_amount": 25.0 + } + ] + + # Case B: extracted grand_total is 1000.0 (the taxable subtotal), but taxes are 50.0 + res = SelfHealingEngine.heal( + meta={"invoice_date": "01/08/2026"}, + fin={ + "subtotal": 1000.0, + "cgst": 25.0, + "sgst": 25.0, + "roundoff": 0.0, + "grand_total": 1000.0 # Mislabeled + }, + raw_items=raw_items + ) + + fin = res["fin"] + # Must be corrected to 1050.0 + assert fin["grand_total"] == 1050.0 + +def test_due_date_inference_from_credit_terms(): + lines = [ + {"text": "Invoice Date: 10/08/2026"}, + {"text": "Payment Terms: Credit 20 Days"}, + {"text": "Thank you for your business"} + ] + + res = SelfHealingEngine.heal( + meta={"invoice_date": "10/08/2026", "due_date": None}, + fin={}, + raw_items=[], + all_ocr_lines=lines + ) + + meta = res["meta"] + # 10/08/2026 + 20 days = 30/08/2026 + assert meta["due_date"] == "30/08/2026" diff --git a/tests/test_table_extractor.py b/tests/test_table_extractor.py new file mode 100644 index 0000000..23707f9 --- /dev/null +++ b/tests/test_table_extractor.py @@ -0,0 +1,188 @@ +import pytest +from pathlib import Path +from app.ocr.table_extractor import TableExtractor + +def test_table_extractor_synthetic(): + # Build synthetic bounding box elements representing a clean table + # Columns at: + # Description (x: 100-300), HSN (x: 400-500), Qty (x: 550-650), Rate (x: 700-800), Amount (x: 850-950) + header_elements = [ + {"text": "Description of Goods", "box": [[100, 100], [300, 100], [300, 130], [100, 130]]}, + {"text": "HSN Code", "box": [[400, 100], [500, 100], [500, 130], [400, 130]]}, + {"text": "Quantity", "box": [[550, 100], [650, 100], [650, 130], [550, 130]]}, + {"text": "Rate", "box": [[700, 100], [800, 100], [800, 130], [700, 130]]}, + {"text": "Amount", "box": [[850, 100], [950, 100], [950, 130], [850, 130]]}, + ] + + # Row 1: Widget A, HSN 84713010, Qty 5, Rate 200, Amount 1000 + row1_elements = [ + {"text": "Widget A", "box": [[100, 160], [300, 160], [300, 190], [100, 190]]}, + {"text": "84713010", "box": [[400, 160], [500, 160], [500, 190], [400, 190]]}, + {"text": "5 pcs", "box": [[550, 160], [650, 160], [650, 190], [550, 190]]}, + {"text": "200.00", "box": [[700, 160], [800, 160], [800, 190], [700, 190]]}, + {"text": "1000.00", "box": [[850, 160], [950, 160], [950, 190], [850, 190]]}, + ] + + # Footer row + footer_elements = [ + {"text": "Total", "box": [[700, 250], [800, 250], [800, 280], [700, 280]]}, + {"text": "1000.00", "box": [[850, 250], [950, 250], [950, 280], [850, 280]]}, + ] + + elements = header_elements + row1_elements + footer_elements + + extractor = TableExtractor() + result = extractor.extract_table(elements) + + assert result["status"] == "success" + assert result["total_items"] == 1 + item = result["line_items"][0] + assert "Widget A" in item["description"] + assert item["hsn_code"] == "84713010" + assert item["quantity"] == 5.0 + assert item["rate"] == 200.0 + assert item["amount"] == 1000.0 + assert item["math_verified"] is True + assert result["table_math_verified"] is True + assert result["calculated_subtotal"] == 1000.0 + +def test_empty_elements(): + extractor = TableExtractor() + res = extractor.extract_table([]) + assert res["status"] == "empty" + assert res["line_items"] == [] + +def test_no_header_elements(): + extractor = TableExtractor() + res = extractor.extract_table([ + {"text": "Some random text", "box": [[0, 0], [10, 0], [10, 10], [0, 10]]} + ]) + assert res["status"] == "no_header_detected" + assert res["line_items"] == [] + +def test_last_line_item_does_not_absorb_totals_row_bleedthrough(): + """ + Regression test: ensures that when the last line item has a multi-line description + and sits directly above a standalone subtotal/totals row (with or without a 'Total' label), + the totals value (e.g. 28,800.00) is NOT absorbed into the product description. + """ + header_elements = [ + {"text": "Description of Goods", "box": [[100, 100], [300, 100], [300, 130], [100, 130]]}, + {"text": "HSN Code", "box": [[400, 100], [500, 100], [500, 130], [400, 130]]}, + {"text": "Quantity", "box": [[550, 100], [650, 100], [650, 130], [550, 130]]}, + {"text": "Rate", "box": [[700, 100], [800, 100], [800, 130], [700, 130]]}, + {"text": "Amount", "box": [[850, 100], [950, 100], [950, 130], [850, 130]]}, + ] + + # Item 1: Nuprep Gel + row1 = [ + {"text": "1 Nuprep Gel", "box": [[100, 150], [300, 150], [300, 180], [100, 180]]}, + {"text": "30067000", "box": [[400, 150], [500, 150], [500, 180], [400, 180]]}, + {"text": "9 no", "box": [[550, 150], [650, 150], [650, 180], [550, 180]]}, + {"text": "1400.00", "box": [[700, 150], [800, 150], [800, 180], [700, 180]]}, + {"text": "12600.00", "box": [[850, 150], [950, 150], [950, 180], [850, 180]]}, + ] + + # Item 2: Paste -Ten 20 (multi-line description) + row2_main = [ + {"text": "2 Paste -Ten 20", "box": [[100, 200], [300, 200], [300, 230], [100, 230]]}, + {"text": "30067000", "box": [[400, 200], [500, 200], [500, 230], [400, 230]]}, + {"text": "9 jar", "box": [[550, 200], [650, 200], [650, 230], [550, 230]]}, + {"text": "1800.00", "box": [[700, 200], [800, 200], [800, 230], [700, 230]]}, + {"text": "16200.00", "box": [[850, 200], [950, 200], [950, 230], [850, 230]]}, + ] + # Continuation row for Item 2 in description column + row2_continuation = [ + {"text": "1 Box= 3 Jar (Weight-228 GM)", "box": [[100, 240], [350, 240], [350, 270], [100, 270]]}, + ] + + # Standalone Subtotal row sitting directly beneath the line items (no label, only amount) + subtotal_row = [ + {"text": "28800.00", "box": [[850, 290], [950, 290], [950, 320], [850, 320]]}, + ] + + # Tax row below subtotal + tax_row = [ + {"text": "Out Put CGST", "box": [[550, 340], [750, 340], [750, 370], [550, 370]]}, + {"text": "720.00", "box": [[850, 340], [950, 340], [950, 370], [850, 370]]}, + ] + + elements = header_elements + row1 + row2_main + row2_continuation + subtotal_row + tax_row + + extractor = TableExtractor() + result = extractor.extract_table(elements) + + assert result["status"] == "success" + assert result["total_items"] == 2 + item2 = result["line_items"][1] + + # Ensure the description contains the legitimate product spec but NOT the subtotal amount + assert "Paste -Ten 20" in item2["description"] + assert "1 Box= 3 Jar" in item2["description"] + assert "28800" not in item2["description"] + assert "28,800" not in item2["description"] + assert item2["amount"] == 16200.0 + assert result["calculated_subtotal"] == 28800.0 + +def test_free_quantity_and_tax_derivation_in_table(): + """ + Validates: + 1. Compound quantity '20+ 2' in quantity column extracts paid=20, free=2, total=22 + 2. Embedded '20+ 2' in description extracts paid=20, free=2, total=22 and cleans description + 3. Row-level tax derivation: calculates cgst_amount & sgst_amount from rates + 4. Promotional item with rate=0 extracts free_quantity=qty and paid quantity=0 + """ + header_elements = [ + {"text": "Description", "box": [[100, 100], [350, 100], [350, 130], [100, 130]]}, + {"text": "Qty", "box": [[400, 100], [480, 100], [480, 130], [400, 130]]}, + {"text": "Rate", "box": [[500, 100], [580, 100], [580, 130], [500, 130]]}, + {"text": "CGST %", "box": [[600, 100], [670, 100], [670, 130], [600, 130]]}, + {"text": "SGST %", "box": [[690, 100], [760, 100], [760, 130], [690, 130]]}, + {"text": "Amount", "box": [[780, 100], [880, 100], [880, 130], [780, 130]]}, + ] + + # Row 1: Compound qty column '20+ 2' + row1 = [ + {"text": "FLUDAC 20MG 15 CAPS", "box": [[100, 150], [350, 150], [350, 180], [100, 180]]}, + {"text": "20+ 2", "box": [[400, 150], [480, 150], [480, 180], [400, 180]]}, + {"text": "48.71", "box": [[500, 150], [580, 150], [580, 180], [500, 180]]}, + {"text": "2.5", "box": [[600, 150], [670, 150], [670, 180], [600, 180]]}, + {"text": "2.5", "box": [[690, 150], [760, 150], [760, 180], [690, 180]]}, + {"text": "974.20", "box": [[780, 150], [880, 150], [880, 180], [780, 180]]}, + ] + + # Row 2: Free promotional item (rate 0, amount 0) + row2 = [ + {"text": "PROMO SAMPLE PEN FREE", "box": [[100, 200], [350, 200], [350, 230], [100, 230]]}, + {"text": "5", "box": [[400, 200], [480, 200], [480, 230], [400, 230]]}, + {"text": "0.00", "box": [[500, 200], [580, 200], [580, 230], [500, 230]]}, + {"text": "0.0", "box": [[600, 200], [670, 200], [670, 230], [600, 230]]}, + {"text": "0.0", "box": [[690, 200], [760, 200], [760, 230], [690, 230]]}, + {"text": "0.00", "box": [[780, 200], [880, 200], [880, 230], [780, 230]]}, + ] + + # Footer + footer = [ + {"text": "Total", "box": [[700, 260], [770, 260], [770, 290], [700, 290]]}, + {"text": "974.20", "box": [[780, 260], [880, 260], [880, 290], [780, 290]]}, + ] + + extractor = TableExtractor() + res = extractor.extract_table(header_elements + row1 + row2 + footer) + + assert res["status"] == "success" + assert res["total_items"] == 2 + + it1 = res["line_items"][0] + assert it1["quantity"] == 20.0 + assert it1["free_quantity"] == 2.0 + assert it1["total_quantity"] == 22.0 + assert it1["cgst_amount"] == 24.36 + assert it1["sgst_amount"] == 24.36 + + it2 = res["line_items"][1] + assert it2["quantity"] == 0.0 + assert it2["free_quantity"] == 5.0 + assert it2["total_quantity"] == 5.0 + + diff --git a/tests/test_table_metrics.py b/tests/test_table_metrics.py new file mode 100644 index 0000000..8dfa675 --- /dev/null +++ b/tests/test_table_metrics.py @@ -0,0 +1,64 @@ +# tests/test_table_metrics.py +import pytest +from app.rrsi.table_metrics import ( + evaluate_table, + TableEvaluationResult, + TableStructureError +) + +def test_table_metrics_perfect_match(): + exp = [ + {"description": "ALBUCEL 20%", "hsn_sac": "30021290", "quantity": 60, "unit_price": "3700.00", "total_price": "222000.00"}, + {"description": "TELIPSA INJ", "hsn_sac": "30049099", "quantity": 120, "unit_price": "198.00", "total_price": "23760.00"} + ] + pred = [ + {"description": "ALBUCEL 20%", "hsn_sac": "30021290", "quantity": 60, "unit_price": "3700.00", "total_price": "222000.00"}, + {"description": "TELIPSA INJ", "hsn_sac": "30049099", "quantity": 120, "unit_price": "198.00", "total_price": "23760.00"} + ] + + res = evaluate_table(exp, pred) + assert res.row_precision == 1.0 + assert res.row_recall == 1.0 + assert res.row_f1 == 1.0 + assert res.cell_f1 == 1.0 + assert len(res.structure_errors) == 0 + +def test_table_metrics_guard_none_none_matches(): + # If both expected and predicted have None/empty cells, it must NOT count as a positive cell match + exp = [{"description": "Item 1", "hsn_sac": None, "unit": None, "quantity": 10, "unit_price": "50.00", "total_price": "500.00"}] + pred = [{"description": "Item 1", "hsn_sac": None, "unit": None, "quantity": 10, "unit_price": "50.00", "total_price": "500.00"}] + + res = evaluate_table(exp, pred) + # Expected cells with values: description, quantity, unit_price, total_price (4 cells) + # None cells should not artificially inflate cell matches + assert res.total_expected_cells == 4 + assert res.correct_cells == 4 + assert res.cell_recall == 1.0 + +def test_table_metrics_row_split_and_merge(): + # Ground truth: 1 row with qty 10, total 1000 + # Prediction: 2 rows with qty 5, total 500 each (row split) + exp = [ + {"description": "Item Alpha", "hsn_sac": "3004", "quantity": 10, "unit_price": "100.00", "total_price": "1000.00"} + ] + pred = [ + {"description": "Item Alpha", "hsn_sac": "3004", "quantity": 5, "unit_price": "100.00", "total_price": "500.00"}, + {"description": "Item Alpha", "hsn_sac": "3004", "quantity": 5, "unit_price": "100.00", "total_price": "500.00"} + ] + + res = evaluate_table(exp, pred) + assert res.row_recall == 1.0 # One matched + assert res.row_precision == 0.5 # 1 out of 2 + assert any(err.error_type == TableStructureError.ROW_SPLIT for err in res.structure_errors) + +def test_table_metrics_column_shift(): + # Rate shifted into HSN column + exp = [ + {"description": "Item Beta", "hsn_sac": "30049099", "quantity": 10, "unit_price": "150.00", "total_price": "1500.00"} + ] + pred = [ + {"description": "Item Beta", "hsn_sac": "150.00", "quantity": 10, "unit_price": None, "total_price": "1500.00"} + ] + + res = evaluate_table(exp, pred) + assert any(err.error_type == TableStructureError.COLUMN_SHIFT for err in res.structure_errors) diff --git a/tests/test_template_similarity.py b/tests/test_template_similarity.py new file mode 100644 index 0000000..3e571a5 --- /dev/null +++ b/tests/test_template_similarity.py @@ -0,0 +1,132 @@ +# tests/test_template_similarity.py + +import io +from pathlib import Path +import pytest +from PIL import Image, ImageDraw +from app.preprocessing.template_similarity_detector import ( + compute_perceptual_hash, + find_template_similar_images, +) + + +@pytest.fixture +def base_invoice_image(): + """Generates a synthetic grayscale invoice-like image with header, boxes, and table lines.""" + img = Image.new("L", (400, 500), 255) + draw = ImageDraw.Draw(img) + # Header logo / box + draw.rectangle([30, 20, 370, 70], fill=120) + # Metadata box + draw.rectangle([30, 90, 370, 160], outline=40, width=2) + # Line items table + draw.rectangle([30, 180, 370, 420], outline=40, width=2) + for y in range(220, 420, 40): + draw.line([30, y, 370, y], fill=100, width=1) + for x in [100, 200, 300]: + draw.line([x, 180, x, 420], fill=100, width=1) + return img + + +def test_recompressed_jpeg_detected_as_template_similar(tmp_path, base_invoice_image): + """Images sharing layout despite compression artifacts have distance <= 4.""" + p1 = tmp_path / "invoice_original.png" + base_invoice_image.save(p1) + + buf = io.BytesIO() + base_invoice_image.save(buf, format="JPEG", quality=25) + buf.seek(0) + img_compressed = Image.open(buf) + p2 = tmp_path / "invoice_recompressed.png" + img_compressed.save(p2) + + result = find_template_similar_images(str(tmp_path), threshold=4) + + assert result["total_images_analyzed"] == 2 + assert result["total_template_similarity_pairs"] == 1 + pair = result["template_similarity_pairs"][0] + assert pair["hamming_distance"] <= 4 + assert set([pair["file_1"], pair["file_2"]]) == {"invoice_original.png", "invoice_recompressed.png"} + assert len(result["template_similarity_groups"]) == 1 + assert "NOT duplicate content" in result["note"] + + +def test_minor_crop_detected_as_template_similar(tmp_path, base_invoice_image): + """A slightly cropped image sharing layout has distance <= 4.""" + p1 = tmp_path / "invoice_original.png" + base_invoice_image.save(p1) + + w, h = base_invoice_image.size + crop_x = 2 + crop_y = 2 + img_cropped = base_invoice_image.crop((crop_x, crop_y, w - crop_x, h - crop_y)) + p2 = tmp_path / "invoice_cropped.png" + img_cropped.save(p2) + + result = find_template_similar_images(str(tmp_path), threshold=4) + + assert result["total_images_analyzed"] == 2 + assert result["total_template_similarity_pairs"] == 1 + assert result["template_similarity_pairs"][0]["hamming_distance"] <= 4 + + +def test_borderline_similarity_pair_logged_separately(tmp_path, base_invoice_image): + """Pairs with distance between 5 and 8 should be logged in borderline_pairs, not template_similarity_pairs.""" + p1 = tmp_path / "invoice_original.png" + base_invoice_image.save(p1) + + w, h = base_invoice_image.size + img_borderline = base_invoice_image.crop((5, 6, w - 5, h - 6)) + p2 = tmp_path / "invoice_borderline.png" + img_borderline.save(p2) + + result = find_template_similar_images(str(tmp_path), threshold=4, borderline_min=5, borderline_max=8) + + assert result["total_images_analyzed"] == 2 + assert result["total_template_similarity_pairs"] == 0 + assert result["total_borderline_pairs"] == 1 + borderline_pair = result["borderline_pairs"][0] + assert 5 <= borderline_pair["hamming_distance"] <= 8 + + +def test_different_images_not_flagged(tmp_path, base_invoice_image): + """Completely distinct visual layouts should not be flagged as template-similar or borderline.""" + p1 = tmp_path / "invoice.png" + base_invoice_image.save(p1) + + img_diff = Image.new("L", (400, 500), 255) + draw = ImageDraw.Draw(img_diff) + draw.ellipse([50, 50, 350, 450], fill=30) + p2 = tmp_path / "circle_document.png" + img_diff.save(p2) + + result = find_template_similar_images(str(tmp_path), threshold=4, borderline_min=5, borderline_max=8) + + assert result["total_images_analyzed"] == 2 + assert result["total_template_similarity_pairs"] == 0 + assert result["total_borderline_pairs"] == 0 + + +def test_target_files_filter(tmp_path, base_invoice_image): + """When target_files is specified, only the specified subset is evaluated.""" + p1 = tmp_path / "inv1.png" + p2 = tmp_path / "inv2.png" + p3 = tmp_path / "inv3.png" + + base_invoice_image.save(p1) + base_invoice_image.save(p2) + base_invoice_image.save(p3) + + result = find_template_similar_images(str(tmp_path), target_files=["inv1.png", "inv2.png"], threshold=4) + + assert result["total_images_analyzed"] == 2 + assert result["total_template_similarity_pairs"] == 1 + assert result["template_similarity_pairs"][0]["file_1"] == "inv1.png" + assert result["template_similarity_pairs"][0]["file_2"] == "inv2.png" + + +def test_invalid_folder(): + """Non-existent directory should return an error structure safely without raising exceptions.""" + result = find_template_similar_images("non_existent_folder_path") + assert "error" in result + assert result["total_images_analyzed"] == 0 diff --git a/tests/test_validators.py b/tests/test_validators.py new file mode 100644 index 0000000..f5b77b2 --- /dev/null +++ b/tests/test_validators.py @@ -0,0 +1,80 @@ +# tests/test_validators.py +import pytest +import json +from pathlib import Path +from decimal import Decimal +from app.validators import ( + ValidationStatus, + ValidationResult, + InvoiceArithmeticValidator, + classify_reconciliation +) + +def test_validator_tristate_pass(): + validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00")) + doc = { + "invoice_amount": "118.00", + "total_gst_amount": "18.00", + "round_off": "0.00", + "items": [ + {"total_price": "100.00", "Discount": "0.00"} + ] + } + res = validator.validate(doc) + assert res.status == ValidationStatus.PASS + assert res.is_valid is True + +def test_validator_tristate_fail(): + validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00")) + doc = { + "invoice_amount": "200.00", # Wrong total + "total_gst_amount": "18.00", + "round_off": "0.00", + "items": [ + {"total_price": "100.00", "Discount": "0.00"} + ] + } + res = validator.validate(doc) + assert res.status == ValidationStatus.FAIL + assert res.is_valid is False + assert res.discrepancy > Decimal("50.0") + +def test_validator_tristate_insufficient_data(): + validator = InvoiceArithmeticValidator() + # Missing items and zero total + res = validator.validate({"invoice_amount": None, "items": []}) + assert res.status == ValidationStatus.INSUFFICIENT_DATA + assert res.is_valid is False + +def test_validator_never_returns_true_on_exception(): + validator = InvoiceArithmeticValidator() + # Malformed data + res = validator.validate({"invoice_amount": "invalid_number", "items": "not_a_list"}) + assert res.status == ValidationStatus.INSUFFICIENT_DATA + assert res.is_valid is False + +def test_failing_invoices_reconciliation_diagnosis(): + # Analyze the 2 failing invoices: WMP/B/04531 and KP26264882 + validator = InvoiceArithmeticValidator(tolerance=Decimal("1.00")) + gt_dir = Path("data_private/ground_truth") + if not gt_dir.exists(): + gt_dir = Path("data/ground_truth") + + p_4531 = gt_dir / "invoice_4531_expected.json" + p_kundan = gt_dir / "kundan_expected.json" + if not p_4531.exists() or not p_kundan.exists(): + pytest.skip("Private ground truth files not present on fresh clone.") + + with open(p_4531, "r", encoding="utf-8") as f: + gt_4531 = json.load(f) + + res_4531 = validator.validate(gt_4531) + assert res_4531.status == ValidationStatus.PASS + assert res_4531.is_valid is True + + with open(p_kundan, "r", encoding="utf-8") as f: + gt_kundan = json.load(f) + + res_kundan = validator.validate(gt_kundan) + assert res_kundan.status == ValidationStatus.PASS + assert res_kundan.is_valid is True