File size: 11,628 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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