futurefantasy commited on
Commit
d0dcf0e
·
verified ·
1 Parent(s): babdd00

Add scripts/extract_vlac2_release_frames.py

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