futurefantasy commited on
Commit
c7a9ef3
·
verified ·
1 Parent(s): 6a65016

Update scripts/extract_vlac2_release_frames.py

Browse files
scripts/extract_vlac2_release_frames.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+ from concurrent.futures import ThreadPoolExecutor, as_completed
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import tqdm
14
+
15
+ SCRIPT_DIR = Path(__file__).resolve().parent
16
+ if str(SCRIPT_DIR) not in sys.path:
17
+ sys.path.insert(0, str(SCRIPT_DIR))
18
+
19
+ from vlac2_release_common import (
20
+ discover_benchmark_jsons,
21
+ dump_json,
22
+ ensure_generated_marker,
23
+ infer_main_path_from_row,
24
+ load_json,
25
+ normalize_main_path,
26
+ PORTABLE_IMAGE_ROOT,
27
+ resolve_benchmark_root,
28
+ )
29
+
30
+ try:
31
+ import cv2 # type: ignore
32
+ except ImportError:
33
+ cv2 = None
34
+
35
+ try:
36
+ import imageio.v2 as imageio # type: ignore
37
+ except ImportError:
38
+ imageio = None
39
+
40
+ try:
41
+ import av # type: ignore
42
+ except ImportError:
43
+ av = None
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class EpisodeSpec:
48
+ main_path: Path
49
+
50
+
51
+ def parse_args() -> argparse.Namespace:
52
+ parser = argparse.ArgumentParser(
53
+ description="Extract the portable VLAC2 release benchmark episodes into a JPG tree."
54
+ )
55
+ parser.add_argument(
56
+ "--data-root",
57
+ type=Path,
58
+ required=True,
59
+ help="Directory containing the extracted raw benchmark videos.",
60
+ )
61
+ parser.add_argument(
62
+ "--frames-root",
63
+ type=Path,
64
+ default=PORTABLE_IMAGE_ROOT,
65
+ help="Directory where extracted benchmark frames will be written. Defaults to _extracted_frames under the release directory.",
66
+ )
67
+ parser.add_argument(
68
+ "--benchmark-root",
69
+ type=Path,
70
+ default=None,
71
+ help="Directory containing benchmark JSON files. Defaults to the release-local benchmark directory.",
72
+ )
73
+ parser.add_argument(
74
+ "--benchmark-json",
75
+ action="append",
76
+ default=[],
77
+ type=Path,
78
+ help="Specific benchmark JSON file(s) to extract frames for. May be passed multiple times.",
79
+ )
80
+ parser.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 8) // 2))
81
+ parser.add_argument(
82
+ "--overwrite-existing",
83
+ action="store_true",
84
+ help="Re-extract even if an output manifest says the target episode-view is already complete.",
85
+ )
86
+ return parser.parse_args()
87
+
88
+
89
+ def bundled_release_root() -> Path:
90
+ return SCRIPT_DIR.parent.resolve()
91
+
92
+
93
+ def resolve_data_root(raw_arg: Path, release_root: Path) -> Path:
94
+ return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve()
95
+
96
+
97
+ def resolve_frames_root(raw_arg: Path, release_root: Path) -> Path:
98
+ return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve()
99
+
100
+
101
+ def resolve_benchmark_path(raw_arg: Path, release_root: Path) -> Path:
102
+ return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve()
103
+
104
+
105
+ def require_decoder() -> None:
106
+ if cv2 is None and imageio is None and av is None:
107
+ raise SystemExit(
108
+ "No video decoder available. Install opencv-python, PyAV, or imageio before running frame extraction."
109
+ )
110
+
111
+
112
+ def benchmark_files_from_root(benchmark_root: Path) -> list[Path]:
113
+ files = discover_benchmark_jsons(benchmark_root)
114
+ if not files:
115
+ raise SystemExit(f"No benchmark json found under {benchmark_root}")
116
+ return files
117
+
118
+
119
+ def benchmark_files_from_args(args: argparse.Namespace, release_root: Path) -> tuple[list[Path], Path | None]:
120
+ if args.benchmark_json:
121
+ benchmark_paths: list[Path] = []
122
+ seen: set[Path] = set()
123
+ for raw_path in args.benchmark_json:
124
+ path = resolve_benchmark_path(raw_path, release_root)
125
+ if not path.exists():
126
+ raise SystemExit(f"Missing benchmark json: {path}")
127
+ if not path.is_file():
128
+ raise SystemExit(f"Expected benchmark json file, got directory: {path}")
129
+ resolved = path.resolve()
130
+ if resolved in seen:
131
+ continue
132
+ seen.add(resolved)
133
+ benchmark_paths.append(resolved)
134
+ if not benchmark_paths:
135
+ raise SystemExit("No benchmark json provided")
136
+ return benchmark_paths, None
137
+
138
+ if args.benchmark_root is not None:
139
+ benchmark_root = resolve_benchmark_path(args.benchmark_root, release_root)
140
+ else:
141
+ benchmark_root = resolve_benchmark_root(release_root)
142
+ return benchmark_files_from_root(benchmark_root), benchmark_root
143
+
144
+
145
+ def episode_group_key(main_path: Path) -> str:
146
+ parts = list(main_path.parts)
147
+ for idx, part in enumerate(parts):
148
+ if part.startswith("observation.images.") and idx + 1 < len(parts):
149
+ return str(Path(*parts[:idx], parts[idx + 1]))
150
+ return str(main_path)
151
+
152
+
153
+ def collect_episode_specs(benchmark_paths: list[Path]) -> tuple[list[EpisodeSpec], dict[str, Any]]:
154
+ grouped: dict[str, tuple[Path, set[str]]] = {}
155
+ stats = {
156
+ "benchmark_files_total": len(benchmark_paths),
157
+ "rows_total": 0,
158
+ "rows_missing_main_path": 0,
159
+ }
160
+
161
+ for benchmark_path in benchmark_paths:
162
+ rows = load_json(benchmark_path)
163
+ if not isinstance(rows, list):
164
+ raise ValueError(f"Expected list json: {benchmark_path}")
165
+ stats["rows_total"] += len(rows)
166
+ for row in rows:
167
+ inferred_main_path = infer_main_path_from_row(row)
168
+ if inferred_main_path is None:
169
+ stats["rows_missing_main_path"] += 1
170
+ continue
171
+ normalized = normalize_main_path(inferred_main_path)
172
+ key = episode_group_key(normalized)
173
+ if key not in grouped:
174
+ grouped[key] = (normalized, {str(benchmark_path)})
175
+ else:
176
+ grouped[key][1].add(str(benchmark_path))
177
+
178
+ specs = [
179
+ EpisodeSpec(main_path=main_path)
180
+ for _group_key, (main_path, _sources) in sorted(grouped.items())
181
+ ]
182
+ stats["episodes_unique"] = len(specs)
183
+ return specs, stats
184
+
185
+
186
+ def resolve_main_video(raw_root: Path, main_path: Path) -> Path:
187
+ candidate = raw_root / main_path
188
+ if candidate.suffix == ".mp4":
189
+ return candidate
190
+
191
+ # Keep the full main_path leaf intact when appending ".mp4" so episode
192
+ # identifiers containing dots (for example timestamps like "....311186")
193
+ # are not truncated. Fall back to with_suffix(".mp4") for compatibility
194
+ # with any legacy raw layouts that already dropped the tail suffix.
195
+ preferred = Path(f"{candidate}.mp4")
196
+ legacy = candidate.with_suffix(".mp4")
197
+ if preferred.exists() or preferred == legacy:
198
+ return preferred
199
+ if legacy.exists():
200
+ return legacy
201
+ return preferred
202
+
203
+
204
+ def discover_view_videos(raw_root: Path, main_path: Path) -> list[Path]:
205
+ main_video = resolve_main_video(raw_root, main_path)
206
+ if not main_video.exists():
207
+ raise FileNotFoundError(f"Missing raw video: {main_video}")
208
+ return [main_video]
209
+
210
+
211
+ def manifest_path_for(output_dir: Path) -> Path:
212
+ return output_dir / ".vlac_extract_manifest.json"
213
+
214
+
215
+ def output_dir_from_video(raw_root: Path, output_root: Path, video_path: Path) -> Path:
216
+ relative = video_path.relative_to(raw_root).with_suffix("")
217
+ return output_root / relative
218
+
219
+
220
+ def is_complete(output_dir: Path, source_video: Path) -> bool:
221
+ manifest_path = manifest_path_for(output_dir)
222
+ if not manifest_path.exists():
223
+ return False
224
+ try:
225
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
226
+ except Exception:
227
+ return False
228
+
229
+ frame_count = int(manifest.get("frame_count") or 0)
230
+ if frame_count <= 0:
231
+ return False
232
+ source_mtime_ns = int(source_video.stat().st_mtime_ns)
233
+ source_size = int(source_video.stat().st_size)
234
+ if int(manifest.get("source_mtime_ns") or -1) != source_mtime_ns:
235
+ return False
236
+ if int(manifest.get("source_size") or -1) != source_size:
237
+ return False
238
+
239
+ jpg_files = sorted(output_dir.glob("*.jpg"))
240
+ return len(jpg_files) == frame_count
241
+
242
+
243
+ def clear_output_dir(output_dir: Path) -> None:
244
+ if not output_dir.exists():
245
+ return
246
+ for pattern in ("*.jpg", "frame_*.jpg", ".vlac_extract_manifest.json"):
247
+ for path in output_dir.glob(pattern):
248
+ if path.is_file():
249
+ path.unlink()
250
+
251
+
252
+ def write_manifest(output_dir: Path, source_video: Path, frame_count: int) -> None:
253
+ manifest = {
254
+ "source_video": str(source_video),
255
+ "source_size": int(source_video.stat().st_size),
256
+ "source_mtime_ns": int(source_video.stat().st_mtime_ns),
257
+ "frame_count": int(frame_count),
258
+ }
259
+ manifest_path_for(output_dir).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
260
+
261
+
262
+ def extract_with_cv2(source_video: Path, output_dir: Path) -> int:
263
+ assert cv2 is not None
264
+ capture = cv2.VideoCapture(str(source_video))
265
+ if not capture.isOpened():
266
+ raise RuntimeError(f"cv2 failed to open {source_video}")
267
+
268
+ temp_paths: list[Path] = []
269
+ frame_idx = 0
270
+ try:
271
+ while True:
272
+ ok, frame = capture.read()
273
+ if not ok:
274
+ break
275
+ temp_path = output_dir / f"frame_{frame_idx:06d}.jpg"
276
+ if not cv2.imwrite(str(temp_path), frame):
277
+ raise RuntimeError(f"cv2 failed to write {temp_path}")
278
+ temp_paths.append(temp_path)
279
+ frame_idx += 1
280
+ finally:
281
+ capture.release()
282
+
283
+ for idx, temp_path in enumerate(temp_paths):
284
+ temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg")
285
+ return frame_idx
286
+
287
+
288
+ def extract_with_imageio(source_video: Path, output_dir: Path) -> int:
289
+ assert imageio is not None
290
+ temp_paths: list[Path] = []
291
+ frame_idx = 0
292
+ try:
293
+ for frame in imageio.get_reader(str(source_video)):
294
+ temp_path = output_dir / f"frame_{frame_idx:06d}.jpg"
295
+ imageio.imwrite(str(temp_path), frame)
296
+ temp_paths.append(temp_path)
297
+ frame_idx += 1
298
+ except Exception as exc:
299
+ if frame_idx == 0:
300
+ raise RuntimeError(f"imageio failed to decode {source_video}: {exc}") from exc
301
+ raise
302
+ for idx, temp_path in enumerate(temp_paths):
303
+ temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg")
304
+ return frame_idx
305
+
306
+
307
+ def extract_with_av(source_video: Path, output_dir: Path) -> int:
308
+ assert av is not None
309
+ container = av.open(str(source_video))
310
+ temp_paths: list[Path] = []
311
+ frame_idx = 0
312
+ try:
313
+ for frame in container.decode(video=0):
314
+ temp_path = output_dir / f"frame_{frame_idx:06d}.jpg"
315
+ frame.to_image().save(temp_path, format="JPEG")
316
+ temp_paths.append(temp_path)
317
+ frame_idx += 1
318
+ finally:
319
+ container.close()
320
+
321
+ for idx, temp_path in enumerate(temp_paths):
322
+ temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg")
323
+ return frame_idx
324
+
325
+
326
+ def extract_one_video(source_video: Path, output_dir: Path, overwrite_existing: bool) -> dict[str, Any]:
327
+ if not overwrite_existing and is_complete(output_dir, source_video):
328
+ manifest = json.loads(manifest_path_for(output_dir).read_text(encoding="utf-8"))
329
+ return {
330
+ "source_video": str(source_video),
331
+ "output_dir": str(output_dir),
332
+ "frame_count": int(manifest["frame_count"]),
333
+ "status": "skipped_existing",
334
+ }
335
+
336
+ output_dir.mkdir(parents=True, exist_ok=True)
337
+ clear_output_dir(output_dir)
338
+ if cv2 is not None:
339
+ frame_count = extract_with_cv2(source_video, output_dir)
340
+ if frame_count == 0 and av is not None:
341
+ clear_output_dir(output_dir)
342
+ frame_count = extract_with_av(source_video, output_dir)
343
+ if frame_count == 0 and imageio is not None:
344
+ clear_output_dir(output_dir)
345
+ frame_count = extract_with_imageio(source_video, output_dir)
346
+ elif av is not None:
347
+ frame_count = extract_with_av(source_video, output_dir)
348
+ elif imageio is not None:
349
+ frame_count = extract_with_imageio(source_video, output_dir)
350
+ else:
351
+ raise RuntimeError("No available decoder")
352
+ if frame_count <= 0:
353
+ raise RuntimeError(f"Decoder produced zero frames for {source_video}")
354
+ write_manifest(output_dir, source_video, frame_count)
355
+ return {
356
+ "source_video": str(source_video),
357
+ "output_dir": str(output_dir),
358
+ "frame_count": frame_count,
359
+ "status": "extracted",
360
+ }
361
+
362
+
363
+
364
+
365
+ def main() -> None:
366
+ args = parse_args()
367
+ require_decoder()
368
+
369
+ release_root = bundled_release_root()
370
+ data_root = resolve_data_root(args.data_root, release_root)
371
+ output_root = resolve_frames_root(args.frames_root, release_root)
372
+ ensure_generated_marker(output_root)
373
+ benchmark_paths, benchmark_root = benchmark_files_from_args(args, release_root)
374
+
375
+ specs, stats = collect_episode_specs(benchmark_paths)
376
+ jobs: list[tuple[Path, Path]] = []
377
+ missing_raw_episodes: list[dict[str, str]] = []
378
+ for spec in specs:
379
+ try:
380
+ view_videos = discover_view_videos(data_root, spec.main_path)
381
+ except FileNotFoundError as exc:
382
+ missing_raw_episodes.append(
383
+ {
384
+ "main_path": str(spec.main_path),
385
+ "error": str(exc),
386
+ }
387
+ )
388
+ continue
389
+ for video_path in view_videos:
390
+ jobs.append((video_path, output_dir_from_video(data_root, output_root, video_path)))
391
+
392
+ results: list[dict[str, Any]] = []
393
+ with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as executor:
394
+ future_to_job = {
395
+ executor.submit(extract_one_video, video_path, output_dir, args.overwrite_existing): (video_path, output_dir)
396
+ for video_path, output_dir in jobs
397
+ }
398
+ for future in tqdm.tqdm(as_completed(future_to_job), total=len(future_to_job), desc="Extract release frames"):
399
+ video_path, output_dir = future_to_job[future]
400
+ try:
401
+ results.append(future.result())
402
+ except Exception as exc:
403
+ results.append(
404
+ {
405
+ "source_video": str(video_path),
406
+ "output_dir": str(output_dir),
407
+ "status": "error",
408
+ "error": str(exc),
409
+ }
410
+ )
411
+
412
+ summary = {
413
+ **stats,
414
+ "release_root": str(release_root),
415
+ "benchmark_root": str(benchmark_root) if benchmark_root is not None else None,
416
+ "data_root": str(data_root),
417
+ "output_root": str(output_root),
418
+ "benchmark_files": [str(path) for path in benchmark_paths],
419
+ "jobs_total": len(jobs),
420
+ "jobs_extracted": sum(1 for row in results if row["status"] == "extracted"),
421
+ "jobs_skipped_existing": sum(1 for row in results if row["status"] == "skipped_existing"),
422
+ "jobs_failed": sum(1 for row in results if row["status"] == "error"),
423
+ "missing_raw_episodes": missing_raw_episodes,
424
+ "results": results,
425
+ }
426
+ summary_path = output_root / "frame_extraction_summary.json"
427
+ dump_json(summary_path, summary)
428
+ print(f"[frame-extraction] {summary_path}")
429
+
430
+
431
+ if __name__ == "__main__":
432
+ main()