File size: 12,352 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import contextlib
import fcntl
import functools
import hashlib
import json
import os
import re
import subprocess
import tempfile
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Iterator

import numpy as np

from .video import VideoConfig, VideoEncoder, decode_frames, encoder_command, validate_video

TARGET_WIDTH = 518
PATCH_MULTIPLE = 14
ROW_SCHEMA = "amodaldrive_scene_row_v1"
IDENTITY_SCHEMA = "amodaldrive_transcode_identity_v1"
VIDEO_NAME = "rgb.mp4"
MANIFEST_NAME = "manifest.jsonl"

GAMMA = 2.2
LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32)
SCENE_ROWS_FRACTION = 0.6
SCENE_SAMPLE_FRAMES = 24


def lin(x: np.ndarray) -> np.ndarray:
    return np.clip(x, 0.0, 1.0).astype(np.float32) ** np.float32(GAMMA)


def luminance(x: np.ndarray) -> np.ndarray:
    return x @ LUMA


def sha256_file(path: Path | str, chunk: int = 1 << 20) -> str:
    digest = hashlib.sha256()
    with open(path, "rb") as stream:
        for block in iter(lambda: stream.read(chunk), b""):
            digest.update(block)
    return digest.hexdigest()


def canonical_json(value: Any) -> str:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def json_sha256(value: Any) -> str:
    return hashlib.sha256(canonical_json(value).encode()).hexdigest()


def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def group_of(time_of_day: str) -> str:
    return "day" if time_of_day in ("day", "dawn") else "night"


@contextlib.contextmanager
def locked(path: Path) -> Iterator[None]:
    lock_path = path.with_name(f".{path.name}.lock")
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with open(lock_path, "a") as handle:
        fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(handle.fileno(), fcntl.LOCK_UN)


def atomic_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
    try:
        with os.fdopen(descriptor, "w") as stream:
            stream.write(text)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, path)
    finally:
        Path(temporary).unlink(missing_ok=True)
    mask = os.umask(0)
    os.umask(mask)
    os.chmod(path, 0o666 & ~mask)


def resize_size(width: int, height: int, target_width: int = TARGET_WIDTH, multiple: int = PATCH_MULTIPLE) -> tuple[int, int]:
    return int(target_width), round(height * (target_width / width) / multiple) * multiple


def pil_resize(frame: np.ndarray, size: tuple[int, int]) -> np.ndarray:
    from PIL import Image
    frame = np.asarray(frame)
    if frame.dtype != np.uint8 or frame.ndim != 3 or frame.shape[-1] != 3:
        raise ValueError("expected an HxWx3 uint8 frame")
    if size[1] > size[0]:
        raise ValueError(f"size {size} is taller than wide; the DGGT loader would centre-crop it")
    image = Image.fromarray(frame).convert("RGB").resize(tuple(size), Image.Resampling.BICUBIC)
    return np.asarray(image)


def resize_identity(native_size: tuple[int, int], size: tuple[int, int], crop: Any = "none") -> dict[str, Any]:
    import PIL
    return {"function": "PIL.Image.Image.resize", "filter": "Image.Resampling.BICUBIC", "mode": "RGB uint8",
            "pillow_version": PIL.__version__, "native_size": list(native_size), "size": list(size),
            "height_rule": f"round(h * {size[0]} / w / {PATCH_MULTIPLE}) * {PATCH_MULTIPLE}", "crop": crop,
            "reference": "DGGT datasets/dataset.py:60-136 image loader (before ToTensor)"}


@functools.lru_cache(maxsize=None)
def _tool_version(binary: str) -> str:
    result = subprocess.run([binary, "-version"], capture_output=True, text=True, check=True)
    return result.stdout.splitlines()[0].strip()


@functools.lru_cache(maxsize=None)
def _x265_version(ffmpeg: str) -> str:
    result = subprocess.run([ffmpeg, "-hide_banner", "-loglevel", "info", "-f", "lavfi", "-i", "color=c=gray:s=64x64:d=0.1",
                             "-frames:v", "1", "-c:v", "libx265", "-f", "null", "-"], capture_output=True, text=True, check=False)
    match = re.search(r"HEVC encoder version (\S+)", result.stderr)
    if not match:
        raise RuntimeError(f"{ffmpeg} did not report a libx265 version: {result.stderr[-400:]}")
    return match.group(1)


