Datasets:
Download code/evaluation-code/v0.2-0c2690ae/tools/evaluation/media.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 8.02 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/tools/evaluation/media.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/v0.2-0c2690ae/tools/evaluation/media.py
-
curl -L -o media.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/tools/evaluation/media.py
8.02 kB
| """Video input construction for model evaluation. | |
| Three input modes mirror how recent video benchmarks feed models: | |
| - ``frames``: a fixed number of uniformly spaced frames per recording | |
| (VSI-Bench / Video-MME style ``nframes``). With several recordings the budget | |
| is either per view or one total split by duration (plan section 7, aligned | |
| input track). | |
| - ``fps``: frames at a fixed rate, capped by ``max_frames`` (Qwen/Gemini style | |
| ``fps`` sampling). | |
| - ``video``: the encoded file itself, for providers with a native video | |
| interface (official default track). Nothing is decoded here; the provider | |
| decides what it reads. | |
| Every request records exactly what was sent (times, sizes, bytes) so access | |
| volume can be reported. | |
| """ | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import shutil | |
| import subprocess | |
| import threading | |
| from pathlib import Path | |
| MODES = ('frames', 'fps', 'video') | |
| BUDGETS = ('per_view', 'total') | |
| def _tool(name): | |
| path = shutil.which(name) | |
| if path is None: | |
| raise RuntimeError(f'{name} is required for video input') | |
| return path | |
| def probe(path): | |
| """Return duration and stream geometry of the first video stream.""" | |
| out = subprocess.run( | |
| [_tool('ffprobe'), '-v', 'error', '-select_streams', 'v:0', | |
| '-show_entries', 'stream=width,height,r_frame_rate,nb_frames,duration:format=duration', | |
| '-of', 'json', str(path)], | |
| check=True, capture_output=True, text=True).stdout | |
| data = json.loads(out) | |
| stream = data['streams'][0] | |
| num, den = (int(x) for x in stream['r_frame_rate'].split('/')) | |
| duration = float(stream.get('duration') or data['format']['duration']) | |
| return {'width': int(stream['width']), 'height': int(stream['height']), | |
| 'fps': num / den if den else None, 'duration_s': duration, | |
| 'frame_count': int(stream['nb_frames']) if stream.get('nb_frames', 'N/A').isdigit() else None} | |
| def uniform_times(duration_s, count, fps=None): | |
| """``count`` instants over [0, last frame], endpoints included. | |
| The last instant is one frame before the container end so that it decodes | |
| to the final frame instead of past the stream. A single frame is the final | |
| frame (the "last frame only" baseline of plan section 7). | |
| """ | |
| if count < 1: | |
| raise ValueError('frame count must be positive') | |
| last = max(0.0, duration_s - (1.0 / fps if fps else 0.0)) | |
| if count == 1: | |
| return [round(last, 6)] | |
| return [round(last * i / (count - 1), 6) for i in range(count)] | |
| def rate_times(duration_s, rate, max_frames=None, fps=None): | |
| """Instants at ``rate`` Hz from 0; uniform ``max_frames`` when the cap binds.""" | |
| if rate <= 0: | |
| raise ValueError('sampling rate must be positive') | |
| last = max(0.0, duration_s - (1.0 / fps if fps else 0.0)) | |
| count = int(math.floor(last * rate + 1e-9)) + 1 | |
| if max_frames is not None and count > max_frames: | |
| return uniform_times(duration_s, max_frames, fps) | |
| return [round(i / rate, 6) for i in range(count)] | |
| def allocate(durations, total): | |
| """Split a total frame budget across views by duration, at least one each. | |
| Largest-remainder rounding keeps the sum exactly ``total``. | |
| """ | |
| if total < len(durations): | |
| raise ValueError('total budget smaller than the number of views') | |
| span = sum(durations) | |
| shares = [total * d / span if span > 0 else total / len(durations) for d in durations] | |
| counts = [max(1, int(math.floor(s))) for s in shares] | |
| order = sorted(range(len(shares)), key=lambda i: shares[i] - math.floor(shares[i]), reverse=True) | |
| i = 0 | |
| while sum(counts) < total: | |
| counts[order[i % len(order)]] += 1 | |
| i += 1 | |
| while sum(counts) > total: | |
| j = max(range(len(counts)), key=lambda k: counts[k]) | |
| counts[j] -= 1 | |
| return counts | |
| def plan_times(infos, mode, *, frames=None, rate=None, max_frames=None, budget='per_view'): | |
| """Sampling instants per view, from probed ``infos`` (one dict per view).""" | |
| if mode == 'frames': | |
| if not frames: | |
| raise ValueError('frames mode needs a frame count') | |
| if budget == 'per_view': | |
| counts = [frames] * len(infos) | |
| elif budget == 'total': | |
| counts = allocate([i['duration_s'] for i in infos], frames) | |
| else: | |
| raise ValueError(f'unknown budget {budget!r}') | |
| return [uniform_times(i['duration_s'], c, i['fps']) for i, c in zip(infos, counts)] | |
| if mode == 'fps': | |
| if not rate: | |
| raise ValueError('fps mode needs a sampling rate') | |
| cap = max_frames | |
| if budget == 'total' and max_frames: | |
| cap = None | |
| per = allocate([i['duration_s'] for i in infos], max_frames) | |
| return [rate_times(i['duration_s'], rate, c, i['fps']) for i, c in zip(infos, per)] | |
| return [rate_times(i['duration_s'], rate, cap, i['fps']) for i in infos] | |
| raise ValueError(f'mode {mode!r} does not sample frames') | |
| def extract(path, times, cache_dir, max_side=None, quality=3): | |
| """Decode one JPEG per requested instant; files are cached by content key.""" | |
| path = Path(path) | |
| digest = hashlib.sha256(f'{path.resolve()}:{path.stat().st_size}:{path.stat().st_mtime_ns}' | |
| .encode()).hexdigest()[:16] | |
| folder = Path(cache_dir) / f'{path.stem}-{digest}' / f'side{max_side or 0}' | |
| folder.mkdir(parents=True, exist_ok=True) | |
| scale = (['-vf', f"scale='if(gt(iw,ih),min({max_side},iw),-2)':'if(gt(iw,ih),-2,min({max_side},ih))'"] | |
| if max_side else []) | |
| frames = [] | |
| for t in times: | |
| out = folder / f'{t:012.6f}.jpg' | |
| if not out.exists(): | |
| # Unique temp name: concurrent workers may decode the same frame. | |
| tmp = out.with_name(f'{out.stem}.{os.getpid()}.{threading.get_ident()}.tmp.jpg') | |
| try: | |
| subprocess.run([_tool('ffmpeg'), '-v', 'error', '-y', '-ss', f'{t:.6f}', '-i', str(path), | |
| '-frames:v', '1', *scale, '-q:v', str(quality), str(tmp)], | |
| check=True, capture_output=True) | |
| if not tmp.exists() or tmp.stat().st_size == 0: | |
| raise RuntimeError(f'no frame decoded at {t:.3f}s from {path}') | |
| tmp.replace(out) | |
| finally: | |
| tmp.unlink(missing_ok=True) | |
| frames.append({'time_s': t, 'path': str(out), 'bytes': out.stat().st_size}) | |
| return frames | |
| def build_inputs(videos, mode, cache_dir, *, frames=None, rate=None, max_frames=None, | |
| budget='per_view', max_side=None): | |
| """Turn ``[{'view', 'path'}]`` into per-view inputs plus an access record.""" | |
| if mode not in MODES: | |
| raise ValueError(f'mode must be one of {MODES}') | |
| infos = [probe(v['path']) for v in videos] | |
| if mode == 'video': | |
| views = [{'view': v['view'], 'kind': 'video', 'path': str(v['path']), | |
| 'bytes': Path(v['path']).stat().st_size, 'source': info} | |
| for v, info in zip(videos, infos)] | |
| else: | |
| plans = plan_times(infos, mode, frames=frames, rate=rate, max_frames=max_frames, budget=budget) | |
| views = [{'view': v['view'], 'kind': 'frames', 'source': info, | |
| 'frames': extract(v['path'], times, cache_dir, max_side)} | |
| for v, info, times in zip(videos, infos, plans)] | |
| access = {'mode': mode, 'budget': budget if mode != 'video' else None, | |
| 'max_side': max_side if mode != 'video' else None, | |
| 'views': [{'view': v['view'], | |
| 'duration_s': v['source']['duration_s'], | |
| 'frames_sent': len(v.get('frames', [])) if v['kind'] == 'frames' else None, | |
| 'times_s': [f['time_s'] for f in v.get('frames', [])], | |
| 'bytes_sent': (sum(f['bytes'] for f in v['frames']) if v['kind'] == 'frames' | |
| else v['bytes'])} | |
| for v in views]} | |
| return views, access | |