π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Option to display detected faces
laurenspriem7360d20ae518
diff --git a/infra/ml/test/README.md b/infra/ml/test/README.mdindex ef1e6ab7ee..a5be53bf22 100644--- a/infra/ml/test/README.md+++ b/infra/ml/test/README.md@@ -32,6 +32,7 @@ Common flags:- `--allow-empty-comparison`- `--output-dir <path>`- `--verbose` (stream full runner/comparator logs to terminal)+- `--render-detection-overlays` (generate annotated detection images under `out/parity/detections/<platform>/`; includes selected platforms plus `python` ground truth)Outputs go to `infra/ml/test/out/parity/` by default, including:@@ -40,6 +41,27 @@ Outputs go to `infra/ml/test/out/parity/` by default, including:`run_suite.sh` compares each available platform against Python ground truth (`python -> <platform>`); non-ground-truth pairwise comparisons are excluded by default.+## Detection Overlay Visualizer++Render face detection overlays (box + score + landmarks) for each platform output:++```bash+uv run --project infra/ml --no-sync --with pillow-heif \+ python infra/ml/test/tools/render_face_detection_overlays.py \+ --parity-dir infra/ml/test/out/parity \+ --platform ios \+ --platform android+```++By default this writes annotated images to:++- `infra/ml/test/out/parity/detections/<platform>/*.png`++Useful optional filters:++- `--file-id <fixture_name>` (repeatable)+- `--output-dir <custom_dir>`+## Manual CI RunWorkflow: `.github/workflows/ml-indexing-parity.yml`diff --git a/infra/ml/test/tools/render_face_detection_overlays.py b/infra/ml/test/tools/render_face_detection_overlays.pynew file mode 100644index 0000000000..1d81dc5fca--- /dev/null+++ b/infra/ml/test/tools/render_face_detection_overlays.py@@ -0,0 +1,381 @@+#!/usr/bin/env python3+from __future__ import annotations++import argparse+import json+from pathlib import Path+import re+import subprocess+import sys+from typing import Any, Mapping++from PIL import Image, ImageDraw, ImageFont++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 decode_image_rgb+++_PALETTE = (+ (230, 25, 75),+ (60, 180, 75),+ (0, 130, 200),+ (245, 130, 48),+ (145, 30, 180),+ (70, 240, 240),+ (240, 50, 230),+ (210, 245, 60),+ (250, 190, 190),+ (0, 128, 128),+ (170, 110, 40),+ (128, 0, 0),+)+++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_source_path(+ source_value: str,+ *,+ ml_dir: Path,+ repo_root: Path,+) -> Path:+ source_path = Path(source_value)+ if source_path.is_absolute():+ return source_path++ ml_relative = ml_dir / source_path+ if ml_relative.exists():+ return ml_relative++ return repo_root / source_path+++def _safe_output_name(file_id: str) -> str:+ sanitized = re.sub(r"[^0-9A-Za-z._-]", "_", file_id)+ if sanitized:+ return sanitized+ return "file"+++def _load_manifest_sources(+ *,+ manifest_path: Path,+ ml_dir: Path,+ repo_root: Path,+) -> dict[str, Path]:+ payload = json.loads(manifest_path.read_text())+ items = payload.get("items", [])+ if not isinstance(items, list):+ raise ValueError("manifest `items` must be a list")++ sources_by_id: dict[str, Path] = {}+ for item in items:+ if not isinstance(item, Mapping):+ continue+ file_id = item.get("file_id")+ source = item.get("source")+ if not isinstance(file_id, str) or not isinstance(source, str):+ continue+ sources_by_id[file_id] = _resolve_source_path(+ source,+ ml_dir=ml_dir,+ repo_root=repo_root,+ )+ return sources_by_id+++def _draw_label(+ *,+ image: Image.Image,+ draw: ImageDraw.ImageDraw,+ text: str,+ position: tuple[float, float],+ color: tuple[int, int, int],+ font: ImageFont.ImageFont,+) -> None:+ x, y = position+ left, top, right, bottom = draw.textbbox((x, y), text, font=font)+ padding = 2+ draw.rectangle(+ (+ left - padding,+ top - padding,+ right + padding,+ bottom + padding,+ ),+ fill=(0, 0, 0, 180),+ )+ draw.text((x, y), text, fill=(*color, 255), font=font)+++def _render_detections(+ *,+ image_rgb: Any,+ file_id: str,+ platform: str,+ faces: list[Mapping[str, Any]],+) -> Image.Image:+ image = Image.fromarray(image_rgb, mode="RGB").convert("RGBA")+ draw = ImageDraw.Draw(image, mode="RGBA")+ width, height = image.size+ line_width = max(1, round(min(width, height) * 0.003))+ point_radius = max(2, round(min(width, height) * 0.004))+ font = ImageFont.load_default()++ header = f"{platform} | {file_id} | faces={len(faces)}"+ _draw_label(+ image=image,+ draw=draw,+ text=header,+ position=(8, 8),+ color=(255, 255, 255),+ font=font,+ )++ for index, face in enumerate(faces):+ color = _PALETTE[index % len(_PALETTE)]+ box_values = face.get("box")+ if not isinstance(box_values, list) or len(box_values) != 4:+ continue++ x_norm, y_norm, w_norm, h_norm = (+ float(box_values[0]),+ float(box_values[1]),+ float(box_values[2]),+ float(box_values[3]),+ )+ x1 = x_norm * width+ y1 = y_norm * height+ x2 = (x_norm + w_norm) * width+ y2 = (y_norm + h_norm) * height++ draw.rectangle((x1, y1, x2, y2), outline=(*color, 255), width=line_width)++ score_value = face.get("score")+ if isinstance(score_value, (int, float)):+ label = f"#{index} score={float(score_value):.3f}"+ else:+ label = f"#{index}"+ label_x = max(0.0, min(x1 + 3.0, width - 1.0))+ label_y = max(0.0, y1 - 16.0)+ _draw_label(+ image=image,+ draw=draw,+ text=label,+ position=(label_x, label_y),+ color=color,+ font=font,+ )++ landmarks = face.get("landmarks")+ if not isinstance(landmarks, list):+ continue+ for point in landmarks:+ if not isinstance(point, list) or len(point) != 2:+ continue+ px = float(point[0]) * width+ py = float(point[1]) * height+ draw.ellipse(+ (+ px - point_radius,+ py - point_radius,+ px + point_radius,+ py + point_radius,+ ),+ fill=(*color, 220),+ outline=(0, 0, 0, 255),+ )++ return image.convert("RGB")+++def _discover_platforms(parity_dir: Path) -> list[str]:+ platforms = []+ if not parity_dir.exists():+ return platforms++ for child in sorted(parity_dir.iterdir()):+ if not child.is_dir():+ continue+ if (child / "results.json").exists():+ platforms.append(child.name)+ return platforms+++def _load_platform_results(results_path: Path) -> list[Mapping[str, Any]]:+ payload = json.loads(results_path.read_text())+ results = payload.get("results")+ if not isinstance(results, list):+ raise ValueError(f"{results_path} must contain `results: []`")+ typed_results: list[Mapping[str, Any]] = []+ for item in results:+ if isinstance(item, Mapping):+ typed_results.append(item)+ return typed_results+++def _iter_file_results(+ results: list[Mapping[str, Any]],+ *,+ only_file_ids: set[str] | None,+) -> list[tuple[str, list[Mapping[str, Any]]]]:+ selected: list[tuple[str, list[Mapping[str, Any]]]] = []+ for item in results:+ file_id = item.get("file_id")+ faces = item.get("faces")+ if not isinstance(file_id, str):+ continue+ if only_file_ids is not None and file_id not in only_file_ids:+ continue+ if not isinstance(faces, list):+ continue+ typed_faces = [face for face in faces if isinstance(face, Mapping)]+ selected.append((file_id, typed_faces))+ return selected+++def main() -> int:+ parser = argparse.ArgumentParser(+ description=(+ "Render annotated face detection overlays for parity results. "+ "Writes files to out/parity/detections/<platform>/."+ ),+ )+ parser.add_argument(+ "--manifest",+ default="infra/ml/test/ground_truth/manifest.json",+ help="Path to manifest.json.",+ )+ parser.add_argument(+ "--parity-dir",+ default="infra/ml/test/out/parity",+ help="Parity output directory containing <platform>/results.json.",+ )+ parser.add_argument(+ "--output-dir",+ help=(+ "Output directory for annotated images. "+ "Defaults to <parity-dir>/detections."+ ),+ )+ parser.add_argument(+ "--platform",+ action="append",+ default=[],+ help="Platform name to render (repeatable). Defaults to all detected platforms.",+ )+ parser.add_argument(+ "--file-id",+ action="append",+ default=[],+ help="Only render specific file_id values (repeatable).",+ )+ args = parser.parse_args()++ repo_root = _repo_root(ML_DIR)+ manifest_path = _resolve_repo_relative(args.manifest, repo_root=repo_root)+ parity_dir = _resolve_repo_relative(args.parity_dir, repo_root=repo_root)+ output_dir = (+ _resolve_repo_relative(args.output_dir, repo_root=repo_root)+ if args.output_dir+ else parity_dir / "detections"+ )++ sources_by_id = _load_manifest_sources(+ manifest_path=manifest_path,+ ml_dir=ML_DIR,+ repo_root=repo_root,+ )++ requested_platforms = args.platform or _discover_platforms(parity_dir)+ if not requested_platforms:+ raise ValueError(f"No platform results discovered in {parity_dir}")++ only_file_ids = set(args.file_id) if args.file_id else None++ total_rendered = 0+ total_skipped = 0+ for platform in requested_platforms:+ results_path = parity_dir / platform / "results.json"+ if not results_path.exists():+ print(f"[skip] {platform}: missing {results_path}")+ total_skipped += 1+ continue++ platform_results = _load_platform_results(results_path)+ file_results = _iter_file_results(+ platform_results,+ only_file_ids=only_file_ids,+ )+ if not file_results:+ print(f"[skip] {platform}: no matching results")+ total_skipped += 1+ continue++ platform_output_dir = output_dir / platform+ platform_output_dir.mkdir(parents=True, exist_ok=True)++ rendered_for_platform = 0+ for file_id, faces in file_results:+ source_path = sources_by_id.get(file_id)+ if source_path is None:+ print(f"[skip] {platform}/{file_id}: no source path in manifest")+ total_skipped += 1+ continue+ if not source_path.exists():+ print(f"[skip] {platform}/{file_id}: source file missing at {source_path}")+ total_skipped += 1+ continue++ try:+ image_rgb = decode_image_rgb(source_path)+ except Exception as exc: # noqa: BLE001+ print(f"[skip] {platform}/{file_id}: failed to decode source ({exc})")+ total_skipped += 1+ continue++ rendered = _render_detections(+ image_rgb=image_rgb,+ file_id=file_id,+ platform=platform,+ faces=faces,+ )+ output_path = platform_output_dir / f"{_safe_output_name(file_id)}.png"+ rendered.save(output_path)+ rendered_for_platform += 1+ total_rendered += 1++ print(+ f"[ok] {platform}: rendered {rendered_for_platform} file(s) -> {platform_output_dir}"+ )++ print(f"Done. Rendered {total_rendered} file(s), skipped {total_skipped}.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/infra/ml/test/tools/run_suite.sh b/infra/ml/test/tools/run_suite.shindex 2b38a1d670..47645c6cbe 100755--- a/infra/ml/test/tools/run_suite.sh+++ b/infra/ml/test/tools/run_suite.sh@@ -19,6 +19,7 @@ CONTINUE_ON_MISSING_DEVICES=trueREQUIRE_COMPARISON_PASS=falseOUTPUT_DIR="$ROOT_DIR/infra/ml/test/out/parity"VERBOSE=false+RENDER_DETECTION_OVERLAYS=falseusage() {cat <<EOF@@ -33,6 +34,7 @@ Flags:--allow-empty-comparison (default: disabled)--output-dir <path> (default: infra/ml/test/out/parity)--verbose (default: disabled)+ --render-detection-overlays (default: disabled; render annotated face detection images to out/parity/detections/<platform>/)EOF}@@ -70,6 +72,10 @@ while (($# > 0)); doVERBOSE=trueshift;;+ --render-detection-overlays)+ RENDER_DETECTION_OVERLAYS=true+ shift+ ;;-h|--help)usageexit 0@@ -124,6 +130,7 @@ echo " continue_on_missing_devices: $CONTINUE_ON_MISSING_DEVICES"echo " fail_on_missing_platform: $FAIL_ON_MISSING_PLATFORM"echo " fail_on_platform_runner_error: $FAIL_ON_PLATFORM_RUNNER_ERROR"echo " allow_empty_comparison: $ALLOW_EMPTY_COMPARISON"+echo " render_detection_overlays: $RENDER_DETECTION_OVERLAYS"declare -a selected_platforms=()case "$PLATFORMS" in@@ -1499,6 +1506,37 @@ for platform in selected_platforms:PY}+render_detection_overlays() {+ local overlays_log="$LOG_DIR/render_detection_overlays.log"+ local overlays_output_dir="$OUTPUT_DIR/detections"+ local -a overlay_platforms=("${selected_platforms[@]}" "python")+ local -a overlay_cmd=(+ uv run --project "$UV_PROJECT_DIR" --no-sync --with pillow-heif+ python "$ML_DIR/tools/render_face_detection_overlays.py"+ --manifest "$MANIFEST_PATH"+ --parity-dir "$OUTPUT_DIR"+ )++ for platform in "${overlay_platforms[@]}"; do+ overlay_cmd+=(--platform "$platform")+ done++ if $VERBOSE; then+ "${overlay_cmd[@]}" 2>&1 | tee "$overlays_log"+ local overlay_exit=${PIPESTATUS[0]}+ if ((overlay_exit != 0)); then+ return "$overlay_exit"+ fi+ else+ if ! "${overlay_cmd[@]}" >"$overlays_log" 2>&1; then+ return 1+ fi+ fi++ echo "Detection overlays: $overlays_output_dir"+ return 0+}+comparison_report_passed() {local report_path="$1"python3 - "$report_path" <<'PY'@@ -1634,6 +1672,13 @@ if [[ -f "$compare_output" ]]; thenfifi+if $RENDER_DETECTION_OVERLAYS; then+ if ! render_detection_overlays; then+ echo "Failed to render detection overlays. Log: $LOG_DIR/render_detection_overlays.log" >&2+ exit 1+ fi+fi+if ((compare_exit != 0)); thenecho "Parity comparison command failed. Log: $compare_log"exit "$compare_exit"