File size: 11,095 Bytes
e6d64b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate Real4D structure, frame counts, metadata, and image headers."""

from __future__ import annotations

import argparse
import json
import re
import struct
import sys
from pathlib import Path


EXPECTED = {
    "dynerf": {
        "resolution": (1352, 1014),
        "scenes": {
            "coffee_martini": 324,
            "cook_spinach": 441,
            "cut_roasted_beef": 400,
            "flame_salmon": 361,
            "flame_steak": 441,
            "sear_steak": 441,
        },
    },
    "meetroom": {
        "resolution": (1280, 720),
        "scenes": {
            "discussion": 169,
            "stepin": 169,
            "trimming": 169,
            "vrheadset": 169,
        },
    },
}

REQUIRED_CAMERA_FIELDS = {
    "image_name",
    "timestamp",
    "w2c",
    "R",
    "T",
    "FoVx",
    "FoVy",
    "fl_x",
    "fl_y",
    "cx",
    "cy",
    "width",
    "height",
}


def child_dirs(path: Path) -> set[str]:
    return {entry.name for entry in path.iterdir() if entry.is_dir()}


def json_stems(path: Path) -> set[str]:
    return {entry.stem for entry in path.iterdir() if entry.is_file() and entry.suffix == ".json"}


def jpeg_size(path: Path) -> tuple[int, int]:
    with path.open("rb") as handle:
        if handle.read(2) != b"\xff\xd8":
            raise ValueError("missing JPEG SOI marker")
        while True:
            byte = handle.read(1)
            while byte == b"\xff":
                byte = handle.read(1)
            if not byte:
                raise ValueError("JPEG size marker not found")
            marker = byte[0]
            if marker in (0xD8, 0xD9):
                continue
            length_raw = handle.read(2)
            if len(length_raw) != 2:
                raise ValueError("truncated JPEG segment")
            length = struct.unpack(">H", length_raw)[0]
            if marker in {
                0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
                0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
            }:
                data = handle.read(5)
                if len(data) != 5:
                    raise ValueError("truncated JPEG SOF segment")
                height, width = struct.unpack(">HH", data[1:5])
                return width, height
            handle.seek(length - 2, 1)


def png_info(path: Path) -> tuple[int, int, int, int]:
    with path.open("rb") as handle:
        header = handle.read(29)
    if len(header) != 29 or header[:8] != b"\x89PNG\r\n\x1a\n" or header[12:16] != b"IHDR":
        raise ValueError("invalid PNG header")
    width, height, bit_depth, color_type = struct.unpack(">IIBB", header[16:26])
    return width, height, bit_depth, color_type


def shape_ok(value, rows: int, cols: int | None = None) -> bool:
    if not isinstance(value, list) or len(value) != rows:
        return False
    if cols is None:
        return True
    return all(isinstance(row, list) and len(row) == cols for row in value)


def validate_trajectory(
    scene_dir: Path,
    trajectory: str,
    resolution: tuple[int, int],
    errors: list[str],
    warnings: list[str],
) -> None:
    rgb_dir = scene_dir / "images" / trajectory
    depth_dir = scene_dir / "depths" / trajectory
    vis_dir = scene_dir / "depth_vis" / trajectory
    rgb_pattern = re.compile(rf"^{re.escape(trajectory)}_(\d{{6}})\.jpg$")
    depth_pattern = re.compile(
        rf"^{re.escape(trajectory)}_(\d{{6}})\.jpg\.geometric\.png$"
    )

    def numbered_files(path: Path, pattern: re.Pattern[str]) -> tuple[list[Path], list[int]]:
        files = sorted(entry for entry in path.iterdir() if entry.is_file())
        numbers = []
        for entry in files:
            match = pattern.match(entry.name)
            if match:
                numbers.append(int(match.group(1)))
        return files, numbers

    rgb_files, rgb_numbers = numbered_files(rgb_dir, rgb_pattern)
    depth_files, depth_numbers = numbered_files(depth_dir, depth_pattern)
    vis_files = sorted(entry for entry in vis_dir.iterdir() if entry.is_file())

    expected_numbers = list(range(1, 301))
    if len(rgb_files) != 300 or rgb_numbers != expected_numbers:
        errors.append(f"{scene_dir}/{trajectory}: RGB numbering/count is not 000001..000300")
    if len(depth_files) != 300 or depth_numbers != expected_numbers:
        errors.append(f"{scene_dir}/{trajectory}: depth numbering/count is not 000001..000300")
    if len(vis_files) != 300:
        errors.append(f"{scene_dir}/{trajectory}: expected 300 depth previews, found {len(vis_files)}")

    camera_path = scene_dir / "camera_params" / f"{trajectory}.json"
    try:
        with camera_path.open("r", encoding="utf-8") as handle:
            records = json.load(handle)
    except Exception as exc:
        errors.append(f"{camera_path}: cannot parse JSON: {exc}")
        return
    if not isinstance(records, list) or len(records) != 300:
        errors.append(f"{camera_path}: expected a 300-entry list")
        return

    timestamps = []
    image_names = set()
    for index, record in enumerate(records):
        missing = REQUIRED_CAMERA_FIELDS - set(record)
        if missing:
            errors.append(f"{camera_path}[{index}]: missing fields {sorted(missing)}")
            break
        timestamps.append(record["timestamp"])
        image_names.add(record["image_name"])
        if (record["width"], record["height"]) != resolution:
            errors.append(f"{camera_path}[{index}]: unexpected resolution")
            break
        if not shape_ok(record["w2c"], 4, 4):
            errors.append(f"{camera_path}[{index}]: w2c must be 4x4")
            break
        if not shape_ok(record["R"], 3, 3) or not shape_ok(record["T"], 3):
            errors.append(f"{camera_path}[{index}]: invalid R or T shape")
            break
    if any(b <= a for a, b in zip(timestamps, timestamps[1:])):
        errors.append(f"{camera_path}: timestamps are not strictly increasing")
    if len(image_names) == 1:
        warnings.append(f"{camera_path}: image_name is a constant source-camera identifier")

    if rgb_files:
        try:
            if jpeg_size(rgb_files[0]) != resolution:
                errors.append(f"{rgb_files[0]}: unexpected JPEG resolution")
        except Exception as exc:
            errors.append(f"{rgb_files[0]}: {exc}")
    if depth_files:
        try:
            width, height, bit_depth, color_type = png_info(depth_files[0])
            if (width, height) != resolution or bit_depth != 16 or color_type != 0:
                errors.append(
                    f"{depth_files[0]}: expected {resolution[0]}x{resolution[1]} "
                    "16-bit grayscale PNG"
                )
        except Exception as exc:
            errors.append(f"{depth_files[0]}: {exc}")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("root", type=Path, help="Real4D dataset root")
    parser.add_argument(
        "--full",
        action="store_true",
        help="scan all 3,084 trajectories; default samples three per scene",
    )
    args = parser.parse_args()
    root = args.root.resolve()
    errors: list[str] = []
    warnings: list[str] = []
    total_trajectories = 0

    for subset, subset_spec in EXPECTED.items():
        subset_dir = root / subset
        expected_scenes = set(subset_spec["scenes"])
        if not subset_dir.is_dir():
            errors.append(f"missing subset directory: {subset_dir}")
            continue
        actual_scenes = child_dirs(subset_dir)
        if actual_scenes != expected_scenes:
            errors.append(
                f"{subset}: scene mismatch; expected {sorted(expected_scenes)}, "
                f"found {sorted(actual_scenes)}"
            )

        for scene, expected_count in subset_spec["scenes"].items():
            scene_dir = subset_dir / scene
            required_dirs = ("images", "depths", "depth_vis", "camera_params", "video")
            missing_dirs = [name for name in required_dirs if not (scene_dir / name).is_dir()]
            if missing_dirs:
                errors.append(f"{scene_dir}: missing directories {missing_dirs}")
                continue

            image_trajectories = child_dirs(scene_dir / "images")
            depth_trajectories = child_dirs(scene_dir / "depths")
            vis_trajectories = child_dirs(scene_dir / "depth_vis")
            camera_trajectories = json_stems(scene_dir / "camera_params")
            total_trajectories += len(image_trajectories)

            if len(image_trajectories) != expected_count:
                errors.append(
                    f"{scene_dir}: expected {expected_count} trajectories, "
                    f"found {len(image_trajectories)}"
                )
            for label, values in (
                ("depths", depth_trajectories),
                ("depth_vis", vis_trajectories),
                ("camera_params", camera_trajectories),
            ):
                if values != image_trajectories:
                    errors.append(f"{scene_dir}: {label} trajectory set differs from images")

            videos = {entry.name for entry in (scene_dir / "video").iterdir() if entry.is_file()}
            missing_videos = [
                filename
                for trajectory in image_trajectories
                for filename in (f"{trajectory}_rgb.mp4", f"{trajectory}_depth.mp4")
                if filename not in videos
            ]
            if missing_videos:
                errors.append(
                    f"{scene_dir}: missing {len(missing_videos)} release preview videos; "
                    f"first={missing_videos[0]}"
                )

            ordered = sorted(image_trajectories)
            selected = ordered if args.full else sorted({ordered[0], ordered[len(ordered) // 2], ordered[-1]})
            for trajectory in selected:
                validate_trajectory(
                    scene_dir,
                    trajectory,
                    subset_spec["resolution"],
                    errors,
                    warnings,
                )
            print(
                f"checked {subset}/{scene}: {len(image_trajectories)} trajectories "
                f"({len(selected)} deeply scanned)"
            )

    if total_trajectories != 3084:
        errors.append(f"expected 3,084 total trajectories, found {total_trajectories}")

    if warnings:
        print(f"\nNotes ({len(warnings)}):")
        limit = len(warnings) if not args.full else min(10, len(warnings))
        for warning in warnings[:limit]:
            print(f"  - {warning}")
        if len(warnings) > limit:
            print(f"  - ... {len(warnings) - limit} identical notes omitted")

    if errors:
        print(f"\nFAILED with {len(errors)} error(s):", file=sys.stderr)
        for error in errors:
            print(f"  - {error}", file=sys.stderr)
        return 1

    mode = "full" if args.full else "quick"
    print(f"\nPASS: {mode} validation; {total_trajectories:,} trajectories found.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())