vibevideobench / fetch_external.py
diaomuxi's picture
VibeVideoBench dataset
b5e3923 verified
Raw History Blame Contribute Delete
10.5 kB
#!/usr/bin/env python3
"""Optional helper: fetch the task inputs this dataset does not ship (external.json, next to this script) into
tasks/. The list, with links and instructions for doing it by hand, is EXTERNAL_INPUTS.md; every file must be in place
before a benchmark run.
python3 fetch_external.py fetch what is missing (already present and matching: skipped)
python3 fetch_external.py --check only report what is missing (exit 1 if anything is)
Entry kinds:
download "url" (and optionally "fallback_url", tried when "url" fails, e.g. the live page behind an archived copy)
zip_member "url" of a .zip and "member": the file inside it
ffmpeg_cut "source_url" (+ "source_sha256", "source_size"), "ffmpeg_input" / "ffmpeg": arguments before / after the input; the
source is downloaded once into data/.external_cache/ and the excerpt re-encoded, so its sha256 differs
from the listed one: it is checked against "expect" (duration, size, frame rate, audio streams) instead
svg_extract "page_url", "svg_index", "raw_sha256", "color": the brand page has its marks only as inline <svg>; take the
svg_index-th one (0-based, document order), drop its class attribute and add style="color:<color>"
manual no download; "steps" says how to make the file by hand
"check": "text" (web pages): the markup of a page changes between captures, so instead of the sha256 the page's text is
compared: at least 95% of "text_blocks" (sha256 prefixes of the benchmark copy's text runs of 20+ characters) must be
found in the download.
The environment's http(s)_proxy is used. Downloads are retried with backoff (rate limits, server errors, dropped
connections) and an interrupted download resumes where it stopped, also on the next run. A file whose sha256 differs from the listed one is kept, with a warning (the
source may have changed); a file that cannot be fetched is listed at the end and the exit code is 1.
"""
import argparse
import re
import hashlib
import html
import json
from pathlib import Path
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
import zipfile
HERE = Path(__file__).resolve().parent
TASKS = HERE / 'tasks'
CACHE = HERE / '.external_cache'
DOC = str(HERE / 'EXTERNAL_INPUTS.md')
UA = {'User-Agent': 'Mozilla/5.0 (vvbench fetch_external; https://vibevideobench.github.io)'}
RETRIES = 6 # attempts per URL
def sha(p):
h = hashlib.sha256()
with open(p, 'rb') as f:
for b in iter(lambda: f.read(1 << 20), b''):
h.update(b)
return h.hexdigest()
def entries():
return json.loads((HERE / 'external.json').read_text())['files']
def missing():
"""Entries whose file is not in place."""
return [e for e in entries() if not (TASKS / e['task'] / 'inputs' / e['path']).exists()]
def retry_after(e):
"""Seconds the server asks to wait (Retry-After in seconds), at most 5 minutes."""
v = e.headers.get('Retry-After') if e.headers else None
return min(int(v), 300) if v and v.strip().isdigit() else None
def get(url, dst):
"""Download url to dst via a .part file: an interrupted download is never taken for a complete one, and the next
attempt (or the next run) resumes it with a Range request. Network errors, 429 and 5xx are retried RETRIES times
with exponential backoff, honouring Retry-After."""
dst.parent.mkdir(parents=True, exist_ok=True)
part = dst.with_name(dst.name + '.part')
for attempt in range(RETRIES):
have = part.stat().st_size if part.exists() else 0
headers = dict(UA, Range=f'bytes={have}-') if have else UA
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=120) as r:
want = int(r.headers['Content-Length']) if r.headers.get('Content-Length') else None
with open(part, 'ab' if have and r.status == 206 else 'wb') as f: # 200: no range support, restart
start = f.tell()
shutil.copyfileobj(r, f, 1 << 20)
got = f.tell() - start
if want is not None and got < want: # a dropped connection ends the read without an error
raise ConnectionError(f'connection closed after {got} of {want} bytes')
part.replace(dst)
return
except urllib.error.HTTPError as e:
if e.code == 416 and have: # the .part already holds the whole file
part.replace(dst)
return
if (e.code != 429 and e.code < 500) or attempt == RETRIES - 1:
raise
wait, why = retry_after(e) or 5 * 2 ** attempt, f'HTTP {e.code}'
except (urllib.error.URLError, OSError) as e: # connection errors, resets, timeouts
if attempt == RETRIES - 1:
raise
wait, why = 5 * 2 ** attempt, str(e)
print(f' {why}; retrying in {wait}s ({attempt + 1}/{RETRIES - 1})', flush=True)
time.sleep(wait)
def probe(p):
j = json.loads(subprocess.run(['ffprobe', '-v', 'error', '-show_streams', '-show_format', '-of', 'json', str(p)],
capture_output=True, text=True, check=True).stdout)
v = next(s for s in j['streams'] if s['codec_type'] == 'video')
return {'duration_s': float(j['format']['duration']), 'width': v['width'], 'height': v['height'],
'fps': v['r_frame_rate'], 'audio_streams': sum(s['codec_type'] == 'audio' for s in j['streams'])}
def text_blocks(p):
"""sha256 prefixes of the visible text runs (20+ characters) of an HTML page."""
s = re.sub(r'(?is)<(script|style|noscript)\b.*?</\1>|<!--.*?-->', '', p.read_text(encoding='utf-8', errors='replace'))
runs = (re.sub(r'\s+', ' ', html.unescape(r)).strip() for r in re.split(r'<[^>]*>', s))
return [hashlib.sha256(t.encode()).hexdigest()[:16] for t in runs if len(t) >= 20]
def matches(e, dst):
"""None if dst matches the entry, else what differs."""
if e.get('check') == 'text':
got = set(text_blocks(dst))
found = sum(b in got for b in e['text_blocks']) / len(e['text_blocks'])
return None if found >= 0.95 else f'only {found:.0%} of the page text found'
if e['kind'] != 'ffmpeg_cut':
return None if sha(dst) == e['sha256'] else 'sha256 differs'
got, want = probe(dst), e['expect']
bad = [k for k in want if (abs(got[k] - want[k]) > 0.05 if k == 'duration_s' else got[k] != want[k])]
return f'{", ".join(bad)} differ: {got}' if bad else None
def fetch(e, dst):
if e['kind'] == 'download':
try:
get(e['url'], dst)
except Exception:
if not e.get('fallback_url'):
raise
print(f' {e["url"]} failed; using {e["fallback_url"]} (its content may have changed)', flush=True)
dst.with_name(dst.name + '.part').unlink(missing_ok=True) # never resume one URL's bytes from another
get(e['fallback_url'], dst)
elif e['kind'] == 'zip_member':
tmp = CACHE / Path(e['url']).name
if not tmp.exists():
get(e['url'], tmp)
dst.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(tmp) as z, z.open(e['member']) as src, open(dst, 'wb') as out:
shutil.copyfileobj(src, out)
elif e['kind'] == 'ffmpeg_cut':
src = CACHE / Path(e['source_url']).name
if not src.exists():
if e.get('source_size'):
print(f' source video {src.name}: {e["source_size"] / 1e9:.2f} GB, downloaded once for all its excerpts',
flush=True)
get(e['source_url'], src)
if e.get('source_sha256') and sha(src) != e['source_sha256']:
print(f' warning: {src.name} differs from the source the excerpts were cut from', flush=True)
dst.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(['ffmpeg', '-v', 'error', '-y', *e.get('ffmpeg_input', []), '-i', str(src), *e['ffmpeg'], str(dst)],
check=True)
elif e['kind'] == 'svg_extract':
page = CACHE / ('page_' + hashlib.sha256(e['page_url'].encode()).hexdigest()[:12] + '.html')
if not page.exists():
get(e['page_url'], page)
svgs = re.findall(r'<svg\b.*?</svg>', page.read_text(encoding='utf-8'), re.S)
svg = svgs[e['svg_index']]
if hashlib.sha256(svg.encode()).hexdigest() != e['raw_sha256']:
print(f' warning: inline svg {e["svg_index"]} of {e["page_url"]} changed since the benchmark took it', flush=True)
svg = re.sub(r'\sclass="[^"]*"', '', svg, count=1).replace('<svg', f'<svg style="color:{e["color"]}"', 1)
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_text(svg, encoding='utf-8')
elif e['kind'] == 'manual':
raise RuntimeError('manual step: ' + e['steps'])
else:
raise ValueError(f'unknown kind {e["kind"]!r}')
def main():
ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
ap.add_argument('--check', action='store_true', help='only report what is missing')
a = ap.parse_args()
es, miss = entries(), missing()
if a.check:
for e in miss:
print(f'missing {e["task"]}/inputs/{e["path"]}')
print(f'{len(es) - len(miss)}/{len(es)} external inputs present' + (f'; see {DOC}' if miss else ''))
sys.exit(1 if miss else 0)
failed, changed = [], []
for e in es:
dst = TASKS / e['task'] / 'inputs' / e['path']
if dst.exists() and matches(e, dst) is None:
continue
print(f'fetch {e["task"]}/inputs/{e["path"]}', flush=True)
try:
fetch(e, dst)
except Exception as exc:
if e['kind'] != 'manual':
dst.unlink(missing_ok=True)
failed.append(f'{e["task"]}/inputs/{e["path"]}: {exc}')
continue
why = matches(e, dst)
if why:
changed.append(f'{e["task"]}/inputs/{e["path"]}: {why}')
for c in changed:
print(f'warning: {c} (not identical to the copy the benchmark was run with; the source may have changed)')
for f in failed:
print(f'FAILED {f}')
print(f'{len(es) - len(failed)}/{len(es)} external inputs in place' + (f'; see {DOC}' if failed else ''))
sys.exit(1 if failed else 0)
if __name__ == '__main__':
main()