File size: 23,365 Bytes
2e6f68f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#!/usr/bin/env python3
"""Convert prompt JSONL into sensor CSVs, cropped videos and OmniTS metadata.

Supported video domains include CoVLA, AgiBot, CUHK-X, Future Factories and
HoloAssist. Intermediate outputs may use local paths; package_release.py
copies referenced assets and writes relative paths for distribution.
Video stream copying preserves the original pipeline's keyframe behavior.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import shutil
import subprocess
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path

import pandas as pd

from probe import probe_ts_shape, probe_video_meta

TS_BLOCK_RE = re.compile(r"<timeseries>(.*?)</timeseries>", re.DOTALL)
DATA_LINE_RE = re.compile(r"^[\d.]+:\s*(.+)$")
TEMPORAL_FIELD_KEYS = ("frames", "segment", "start_frame", "end_frame", "start", "end")


def safe_filename_component(value: str) -> str:
    safe_value = re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("_")
    return safe_value or "unknown"


def source_cache_key(value: str) -> str:
    return hashlib.sha1(value.encode("utf-8")).hexdigest()[:10]


def stable_video_id(entry: dict, dataset_name: str) -> str:
    """Use existing video_id when present; otherwise create a stable trace id."""
    existing = entry.get("video_id")
    if existing:
        return safe_filename_component(str(existing))

    identity = {
        "dataset": dataset_name,
        "task_id": entry.get("task_id"),
        "video_path": entry.get("video_path"),
        "frames": entry.get("frames"),
        "segment": entry.get("segment"),
        "start_frame": entry.get("start_frame"),
        "end_frame": entry.get("end_frame"),
        "start": entry.get("start"),
        "end": entry.get("end"),
    }
    digest = source_cache_key(json.dumps(identity, sort_keys=True, ensure_ascii=False))
    task_id = safe_filename_component(str(entry.get("task_id", "no_task_id")))
    dataset_part = safe_filename_component(dataset_name)
    return f"{dataset_part}_{task_id}_{digest}"


def has_temporal_bounds(entry: dict) -> bool:
    """Return True when a row has the temporal fields used by video preprocessing."""
    if entry.get("frames") is not None or entry.get("segment") is not None:
        return True
    if entry.get("start_frame") is not None and entry.get("end_frame") is not None:
        return True
    return entry.get("start") is not None and entry.get("end") is not None


def has_frame_bounds(entry: dict) -> bool:
    """Frame bounds take priority over time bounds, as in preprocess_video_segments."""
    if isinstance(entry.get("frames"), dict):
        return True
    return entry.get("start_frame") is not None and entry.get("end_frame") is not None


def extract_frame_bounds(entry: dict) -> tuple[int, int]:
    """Extract [start_frame, end_frame] from ``frames`` or top-level fields."""
    frames = entry.get("frames")
    if isinstance(frames, dict):
        start = int(frames.get("start_frame", entry.get("start_frame", 0)))
        end = int(frames.get("end_frame", entry.get("end_frame", 0)))
    else:
        start = int(entry.get("start_frame", 0))
        end = int(entry.get("end_frame", 0))
    if end < start:
        raise ValueError(f"invalid frame range: start={start}, end={end}")
    return start, end


def extract_time_bounds(entry: dict) -> tuple[float, float]:
    """Extract [start, end] seconds from ``segment`` or top-level fields."""
    segment = entry.get("segment")
    if isinstance(segment, dict):
        start = segment.get("start")
        end = segment.get("end")
        if start is not None and end is not None:
            start = float(start)
            end = float(end)
            if end < start:
                raise ValueError(f"invalid time range: start={start}, end={end}")
            return start, end

    start = entry.get("start")
    end = entry.get("end")
    if start is not None and end is not None:
        start = float(start)
        end = float(end)
        if end < start:
            raise ValueError(f"invalid time range: start={start}, end={end}")
        return start, end

    raise KeyError("no valid time bounds found")


def _video_meta_dict(meta) -> dict | None:
    """Shape the 5-tuple from probe_video_meta into the jsonl dict form."""
    if meta is None:
        return None
    w, h, sfps, nf, dur = meta
    return {
        "width": int(w), "height": int(h),
        "source_fps": float(sfps),
        "nb_frames": int(nf),
        "duration": float(dur),
    }


def parse_timeseries_data_line(line: str) -> dict[str, float] | None:
    """Parse one prompt timeseries row into numeric channel values.

    Supported prompt row shapes:
      * ``12.345: x=1, y=2`` used by CoVLA/Holo/AgiBot/CUHK-X
      * ``2023-...Z, x=1, y=2`` used by Future Factories
    """
    stripped = line.strip()
    if not stripped:
        return None

    m = DATA_LINE_RE.match(stripped)
    if m:
        kv_part = m.group(1)
    elif "," in stripped:
        timestamp, kv_part = stripped.split(",", 1)
        if not re.fullmatch(r"\d{4}-\d{2}-\d{2}(?:[T ].+)?", timestamp.strip()):
            return None
    else:
        return None

    if "..." in kv_part:
        return None

    row: dict[str, float] = {}
    for pair in kv_part.split(","):
        if "=" not in pair:
            continue
        k, v = pair.split("=", 1)
        k, v = k.strip(), v.strip()
        if not k:
            continue
        if v in ("null", "None", "nan", "NaN", ""):
            row[k] = float("nan")
        else:
            row[k] = float(v)
    return row or None


def parse_timeseries_block(text: str) -> pd.DataFrame:
    """Extract numeric rows from a <timeseries>...</timeseries> block into a DataFrame.

    Each data line looks like: "25.5: vEgo=6.517, aEgo=0.197, ..., lead_a=null".
    Returns a DataFrame with one column per variable; "null" or empty becomes NaN.
    """
    match = TS_BLOCK_RE.search(text)
    if not match:
        raise ValueError("no <timeseries> block found")
    body = match.group(1)

    records: list[dict[str, float]] = []
    for line in body.splitlines():
        row = parse_timeseries_data_line(line)
        if row:
            records.append(row)

    if not records:
        raise ValueError("<timeseries> block had no data rows")

    return pd.DataFrame.from_records(records)


def probe_video_fps(video_path: Path) -> float:
    """Use ffprobe to read the source video's avg_frame_rate as a float."""
    result = subprocess.run(
        [
            "ffprobe", "-v", "error", "-select_streams", "v:0",
            "-show_entries", "stream=avg_frame_rate",
            "-of", "default=nw=1:nk=1",
            str(video_path),
        ],
        capture_output=True, text=True, check=True,
    )
    num, den = result.stdout.strip().split("/")
    num_f, den_f = float(num), float(den)
    if den_f == 0:
        return 0.0
    return num_f / den_f