FRAME_RATE_RULE = "video_fps = 1e6 / median start-timestamp interval of frames.jsonl"


def transcode_identity(*, ffmpeg: str, ffprobe: str, config: VideoConfig, native_size: tuple[int, int],
                       size: tuple[int, int], decoder: dict[str, Any], crop: Any = "none") -> dict[str, Any]:
    arguments = encoder_command("<ffmpeg>", "<rgb.mp4>.partial", size[0], size[1], 1.0, config)
    arguments[arguments.index("-r") + 1] = "<video_fps:.9f>"
    identity = {"schema": IDENTITY_SCHEMA, "decoder": decoder, "resize": resize_identity(native_size, size, crop),
                "encoder": {"config": asdict(config), "arguments": arguments, "ffmpeg_version": _tool_version(ffmpeg),
                            "x265_version": _x265_version(ffmpeg), "frame_rate_rule": FRAME_RATE_RULE},
                "validator": {"ffprobe_version": _tool_version(ffprobe)}}
    identity["identity_sha256"] = json_sha256(identity)
    return identity


def write_metadata(destination: Path, name: str, content: bytes) -> dict[str, Any]:
    if name == VIDEO_NAME or Path(name).name != name:
        raise ValueError(f"invalid metadata file name {name!r}")
    destination.mkdir(parents=True, exist_ok=True)
    target = destination / name
    temporary = target.with_name(name + ".partial")
    with open(temporary, "wb") as stream:
        stream.write(content)
        stream.flush()
        os.fsync(stream.fileno())
    mask = os.umask(0)
    os.umask(mask)
    os.chmod(temporary, 0o666 & ~mask)
    os.replace(temporary, target)
    digest = sha256_file(target)
    if digest != hashlib.sha256(content).hexdigest():
        raise OSError(f"{target} does not read back as written")
    return {"sha256": digest, "bytes": target.stat().st_size}


def write_scene(destination: Path, frames: Iterable[np.ndarray], *, size: tuple[int, int], fps: float, frame_count: int,
                metadata: dict[str, bytes], ffmpeg: str, ffprobe: str, config: VideoConfig) -> dict[str, Any]:
    width, height = (int(v) for v in size)
    destination.mkdir(parents=True, exist_ok=True)
    files: dict[str, dict[str, Any]] = {}
    for name, source in metadata.items():
        files[name] = write_metadata(destination, name, source)
    video = destination / VIDEO_NAME
    video.unlink(missing_ok=True)
    written = 0
    with VideoEncoder(ffmpeg, video, width, height, fps, config) as encoder:
        for frame in frames:
            frame = np.asarray(frame)
            if frame.dtype != np.uint8 or frame.shape != (height, width, 3):
                raise ValueError(f"frame {written} is {frame.dtype} {frame.shape}, expected uint8 {(height, width, 3)}")
            encoder.write(frame)
            written += 1
        if written != frame_count:
            raise ValueError(f"source produced {written} frames, expected {frame_count}")
    check = validate_video(video, width=width, height=height, count=frame_count, fps=fps, ffprobe=ffprobe,
                           pixel_format=config.pixel_format)
    files[VIDEO_NAME] = {"sha256": sha256_file(video), "bytes": video.stat().st_size}
    return {"files": files, "video": check}


def scene_row(*, data_root: Path, destination: Path, written: dict[str, Any], source_id: str, scene_id: str,
              dataset_id: str, camera_id: str, fps: int | float, video_fps: float, frame_count: int, time_of_day: str,
              size: tuple[int, int], native_size: tuple[int, int], transcode: dict[str, Any],
              provenance: dict[str, Any], extra: dict[str, Any] | None = None) -> dict[str, Any]:
    files = {}
    for name, info in sorted(written["files"].items()):
        key = "rgb" if name == VIDEO_NAME else Path(name).stem
        files[key] = {"relative_path": (destination / name).relative_to(data_root).as_posix(), **info}
    row = {"schema": ROW_SCHEMA, "source_id": source_id, "scene_id": scene_id, "dataset_id": dataset_id,
           "camera_id": camera_id, "fps": fps, "video_fps": float(video_fps), "frame_count": int(frame_count),
           "time_of_day": time_of_day, "group": group_of(time_of_day),
           "resolution": [int(size[0]), int(size[1])], "native_resolution": [int(native_size[0]), int(native_size[1])],
           "files": files, "video": written["video"], "transcode": transcode, "provenance": provenance,
           "built_utc": utc_now()}
    extra = dict(extra or {})
    clash = sorted(set(extra) & set(row))
    if clash:
        raise ValueError(f"extra row fields redefine common fields {clash}")
    row.update(extra)
    return row


