photo.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. """Optional, hash-bound affine board-photo overlay preparation."""
  2. from __future__ import annotations
  3. import shutil
  4. from collections.abc import Mapping, Sequence
  5. from dataclasses import dataclass
  6. from pathlib import Path
  7. from .assets import sha256_file
  8. class PhotoOverlayError(RuntimeError):
  9. """Raised when optional photo calibration cannot be trusted."""
  10. @dataclass(frozen=True)
  11. class PreparedPhotoOverlay:
  12. data: dict[str, object]
  13. source_path: Path
  14. asset_path: Path
  15. def _point(item: Mapping[str, object], name: str) -> tuple[float, float]:
  16. value = item.get(name)
  17. if not isinstance(value, Mapping):
  18. raise PhotoOverlayError(f"control point {name} must be an object")
  19. try:
  20. return float(value["x"]), float(value["y"])
  21. except (KeyError, TypeError, ValueError) as exc:
  22. raise PhotoOverlayError(f"control point {name} must contain numeric x/y") from exc
  23. def _has_non_collinear(points: Sequence[tuple[float, float]]) -> bool:
  24. for first in range(len(points) - 2):
  25. for second in range(first + 1, len(points) - 1):
  26. for third in range(second + 1, len(points)):
  27. a, b, c = points[first], points[second], points[third]
  28. area2 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
  29. if abs(area2) > 1e-9:
  30. return True
  31. return False
  32. def _solve_three_by_three(matrix: list[list[float]], values: list[float]) -> list[float]:
  33. augmented = [row[:] + [value] for row, value in zip(matrix, values, strict=True)]
  34. for column in range(3):
  35. pivot = max(range(column, 3), key=lambda row: abs(augmented[row][column]))
  36. if abs(augmented[pivot][column]) <= 1e-12:
  37. raise PhotoOverlayError("control points must include non-collinear coordinates")
  38. augmented[column], augmented[pivot] = augmented[pivot], augmented[column]
  39. divisor = augmented[column][column]
  40. augmented[column] = [value / divisor for value in augmented[column]]
  41. for row in range(3):
  42. if row == column:
  43. continue
  44. factor = augmented[row][column]
  45. augmented[row] = [
  46. value - factor * pivot_value
  47. for value, pivot_value in zip(augmented[row], augmented[column], strict=True)
  48. ]
  49. return [augmented[row][3] for row in range(3)]
  50. def solve_affine_matrix(
  51. control_points: Sequence[Mapping[str, object]], *, board_bounds: Mapping[str, float]
  52. ) -> list[float]:
  53. if len(control_points) < 3:
  54. raise PhotoOverlayError("photo overlay requires at least three control points")
  55. image_points = [_point(item, "image") for item in control_points]
  56. board_points = [_point(item, "board") for item in control_points]
  57. if not _has_non_collinear(image_points) or not _has_non_collinear(board_points):
  58. raise PhotoOverlayError("control points must include non-collinear coordinates")
  59. rows = [[x, y, 1.0] for x, y in image_points]
  60. normal = [
  61. [sum(row[left] * row[right] for row in rows) for right in range(3)]
  62. for left in range(3)
  63. ]
  64. target_x = [point[0] - float(board_bounds["x"]) for point in board_points]
  65. target_y = [point[1] - float(board_bounds["y"]) for point in board_points]
  66. normal_x = [sum(row[column] * value for row, value in zip(rows, target_x, strict=True)) for column in range(3)]
  67. normal_y = [sum(row[column] * value for row, value in zip(rows, target_y, strict=True)) for column in range(3)]
  68. x_coefficients = _solve_three_by_three(normal, normal_x)
  69. y_coefficients = _solve_three_by_three(normal, normal_y)
  70. return [
  71. x_coefficients[0],
  72. y_coefficients[0],
  73. x_coefficients[1],
  74. y_coefficients[1],
  75. x_coefficients[2],
  76. y_coefficients[2],
  77. ]
  78. def prepare_photo_overlay(
  79. configuration: Mapping[str, object] | None,
  80. *,
  81. repository_root: Path | str,
  82. assets_dir: Path | str,
  83. board_bounds: Mapping[str, float],
  84. ) -> PreparedPhotoOverlay | None:
  85. if configuration is None:
  86. return None
  87. repository = Path(repository_root).resolve()
  88. source = (repository / str(configuration.get("path") or "")).resolve()
  89. try:
  90. source.relative_to(repository)
  91. except ValueError as exc:
  92. raise PhotoOverlayError("photo overlay path must stay inside repository") from exc
  93. if not source.is_file():
  94. raise PhotoOverlayError(f"photo overlay source is missing: {source}")
  95. expected_hash = str(configuration.get("sha256") or "")
  96. actual_hash = sha256_file(source)
  97. if actual_hash != expected_hash:
  98. raise PhotoOverlayError(f"photo overlay SHA-256 mismatch: expected {expected_hash}, got {actual_hash}")
  99. suffix = source.suffix.lower()
  100. if suffix not in {".png", ".jpg", ".jpeg", ".webp"}:
  101. raise PhotoOverlayError(f"unsupported photo overlay format: {suffix}")
  102. control_points = configuration.get("control_points")
  103. if not isinstance(control_points, list):
  104. raise PhotoOverlayError("photo overlay control_points must be an array")
  105. matrix = solve_affine_matrix(control_points, board_bounds=board_bounds)
  106. asset_path = Path(assets_dir) / f"board-photo{suffix}"
  107. shutil.copy2(source, asset_path)
  108. return PreparedPhotoOverlay(
  109. data={
  110. "asset": asset_path.name,
  111. "sha256": actual_hash,
  112. "matrix": matrix,
  113. "control_point_count": len(control_points),
  114. },
  115. source_path=source,
  116. asset_path=asset_path,
  117. )