#!/usr/bin/env python3 """Create a deterministic, content-hashed QA record for generated view sequences.""" from __future__ import annotations import argparse import glob import hashlib import json from datetime import datetime, timezone from pathlib import Path import cv2 import numpy as np from skimage.metrics import structural_similarity def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as source: for block in iter(lambda: source.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def load_gray(path: Path, width: int = 480) -> np.ndarray: image = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE) if image is None: raise ValueError(f"Could not read image: {path}") height = round(image.shape[0] * width / image.shape[1]) return cv2.resize(image, (width, height), interpolation=cv2.INTER_AREA) def flow_warp_metrics(previous: np.ndarray, current: np.ndarray) -> dict[str, float]: flow = cv2.calcOpticalFlowFarneback( previous, current, None, pyr_scale=0.5, levels=4, winsize=31, iterations=5, poly_n=7, poly_sigma=1.5, flags=0, ) height, width = previous.shape x, y = np.meshgrid(np.arange(width), np.arange(height)) map_x = (x + flow[..., 0]).astype(np.float32) map_y = (y + flow[..., 1]).astype(np.float32) valid = (map_x >= 0) & (map_x <= width - 1) & (map_y >= 0) & (map_y <= height - 1) warped = cv2.remap(current, map_x, map_y, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT) difference = np.abs(previous.astype(np.float32) - warped.astype(np.float32)) return { "valid_pixel_ratio": round(float(valid.mean()), 6), "mae_0_255": round(float(difference[valid].mean()), 6), "ssim": round(float(structural_similarity(previous, warped, data_range=255)), 6), } def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("input_glob") parser.add_argument("output_json", type=Path) parser.add_argument("--observed-count", type=int, default=1) parser.add_argument("--run-record", type=Path) parser.add_argument("--camera-bundle", type=Path) args = parser.parse_args() paths = [Path(item).resolve() for item in sorted(glob.glob(args.input_glob))] if not paths: raise SystemExit(f"No frames matched: {args.input_glob}") if args.camera_bundle: bundle = json.loads(args.camera_bundle.read_text(encoding="utf-8")) provenance = bundle["provenance"] if bundle["frame_count"] != len(paths) or len(provenance) != len(paths): raise SystemExit("Camera bundle and output frames disagree") observed = provenance.count("observed") if provenance != ["observed"] * observed + ["generated"] * (len(paths) - observed): raise SystemExit("Expected source anchors before generated views") args.observed_count = observed if not 0 <= args.observed_count < len(paths): raise SystemExit("At least one generated frame is required") frames = [] grays = [] for index, path in enumerate(paths): color = cv2.imread(str(path), cv2.IMREAD_COLOR) if color is None: raise SystemExit(f"Could not read image: {path}") gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY) grays.append(load_gray(path)) frames.append( { "index": index, "provenance": "observed" if index < args.observed_count else "generated", "file": path.name, "sha256": sha256(path), "width": int(color.shape[1]), "height": int(color.shape[0]), "black_pixel_ratio_rgb_le_8": round(float(np.all(color <= 8, axis=2).mean()), 8), "near_black_ratio_luma_le_16": round(float((gray <= 16).mean()), 8), "clipped_white_ratio_luma_ge_247": round(float((gray >= 247).mean()), 8), "mean_luma": round(float(gray.mean()), 6), "laplacian_variance": round(float(cv2.Laplacian(gray, cv2.CV_64F).var()), 6), } ) transitions = [] for index in range(1, len(grays)): transitions.append( { "from": index - 1, "to": index, **flow_warp_metrics(grays[index - 1], grays[index]), } ) generated = frames[args.observed_count :] record = { "schema": "kineworld.generated-view-evaluation.v1", "created_at": datetime.now(timezone.utc).isoformat(), "method": { "dark_pixels": "fraction of pixels where every RGB channel is <= 8; includes real dark objects and is NOT a geometric hole detector", "near_black": "fraction of grayscale pixels <= 16", "sharpness": "variance of the grayscale Laplacian; descriptive, not a quality score", "transition": "Farneback optical-flow warp at 480 px width, then MAE and SSIM", }, "observed_count": args.observed_count, "limitations": ["No geometric correctness or unseen-surface ground truth measured", "Flow-warp consistency is not a product quality ranking", "Image darkness cannot distinguish black objects from missing geometry"], "generated_count": len(generated), "frames": frames, "transitions": transitions, "summary": { "generated_black_pixel_ratio_max": max(item["black_pixel_ratio_rgb_le_8"] for item in generated), "generated_near_black_ratio_max": max(item["near_black_ratio_luma_le_16"] for item in generated), "generated_laplacian_variance_mean": round( float(np.mean([item["laplacian_variance"] for item in generated])), 6 ), "transition_warp_mae_mean": round(float(np.mean([item["mae_0_255"] for item in transitions])), 6), "transition_warp_ssim_mean": round(float(np.mean([item["ssim"] for item in transitions])), 6), }, } if args.run_record: run_record = args.run_record.resolve() record["run_record"] = {"file": str(run_record), "sha256": sha256(run_record)} if args.camera_bundle: record["camera_bundle"] = {"file": str(args.camera_bundle.resolve()), "sha256": sha256(args.camera_bundle)} args.output_json.parent.mkdir(parents=True, exist_ok=True) args.output_json.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(json.dumps(record["summary"], indent=2)) if __name__ == "__main__": main()