#!/usr/bin/env python3 """Resolve public relative video paths into local, trainer-compatible Parquet. No download or video decoding is performed. Existing output files are not replaced. """ import argparse import copy import json from functools import lru_cache from pathlib import Path, PurePosixPath import pyarrow as pa import pyarrow.parquet as pq def candidates(relative, video_root, llava_root=None, kinetics_root=None): parts = PurePosixPath(relative).parts if not parts or PurePosixPath(relative).is_absolute() or '..' in parts: raise ValueError('Video paths must be relative without parent traversal') if parts[0] == 'LLaVA-Video-178K': base = llava_root or video_root / 'LLaVA-Video-178K' yield base.joinpath(*parts[1:]) # Original video archives often extract source folders directly, without # the historical extra 'data/' alias used in annotation paths. if len(parts) > 3 and parts[2] == 'data': yield base.joinpath(parts[1], *parts[3:]) elif parts[0] == 'Kinetics-700': if kinetics_root: yield kinetics_root.joinpath(*parts[1:]) else: if directory_exists(video_root / 'Kinetics-700'): yield video_root.joinpath(*parts) if directory_exists(video_root / 'tarsier2_unzip' / 'Kinetics-700'): yield video_root.joinpath('tarsier2_unzip', *parts) else: raise ValueError('Unsupported video source: ' + parts[0]) @lru_cache(maxsize=65536) def resolved_parent(parent): return parent.resolve() @lru_cache(maxsize=65536) def directory_exists(path): return path.is_dir() @lru_cache(maxsize=65536) def directory_files(path): # Scandir avoids one remote metadata round-trip per video on shared storage. if not directory_exists(path): return frozenset() import os with os.scandir(path) as entries: return frozenset(e.name for e in entries if e.is_file()) def file_exists(path): return path.name in directory_files(path.parent) def resolved_file(path): return path.resolve() if path.is_symlink() else resolved_parent(path.parent) / path.name def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('--release-dir', type=Path, default=Path(__file__).resolve().parents[1]) ap.add_argument('--config', choices=['current', 'legacy_25118', 'grpo_25114'], default='current') ap.add_argument('--video-root', type=Path, required=True) ap.add_argument('--llava-root', type=Path, help='Optional extracted LLaVA-Video-178K root') ap.add_argument('--kinetics-root', type=Path, help='Optional Kinetics-700 root containing videos/') ap.add_argument('--output-dir', type=Path) ap.add_argument('--check-only', action='store_true') args = ap.parse_args() if not args.check_only and args.output_dir is None: ap.error('--output-dir is required unless --check-only is set') tables = {} missing = [] mappings = {} for split in ['train', 'validation']: table = pq.read_table(args.release_dir / 'data' / args.config / (split + '.parquet')) videos = copy.deepcopy(table['videos'].to_pylist()) for row_id, row in enumerate(videos): for video in row: relative = video['video'] if relative not in mappings: matches = {resolved_file(p) for p in candidates(relative, args.video_root, args.llava_root, args.kinetics_root) if file_exists(p)} if len(matches) > 1: raise ValueError('Multiple distinct files match ' + relative) mappings[relative] = str(next(iter(matches))) if matches else None resolved = mappings[relative] if resolved is None: missing.append({'split': split, 'row': row_id, 'video': relative}) else: video['video'] = resolved if (row_id + 1) % 5000 == 0: print(json.dumps({'split': split, 'checked_rows': row_id + 1}), flush=True) table = table.set_column(table.schema.get_field_index('videos'), table.schema.field('videos'), pa.array(videos, type=table.schema.field('videos').type)) # The project trainer uses this numeric ID to join original row records. table = table.append_column('rebuttal_row_id', table['source_row_id']) tables[split] = table summary = {'config': args.config, 'unique_video_paths': len(mappings), 'resolved_unique_video_paths': sum(p is not None for p in mappings.values()), 'missing_references': len(missing), 'missing_examples': missing[:10], 'rows': {s: t.num_rows for s, t in tables.items()}, 'video_decoding_performed': False} print(json.dumps(summary, indent=2)) if missing: raise SystemExit('Missing videos; no training files were written') if args.check_only: return args.output_dir.mkdir(parents=True, exist_ok=True) outputs = [args.output_dir / (split + '.parquet') for split in tables] if any(p.exists() for p in outputs): raise SystemExit('Output exists; choose a new output directory') for split, table in tables.items(): pq.write_table(table, args.output_dir / (split + '.parquet'), compression='zstd') print('Wrote local train.parquet and validation.parquet') if __name__ == '__main__': main()