from __future__ import annotations import json import os import shutil import subprocess from datetime import UTC, datetime from pathlib import Path from PIL import Image from packages.core.files import atomic_write_text def _ffmpeg_executable() -> str | None: configured = os.environ.get("RHG_FFMPEG", "").strip() if configured: candidate = Path(configured).expanduser() if candidate.is_file() and os.access(candidate, os.X_OK): return str(candidate) discovered = shutil.which("ffmpeg") if discovered: return discovered data_root = os.environ.get("RHG_DATA_ROOT", "").strip() if data_root: for relative in ("tools/bin/ffmpeg", "tmp/rhg-tools/ffmpeg"): candidate = Path(data_root) / relative if candidate.is_file() and os.access(candidate, os.X_OK): return str(candidate) try: import imageio_ffmpeg # type: ignore[import-not-found] bundled = Path(imageio_ffmpeg.get_ffmpeg_exe()) if bundled.is_file() and os.access(bundled, os.X_OK): return str(bundled) except (ImportError, OSError, RuntimeError): pass return None def ensure_version_media( output: Path, *, force_snapshot: bool = False, allow_final_preview_fallback: bool = True, ) -> dict[str, object]: """Materialize the mandatory per-attempt visual contract. This runs in the Supervisor lifecycle, not only at the end of a successful SceneSmith export, so failed and interrupted attempts keep their own visual history instead of inheriting a floor-plan still from another attempt. """ output = output.resolve() scenesmith = output / "scenesmith" scenesmith.mkdir(parents=True, exist_ok=True) upstream = scenesmith / "upstream" history = scenesmith / "iteration_history.mp4" history_error: str | None = None if upstream.is_dir(): try: from scripts.index_scenesmith_iterations import build_iteration_history build_iteration_history(upstream, scenesmith) except Exception as error: history_error = f"{type(error).__name__}: {error}" if not history.is_file() or history.stat().st_size == 0: diagnostic = _ensure_diagnostic_frame(output, history_error) _encode_still_video(diagnostic, history) _stamp_iteration_manifest(output) native_preview = scenesmith / "preview.mp4" root_preview = output / "preview.mp4" preview_method: str | None = "generated_scene_preview" if allow_final_preview_fallback: if not native_preview.is_file() or native_preview.stat().st_size == 0: _replace_hardlink(history, native_preview) preview_method = "iteration_history_fallback" _replace_hardlink(native_preview, root_preview) else: native_preview.unlink(missing_ok=True) root_preview.unlink(missing_ok=True) preview_method = None root_history = output / "iteration_history.mp4" _replace_hardlink(history, root_history) snapshot = ensure_version_snapshot(output, force=force_snapshot) payload: dict[str, object] = { "schema_version": "1.0", "created_at": datetime.now(UTC).isoformat(), "status": "complete" if allow_final_preview_fallback else "diagnostic_complete", "snapshot": snapshot.relative_to(output).as_posix(), "preview": ( root_preview.relative_to(output).as_posix() if allow_final_preview_fallback else None ), "backend_preview": ( native_preview.relative_to(output).as_posix() if allow_final_preview_fallback else None ), "preview_method": preview_method, "final_video_withheld": not allow_final_preview_fallback, "iteration_history": root_history.relative_to(output).as_posix(), "backend_iteration_history": history.relative_to(output).as_posix(), "history_error": history_error, } atomic_write_text( output / "supervisor" / "media_manifest.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n", ) return payload def ensure_version_snapshot(output: Path, *, force: bool = False) -> Path: """Persist one stable, human-readable still image for a generated version.""" output = output.resolve() target = output / "snapshot.jpg" if not force and target.is_file() and target.stat().st_size > 0: return target image_source = _find_image_source(output) video_source = _find_video_source(output) source: Path | None = None method: str target.parent.mkdir(parents=True, exist_ok=True) ffmpeg = _ffmpeg_executable() if video_source is not None and ffmpeg: result = subprocess.run( [ ffmpeg, "-y", "-ss", "00:00:00.500", "-i", str(video_source), "-frames:v", "1", "-q:v", "2", str(target), ], capture_output=True, timeout=60, check=False, ) if result.returncode != 0 or not target.is_file() or target.stat().st_size == 0: target.unlink(missing_ok=True) if image_source is None: raise RuntimeError(f"failed to extract version snapshot from {video_source}") with Image.open(image_source) as image: image.convert("RGB").save(target, format="JPEG", quality=92) source = image_source method = "image_after_video_fallback" else: source = video_source method = "video_frame_0_5s" elif image_source is not None: with Image.open(image_source) as image: image.convert("RGB").save(target, format="JPEG", quality=92) source = image_source method = "image" else: raise RuntimeError(f"no render image or readable preview video found under {output}") payload = { "schema_version": "1.0", "created_at": datetime.now(UTC).isoformat(), "snapshot": target.relative_to(output).as_posix(), "source": source.relative_to(output).as_posix(), "method": method, } atomic_write_text( output / "supervisor" / "snapshot_manifest.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n", ) return target def _find_image_source(output: Path) -> Path | None: preferred = [ output / "supervisor" / "critic_frame.jpg", output / "scenesmith" / "preview.jpg", output / "scenesmith" / "preview.png", ] for path in preferred: if path.is_file() and path.stat().st_size > 0: return path # Iteration contact sheets encode both stage and version, and therefore are # a better attempt snapshot than a reused floor plan. iteration_candidates = [ path for pattern in ( "scenesmith/iteration_frames/*.png", "scenesmith/iteration_frames/*.jpg", ) for path in output.glob(pattern) if path.is_file() ] if iteration_candidates: return max(iteration_candidates, key=lambda path: path.stat().st_mtime) patterns = ( "scenesmith/**/*preview*.png", "scenesmith/**/*preview*.jpg", "scenesmith/**/floor_plan.png", ) candidates = [path for pattern in patterns for path in output.glob(pattern) if path.is_file()] return max(candidates, key=lambda path: path.stat().st_mtime) if candidates else None def _ensure_diagnostic_frame(output: Path, history_error: str | None) -> Path: frame = output / "scenesmith" / "iteration_frames" / "frame_0000.png" frame.parent.mkdir(parents=True, exist_ok=True) image = Image.new("RGB", (1280, 720), (24, 27, 30)) from PIL import ImageDraw draw = ImageDraw.Draw(image) manifest = output / "supervisor" / "attempt_manifest.json" attempt = json.loads(manifest.read_text(encoding="utf-8")) if manifest.is_file() else {} lines = [ f"RoboHouseGen attempt: {output.name}", f"status: {attempt.get('status', 'running')}", "No SceneSmith render state was completed before this checkpoint.", ] error = attempt.get("error") or history_error if error: lines.extend(("", "diagnostic:", str(error)[:700])) y = 56 for line in lines: draw.text((56, y), line, fill=(242, 242, 238)) y += 42 image.save(frame, optimize=True) manifest_payload = { "schema_version": "1.1", "attempt_version": output.name, "iteration_count": 1, "visual_iteration_count": 1, "critic_iteration_count": 0, "critic_total_duration_s": 0.0, "iterations": [ { "index": 0, "scene": "diagnostic", "room": "diagnostic", "stage": "attempt_lifecycle", "iteration": output.name, "contact_sheet": frame.relative_to(output).as_posix(), } ], } atomic_write_text( output / "scenesmith" / "iterations_manifest.json", json.dumps(manifest_payload, ensure_ascii=False, indent=2) + "\n", ) return frame def _encode_still_video(frame: Path, target: Path) -> None: ffmpeg = _ffmpeg_executable() if not ffmpeg: raise RuntimeError("ffmpeg is required for the per-version media contract") target.parent.mkdir(parents=True, exist_ok=True) # Keep fallback diagnostics bounded even on heavily shared machines. The # bundled ffmpeg otherwise probes all logical CPUs and can stall for minutes # while encoding a single repeated frame under contention. result = subprocess.run( [ ffmpeg, "-y", "-loop", "1", "-framerate", "1", "-i", str(frame), "-frames:v", "1", "-c:v", "libx264", "-preset", "ultrafast", "-tune", "stillimage", "-threads", "1", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(target), ], capture_output=True, text=True, timeout=30, check=False, ) if result.returncode or not target.is_file(): raise RuntimeError(f"diagnostic video encoding failed: {result.stderr[-2000:]}") def _stamp_iteration_manifest(output: Path) -> None: """Attach attempt identity even when history was reused from a checkpoint.""" path = output / "scenesmith" / "iterations_manifest.json" if not path.is_file(): return payload = json.loads(path.read_text(encoding="utf-8")) if payload.get("attempt_version") == output.name: return payload["attempt_version"] = output.name atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") def _replace_hardlink(source: Path, destination: Path) -> None: if destination.is_file(): try: if os.path.samefile(source, destination): return except OSError: pass destination.unlink() destination.parent.mkdir(parents=True, exist_ok=True) os.link(source, destination) def _find_video_source(output: Path) -> Path | None: preferred = output / "scenesmith" / "preview.mp4" if preferred.is_file() and preferred.stat().st_size > 0: return preferred candidates = [path for path in output.glob("**/preview.mp4") if path.is_file()] return max(candidates, key=lambda path: path.stat().st_mtime) if candidates else None