def probe_video_frame_count(video_path: Path) -> int:
    """Use ffprobe to estimate total frames for whole-clip conversion."""
    meta = probe_video_meta(str(video_path))
    if meta is None:
        return 0
    _width, _height, source_fps, nb_frames, duration = meta
    if nb_frames > 0:
        return int(nb_frames)
    if source_fps > 0 and duration > 0:
        return max(1, int(duration * source_fps))
    return 0


def get_video_fps(src_video: Path, fps_cache: dict[Path, float]) -> float:
    """Read and cache source fps for frame/time conversion."""
    if src_video not in fps_cache:
        fps_cache[src_video] = probe_video_fps(src_video)
    fps = fps_cache[src_video]
    if fps <= 0:
        raise RuntimeError(f"could not probe fps for {src_video}")
    return fps


def time_to_frame_bounds(start_time: float, end_time: float, fps: float) -> tuple[int, int]:
    """Convert seconds to inclusive frame bounds, matching preprocess_video_segments."""
    if fps <= 0:
        raise RuntimeError(f"cannot convert time bounds with invalid fps={fps}")
    start_frame = max(0, int(start_time * fps))
    end_frame = max(start_frame, int(end_time * fps))
    return start_frame, end_frame


def resolve_frame_bounds(
    entry: dict,
    src_video: Path,
    fps_cache: dict[Path, float],
) -> tuple[int, int]:
    """Resolve supported temporal fields into inclusive frame bounds.

    ``preprocess_video_segments.py`` accepts both frame fields and time fields.
    This converter keeps the same precedence: explicit frame bounds are used
    directly; otherwise ``segment`` / ``start`` / ``end`` are converted through
    the source video's fps.
    """
    if has_frame_bounds(entry):
        return extract_frame_bounds(entry)

    if has_temporal_bounds(entry):
        start_sec, end_sec = extract_time_bounds(entry)
        fps = get_video_fps(src_video, fps_cache)
        return time_to_frame_bounds(start_sec, end_sec, fps)

    total_frames = probe_video_frame_count(src_video)
    if total_frames <= 0:
        raise KeyError(
            "no temporal bounds found and failed to probe whole-video frame count; "
            "expected frames, segment, start_frame/end_frame, or start/end"
        )
    return 0, total_frames - 1


