RememBench / scripts /prepare_i2v_images.py
evanbuzzZ's picture
Add RememBench evaluation inputs and documentation
ba6cc4c verified
Raw History Blame Contribute Delete
4.44 kB
#!/usr/bin/env python3
"""Prepare the exact I2V inputs from user-authorized DL3DV source data."""
import argparse
import hashlib
import io
import json
from pathlib import Path, PurePosixPath
import zipfile
from PIL import Image
EXTENSIONS = {'.png', '.jpg', '.jpeg'}
def prepare_image(data, row):
image = Image.open(io.BytesIO(data)).convert('RGB')
w, h = image.size
width, height = row['width'], row['height']
aspect = width / height
if w / h > aspect:
crop = int(round(h * aspect))
image = image.crop(((w - crop) // 2, 0, (w - crop) // 2 + crop, h))
elif w / h < aspect:
crop = int(round(w / aspect))
image = image.crop((0, (h - crop) // 2, w, (h - crop) // 2 + crop))
image = image.resize((width, height), Image.Resampling.LANCZOS)
actual = hashlib.sha256(image.tobytes()).hexdigest()
if actual != row['rgb_sha256']:
raise ValueError(f"Input image mismatch for {row['scene_id']}: expected {row['rgb_sha256']}, got {actual}. Check the upstream source and preprocessing version.")
return image
def archive_image(archive):
with zipfile.ZipFile(archive) as z:
names = sorted(n for n in z.namelist() if PurePosixPath(n).suffix.lower() in EXTENSIONS)
if not names:
raise ValueError(f'No image members in {archive}')
return z.read(names[0])
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1])
source = ap.add_mutually_exclusive_group(required=True)
source.add_argument('--source-dir', type=Path, help='Local DL3DV archives or extracted scene directories')
source.add_argument('--download', action='store_true', help='Read first frames from DL3DV with HTTP range requests using your own HF access')
ap.add_argument('--limit', type=int, help='Prepare only the first N scenes')
args = ap.parse_args()
if args.limit is not None and args.limit < 1:
ap.error('--limit must be positive')
rows = [json.loads(s) for s in (args.root / 'sources/i2v_images.jsonl').read_text().splitlines()]
if args.limit is not None:
rows = rows[:args.limit]
archives = {}
if args.source_dir:
if not args.source_dir.is_dir():
ap.error('--source-dir must be an existing directory')
for path in args.source_dir.rglob('*.zip'):
if path.stem in archives:
raise ValueError(f'Ambiguous source archives for {path.stem}')
archives[path.stem] = path
for i, row in enumerate(rows, 1):
target = args.root / row['image_path']
if target.is_file():
im = Image.open(target).convert('RGB')
if im.size != (row['width'], row['height']) or hashlib.sha256(im.tobytes()).hexdigest() != row['rgb_sha256']:
raise ValueError(f'Existing image does not match the benchmark: {target}')
print(f'{i}/{len(rows)} verified {row["scene_id"]}', flush=True)
continue
if args.download:
import fsspec
from huggingface_hub import get_token, hf_hub_url
token = get_token()
if not token:
raise RuntimeError('Run hf auth login with an account that has accepted the DL3DV terms.')
url = hf_hub_url(repo_id=row['source_repo'], filename=row['source_archive'],
revision=row['source_revision'], repo_type='dataset')
with fsspec.open(url, mode='rb', block_size=65536,
headers={'Authorization': 'Bearer ' + token}) as remote:
data = archive_image(remote)
elif row['scene_id'] in archives:
data = archive_image(archives[row['scene_id']])
else:
scene = args.source_dir / row['scene_id']
files = sorted((p for p in scene.rglob('*') if p.is_file() and p.suffix.lower() in EXTENSIONS),
key=lambda p: p.relative_to(scene).as_posix())
if not files:
raise FileNotFoundError(f"No archive or extracted images found for {row['scene_id']}")
data = files[0].read_bytes()
image = prepare_image(data, row)
target.parent.mkdir(parents=True, exist_ok=True)
image.save(target)
print(f'{i}/{len(rows)} prepared {row["scene_id"]}', flush=True)
if __name__ == '__main__':
main()