File size: 5,587 Bytes
1cfe2ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0489d8d
 
 
 
 
 
 
 
 
1cfe2ac
 
 
 
 
 
 
 
 
 
 
0489d8d
 
1cfe2ac
 
 
 
 
 
 
 
 
 
0489d8d
1cfe2ac
0489d8d
1cfe2ac
 
 
0489d8d
1cfe2ac
 
 
0489d8d
1cfe2ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verify a VideoVera release and materialize local training inputs (Python >=3.10)."""
import argparse
import hashlib
import json
import os
import shutil
import tarfile
from pathlib import Path


def sha256(path):
    digest = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(8 * 1024**2), b''):
            digest.update(block)
    return digest.hexdigest()


def records(path):
    with path.open(encoding='utf-8') as stream:
        for line in stream:
            if line.strip():
                yield json.loads(line)


def source_file(root, name):
    relative = Path(name)
    if relative.is_absolute() or '..' in relative.parts:
        raise ValueError('Unsafe repository path: ' + name)
    # snapshot_download uses symlinks into the Hub cache's shared blobs directory.
    # Validate the repository-relative name while allowing those cache symlinks.
    return root / relative


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, required=True, help='Downloaded repository snapshot')
    parser.add_argument('--output', type=Path, required=True, help='New output directory')
    args = parser.parse_args()
    root, output = args.root.resolve(), args.output.resolve()
    if output.exists():
        raise ValueError('Use a new output directory; existing data are preserved: ' + str(output))
    manifest = json.loads((root / 'MANIFEST.json').read_text())
    checksums = json.loads((root / 'SHA256SUMS.json').read_text())
    for index, (name, expected) in enumerate(checksums.items(), 1):
        source = source_file(root, name)
        if sha256(source) != expected:
            raise ValueError('Release checksum mismatch: ' + name)
        if index % 500 == 0:
            print(f'Checksums verified: {index}/{len(checksums)}', flush=True)
    media = {row['path']: row for row in records(root / 'media/video_index.jsonl')}
    if len(media) != manifest['unique_video_files']:
        raise ValueError('Media index count mismatch')
    output.mkdir(parents=True)
    for row in media.values():
        if 'repository_path' not in row:
            continue
        source = source_file(root, row['repository_path'])
        target = (output / row['path']).resolve()
        if not target.is_relative_to(output):
            raise ValueError('Unsafe indexed media path')
        target.parent.mkdir(parents=True, exist_ok=True)
        try:
            os.link(source.resolve(), target)
        except OSError:
            shutil.copyfile(source, target)
    for name in manifest['media_shards']:
        with tarfile.open(source_file(root, name), 'r') as archive:
            for member in archive:
                target = (output / member.name).resolve()
                if not member.isfile() or member.name not in media or not target.is_relative_to(output):
                    raise ValueError('Unexpected archive member: ' + member.name)
                if target.exists():
                    if sha256(target) != media[member.name]['sha256']:
                        raise ValueError('Existing media mismatch: ' + member.name)
                    continue
                target.parent.mkdir(parents=True, exist_ok=True)
                partial = target.with_suffix('.mp4.partial')
                with archive.extractfile(member) as source, partial.open('xb') as stream:
                    shutil.copyfileobj(source, stream, length=8 * 1024**2)
                if sha256(partial) != media[member.name]['sha256']:
                    raise ValueError('Extracted media mismatch; partial preserved: ' + member.name)
                partial.rename(target)
    for row in media.values():
        if sha256(output / row['path']) != row['sha256']:
            raise ValueError('Media checksum mismatch: ' + row['path'])
    alias_file = root / 'media/path_aliases.json'
    aliases = json.loads(alias_file.read_text()) if alias_file.exists() else {}

    def runtime(value):
        if isinstance(value, dict):
            return {key: runtime(item) for key, item in value.items()}
        if isinstance(value, list):
            return [runtime(item) for item in value]
        if isinstance(value, str):
            relative = aliases.get(value, value)
            if relative in media:
                return str(output / relative)
        return value

    ids = {}
    for source in sorted((root / 'data').glob('*.jsonl')):
        current = []
        with (output / source.name).open('x', encoding='utf-8') as stream:
            for row in records(source):
                current.append(row['id'])
                stream.write(json.dumps(runtime(row), ensure_ascii=False) + '\n')
        if len(current) != len(set(current)):
            raise ValueError('Duplicate IDs: ' + source.name)
        ids[source.name] = current
    warm, policy, full = (set(ids[name]) for name in ['sft_warmup.jsonl', 'grpo_policy.jsonl', 'all.jsonl'])
    if warm & policy or warm | policy != full:
        raise ValueError('Warm-up / policy partition mismatch')
    if ids['grpo_policy.jsonl'] != ids['grpo_targets.jsonl'] or ids['grpo_policy.jsonl'] != ids['grpo_structured_gold.jsonl']:
        raise ValueError('Policy and reference target order mismatch')
    assert (len(full), len(warm), len(policy)) == (manifest['records'], manifest['warmup_sft'], manifest['grpo'])
    print(json.dumps({'status': 'VIDEOVERA_INPUTS_VERIFIED', 'records': len(full), 'warmup': len(warm), 'rl': len(policy), 'output': str(output)}))


if __name__ == '__main__':
    main()