refactor(pipeline): remove hardcodes and replace static geometry with layout anchors

This commit is contained in:
omkarande14
2026-09-28 17:13:23 +05:30
parent 6f3831ecdb
commit 3729100817
44 changed files with 9315 additions and 1 deletions
+16
View File
@@ -0,0 +1,16 @@
from app.preprocessing.image_converter import convert_file
from app.preprocessing.duplicate_detector import find_exact_duplicates
from app.preprocessing.template_similarity_detector import find_template_similar_images
from app.preprocessing.orientation_corrector import detect_and_correct_orientation
from app.preprocessing.deskew_corrector import deskew_image
from app.preprocessing.copy_selector import DualCopySelector, CopySelectionResult
__all__ = [
"convert_file",
"find_exact_duplicates",
"find_template_similar_images",
"detect_and_correct_orientation",
"deskew_image",
"DualCopySelector",
"CopySelectionResult"
]
+321
View File
@@ -0,0 +1,321 @@
# app/preprocessing/copy_selector.py
"""
Dual-Invoice Page Detector & Customer Copy Selector.
Detects whether an invoice image contains multiple side-by-side or stacked copies
on a single page (e.g. 'Customer Copy' on left, 'Office Copy' on right, or
'Original for Recipient' vs 'Duplicate for Transporter').
Calculates the spatial dividing boundary through the margin/gutter and crops
the page strictly to the primary deliverable copy (Customer Copy / Original).
"""
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
import cv2
import numpy as np
from PIL import Image
import pytesseract
@dataclass
class CopySelectionResult:
is_dual_copy: bool
selected_copy: Optional[str]
detected_labels: List[str]
split_axis: Optional[str] # 'horizontal' or 'vertical'
boundary_coord: Optional[int]
output_image_path: Path
details: Dict[str, Any]
class DualCopySelector:
"""
Detects dual-copy invoice pages and extracts only the Customer/Original copy.
"""
PRIMARY_LABELS = [
"customer copy", "original for recipient", "original copy", "original"
]
SECONDARY_LABELS = [
"office copy", "duplicate for transporter", "duplicate copy",
"triplicate for supplier", "duplicate", "transporter copy"
]
DEFAULT_TESSERACT_CMD = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
def __init__(self, tesseract_cmd: Optional[str] = None):
import os
cmd = tesseract_cmd or self.DEFAULT_TESSERACT_CMD
if cmd and os.path.exists(cmd):
pytesseract.pytesseract.tesseract_cmd = cmd
def inspect_and_select(
self,
image_path: Path,
output_dir: Optional[Path] = None,
extracted_lines: Optional[List[Dict[str, Any]]] = None
) -> CopySelectionResult:
"""
Main entrypoint:
1. Checks if dual-copy anchors exist in the header region.
2. If detected, determines horizontal or vertical split and finds the dividing gutter.
3. Crops the image to the Customer Copy and saves it.
4. If not dual copy, returns the original image path.
"""
img_path = Path(image_path)
if not img_path.exists():
raise FileNotFoundError(f"Image not found: {img_path}")
with Image.open(img_path) as pil_img:
w, h = pil_img.size
pil_img_rgb = pil_img.convert("RGB")
# Step 1: Detect copy anchor text
anchors = self._detect_anchors(img_path, (w, h), extracted_lines)
primary_anchor = anchors.get("primary")
secondary_anchor = anchors.get("secondary")
if not (primary_anchor and secondary_anchor):
return CopySelectionResult(
is_dual_copy=False,
selected_copy=None,
detected_labels=[k for k, v in anchors.items() if v],
split_axis=None,
boundary_coord=None,
output_image_path=img_path,
details={"reason": "No dual-copy anchor pair detected"}
)
# Step 2: Determine split axis (horizontal vs vertical)
p_box = primary_anchor["box"]
s_box = secondary_anchor["box"]
p_xc = (min(p[0] for p in p_box) + max(p[0] for p in p_box)) / 2.0
s_xc = (min(p[0] for p in s_box) + max(p[0] for p in s_box)) / 2.0
p_yc = (min(p[1] for p in p_box) + max(p[1] for p in p_box)) / 2.0
s_yc = (min(p[1] for p in s_box) + max(p[1] for p in s_box)) / 2.0
is_horizontal_split = abs(p_xc - s_xc) > abs(p_yc - s_yc)
out_folder = output_dir if output_dir else img_path.parent
out_folder.mkdir(parents=True, exist_ok=True)
if is_horizontal_split:
# Customer copy is typically on the left half (lower X)
split_x = self._find_vertical_gutter(pil_img_rgb, (w, h), p_xc, s_xc)
# Crop to Customer Copy (left half: 0 to split_x)
cropped = pil_img_rgb.crop((0, 0, split_x, h))
out_filename = f"{img_path.stem}_customer_copy.png"
out_path = out_folder / out_filename
cropped.save(out_path)
return CopySelectionResult(
is_dual_copy=True,
selected_copy="Customer Copy",
detected_labels=[primary_anchor["text"], secondary_anchor["text"]],
split_axis="horizontal",
boundary_coord=split_x,
output_image_path=out_path,
details={
"original_size": (w, h),
"cropped_size": cropped.size,
"split_x": split_x,
"primary_label": primary_anchor["text"],
"secondary_label": secondary_anchor["text"]
}
)
else:
# Vertical split (top vs bottom)
split_y = self._find_horizontal_gutter(pil_img_rgb, (w, h), p_yc, s_yc)
cropped = pil_img_rgb.crop((0, 0, w, split_y))
out_filename = f"{img_path.stem}_customer_copy.png"
out_path = out_folder / out_filename
cropped.save(out_path)
return CopySelectionResult(
is_dual_copy=True,
selected_copy="Customer Copy",
detected_labels=[primary_anchor["text"], secondary_anchor["text"]],
split_axis="vertical",
boundary_coord=split_y,
output_image_path=out_path,
details={
"original_size": (w, h),
"cropped_size": cropped.size,
"split_y": split_y,
"primary_label": primary_anchor["text"],
"secondary_label": secondary_anchor["text"]
}
)
def _detect_anchors(
self,
image_path: Path,
dimensions: Tuple[int, int],
extracted_lines: Optional[List[Dict[str, Any]]] = None
) -> Dict[str, Optional[Dict[str, Any]]]:
"""Detects presence and bounding boxes of primary and secondary copy labels."""
w, h = dimensions
anchors = {"primary": None, "secondary": None}
# Use existing OCR lines if provided
lines = extracted_lines
if not lines:
# Fast lightweight OCR on the top 25% header strip
with Image.open(image_path) as im:
header_strip = im.crop((0, 0, w, int(h * 0.25)))
try:
ocr_data = pytesseract.image_to_data(header_strip, output_type=pytesseract.Output.DICT)
except Exception:
return anchors
word_list = []
n_boxes = len(ocr_data["text"])
for i in range(n_boxes):
t = ocr_data["text"][i].strip()
if t:
x, y, bw, bh = (
ocr_data["left"][i],
ocr_data["top"][i],
ocr_data["width"][i],
ocr_data["height"][i]
)
word_list.append({
"text": t,
"line_id": (ocr_data["block_num"][i], ocr_data["par_num"][i], ocr_data["line_num"][i]),
"box": [[x, y], [x + bw, y], [x + bw, y + bh], [x, y + bh]]
})
lines = []
# 1. Single words
for w_item in word_list:
lines.append(w_item)
# 2. Sliding bigrams (e.g. 'Customer Copy', 'Office Copy')
for i in range(len(word_list) - 1):
w1 = word_list[i]
w2 = word_list[i + 1]
if w1["line_id"] == w2["line_id"]:
bigram_text = f"{w1['text']} {w2['text']}"
b_min_x = min(w1["box"][0][0], w2["box"][0][0])
b_min_y = min(w1["box"][0][1], w2["box"][0][1])
b_max_x = max(w1["box"][2][0], w2["box"][2][0])
b_max_y = max(w1["box"][2][1], w2["box"][2][1])
lines.append({
"text": bigram_text,
"box": [[b_min_x, b_min_y], [b_max_x, b_min_y], [b_max_x, b_max_y], [b_min_x, b_max_y]]
})
# Match labels against lines
for el in lines:
t = el["text"].strip().lower()
b = el["box"]
ymin = min(p[1] for p in b)
# Confine search to top 25% of image
if ymin > h * 0.25:
continue
if not anchors["primary"]:
for pl in self.PRIMARY_LABELS:
if pl in t:
anchors["primary"] = el
break
if not anchors["secondary"]:
for sl in self.SECONDARY_LABELS:
if sl in t:
anchors["secondary"] = el
break
return anchors
def _find_vertical_gutter(
self,
image: Image.Image,
dimensions: Tuple[int, int],
p_xc: float,
s_xc: float
) -> int:
"""Finds the optimal vertical dividing column (white gutter or border line) between copies."""
w, h = dimensions
arr = np.array(image.convert("L"))
# Search region: strictly between primary anchor and secondary anchor
left_bound = int(max(p_xc + 100, w * 0.40))
right_bound = int(min(s_xc - 100, w * 0.75))
if right_bound <= left_bound:
return int(w / 2.0)
# Profile: column average brightness across Y in the middle 70% of the page
sub = arr[int(h * 0.15):int(h * 0.85), left_bound:right_bound]
col_means = sub.mean(axis=0)
# Find continuous white run (intensity > 245)
is_white = col_means > 245
max_run = 0
best_start = 0
cur_run = 0
cur_start = 0
for i, val in enumerate(is_white):
if val:
if cur_run == 0:
cur_start = i
cur_run += 1
if cur_run > max_run:
max_run = cur_run
best_start = cur_start
else:
cur_run = 0
if max_run >= 10:
# Centered in the white gutter
return left_bound + best_start + (max_run // 2)
# Fallback: find darkest column (vertical divider line) or midpoint
darkest_idx = int(np.argmin(col_means))
return left_bound + darkest_idx
def _find_horizontal_gutter(
self,
image: Image.Image,
dimensions: Tuple[int, int],
p_yc: float,
s_yc: float
) -> int:
"""Finds the optimal horizontal dividing row for vertically stacked copies."""
w, h = dimensions
arr = np.array(image.convert("L"))
top_bound = int(max(p_yc + 50, h * 0.35))
bot_bound = int(min(s_yc - 50, h * 0.65))
if bot_bound <= top_bound:
return int(h / 2.0)
sub = arr[top_bound:bot_bound, int(w * 0.10):int(w * 0.90)]
row_means = sub.mean(axis=1)
is_white = row_means > 245
max_run = 0
best_start = 0
cur_run = 0
cur_start = 0
for i, val in enumerate(is_white):
if val:
if cur_run == 0:
cur_start = i
cur_run += 1
if cur_run > max_run:
max_run = cur_run
best_start = cur_start
else:
cur_run = 0
if max_run >= 10:
return top_bound + best_start + (max_run // 2)
return (top_bound + bot_bound) // 2
+239
View File
@@ -0,0 +1,239 @@
# app/preprocessing/deskew_corrector.py
from pathlib import Path
import cv2
import numpy as np
from PIL import Image
def detect_skew_angle(image: Image.Image) -> tuple[float, int]:
"""
Detects the tilt/skew angle (in degrees) of an image using the Hough Line Transform.
Finds prominent straight horizontal lines (table borders, invoice dividers, text baselines)
and computes their median angle relative to the horizontal axis.
Returns:
(skew_angle, line_count):
skew_angle: Detected angle in degrees.
In image coordinate space, rotating a Pillow image by
skew_angle (counter-clockwise) levels the line to horizontal (0°).
line_count: Number of horizontal lines found and used for the median angle.
"""
np_img = np.array(image)
if len(np_img.shape) == 3:
np_img = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY)
# Mild Gaussian blur to smooth pixel staircases from slight rotations
blurred = cv2.GaussianBlur(np_img, (5, 5), 0)
# Edge detection using Canny
edges = cv2.Canny(blurred, 30, 100, apertureSize=3)
# Lines should have meaningful length (at least 80px or 8% of width)
min_line_len = max(80, int(np_img.shape[1] * 0.08))
lines = cv2.HoughLinesP(
edges,
rho=1,
theta=np.pi / 180,
threshold=50,
minLineLength=min_line_len,
maxLineGap=20,
)
if lines is None or len(lines) == 0:
return 0.0, 0
angles = []
for line in lines:
x1, y1, x2, y2 = line.flatten()
# In image coordinates, y increases downward.
angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
# Normalize angles to [-45, 45] range relative to horizontal
if angle < -45:
angle += 90
elif angle > 45:
angle -= 90
# Keep lines within +/- 15 degrees of horizontal (ignore vertical table dividers)
if abs(angle) <= 15.0:
angles.append(angle)
if not angles:
return 0.0, 0
median_angle = float(np.median(angles))
return round(median_angle, 2), len(angles)
def deskew_image(
image_path: str,
output_folder: str,
min_skew: float = 0.5,
max_skew: float = 15.0,
) -> dict:
"""
Detects skew on a single image and applies fine-angle rotation if skew exceeds min_skew.
Traceability:
The source image is NEVER modified or overwritten.
Corrected output is saved to: <output_folder>/<stem>_deskewed.png
Parameters:
image_path: Path to the input image (typically in data/oriented/).
output_folder: Destination folder (typically data/deskewed/).
min_skew: Minimum skew in degrees below which no rotation is performed (avoids interpolation blur).
max_skew: Maximum plausible skew angle (larger angles are flagged as anomalies).
Returns:
A dictionary detailing the operation:
- filename: original file name
- output_path: path to saved deskewed image
- detected_skew_angle: detected angle in degrees
- correction_applied_deg: degrees of rotation applied (0.0 if not rotated)
- line_count: number of horizontal lines detected
- rotated: boolean indicating if rotation occurred
- status: 'straight', 'deskewed', 'outlier_skew', or 'failed'
- message: human-readable explanation
"""
path = Path(image_path)
out_dir = Path(output_folder)
out_dir.mkdir(parents=True, exist_ok=True)
output_filename = f"{path.stem}_deskewed.png"
output_path = out_dir / output_filename
result = {
"filename": path.name,
"output_path": str(output_path),
"detected_skew_angle": 0.0,
"correction_applied_deg": 0.0,
"line_count": 0,
"rotated": False,
"status": "unknown",
"message": "",
}
try:
with Image.open(path) as img:
skew_angle, line_count = detect_skew_angle(img)
result["detected_skew_angle"] = skew_angle
result["line_count"] = line_count
abs_skew = abs(skew_angle)
if abs_skew < min_skew:
# Sub-threshold tilt: image is straight enough. Preserve pristine sharpness.
img.save(output_path, format="PNG")
result["status"] = "straight"
result["rotated"] = False
result["message"] = (
f"Skew {skew_angle:+.2f}° is below threshold ({min_skew}°); saved unrotated to preserve sharpness"
)
elif abs_skew > max_skew:
# Outlier: unusually large tilt beyond normal scanner skew. Flag for review.
img.save(output_path, format="PNG")
result["status"] = "outlier_skew"
result["rotated"] = False
result["message"] = (
f"Skew {skew_angle:+.2f}° exceeds max threshold ({max_skew}°); saved unrotated for review"
)
else:
# Meaningful skew detected: rotate to level horizontal lines.
# In Pillow, rotate(angle) is counter-clockwise.
# rotating by skew_angle levels the detected tilt.
deskewed_img = img.rotate(
skew_angle,
expand=True,
resample=Image.Resampling.BICUBIC,
fillcolor=255, # Fill newly exposed corner margins with white
)
deskewed_img.save(output_path, format="PNG")
result["correction_applied_deg"] = skew_angle
result["status"] = "deskewed"
result["rotated"] = True
result["message"] = (
f"Rotated {skew_angle:+.2f}° to level horizontal baselines (from {line_count} lines)"
)
except Exception as e:
result["status"] = "failed"
result["message"] = f"Deskew processing error: {e}"
# Fallback copy to ensure pipeline continuity
try:
with Image.open(path) as img:
img.save(output_path, format="PNG")
except Exception:
pass
return result
def process_folder_deskew(
input_folder: str,
output_folder: str,
target_files: list = None,
min_skew: float = 0.5,
max_skew: float = 15.0,
) -> dict:
"""
Processes all PNG images in input_folder (or subset in target_files),
correcting small tilt angles and saving outputs into output_folder.
Returns:
{
"total_images_processed": int,
"straight_count": int,
"deskewed_count": int,
"outlier_count": int,
"failed_count": int,
"threshold_deg": float,
"corrections": [...],
"all_results": [...]
}
"""
in_dir = Path(input_folder)
out_dir = Path(output_folder)
out_dir.mkdir(parents=True, exist_ok=True)
if target_files is not None:
target_set = set(target_files)
image_files = sorted(
[p for p in in_dir.iterdir() if p.is_file() and p.name in target_set]
)
else:
image_files = sorted(
[p for p in in_dir.iterdir() if p.is_file() and p.suffix.lower() == ".png"]
)
summary = {
"total_images_processed": len(image_files),
"straight_count": 0,
"deskewed_count": 0,
"outlier_count": 0,
"failed_count": 0,
"threshold_deg": min_skew,
"corrections": [],
"all_results": [],
}
for img_path in image_files:
res = deskew_image(
str(img_path),
str(out_dir),
min_skew=min_skew,
max_skew=max_skew,
)
summary["all_results"].append(res)
if res["status"] == "straight":
summary["straight_count"] += 1
elif res["status"] == "deskewed":
summary["deskewed_count"] += 1
summary["corrections"].append(res)
elif res["status"] == "outlier_skew":
summary["outlier_count"] += 1
elif res["status"] == "failed":
summary["failed_count"] += 1
return summary
+52
View File
@@ -0,0 +1,52 @@
# app/preprocessing/duplicate_detector.py
from pathlib import Path
import hashlib
from PIL import Image
def compute_image_hash(image_path: str) -> str:
"""
Returns a SHA-256 hash of the image's actual decoded pixel data.
Two images with identical visual content produce the same hash,
even if their PNG file bytes differ slightly (e.g. compression settings).
"""
with Image.open(image_path) as img:
pixel_data = img.tobytes()
return hashlib.sha256(pixel_data).hexdigest()
def find_exact_duplicates(folder_path: str) -> dict:
"""
Scans all PNG images in folder_path and groups exact visual duplicates.
Returns:
{
"total_images": 79,
"unique_images": 68,
"total_duplicate_groups": 5,
"redundant_copies": 11,
"duplicate_groups": [
["fileA_page_1.png", "fileB_page_1.png"],
...
]
}
"""
folder = Path(folder_path)
hash_to_files = {}
for item in sorted(folder.iterdir()):
if item.is_file() and item.suffix.lower() == ".png":
image_hash = compute_image_hash(str(item))
hash_to_files.setdefault(image_hash, []).append(item.name)
duplicate_groups = [files for files in hash_to_files.values() if len(files) > 1]
redundant_copies = sum(len(group) - 1 for group in duplicate_groups)
return {
"total_images": sum(len(v) for v in hash_to_files.values()),
"unique_images": len(hash_to_files),
"total_duplicate_groups": len(duplicate_groups),
"redundant_copies": redundant_copies,
"duplicate_groups": duplicate_groups,
}
+61
View File
@@ -0,0 +1,61 @@
# app/preprocessing/image_converter.py
from pathlib import Path
import pymupdf as fitz
from PIL import Image
DPI = 200
def convert_file(file_path: str, output_folder: str) -> list:
"""
Converts a single file (PDF or image) into one or more normalized
grayscale PNG images saved into output_folder.
Returns a list of saved image paths (as strings).
"""
path = Path(file_path)
extension = path.suffix.lower()
output_dir = Path(output_folder)
output_dir.mkdir(parents=True, exist_ok=True)
if extension == ".pdf":
return _convert_pdf(path, output_dir)
elif extension in {".jpg", ".jpeg", ".png"}:
return [_convert_image(path, output_dir)]
else:
raise ValueError(f"Unsupported file type: {extension}")
def _convert_pdf(path: Path, output_dir: Path) -> list:
saved_paths = []
doc = fitz.open(path)
# Matrix scales the render resolution. 72 is PDF's default DPI,
# so (DPI / 72) gives us the zoom factor needed to reach our target DPI.
zoom = DPI / 72
matrix = fitz.Matrix(zoom, zoom)
for page_number in range(len(doc)):
page = doc[page_number]
# csGRAY renders directly in grayscale - no separate conversion step needed
pixmap = page.get_pixmap(matrix=matrix, colorspace=fitz.csGRAY)
output_name = f"{path.stem}_page_{page_number + 1}.png"
output_path = output_dir / output_name
pixmap.save(str(output_path))
saved_paths.append(str(output_path))
doc.close()
return saved_paths
def _convert_image(path: Path, output_dir: Path) -> str:
with Image.open(path) as img:
grayscale_img = img.convert("L") # "L" = 8-bit grayscale in Pillow
output_name = f"{path.stem}_page_1.png"
output_path = output_dir / output_name
grayscale_img.save(output_path, format="PNG")
return str(output_path)
@@ -0,0 +1,26 @@
# app/preprocessing/near_duplicate_detector.py
"""
CRITICAL ARCHITECTURAL PRINCIPLE:
---------------------------------
This module detects shared visual template/layout, NOT duplicate content,
and results must never be used to skip, merge, or exclude files from downstream processing.
Real-world verification on this dataset confirmed that different invoices
from the same vendor share identical or near-identical layouts (pHash distance 0-4)
while having completely different invoice numbers, line items, and GST amounts.
This module is maintained as an alias to `template_similarity_detector.py`.
"""
from app.preprocessing.template_similarity_detector import (
compute_perceptual_hash,
find_template_similar_images as find_near_duplicates,
find_template_similar_images,
)
__all__ = [
"compute_perceptual_hash",
"find_near_duplicates",
"find_template_similar_images",
]
+254
View File
@@ -0,0 +1,254 @@
# app/preprocessing/orientation_corrector.py
import os
import shutil
from pathlib import Path
from PIL import Image
import pytesseract
# Default standard Tesseract installation location on Windows
DEFAULT_TESSERACT_WINDOWS_PATH = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
def configure_tesseract_path() -> str:
"""
Ensures pytesseract knows where the Tesseract binary is located.
Checks system PATH first; if not found, checks standard Windows install paths.
"""
cmd = shutil.which("tesseract")
if cmd:
pytesseract.pytesseract.tesseract_cmd = cmd
return cmd
if os.path.exists(DEFAULT_TESSERACT_WINDOWS_PATH):
pytesseract.pytesseract.tesseract_cmd = DEFAULT_TESSERACT_WINDOWS_PATH
return DEFAULT_TESSERACT_WINDOWS_PATH
# If neither is found, pytesseract will attempt default command name ('tesseract')
return "tesseract"
# Initialize tesseract path on module load
configure_tesseract_path()
def score_orientation_keywords(img: Image.Image) -> int:
"""
Counts matches of standard invoice domain keywords to verify upright readability.
"""
try:
txt = pytesseract.image_to_string(img).lower()
keywords = {
"invoice", "tax", "gst", "total", "date", "bill", "amount",
"rate", "qty", "hsn", "mrp", "phone", "pack", "batch",
"medico", "stores", "hospital", "buyer", "customer", "seller"
}
return sum(1 for kw in keywords if kw in txt)
except Exception:
return 0
def detect_and_correct_orientation(
image_path: str,
output_folder: str,
min_confidence: float = 0.5,
) -> dict:
"""
Detects the orientation of an image using Tesseract OSD (Orientation and Script Detection)
and content keyword verification, rotates it to upright (0 degrees) if needed,
and saves the result to output_folder.
Traceability:
The original image in image_path is NEVER modified or overwritten.
The output is saved as: <output_folder>/<image_name_stem>_oriented.png
Parameters:
image_path: Path to the source image.
output_folder: Directory to save the corrected image.
min_confidence: Minimum OSD confidence required to apply rotation (default 0.5).
If confidence is below this threshold, the image is saved without rotation
and flagged as low-confidence.
Returns:
A dictionary detailing:
- filename: name of the source image
- output_path: path to the saved oriented image
- detected_angle: orientation detected by OSD (0, 90, 180, 270)
- rotate_angle: clockwise degrees needed to make upright (0, 90, 180, 270)
- confidence: confidence score reported by Tesseract
- rotated: boolean indicating if a rotation was performed
- status: 'upright', 'corrected', 'low_confidence', or 'failed'
- message: human-readable explanation
"""
path = Path(image_path)
out_dir = Path(output_folder)
out_dir.mkdir(parents=True, exist_ok=True)
output_filename = f"{path.stem}_oriented.png"
output_path = out_dir / output_filename
result = {
"filename": path.name,
"output_path": str(output_path),
"detected_angle": 0,
"rotate_angle": 0,
"confidence": 0.0,
"rotated": False,
"status": "unknown",
"message": "",
}
try:
with Image.open(path) as img:
# Run Tesseract Orientation and Script Detection
osd = pytesseract.image_to_osd(img, output_type=pytesseract.Output.DICT)
detected_angle = int(osd.get("orientation", 0))
rotate_angle = int(osd.get("rotate", 0))
confidence = float(osd.get("orientation_conf", 0.0))
result["detected_angle"] = detected_angle
result["rotate_angle"] = rotate_angle
result["confidence"] = confidence
# Check if rotation is needed
if rotate_angle == 0:
# Already upright according to OSD
img.save(output_path, format="PNG")
result["status"] = "upright"
result["rotated"] = False
result["message"] = f"Image is already upright (confidence: {confidence:.2f})"
elif confidence < min_confidence:
# Rotation suggested but confidence is too low to trust blindly
img.save(output_path, format="PNG")
result["status"] = "low_confidence"
result["rotated"] = False
result["message"] = (
f"Suggested rotate {rotate_angle}° but confidence {confidence:.2f} "
f"is below threshold {min_confidence:.2f}; saved unrotated for review"
)
else:
# Confident non-upright image: rotate to upright
# In Pillow, rotate(angle) is counter-clockwise.
# rotate(-rotate_angle) rotates clockwise by rotate_angle.
corrected_img = img.rotate(-rotate_angle, expand=True)
corrected_img.save(output_path, format="PNG")
result["status"] = "corrected"
result["rotated"] = True
result["message"] = (
f"Rotated {rotate_angle}° clockwise to upright (confidence: {confidence:.2f})"
)
except pytesseract.TesseractError as e:
# Handles images with too few characters, unusual resolution, or blank pages
# Attempt fallback keyword scoring across cardinal angles (0, 90, 180, 270)
try:
with Image.open(path) as img:
best_angle = 0
best_score = score_orientation_keywords(img)
for ang in [90, 180, 270]:
cand_img = img.rotate(-ang, expand=True)
score = score_orientation_keywords(cand_img)
if score > best_score and score >= 3:
best_score = score
best_angle = ang
if best_angle != 0:
corrected_img = img.rotate(-best_angle, expand=True)
corrected_img.save(output_path, format="PNG")
result["status"] = "corrected"
result["rotated"] = True
result["rotate_angle"] = best_angle
result["confidence"] = 3.0
result["message"] = f"Rotated {best_angle}° clockwise using keyword fallback (score: {best_score})"
return result
else:
img.save(output_path, format="PNG")
result["status"] = "failed"
result["message"] = f"Tesseract OSD could not determine orientation: {e}"
except Exception:
shutil.copyfile(str(path), str(output_path))
result["status"] = "failed"
result["message"] = f"Tesseract OSD could not determine orientation: {e}"
except Exception as e:
result["status"] = "failed"
result["message"] = f"Unexpected error during orientation correction: {e}"
try:
shutil.copyfile(str(path), str(output_path))
except Exception:
pass
return result
def process_folder_orientation(
input_folder: str,
output_folder: str,
target_files: list = None,
min_confidence: float = 2.0,
) -> dict:
"""
Processes all PNG images in input_folder (or subset in target_files), corrects
their orientation, and saves them into output_folder.
Returns:
{
"total_images_processed": int,
"upright_count": int,
"corrected_count": int,
"low_confidence_count": int,
"failed_count": int,
"corrections": [...],
"low_confidence_detections": [...],
"failed_detections": [...],
"all_results": [...]
}
"""
in_dir = Path(input_folder)
out_dir = Path(output_folder)
out_dir.mkdir(parents=True, exist_ok=True)
if target_files is not None:
target_set = set(target_files)
image_files = sorted(
[p for p in in_dir.iterdir() if p.is_file() and p.name in target_set]
)
else:
image_files = sorted(
[p for p in in_dir.iterdir() if p.is_file() and p.suffix.lower() == ".png"]
)
summary = {
"total_images_processed": len(image_files),
"upright_count": 0,
"corrected_count": 0,
"low_confidence_count": 0,
"failed_count": 0,
"corrections": [],
"low_confidence_detections": [],
"failed_detections": [],
"all_results": [],
}
for img_path in image_files:
res = detect_and_correct_orientation(
str(img_path),
str(out_dir),
min_confidence=min_confidence,
)
summary["all_results"].append(res)
if res["status"] == "upright":
summary["upright_count"] += 1
elif res["status"] == "corrected":
summary["corrected_count"] += 1
summary["corrections"].append(res)
elif res["status"] == "low_confidence":
summary["low_confidence_count"] += 1
summary["low_confidence_detections"].append(res)
elif res["status"] == "failed":
summary["failed_count"] += 1
summary["failed_detections"].append(res)
return summary
@@ -0,0 +1,174 @@
# app/preprocessing/template_similarity_detector.py
"""
Template Similarity Detector (Milestone 3b)
CRITICAL ARCHITECTURAL PRINCIPLE:
---------------------------------
This module detects shared visual template/layout structures using perceptual
hashing (pHash), NOT document or content duplication.
Real-world evaluation on this dataset confirmed that different invoices issued
by the same vendor (e.g. INVOICE NO 556 vs Invoice no. 591, or DMH INV NO-4663
vs DMH INV NO-4938) share identical or near-identical visual layouts (Hamming
distance 0-4) while containing completely different line items, quantities,
and GST amounts.
Therefore:
1. Perceptual hashing is NOT a reliable duplicate-detection signal for this dataset.
2. These results must NEVER be used to skip, merge, or exclude files from downstream
processing or OCR.
3. True "same invoice, different scan" deduplication must wait until post-OCR content
extraction (comparing invoice numbers, dates, vendor GSTIN, and line items).
4. The layout groupings captured here remain valuable for downstream template-aware
OCR and field extraction (Milestones 4-6).
"""
from pathlib import Path
from typing import List, Optional, Dict, Any
from PIL import Image
import imagehash
def compute_perceptual_hash(image_path: str, hash_size: int = 8) -> imagehash.ImageHash:
"""
Computes a 64-bit perceptual hash (pHash) for an image using
Discrete Cosine Transform (DCT).
"""
with Image.open(image_path) as img:
return imagehash.phash(img, hash_size=hash_size)
def find_template_similar_images(
folder_path: str,
target_files: Optional[List[str]] = None,
threshold: int = 4,
borderline_min: int = 5,
borderline_max: int = 8,
) -> Dict[str, Any]:
"""
Identifies images with shared visual layouts/templates among target files
in folder_path using perceptual hashing (pHash) and Hamming distance.
Args:
folder_path: Directory containing the images.
target_files: Optional explicit list of filenames to analyze.
If None, all PNG files in folder_path are scanned.
Typically, this should be the canonical unique images
identified from exact duplicate detection (Milestone 3a).
threshold: Maximum Hamming distance to classify two images as
sharing a template layout (default: 4).
borderline_min: Lower bound Hamming distance for borderline watchlist.
borderline_max: Upper bound Hamming distance for borderline watchlist.
Returns:
A structured dictionary containing:
- "threshold": Layout similarity cutoff (distance <= threshold)
- "borderline_range": [min, max] for borderline layout watchlist
- "total_images_analyzed": Number of images evaluated
- "total_template_similarity_pairs": Count of pairs with distance <= threshold
- "template_similarity_pairs": Detailed list of template-sharing pairs
- "total_template_similarity_groups": Count of connected layout clusters
- "template_similarity_groups": Clustered groups of images sharing templates
- "total_borderline_pairs": Count of borderline layout pairs
- "borderline_pairs": List of pairs with distance in [borderline_min, borderline_max]
- "note": Warning that these indicate template similarity, not duplicate invoices.
"""
folder = Path(folder_path)
if not folder.exists() or not folder.is_dir():
return {
"error": f"Folder not found: {folder_path}",
"threshold": threshold,
"borderline_range": [borderline_min, borderline_max],
"total_images_analyzed": 0,
"total_template_similarity_pairs": 0,
"template_similarity_pairs": [],
"total_template_similarity_groups": 0,
"template_similarity_groups": [],
"total_borderline_pairs": 0,
"borderline_pairs": [],
"note": "Detects shared visual template/layout, NOT duplicate content.",
}
# Determine files to process
if target_files is not None:
files_to_process = [f for f in sorted(target_files) if (folder / f).is_file()]
else:
files_to_process = sorted([item.name for item in folder.iterdir() if item.is_file() and item.suffix.lower() == ".png"])
# Compute perceptual hash for each image
file_hashes: Dict[str, imagehash.ImageHash] = {}
for filename in files_to_process:
filepath = folder / filename
try:
file_hashes[filename] = compute_perceptual_hash(str(filepath))
except Exception:
continue
analyzed_filenames = list(file_hashes.keys())
template_similarity_pairs = []
borderline_pairs = []
# Pairwise comparison
total_files = len(analyzed_filenames)
for i in range(total_files):
for j in range(i + 1, total_files):
file_1 = analyzed_filenames[i]
file_2 = analyzed_filenames[j]
h1 = file_hashes[file_1]
h2 = file_hashes[file_2]
dist = int(h1 - h2)
similarity = round((1.0 - (dist / 64.0)) * 100, 2)
pair_info = {
"file_1": file_1,
"file_2": file_2,
"hamming_distance": dist,
"similarity_percentage": similarity,
}
if dist <= threshold:
template_similarity_pairs.append(pair_info)
elif borderline_min <= dist <= borderline_max:
borderline_pairs.append(pair_info)
# Build connected clusters for template similarity groups
adjacency: Dict[str, set] = {f: set() for f in analyzed_filenames}
for pair in template_similarity_pairs:
adjacency[pair["file_1"]].add(pair["file_2"])
adjacency[pair["file_2"]].add(pair["file_1"])
visited = set()
template_similarity_groups = []
for f in analyzed_filenames:
if f not in visited and len(adjacency[f]) > 0:
component = []
queue = [f]
visited.add(f)
while queue:
curr = queue.pop(0)
component.append(curr)
for neighbor in sorted(adjacency[curr]):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
component.sort()
template_similarity_groups.append(component)
return {
"threshold": threshold,
"borderline_range": [borderline_min, borderline_max],
"total_images_analyzed": len(analyzed_filenames),
"total_template_similarity_pairs": len(template_similarity_pairs),
"template_similarity_pairs": template_similarity_pairs,
"total_template_similarity_groups": len(template_similarity_groups),
"template_similarity_groups": template_similarity_groups,
"total_borderline_pairs": len(borderline_pairs),
"borderline_pairs": borderline_pairs,
"note": (
"Detects shared visual template/layout, NOT duplicate content. "
"Results must never be used to skip, merge, or exclude files from downstream processing."
),
}