"""Optional, hash-bound affine board-photo overlay preparation.""" from __future__ import annotations import shutil from collections.abc import Mapping, Sequence from dataclasses import dataclass from pathlib import Path from .assets import sha256_file class PhotoOverlayError(RuntimeError): """Raised when optional photo calibration cannot be trusted.""" @dataclass(frozen=True) class PreparedPhotoOverlay: data: dict[str, object] source_path: Path asset_path: Path def _point(item: Mapping[str, object], name: str) -> tuple[float, float]: value = item.get(name) if not isinstance(value, Mapping): raise PhotoOverlayError(f"control point {name} must be an object") try: return float(value["x"]), float(value["y"]) except (KeyError, TypeError, ValueError) as exc: raise PhotoOverlayError(f"control point {name} must contain numeric x/y") from exc def _has_non_collinear(points: Sequence[tuple[float, float]]) -> bool: for first in range(len(points) - 2): for second in range(first + 1, len(points) - 1): for third in range(second + 1, len(points)): a, b, c = points[first], points[second], points[third] area2 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) if abs(area2) > 1e-9: return True return False def _solve_three_by_three(matrix: list[list[float]], values: list[float]) -> list[float]: augmented = [row[:] + [value] for row, value in zip(matrix, values, strict=True)] for column in range(3): pivot = max(range(column, 3), key=lambda row: abs(augmented[row][column])) if abs(augmented[pivot][column]) <= 1e-12: raise PhotoOverlayError("control points must include non-collinear coordinates") augmented[column], augmented[pivot] = augmented[pivot], augmented[column] divisor = augmented[column][column] augmented[column] = [value / divisor for value in augmented[column]] for row in range(3): if row == column: continue factor = augmented[row][column] augmented[row] = [ value - factor * pivot_value for value, pivot_value in zip(augmented[row], augmented[column], strict=True) ] return [augmented[row][3] for row in range(3)] def solve_affine_matrix( control_points: Sequence[Mapping[str, object]], *, board_bounds: Mapping[str, float] ) -> list[float]: if len(control_points) < 3: raise PhotoOverlayError("photo overlay requires at least three control points") image_points = [_point(item, "image") for item in control_points] board_points = [_point(item, "board") for item in control_points] if not _has_non_collinear(image_points) or not _has_non_collinear(board_points): raise PhotoOverlayError("control points must include non-collinear coordinates") rows = [[x, y, 1.0] for x, y in image_points] normal = [ [sum(row[left] * row[right] for row in rows) for right in range(3)] for left in range(3) ] target_x = [point[0] - float(board_bounds["x"]) for point in board_points] target_y = [point[1] - float(board_bounds["y"]) for point in board_points] normal_x = [sum(row[column] * value for row, value in zip(rows, target_x, strict=True)) for column in range(3)] normal_y = [sum(row[column] * value for row, value in zip(rows, target_y, strict=True)) for column in range(3)] x_coefficients = _solve_three_by_three(normal, normal_x) y_coefficients = _solve_three_by_three(normal, normal_y) return [ x_coefficients[0], y_coefficients[0], x_coefficients[1], y_coefficients[1], x_coefficients[2], y_coefficients[2], ] def prepare_photo_overlay( configuration: Mapping[str, object] | None, *, repository_root: Path | str, assets_dir: Path | str, board_bounds: Mapping[str, float], ) -> PreparedPhotoOverlay | None: if configuration is None: return None repository = Path(repository_root).resolve() source = (repository / str(configuration.get("path") or "")).resolve() try: source.relative_to(repository) except ValueError as exc: raise PhotoOverlayError("photo overlay path must stay inside repository") from exc if not source.is_file(): raise PhotoOverlayError(f"photo overlay source is missing: {source}") expected_hash = str(configuration.get("sha256") or "") actual_hash = sha256_file(source) if actual_hash != expected_hash: raise PhotoOverlayError(f"photo overlay SHA-256 mismatch: expected {expected_hash}, got {actual_hash}") suffix = source.suffix.lower() if suffix not in {".png", ".jpg", ".jpeg", ".webp"}: raise PhotoOverlayError(f"unsupported photo overlay format: {suffix}") control_points = configuration.get("control_points") if not isinstance(control_points, list): raise PhotoOverlayError("photo overlay control_points must be an array") matrix = solve_affine_matrix(control_points, board_bounds=board_bounds) asset_path = Path(assets_dir) / f"board-photo{suffix}" shutil.copy2(source, asset_path) return PreparedPhotoOverlay( data={ "asset": asset_path.name, "sha256": actual_hash, "matrix": matrix, "control_point_count": len(control_points), }, source_path=source, asset_path=asset_path, )