Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Fix double rotation in python ground truth orientation

laurenspriem7a3e14734521
diff --git a/infra/ml/test/ground_truth/_runtime.py b/infra/ml/test/ground_truth/_runtime.py
index 6d4e984410..9057b58d96 100644
--- a/infra/ml/test/ground_truth/_runtime.py
+++ b/infra/ml/test/ground_truth/_runtime.py
@@ -37,6 +37,7 @@ ORIENTATION_TRANSPOSE_METHODS: Final[dict[int, Image.Transpose]] = {
7: Image.Transpose.TRANSVERSE,
8: Image.Transpose.ROTATE_90,
}
+HEIF_EXTENSIONS: Final[frozenset[str]] = frozenset({".heic", ".heif"})
@dataclass(frozen=True)
@@ -132,7 +133,203 @@ def _parse_orientation(value: object) -> int | None:
return orientation if 1 <= orientation <= 8 else None
-def _correct_image_orientation(image: Image.Image) -> Image.Image:
+def _iter_bmff_boxes(
+ payload: bytes,
+ *,
+ start: int = 0,
+ end: int | None = None,
+) -> list[tuple[bytes, int, int, int]]:
+ if end is None:
+ end = len(payload)
+ boxes: list[tuple[bytes, int, int, int]] = []
+ cursor = start
+ while cursor + 8 <= end:
+ box_start = cursor
+ size_32 = int.from_bytes(payload[cursor : cursor + 4], byteorder="big")
+ box_type = payload[cursor + 4 : cursor + 8]
+ cursor += 8
+
+ if size_32 == 1:
+ if cursor + 8 > end:
+ break
+ box_size = int.from_bytes(payload[cursor : cursor + 8], byteorder="big")
+ cursor += 8
+ elif size_32 == 0:
+ box_size = end - box_start
+ else:
+ box_size = size_32
+
+ if box_type == b"uuid":
+ if cursor + 16 > end:
+ break
+ cursor += 16
+
+ header_size = cursor - box_start
+ if box_size < header_size:
+ break
+ box_end = box_start + box_size
+ if box_end > end:
+ break
+
+ boxes.append((box_type, box_start, cursor, box_end))
+ cursor = box_end
+ if box_size == 0:
+ break
+
+ return boxes
+
+
+def _parse_pitm_item_id(meta_payload: bytes, pitm_box: tuple[bytes, int, int, int]) -> int | None:
+ _, _, payload_start, payload_end = pitm_box
+ if payload_start + 4 > payload_end:
+ return None
+ version = meta_payload[payload_start]
+ cursor = payload_start + 4
+ if version == 0:
+ if cursor + 2 > payload_end:
+ return None
+ return int.from_bytes(meta_payload[cursor : cursor + 2], byteorder="big")
+ if version == 1:
+ if cursor + 4 > payload_end:
+ return None
+ return int.from_bytes(meta_payload[cursor : cursor + 4], byteorder="big")
+ return None
+
+
+def _parse_ipco_properties(
+ payload: bytes,
+ ipco_box: tuple[bytes, int, int, int],
+) -> list[tuple[bytes, bytes]]:
+ _, _, payload_start, payload_end = ipco_box
+ properties: list[tuple[bytes, bytes]] = []
+ for prop_type, _, prop_payload_start, prop_payload_end in _iter_bmff_boxes(
+ payload, start=payload_start, end=payload_end
+ ):
+ properties.append((prop_type, payload[prop_payload_start:prop_payload_end]))
+ return properties
+
+
+def _parse_primary_item_ipma_associations(
+ payload: bytes,
+ ipma_box: tuple[bytes, int, int, int],
+ *,
+ primary_item_id: int,
+) -> list[int]:
+ _, _, payload_start, payload_end = ipma_box
+ if payload_start + 8 > payload_end:
+ return []
+
+ version = payload[payload_start]
+ flags = int.from_bytes(payload[payload_start + 1 : payload_start + 4], byteorder="big")
+ cursor = payload_start + 4
+ entry_count = int.from_bytes(payload[cursor : cursor + 4], byteorder="big")
+ cursor += 4
+ use_extended_property_index = bool(flags & 0x1)
+
+ associations: list[int] = []
+ for _ in range(entry_count):
+ if version == 0:
+ if cursor + 2 > payload_end:
+ break
+ item_id = int.from_bytes(payload[cursor : cursor + 2], byteorder="big")
+ cursor += 2
+ elif version == 1:
+ if cursor + 4 > payload_end:
+ break
+ item_id = int.from_bytes(payload[cursor : cursor + 4], byteorder="big")
+ cursor += 4
+ else:
+ break
+
+ if cursor + 1 > payload_end:
+ break
+ association_count = payload[cursor]
+ cursor += 1
+
+ for _ in range(association_count):
+ if use_extended_property_index:
+ if cursor + 2 > payload_end:
+ break
+ value = int.from_bytes(payload[cursor : cursor + 2], byteorder="big")
+ cursor += 2
+ property_index = value & 0x7FFF
+ else:
+ if cursor + 1 > payload_end:
+ break
+ value = payload[cursor]
+ cursor += 1
+ property_index = value & 0x7F
+
+ if item_id == primary_item_id and property_index > 0:
+ associations.append(property_index)
+
+ return associations
+
+
+def _heif_primary_item_has_orientation_transform(source_path: Path) -> bool:
+ try:
+ payload = source_path.read_bytes()
+ except Exception:
+ return False
+
+ top_level = _iter_bmff_boxes(payload)
+ meta_box = next((box for box in top_level if box[0] == b"meta"), None)
+ if meta_box is None:
+ return False
+
+ _, _, meta_payload_start, meta_payload_end = meta_box
+ if meta_payload_start + 4 > meta_payload_end:
+ return False
+ # Skip full box header (version + flags).
+ meta_children_start = meta_payload_start + 4
+ meta_children = _iter_bmff_boxes(payload, start=meta_children_start, end=meta_payload_end)
+
+ pitm_box = next((box for box in meta_children if box[0] == b"pitm"), None)
+ if pitm_box is None:
+ return False
+ primary_item_id = _parse_pitm_item_id(payload, pitm_box)
+ if primary_item_id is None:
+ return False
+
+ iprp_box = next((box for box in meta_children if box[0] == b"iprp"), None)
+ if iprp_box is None:
+ return False
+
+ _, _, iprp_payload_start, iprp_payload_end = iprp_box
+ iprp_children = _iter_bmff_boxes(payload, start=iprp_payload_start, end=iprp_payload_end)
+
+ ipco_properties: list[tuple[bytes, bytes]] = []
+ for ipco_box in [box for box in iprp_children if box[0] == b"ipco"]:
+ ipco_properties.extend(_parse_ipco_properties(payload, ipco_box))
+ if not ipco_properties:
+ return False
+
+ associated_property_indexes: list[int] = []
+ for ipma_box in [box for box in iprp_children if box[0] == b"ipma"]:
+ associated_property_indexes.extend(
+ _parse_primary_item_ipma_associations(
+ payload,
+ ipma_box,
+ primary_item_id=primary_item_id,
+ )
+ )
+ if not associated_property_indexes:
+ return False
+
+ for property_index in associated_property_indexes:
+ if property_index > len(ipco_properties):
+ continue
+ property_type, property_payload = ipco_properties[property_index - 1]
+ if property_type == b"imir":
+ return True
+ if property_type == b"irot" and property_payload:
+ if (property_payload[0] & 0x03) != 0:
+ return True
+
+ return False
+
+
+def _correct_image_orientation(image: Image.Image, *, source_path: Path | None = None) -> Image.Image:
exif_orientation = _parse_orientation(image.getexif().get(EXIF_ORIENTATION_TAG, 1)) or 1
# pillow-heif can normalize EXIF orientation to 1 while preserving the original
# value in `image.info["original_orientation"]`.
@@ -145,6 +342,13 @@ def _correct_image_orientation(image: Image.Image) -> Image.Image:
manual_method = ORIENTATION_TRANSPOSE_METHODS.get(original_orientation)
if manual_method is None:
return corrected
+
+ if source_path is not None and source_path.suffix.lower() in HEIF_EXTENSIONS:
+ # Some HEIF images carry irot/imir primary-item transforms. In those
+ # cases, applying original_orientation from pillow-heif can double-rotate.
+ if _heif_primary_item_has_orientation_transform(source_path):
+ return corrected
+
return corrected.transpose(manual_method)
@@ -153,7 +357,7 @@ def decode_image_rgb(source_path: Path) -> np.ndarray:
try:
with Image.open(source_path) as image:
- image = _correct_image_orientation(image)
+ image = _correct_image_orientation(image, source_path=source_path)
image = image.convert("RGB")
pixels = np.array(image, dtype=np.uint8, copy=True)
return np.ascontiguousarray(pixels)
diff --git a/infra/ml/test/tests/test_runtime.py b/infra/ml/test/tests/test_runtime.py
index 46af60a60a..2bb5642fb0 100644
--- a/infra/ml/test/tests/test_runtime.py
+++ b/infra/ml/test/tests/test_runtime.py
@@ -2,8 +2,9 @@ from __future__ import annotations
import numpy as np
from PIL import Image
+from pathlib import Path
-from ground_truth._runtime import _correct_image_orientation
+import ground_truth._runtime as runtime
def _sample_image() -> Image.Image:
@@ -24,7 +25,7 @@ def test_correct_image_orientation_applies_standard_exif_orientation() -> None:
exif[274] = 6
image.info["exif"] = exif.tobytes()
- corrected = _correct_image_orientation(image)
+ corrected = runtime._correct_image_orientation(image)
assert corrected.size == (2, 3)
@@ -36,7 +37,7 @@ def test_correct_image_orientation_uses_original_orientation_when_exif_is_normal
image.info["exif"] = exif.tobytes()
image.info["original_orientation"] = 6
- corrected = _correct_image_orientation(image)
+ corrected = runtime._correct_image_orientation(image)
assert corrected.size == (2, 3)
@@ -44,6 +45,29 @@ def test_correct_image_orientation_uses_original_orientation_when_exif_is_normal
def test_correct_image_orientation_leaves_image_unchanged_without_orientation_metadata() -> None:
image = _sample_image()
- corrected = _correct_image_orientation(image)
+ corrected = runtime._correct_image_orientation(image)
+
+ assert corrected.size == image.size
+
+
+def test_correct_image_orientation_skips_original_orientation_for_heif_with_primary_transform(
+ monkeypatch,
+) -> None:
+ image = _sample_image()
+ exif = image.getexif()
+ exif[274] = 1
+ image.info["exif"] = exif.tobytes()
+ image.info["original_orientation"] = 6
+
+ monkeypatch.setattr(
+ runtime,
+ "_heif_primary_item_has_orientation_transform",
+ lambda _: True,
+ )
+
+ corrected = runtime._correct_image_orientation(
+ image,
+ source_path=Path("/tmp/example.HEIC"),
+ )
assert corrected.size == image.size
diff --git a/infra/ml/test/tools/tmp_visualize_ground_truth_decodes.py b/infra/ml/test/tools/tmp_visualize_ground_truth_decodes.py
new file mode 100644
index 0000000000..0d65173f9b
--- /dev/null
+++ b/infra/ml/test/tools/tmp_visualize_ground_truth_decodes.py
@@ -0,0 +1,276 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import argparse
+from datetime import datetime, timezone
+import html
+import json
+from pathlib import Path
+import re
+import subprocess
+import sys
+from typing import Any
+
+from PIL import Image
+
+ML_DIR = Path(__file__).resolve().parents[1]
+if str(ML_DIR) not in sys.path:
+ sys.path.insert(0, str(ML_DIR))
+
+from ground_truth._runtime import EXIF_ORIENTATION_TAG, decode_image_rgb
+
+
+def _repo_root(ml_dir: Path) -> Path:
+ try:
+ completed = subprocess.run(
+ ["git", "-C", str(ml_dir), "rev-parse", "--show-toplevel"],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ except (subprocess.SubprocessError, FileNotFoundError):
+ return ml_dir.parents[2]
+
+ root = completed.stdout.strip()
+ if not root:
+ return ml_dir.parents[2]
+ return Path(root)
+
+
+def _resolve_repo_relative(path_value: str, *, repo_root: Path) -> Path:
+ path = Path(path_value)
+ if path.is_absolute():
+ return path
+ return repo_root / path
+
+
+def _resolve_ml_relative(path_value: str, *, ml_dir: Path) -> Path:
+ path = Path(path_value)
+ if path.is_absolute():
+ return path
+ return ml_dir / path
+
+
+def _sanitize_file_name(name: str) -> str:
+ return re.sub(r"[^A-Za-z0-9._-]", "_", name)
+
+
+def _build_html(records: list[dict[str, Any]]) -> str:
+ generated_at = datetime.now(timezone.utc).isoformat()
+ cards: list[str] = []
+ for record in records:
+ file_id = html.escape(str(record["file_id"]))
+ source = html.escape(str(record["source"]))
+ decoded_image = html.escape(str(record["decoded_png_rel"]))
+ source_size = html.escape(str(record["source_size"]))
+ decoded_size = html.escape(str(record["decoded_size"]))
+ exif_orientation = html.escape(str(record["exif_orientation"]))
+ original_orientation = html.escape(str(record["original_orientation"]))
+ tags = html.escape(", ".join(record["tags"]))
+
+ cards.append(
+ (
+ "<article class='card'>"
+ f"<a href='{decoded_image}' target='_blank' rel='noreferrer'>"
+ f"<img src='{decoded_image}' alt='{file_id}' loading='lazy' /></a>"
+ f"<h2>{file_id}</h2>"
+ "<ul>"
+ f"<li><strong>source</strong>: {source}</li>"
+ f"<li><strong>source_size</strong>: {source_size}</li>"
+ f"<li><strong>decoded_size</strong>: {decoded_size}</li>"
+ f"<li><strong>EXIF orientation</strong>: {exif_orientation}</li>"
+ f"<li><strong>original_orientation</strong>: {original_orientation}</li>"
+ f"<li><strong>tags</strong>: {tags}</li>"
+ "</ul>"
+ "</article>"
+ )
+ )
+
+ cards_markup = "\n".join(cards)
+ return f"""<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>ML Ground Truth Decode Preview</title>
+ <style>
+ :root {{
+ color-scheme: light;
+ --bg: #f7f8fa;
+ --fg: #1d232f;
+ --card: #ffffff;
+ --border: #d9dde6;
+ --muted: #4f5d75;
+ --link: #0d66d0;
+ }}
+ body {{
+ margin: 0;
+ padding: 24px;
+ background: radial-gradient(circle at top left, #fefcf6 0%, var(--bg) 45%);
+ color: var(--fg);
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
+ }}
+ h1 {{
+ margin: 0 0 8px;
+ font-size: 28px;
+ }}
+ p.meta {{
+ margin: 0 0 20px;
+ color: var(--muted);
+ font-size: 14px;
+ }}
+ .grid {{
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
+ gap: 16px;
+ }}
+ .card {{
+ background: var(--card);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ padding: 12px;
+ box-shadow: 0 1px 6px rgba(17, 24, 39, 0.05);
+ }}
+ img {{
+ width: 100%;
+ max-height: 280px;
+ object-fit: contain;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: #111;
+ }}
+ h2 {{
+ margin: 10px 0 8px;
+ font-size: 16px;
+ line-height: 1.3;
+ word-break: break-word;
+ }}
+ ul {{
+ margin: 0;
+ padding-left: 18px;
+ color: var(--muted);
+ font-size: 13px;
+ line-height: 1.35;
+ }}
+ a {{
+ color: var(--link);
+ }}
+ </style>
+</head>
+<body>
+ <h1>ML Ground Truth Decode Preview</h1>
+ <p class="meta">
+ Generated: {html.escape(generated_at)} | Count: {len(records)} | Decoder:
+ ground_truth._runtime.decode_image_rgb
+ </p>
+ <div class="grid">
+ {cards_markup}
+ </div>
+</body>
+</html>
+"""
+
+
+def _decode_all(
+ *,
+ manifest_items: list[dict[str, Any]],
+ ml_dir: Path,
+ output_dir: Path,
+) -> list[dict[str, Any]]:
+ decoded_dir = output_dir / "decoded"
+ decoded_dir.mkdir(parents=True, exist_ok=True)
+
+ records: list[dict[str, Any]] = []
+ for index, item in enumerate(manifest_items, start=1):
+ file_id = str(item.get("file_id", ""))
+ source_value = str(item.get("source", ""))
+ source_path = _resolve_ml_relative(source_value, ml_dir=ml_dir)
+ if not source_path.exists():
+ raise FileNotFoundError(
+ f"Source file missing for manifest item '{file_id}': {source_path}"
+ )
+
+ with Image.open(source_path) as source_img:
+ source_size = f"{source_img.width}x{source_img.height}"
+ exif_orientation = source_img.getexif().get(EXIF_ORIENTATION_TAG)
+ original_orientation = source_img.info.get("original_orientation")
+
+ decoded = decode_image_rgb(source_path)
+ decoded_img = Image.fromarray(decoded, mode="RGB")
+ decoded_size = f"{decoded_img.width}x{decoded_img.height}"
+
+ file_stem = _sanitize_file_name(file_id.replace("/", "__"))
+ if not file_stem:
+ file_stem = f"item_{index:03d}"
+ output_png = decoded_dir / f"{index:03d}_{file_stem}.png"
+ decoded_img.save(output_png, format="PNG")
+
+ records.append(
+ {
+ "file_id": file_id,
+ "source": str(source_path.relative_to(ml_dir)),
+ "source_size": source_size,
+ "decoded_size": decoded_size,
+ "decoded_png_rel": str(output_png.relative_to(output_dir)),
+ "exif_orientation": exif_orientation,
+ "original_orientation": original_orientation,
+ "tags": list(item.get("tags") or []),
+ }
+ )
+
+ return records
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Decode all ML parity fixtures via ground_truth._runtime.decode_image_rgb "
+ "and generate an HTML gallery for visual inspection."
+ )
+ )
+ parser.add_argument(
+ "--manifest",
+ default="infra/ml/test/ground_truth/manifest.json",
+ help="Path to parity manifest.json.",
+ )
+ parser.add_argument(
+ "--output-dir",
+ default="infra/ml/test/out/parity/python_decode_preview",
+ help="Directory where decoded PNGs and index.html are written.",
+ )
+ parser.add_argument(
+ "--open",
+ action="store_true",
+ help="Open generated index.html in the default browser.",
+ )
+ args = parser.parse_args()
+
+ repo_root = _repo_root(ML_DIR)
+ manifest_path = _resolve_repo_relative(args.manifest, repo_root=repo_root)
+ output_dir = _resolve_repo_relative(args.output_dir, repo_root=repo_root)
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ manifest_payload = json.loads(manifest_path.read_text())
+ items = list(manifest_payload.get("items") or [])
+ if not items:
+ raise ValueError(f"No manifest items found in {manifest_path}")
+
+ records = _decode_all(
+ manifest_items=items,
+ ml_dir=ML_DIR,
+ output_dir=output_dir,
+ )
+
+ index_path = output_dir / "index.html"
+ index_path.write_text(_build_html(records), encoding="utf-8")
+
+ if args.open:
+ subprocess.run(["open", str(index_path)], check=False)
+
+ print(f"Decoded {len(records)} fixture image(s).")
+ print(f"Gallery: {index_path}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())