def frame_bounds_to_seconds(
    start_frame: int,
    end_frame: int,
    src_video: Path,
    fps_cache: dict[Path, float],
) -> tuple[float, float]:
    """Convert inclusive frame bounds to ffmpeg -ss / -t seconds."""
    fps = get_video_fps(src_video, fps_cache)
    start_sec = start_frame / fps
    duration_sec = max(1e-3, (end_frame - start_frame + 1) / fps)
    return start_sec, duration_sec


def slice_video(src: Path, dst: Path, start_sec: float, duration_sec: float) -> None:
    """Copy a segment with -c copy (stream copy, near-instant). Overwrites dst.

    Caveat: `-ss` before `-i` with `-c copy` seeks to the nearest keyframe, so
    clip start may be offset by up to the GOP length (typically ≤ 1s). For
    video-QA training on multi-second segments this is acceptable.
    """
    dst.parent.mkdir(parents=True, exist_ok=True)
    if shutil.which("ffmpeg") is None:
        raise RuntimeError("ffmpeg not found on PATH")
    cmd = [
        "ffmpeg", "-y", "-loglevel", "error",
        "-ss", f"{start_sec:.3f}",
        "-i", str(src),
        "-t", f"{duration_sec:.3f}",
        "-an",
        "-c", "copy",
        "-avoid_negative_ts", "make_zero",
        str(dst),
    ]
    subprocess.run(cmd, check=True, capture_output=True)


def convert_entry(
    entry: dict,
    csv_dir: Path,
    clip_dir: Path,
    fps_cache: dict[Path, float],
    prompt_only: bool = False,
    dataset_name: str = "dataset",
    copy_full_video: bool = True,
) -> dict:
    """Convert one CoVLA row into the unified OmniTS row.

    Returns: ``{video_id, video_path, timeseries_path, prompt, answer}`` where
    ``prompt`` retains the inline ``<timeseries>...</timeseries>`` body.

    ``prompt_only=True`` skips TS-CSV writing and video slicing. The derived
    paths must already exist on disk. Use this to refresh prompts after the
    source prompt text changes without re-running the expensive work.
    """
    csv_dir = Path(csv_dir).resolve()
    clip_dir = Path(clip_dir).resolve()
    if not prompt_only:
        csv_dir.mkdir(parents=True, exist_ok=True)
        clip_dir.mkdir(parents=True, exist_ok=True)

    video_id = stable_video_id(entry, dataset_name)
    src_video = Path(entry["video_path"]).expanduser().resolve()
    start_frame, end_frame = resolve_frame_bounds(
        entry=entry,
        src_video=src_video,
        fps_cache=fps_cache,
    )

    # 1. Time-series CSV. In prompt-only mode we read the shape from the
    # existing file; in fresh mode we use the in-memory DataFrame's shape
    # directly (no extra IO).
    csv_name = f"{video_id}_{start_frame}_{end_frame}.csv"
    csv_path = csv_dir / csv_name
    if prompt_only:
        if not csv_path.exists():
            raise FileNotFoundError(f"prompt-only mode: missing csv {csv_path}")
        ts_shape = probe_ts_shape(str(csv_path))
    else:
        df = parse_timeseries_block(entry["prompt"])
        df.to_csv(csv_path, index=False)
        ts_shape = (int(df.shape[0]), int(df.shape[1]))

    # 2. Video clip (ffmpeg-sliced). Reuse if it already exists.
    clip_name = f"{video_id}_{start_frame}_{end_frame}.mp4"
    clip_path = clip_dir / clip_name
    if prompt_only:
        if not (clip_path.exists() and clip_path.stat().st_size > 0):
            raise FileNotFoundError(f"prompt-only mode: missing clip {clip_path}")
    elif not (clip_path.exists() and clip_path.stat().st_size > 0):
        if copy_full_video and not has_temporal_bounds(entry):
            clip_path.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(src_video, clip_path)
        else:
            start_sec, duration_sec = frame_bounds_to_seconds(
                start_frame=start_frame,
                end_frame=end_frame,
                src_video=src_video,
                fps_cache=fps_cache,
            )
            slice_video(src_video, clip_path, start_sec, duration_sec)

    # 2b. Probe the sliced clip for the meta that `compute_exact_lengths`
    # needs — same whether we just wrote it or are reusing an existing clip.
    video_meta = _video_meta_dict(probe_video_meta(str(clip_path)))

    # 3. Unified row — prompt retains inline TS body; baseline uses it as-is,
    # omnits strips it in the collator via strip_ts_block(). video_meta /
    # ts_shape are optional hints consumed by the length estimator.
    row: dict = {
        "video_id": video_id,
        "video_path": str(clip_path),
        "timeseries_path": str(csv_path),
        "prompt": entry["prompt"],
        "answer": entry["ground_truth"],
    }
    if video_meta is not None:
        row["video_meta"] = video_meta
    if ts_shape is not None:
        row["ts_shape"] = [int(ts_shape[0]), int(ts_shape[1])]
    return row


