File size: 7,809 Bytes
7f79b39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reconstruct labeled PhysicalAI-Event-Videos chunks from downloaded parents."""

from __future__ import annotations

import argparse
import concurrent.futures
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path


VIDEO_SUFFIXES = {".avi", ".mkv", ".mov", ".mp4", ".webm"}


def safe_part(value: object, field: str) -> str:
    text = str(value or "")
    if not text or text in {".", ".."} or Path(text).name != text:
        raise ValueError(f"unsafe {field}: {text!r}")
    return text


def parent_basename(record: dict) -> str:
    source = record.get("source_video") or {}
    for value in (
        record.get("video_path"),
        source.get("path"),
        source.get("repository_path"),
        source.get("archive_member"),
    ):
        if value:
            return Path(str(value)).name
    raise ValueError(f"no parent-video path for {record.get('dataset')}/{record.get('video_id')}")


def index_parents(root: Path, wanted: set[str]) -> tuple[dict[str, Path], dict[str, list[Path]]]:
    found: dict[str, Path] = {}
    duplicates: dict[str, list[Path]] = {}
    for path in root.rglob("*"):
        if not path.is_file() or path.suffix.lower() not in VIDEO_SUFFIXES or path.name not in wanted:
            continue
        if path.name in found:
            duplicates.setdefault(path.name, [found[path.name]]).append(path)
        else:
            found[path.name] = path
    return found, duplicates


def probe(path: Path, ffprobe: str, expected_duration: float) -> tuple[bool, str]:
    proc = subprocess.run(
        [
            ffprobe, "-v", "error", "-show_entries",
            "format=duration:stream=codec_name,pix_fmt", "-of", "json", str(path),
        ],
        capture_output=True,
        text=True,
    )
    if proc.returncode:
        return False, proc.stderr.strip()[-300:]
    try:
        data = json.loads(proc.stdout)
        duration = float(data["format"]["duration"])
        video = next(stream for stream in data["streams"] if stream.get("codec_name"))
    except (KeyError, StopIteration, TypeError, ValueError, json.JSONDecodeError) as exc:
        return False, f"invalid ffprobe output: {exc}"
    if abs(duration - expected_duration) > 0.10:
        return False, f"duration {duration:.3f}s != {expected_duration:.3f}s"
    if video.get("codec_name") != "h264" or video.get("pix_fmt") != "yuv420p":
        return False, f"unexpected video format {video.get('codec_name')}/{video.get('pix_fmt')}"
    return True, ""


def encode(job: tuple[Path, Path, float, float], ffmpeg: str, ffprobe: str, force: bool) -> tuple[Path, str]:
    source, output, start, end = job
    duration = end - start
    if output.exists() and not force:
        valid, _ = probe(output, ffprobe, duration)
        if valid:
            return output, "skipped"

    output.parent.mkdir(parents=True, exist_ok=True)
    temporary = output.with_name(output.name + ".part.mp4")
    temporary.unlink(missing_ok=True)
    proc = subprocess.run(
        [
            ffmpeg, "-nostdin", "-hide_banner", "-loglevel", "error", "-y",
            "-ss", f"{start:.6f}", "-i", str(source), "-t", f"{duration:.6f}",
            "-c:v", "libx264", "-preset", "fast", "-crf", "23",
            "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-an", str(temporary),
        ],
        capture_output=True,
        text=True,
    )
    if proc.returncode:
        temporary.unlink(missing_ok=True)
        raise RuntimeError(f"ffmpeg failed for {source}: {proc.stderr.strip()[-400:]}")
    valid, error = probe(temporary, ffprobe, duration)
    if not valid:
        temporary.unlink(missing_ok=True)
        raise RuntimeError(f"validation failed for {source}: {error}")
    os.replace(temporary, output)
    return output, "written"


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--labels", required=True, type=Path)
    parser.add_argument("--videos-dir", required=True, type=Path)
    parser.add_argument("--output-dir", required=True, type=Path)
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--dataset", action="append", help="Process only this dataset; repeatable.")
    parser.add_argument("--dry-run", action="store_true", help="Resolve inputs and outputs without encoding.")
    parser.add_argument("--force", action="store_true", help="Replace valid existing chunks.")
    args = parser.parse_args()

    if args.workers < 1:
        parser.error("--workers must be at least 1")
    labels = json.loads(args.labels.read_text(encoding="utf-8"))
    selected = set(args.dataset or [])
    records = [record for record in labels if not selected or record.get("dataset") in selected]
    if selected - {record.get("dataset") for record in labels}:
        parser.error(f"unknown dataset(s): {sorted(selected - {r.get('dataset') for r in labels})}")

    wanted = {parent_basename(record) for record in records}
    parents, duplicates = index_parents(args.videos_dir, wanted)
    if duplicates:
        for name, paths in sorted(duplicates.items())[:10]:
            print(f"duplicate parent basename {name}: {', '.join(map(str, paths))}", file=sys.stderr)
        return 2

    jobs: list[tuple[Path, Path, float, float]] = []
    missing: list[str] = []
    for record in records:
        dataset = safe_part(record.get("dataset"), "dataset")
        video_id = safe_part(record.get("video_id"), "video_id")
        basename = parent_basename(record)
        source = parents.get(basename)
        if source is None:
            missing.append(basename)
            continue
        for chunk in record.get("chunks", []):
            chunk_file = safe_part(
                chunk.get("chunk_file") or f"chunk_{int(chunk['chunk_index']):03d}.mp4",
                "chunk_file",
            )
            start = float(chunk["start_time_sec"])
            end = float(chunk["end_time_sec"])
            if start < 0 or end <= start:
                raise ValueError(f"invalid interval {start}..{end} for {dataset}/{video_id}/{chunk_file}")
            jobs.append((source, args.output_dir / dataset / video_id / chunk_file, start, end))

    if missing:
        print(f"missing {len(missing)} parent videos; examples: {', '.join(sorted(missing)[:10])}", file=sys.stderr)
        return 2
    if len({job[1] for job in jobs}) != len(jobs):
        raise RuntimeError("duplicate output chunk paths")

    print(f"resolved {len(records):,} parent videos and {len(jobs):,} labeled chunks")
    if args.dry_run:
        print("dry run passed; no files written")
        return 0

    ffmpeg = shutil.which("ffmpeg")
    ffprobe = shutil.which("ffprobe")
    if not ffmpeg or not ffprobe:
        print("ffmpeg and ffprobe must both be available on PATH", file=sys.stderr)
        return 2

    counts = {"written": 0, "skipped": 0}
    failures: list[str] = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as pool:
        futures = [pool.submit(encode, job, ffmpeg, ffprobe, args.force) for job in jobs]
        for index, future in enumerate(concurrent.futures.as_completed(futures), 1):
            try:
                _, status = future.result()
                counts[status] += 1
            except Exception as exc:  # keep processing independent clips
                failures.append(str(exc))
            if index % 100 == 0 or index == len(futures):
                print(f"processed {index:,}/{len(futures):,}")

    print(f"written {counts['written']:,}; skipped {counts['skipped']:,}; failed {len(failures):,}")
    for failure in failures[:10]:
        print(f"ERROR: {failure}", file=sys.stderr)
    return 1 if failures else 0


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