File size: 5,520 Bytes
aaee8cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()