def _worker_convert(args: tuple[dict, str, str, bool, str, bool]) -> tuple[int, dict]:
    """Worker for ProcessPoolExecutor: convert a single entry.

    Returns (line_no, row). fps_cache is per-worker (no sharing).
    """
    entry, csv_dir, clip_dir, prompt_only, dataset_name, copy_full_video = args
    line_no = entry["_line_no"]
    _entry = {k: v for k, v in entry.items() if k != "_line_no"}
    row = convert_entry(
        _entry, csv_dir=Path(csv_dir), clip_dir=Path(clip_dir),
        fps_cache={}, prompt_only=prompt_only, dataset_name=dataset_name,
        copy_full_video=copy_full_video,
    )
    return line_no, row


def _annotate_only(jsonl_path: Path, num_workers: int, force: bool) -> None:
    """Backfill video_meta / ts_shape into an existing unified OmniTS jsonl.

    Use when clips + csvs already exist on disk and you only need the meta
    fields added. Rewrites `jsonl_path` in place via .tmp + rename. Skips
    rows that already have both fields unless --force is passed."""
    with jsonl_path.open() as f:
        rows = [json.loads(l) for l in f if l.strip()]
    print(f"[ANNOTATE] loaded {len(rows)} rows from {jsonl_path}")

    v_todo = [
        i for i, r in enumerate(rows)
        if force or not isinstance(r.get("video_meta"), dict)
    ]
    t_todo = [
        i for i, r in enumerate(rows)
        if r.get("timeseries_path") and
           (force or not isinstance(r.get("ts_shape"), (list, tuple)))
    ]
    print(f"[ANNOTATE] to probe: {len(v_todo)} videos, {len(t_todo)} TS csvs "
          f"(workers={num_workers})")

    if v_todo:
        done = 0
        with ProcessPoolExecutor(max_workers=num_workers) as pool:
            futs = {pool.submit(probe_video_meta, rows[i]["video_path"]): i for i in v_todo}
            for fut in as_completed(futs):
                i = futs[fut]
                vm = _video_meta_dict(fut.result())
                if vm is not None:
                    rows[i]["video_meta"] = vm
                done += 1
                if done % 1000 == 0:
                    print(f"[ANNOTATE]   video {done}/{len(v_todo)}", flush=True)

    if t_todo:
        done = 0
        with ProcessPoolExecutor(max_workers=num_workers) as pool:
            futs = {pool.submit(probe_ts_shape, rows[i]["timeseries_path"]): i for i in t_todo}
            for fut in as_completed(futs):
                i = futs[fut]
                shape = fut.result()
                if shape is not None:
                    rows[i]["ts_shape"] = [int(shape[0]), int(shape[1])]
                done += 1
                if done % 2000 == 0:
                    print(f"[ANNOTATE]   ts {done}/{len(t_todo)}", flush=True)

    tmp = jsonl_path.with_suffix(jsonl_path.suffix + ".tmp")
    with tmp.open("w") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    tmp.replace(jsonl_path)

    n_vm = sum(1 for r in rows if isinstance(r.get("video_meta"), dict))
    n_ts = sum(1 for r in rows if isinstance(r.get("ts_shape"), (list, tuple)))
    print(f"[ANNOTATE] wrote {jsonl_path}: {n_vm}/{len(rows)} video_meta, "
          f"{n_ts}/{len(rows)} ts_shape")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument(
        "--annotate-only", action="store_true",
        help="Skip slicing/parsing. Probe existing clips+csvs and write "
             "video_meta / ts_shape back into --jsonl in place.",
    )
    ap.add_argument("--jsonl", type=Path,
                   help="[annotate-only mode] path to unified omnits jsonl to update in place.")
    ap.add_argument("--force", action="store_true",
                   help="[annotate-only mode] re-probe rows that already have meta.")
    ap.add_argument("--in-jsonl", type=Path)
    ap.add_argument("--out-jsonl", type=Path)
    ap.add_argument("--csv-dir", type=Path)
    ap.add_argument("--clip-dir", type=Path)
    ap.add_argument(
        "--dataset-name",
        default="dataset",
        help="Prefix used when rows do not already contain video_id.",
    )
    ap.add_argument("--limit", type=int, default=None, help="First N rows only (smoke).")
    ap.add_argument(
        "--num-workers",
        type=int,
        default=1,
        help="Parallel ffmpeg / probe workers. 1 = sequential.",
    )
    ap.add_argument(
        "--prompt-only",
        action="store_true",
        help="Refresh prompts only: reuse existing TS CSVs and video clips, "
             "skip ffmpeg slicing and TS parsing. Fails if derived files are missing.",
    )
    ap.add_argument(
        "--slice-full-video",
        action="store_true",
        help="When a row has no temporal bounds, still rewrite the whole video with ffmpeg. "
             "Default is to copy the already-segmented video into --clip-dir.",
    )
    ap.add_argument(
        "--skip-errors",
        action="store_true",
        help="Skip rows that fail conversion and report their line numbers instead of stopping.",
    )
    ap.add_argument("--source-root", type=Path, help="Base directory for relative input video paths.")
    ap.add_argument("--path-map", action="append", default=[], metavar="OLD=NEW",
                    help="Remap a legacy path prefix; repeat for multiple roots.")
    args = ap.parse_args()
    path_maps = []
    for item in args.path_map:
        if "=" not in item:
            ap.error("--path-map must have the form OLD=NEW")
        path_maps.append(tuple(item.split("=", 1)))

    if args.annotate_only:
        if args.jsonl is None:
            ap.error("--annotate-only requires --jsonl")
        _annotate_only(args.jsonl, args.num_workers, args.force)
        return

    missing = [n for n in ("in_jsonl", "out_jsonl", "csv_dir", "clip_dir")
               if getattr(args, n) is None]
    if missing:
        ap.error(f"missing required args for conversion: {missing}")

    args.out_jsonl.parent.mkdir(parents=True, exist_ok=True)
    entries: list[dict] = []
    with args.in_jsonl.open() as fin:
        for line_no, line in enumerate(fin, 1):
            if args.limit is not None and line_no > args.limit:
                break
            entry = json.loads(line)
            raw = entry["video_path"]
            for old, new in path_maps:
                if raw == old or raw.startswith(old.rstrip("/") + "/"):
                    raw = new.rstrip("/") + raw[len(old.rstrip("/")):]
                    break
            source_video = Path(raw).expanduser()
            if not source_video.is_absolute():
                source_video = (args.source_root or args.in_jsonl.resolve().parent) / source_video
            entry["video_path"] = str(source_video.resolve())
            entry["_line_no"] = line_no
            entries.append(entry)

    fout = args.out_jsonl.open("w")
    n = 0
    skipped: list[tuple[int, str]] = []

    if args.num_workers <= 1:
        fps_cache: dict[Path, float] = {}
        try:
            for entry in entries:
                line_no = entry.pop("_line_no")
                try:
                    row = convert_entry(
                        entry, csv_dir=args.csv_dir, clip_dir=args.clip_dir,
                        fps_cache=fps_cache, prompt_only=args.prompt_only,
                        dataset_name=args.dataset_name,
                        copy_full_video=not args.slice_full_video,
                    )
                except (ValueError, KeyError, RuntimeError,
                        subprocess.CalledProcessError) as exc:
                    if args.skip_errors:
                        skipped.append((line_no, str(exc)))
                        continue
                    raise RuntimeError(f"line {line_no}: {exc}") from exc
                fout.write(json.dumps(row, ensure_ascii=False) + "\n")
                n += 1
        finally:
            fout.close()
    else:
        # Parallel: write rows as they complete (no order guarantee — shuffle-safe).
        work = [
            (
                e,
                str(args.csv_dir),
                str(args.clip_dir),
                args.prompt_only,
                args.dataset_name,
                not args.slice_full_video,
            )
            for e in entries
        ]
        try:
            with ProcessPoolExecutor(max_workers=args.num_workers) as pool:
                for future in as_completed(
                    [pool.submit(_worker_convert, w) for w in work]
                ):
                    try:
                        _line_no, row = future.result()
                    except Exception as exc:
                        if args.skip_errors:
                            skipped.append((-1, str(exc)))
                            continue
                        raise
                    fout.write(json.dumps(row, ensure_ascii=False) + "\n")
                    fout.flush()
                    n += 1
                    if n % 200 == 0:
                        print(f"  converted {n}/{len(entries)}", flush=True)
        finally:
            fout.close()

    print(f"converted {n} entries → {args.out_jsonl}")
    if skipped:
        print(f"skipped {len(skipped)} entries")
        for line_no, reason in skipped[:20]:
            location = f"line {line_no}" if line_no > 0 else "worker"
            print(f"  {location}: {reason}")
        if len(skipped) > 20:
            print(f"  ... {len(skipped) - 20} more")


if __name__ == "__main__":
    main()