def scene_complete(data_root: Path, row: dict[str, Any] | None, *, identity: dict[str, Any]) -> bool:
    if row is None or row.get("transcode", {}).get("identity_sha256") != identity["identity_sha256"]:
        return False
    for info in row["files"].values():
        path = data_root / info["relative_path"]
        if not path.is_file() or path.stat().st_size != info["bytes"] or sha256_file(path) != info["sha256"]:
            return False
    return True


def scene_statistics_from_frames(frames: Iterable[np.ndarray], indices: Iterable[int], frame_count: int) -> dict[str, Any]:
    indices = [int(i) for i in indices]
    stack = [np.asarray(f) for f in frames]
    if len(stack) != len(indices) or not stack:
        raise ValueError(f"{len(stack)} frames for {len(indices)} sampled indices")
    height = stack[0].shape[0]
    rows = max(1, int(round(height * SCENE_ROWS_FRACTION)))
    if any(f.dtype != np.uint8 or f.ndim != 3 or f.shape[0] != height for f in stack):
        raise ValueError("expected HxWx3 uint8 frames of one size")
    data = np.stack([lin(f[:rows].astype(np.float32) / np.float32(255.0)) for f in stack])
    lum = luminance(data)
    mean_rgb = data.reshape(-1, 3).mean(axis=0)
    mean_luminance = float(max(luminance(mean_rgb), 1e-6))
    return {"schema_version": 1, "domain": "linear_light_gamma_2.2", "rows_fraction": SCENE_ROWS_FRACTION, "rows": int(rows),
            "sampled_frames": indices, "frame_count": int(frame_count),
            "mean_luminance": float(lum.mean()), "median_luminance": float(np.median(lum)),
            "p99_luminance": float(np.percentile(lum, 99)), "mean_rgb": [float(v) for v in mean_rgb],
            "white_balance_gain": [float(v / mean_luminance) for v in mean_rgb]}


def sampled_frame_indices(frame_count: int) -> list[int]:
    return [int(i) for i in np.unique(np.linspace(0, frame_count - 1, min(SCENE_SAMPLE_FRAMES, frame_count)).round().astype(int))]


def scene_statistics_from_video(path: Path, frame_count: int) -> dict[str, Any]:
    indices = sampled_frame_indices(frame_count)
    wanted = set(indices)
    frames = [f for i, f in enumerate(decode_frames(path, expected_frames=frame_count)) if i in wanted]
    stats = scene_statistics_from_frames(frames, indices, frame_count)
    stats["input"] = "decoded clean rgb.mp4 (PyAV rgb24, uint8 / 255), not the HDF5 render cache"
    return stats


def read_manifest(path: Path) -> list[dict[str, Any]]:
    if not path.is_file():
        return []
    return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]


def merge_manifest(path: Path, rows: Iterable[dict[str, Any]]) -> dict[str, int]:
    rows = list(rows)
    keys = [(r["source_id"], r["scene_id"]) for r in rows]
    if len(set(keys)) != len(keys):
        raise ValueError("duplicate (source_id, scene_id) in one manifest merge")
    with locked(path):
        existing = {(r["source_id"], r["scene_id"]): r for r in read_manifest(path)}
        replaced = sum(1 for k in keys if k in existing)
        existing.update(zip(keys, rows))
        ordered = [existing[k] for k in sorted(existing)]
        atomic_text(path, "".join(canonical_json(r) + "\n" for r in ordered))
    return {"rows": len(ordered), "inserted": len(rows) - replaced, "replaced": replaced}