MMTA-v1.0 / processing /common /convert_videos.py
Lishenyi04's picture
Add six source-processing recipes and document local reconstruction
2e6f68f verified
Raw History Blame Contribute Delete
23.4 kB
#!/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()