"""Before/after degradation comparison -- ported from projectA's ``metrics_overlay.py::build_before_after_preview()``/``render_metrics_overlay()``. Side by side: the clean render (signature placed and blended, before any document-level augmentation -- stains/tilt/blur/noise/etc.), annotated with the same "what was actually measured" overlay projectA drew (target box, actual signature bbox, ink polygon, cosmetic field boxes on the image; their color legend, exact numbers, a difficulty-score breakdown, and a list of which augmentation effects actually fired in an info panel below -- see ``_render_info_panel``'s docstring for why numbers/legend live there and not as text floating on the image itself) -- next to the final look (after whatever augmentation actually fired for this sample). Answers both "was this measured correctly" and "what did degradation actually do to this document" at a glance -- distinct from :func:`~src.visualization.visualizer.save_visualization`'s single-image, matplotlib-based multi-panel figure (crop + mask + bar chart), which is heavier and only shows the final image, not a before/after. """ from __future__ import annotations from pathlib import Path from typing import Any import numpy as np from PIL import Image, ImageDraw, ImageFont from src.utils.logging_utils import get_logger logger = get_logger(__name__) _OVERLAY_COLORS = { "target_box": (220, 40, 40), "signature_bbox": (230, 200, 30), "polygon": (60, 220, 90), "field_box": (40, 170, 230), "field_target_box": (240, 140, 20), } # A second, visually distinct palette for OTHER signed boxes on a # multi-box template (companion / additional_signatures) -- these are # genuinely rendered with a real signature but aren't this sample's SCORED # target (geometry/difficulty stay keyed to the one target box), so # without some overlay a reviewer sees one scored signature and one # unexplained, unlabeled scribble elsewhere on the page. _EXTRA_OVERLAY_COLORS = { "target_box": (150, 60, 200), "signature_bbox": (200, 150, 255), "polygon": (255, 120, 220), } # (label, weight_attr, component_key) -- display order matches # projectA's DIFFICULTY BREAKDOWN panel and configs/default.yaml's # difficulty: section. _DIFFICULTY_COMPONENTS = [ ("misplacement", "misplacement"), ("whitespace", "whitespace"), ("faintness", "faintness"), ("smallness", "smallness"), ("low_texture", "low_texture"), ] def _get_font(size: int = 14, bold: bool = False) -> "ImageFont.FreeTypeFont": candidates = [ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/Library/Fonts/Arial Bold.ttf" if bold else "/Library/Fonts/Arial.ttf", "C:\\Windows\\Fonts\\arialbd.ttf" if bold else "C:\\Windows\\Fonts\\arial.ttf", "arialbd.ttf" if bold else "arial.ttf", "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf", ] for path in candidates: try: return ImageFont.truetype(path, size) except Exception: continue try: return ImageFont.load_default(size=size) except TypeError: return ImageFont.load_default() def _label_banner(image: "np.ndarray | Image.Image", text: str, bg_color=(30, 41, 59), text_color=(255, 255, 255)) -> Image.Image: """A small labeled title bar across the top of a copy of ``image``.""" labeled = (image if isinstance(image, Image.Image) else Image.fromarray(image.astype(np.uint8))).convert("RGB") draw = ImageDraw.Draw(labeled) font = _get_font(20, bold=True) draw.rectangle([0, 0, labeled.width, 34], fill=bg_color) draw.text((10, 6), text, fill=text_color, font=font) return labeled def _applied_effects_summary(metadata: "dict[str, Any]") -> str: effects = (metadata.get("augmentation") or {}).get("effects") or {} applied = sorted(name for name, rec in effects.items() if rec.get("applied")) if not applied: return "no augmentation effects applied" return f"{len(applied)} effect(s): " + ", ".join(applied) def _fill_polygon(fill_draw: "ImageDraw.ImageDraw", geometry: "dict[str, Any]", colors: "dict[str, tuple]") -> None: """Tints the actual ink -- and only the actual ink -- with a translucent fill. `signature_polygon_px` (the convex hull, used for scoring, matches projectA's own computation including its approxPolyDP simplification) "bridges" gaps between separate ink blobs (e.g. between letters, or a flourish far from the main strokes) with straight lines -- correct for coverage/IoU math, but on direct user feedback, confirmed to still visibly fail to "hug" a signature with a real gap even when rendered exactly the way projectA renders it (an outline, no fill) -- that's projectA's own known tradeoff, just not visible on a compact signature with no internal gap. `display_contours` (real per-ink-blob boundaries -- see the field's docstring on GeometryResult) fixes this: each disjoint blob gets its own fill, so the tint only ever lands on actual ink. An *outline* of these same per-blob contours was tried once and rejected -- for a multi-letter cursive/Devanagari signature, the dense scribbly outline itself visually resembled a second overlaid signature. A translucent *fill* has no separate line art to be confused with handwriting, just a soft wash exactly where the ink already is. Falls back to filling the hull for any geometry dict that predates this field. """ contours = geometry.get("display_contours") if contours: for contour in contours: if len(contour) >= 3: fill_draw.polygon([tuple(p) for p in contour], fill=(*colors["polygon"], 90)) return polygon = geometry.get("signature_polygon_px") or [] if len(polygon) >= 3: fill_draw.polygon([tuple(p) for p in polygon], fill=(*colors["polygon"], 70), outline=(*colors["polygon"], 200)) def _draw_box_outlines(draw: "ImageDraw.ImageDraw", geometry: "dict[str, Any]", colors: "dict[str, tuple]") -> None: """Draws one box's target rectangle and detected signature bbox -- shared by the primary (scored) box and any extra (companion/additional, not scored) boxes, just with different colors. No floating text on the image itself (see ``_render_info_panel``'s SIGNATURE BOXES section for the numbers): two boxes close together (e.g. side-by-side Borrower/Lender lines) used to get their metric-text labels drawn right on top of each other, and a legend pinned to a fixed corner collided with real document text on wide multi-page-spread scans. Both were real bugs, not intentional -- text in a dedicated panel can't collide with the document OR with another box's numbers, regardless of page layout.""" tb = geometry.get("target_box") ab = geometry.get("actual_box") if tb: draw.rectangle(list(tb), outline=colors["target_box"], width=3) if ab: draw.rectangle(list(ab), outline=colors["signature_bbox"], width=2) def _draw_metric_overlays( clean_image: "np.ndarray", metadata: "dict[str, Any]", extra_boxes: "list[dict] | None" = None, ) -> Image.Image: """Draws the target box, the actual placed signature bbox, its detected ink polygon (as a translucent fill of the real ink blob(s) -- see ``_fill_polygon``'s docstring), and any cosmetic field boxes onto a copy of ``clean_image`` -- the same "what was actually measured" overlay as projectA's ``render_metrics_overlay()``. This pipeline scores exactly one target box per sample (unlike projectA's per-box list), but a multi-box template can have OTHER boxes genuinely signed too (companion / additional_signatures) -- ``extra_boxes`` (see :func:`src.generator.compute_extra_signature_overlays`) draws those too, in a visually distinct color. The actual numbers/legend live in the info panel below, not as text overlaid on the image -- see ``_draw_box_outlines``'s docstring for why.""" overlay = Image.fromarray(clean_image.astype(np.uint8)).convert("RGB") # Fills drawn on a separate transparent layer, then alpha-composited # onto the image once -- PIL's ImageDraw has no direct way to paint a # translucent shape onto an opaque RGB image. fill_layer = Image.new("RGBA", overlay.size, (0, 0, 0, 0)) fill_draw = ImageDraw.Draw(fill_layer) geometry = metadata.get("geometry") or {} _fill_polygon(fill_draw, geometry, _OVERLAY_COLORS) for extra in extra_boxes or []: _fill_polygon(fill_draw, extra.get("geometry") or {}, _EXTRA_OVERLAY_COLORS) overlay = Image.alpha_composite(overlay.convert("RGBA"), fill_layer).convert("RGB") draw = ImageDraw.Draw(overlay) _draw_box_outlines(draw, geometry, _OVERLAY_COLORS) for extra in extra_boxes or []: _draw_box_outlines(draw, extra.get("geometry") or {}, _EXTRA_OVERLAY_COLORS) for field_name, boxes in ((metadata.get("cosmetics") or {}).get("field_boxes") or {}).items(): target_box = boxes.get("target_box") if isinstance(boxes, dict) else None actual_box = boxes.get("actual_box") if isinstance(boxes, dict) else boxes if target_box: x1, y1, x2, y2 = target_box draw.rectangle([x1 + 2, y1 + 2, x2 - 2, y2 - 2], outline=_OVERLAY_COLORS["field_target_box"], width=1) if actual_box: draw.rectangle(list(actual_box), outline=_OVERLAY_COLORS["field_box"], width=1) return overlay def _metrics_line(metrics: "dict[str, Any]") -> str: return ( f"cov {metrics.get('box_coverage_pct', 0):.1f}% | contain {metrics.get('containment_pct', 0):.1f}% | " f"IoU {metrics.get('polygon_overlap_proxy', 0):.3f} | ink_fill {metrics.get('ink_fill_ratio', 0):.3f} | " f"dark {metrics.get('mean_dark_intensity', 0):.1f} | margin {metrics.get('margin_utilization', 0):.3f}" ) def _render_info_panel( width: int, metadata: "dict[str, Any]", difficulty_weights: "Any | None", extra_boxes: "list[dict] | None" = None, ) -> Image.Image: """Bottom info panel, appended below the overlaid clean image: a SIGNATURE BOXES section (color legend + exact numbers for the target box and any extra signed boxes -- see below for why these live here and not as floating text on the image), a DIFFICULTY BREAKDOWN section (what built the score -- each weighted component), and an AUGMENTATION APPLIED section (every effect this sample rolled, on/off and at what strength) -- the same two latter sections as projectA's ``_render_breakdown_and_degradation_panel()``. Numbers and the color legend live here, in a plain vertically-stacked list, rather than as text floating above each box on the document image itself (the original design, ported from projectA) -- two boxes close together (e.g. side-by-side Borrower/Lender signature lines, or a signature box near its own cosmetic "Print Name:" field) drew their text right on top of each other, and a legend pinned to a fixed image corner collided with real document text on wide multi-page-spread scans. A dedicated panel can't collide with either, regardless of the document's own layout. """ line_h = 17 pad = 10 swatch = 12 header_font = _get_font(14, bold=True) body_font = _get_font(12) difficulty = metadata.get("difficulty") or {} effects = (metadata.get("augmentation") or {}).get("effects") or {} extra_boxes = extra_boxes or [] # (color_or_None, text, text_color) -- color_or_None draws a small # swatch to the left of the line; None means no swatch (plain text). lines: "list[tuple[tuple | None, str, tuple]]" = [] lines.append((None, "SIGNATURE BOXES -- what was measured", (20, 20, 20))) lines.append((_OVERLAY_COLORS["target_box"], "target (scored)", (20, 20, 20))) lines.append((None, " " + _metrics_line(metadata.get("metrics") or {}), (20, 20, 20))) for extra in extra_boxes: lines.append((_EXTRA_OVERLAY_COLORS["target_box"], f"{extra.get('label') or 'other signed box'} (not scored)", (20, 20, 20))) metrics = extra.get("metrics") lines.append((None, " " + (_metrics_line(metrics) if metrics else "no ink detected"), (20, 20, 20))) if (metadata.get("cosmetics") or {}).get("field_boxes"): lines.append((_OVERLAY_COLORS["field_box"], "cosmetic field box (actual)", (20, 20, 20))) lines.append((_OVERLAY_COLORS["field_target_box"], "cosmetic field box (target cell)", (20, 20, 20))) lines.append((None, "", (0, 0, 0))) # spacer lines.append((None, "DIFFICULTY BREAKDOWN -- what built the score", (20, 20, 20))) for label, key in _DIFFICULTY_COMPONENTS: value = difficulty.get(key) if value is None: continue weight = getattr(difficulty_weights, key, None) if difficulty_weights is not None else None if weight is not None: lines.append((None, f" {label}: {value:.3f} x {weight:.2f} = {value * weight:.3f}", (20, 20, 20))) else: lines.append((None, f" {label}: {value:.3f}", (20, 20, 20))) lines.append((None, f"difficulty_score = {difficulty.get('score')} -> {str(difficulty.get('tier')).upper()}", (20, 20, 20))) lines.append((None, "", (0, 0, 0))) # spacer lines.append((None, "AUGMENTATION APPLIED -- document/signature-layer effects", (20, 20, 20))) if not effects: lines.append((None, " (no per-effect record in this sample's metadata)", (90, 90, 90))) for name in sorted(effects): rec = effects[name] or {} if rec.get("applied"): lines.append((None, f" {name}: ON (strength={rec.get('strength')})", (20, 20, 20))) else: lines.append((None, f" {name}: off", (120, 120, 120))) height = pad * 2 + len(lines) * line_h + 10 panel = Image.new("RGB", (width, height), (245, 246, 248)) draw = ImageDraw.Draw(panel) y = pad header_texts = {"SIGNATURE BOXES -- what was measured", "DIFFICULTY BREAKDOWN -- what built the score", "AUGMENTATION APPLIED -- document/signature-layer effects"} for color, text, text_color in lines: font = header_font if text in header_texts else body_font text_x = pad if color is not None: draw.rectangle([pad, y + 2, pad + swatch, y + 2 + swatch], outline=color, width=2) text_x = pad + swatch + 8 if text: draw.text((text_x, y), text, fill=text_color, font=font) y += line_h return panel def save_before_after_preview( path: "str | Path", clean_image: "np.ndarray", final_image: "np.ndarray", metadata: "dict[str, Any]", difficulty_weights: "Any | None" = None, extra_boxes: "list[dict] | None" = None, ) -> None: """Save a side-by-side clean-vs-final comparison PNG. Args: path: Output PNG path. clean_image: The document right after signature placement/blend, before any document-level augmentation. final_image: The fully augmented, final rendered document. metadata: The sample's full metadata dict (used to draw the metric overlays/legend/difficulty-breakdown/augmentation-applied panel on the BEFORE panel, and to label the AFTER panel with which/how many effects actually fired). difficulty_weights: Optional ``cfg.difficulty`` (a :class:`~src.config.schema.DifficultyWeights`) -- when given, the difficulty breakdown shows each component's actual weighted contribution (``value x weight = contribution``), matching the run's real config instead of just the raw component values. extra_boxes: Optional list from :func:`src.generator.compute_extra_signature_overlays` -- every OTHER signed box on this sample's template (companion / additional_signatures), drawn in a distinct color so a multi-box template's second signature isn't left unexplained on the preview. """ path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) overlaid = _draw_metric_overlays(clean_image, metadata, extra_boxes) panel = _render_info_panel(overlaid.width, metadata, difficulty_weights, extra_boxes) left_combined = Image.new("RGB", (overlaid.width, overlaid.height + panel.height), (255, 255, 255)) left_combined.paste(overlaid, (0, 0)) left_combined.paste(panel, (0, overlaid.height)) left = _label_banner(left_combined, "BEFORE - metrics (measured here, pre-degradation)") right = _label_banner(final_image, f"AFTER - {_applied_effects_summary(metadata)}") combined = Image.new("RGB", (left.width + right.width + 10, max(left.height, right.height)), (255, 255, 255)) combined.paste(left, (0, 0)) combined.paste(right, (left.width + 10, 0)) combined.save(path)