VideoVera-12k / tools /prepare_data.py
YilingMa's picture
final version
0489d8d verified
Raw History Blame Contribute Delete
5.59 kB
"""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()