"""Run one model endpoint over an evaluation item set. Items (``items.jsonl``, public, one JSON object per line):: {"item_id": "...", "version_id": "position.coordinates.at_time/single_ego", "question": {"zh": "...", "en": "..."}, # instantiated public text "answer": {...}, # v0 answer spec (public) "scoring": {...}, # answer.scoring (prover.scoring.rule) "granularity": "sector4", # choice items only "videos": [{"view": "A", "path": "A.mp4"}, ...], # relative to items file "tags": {...}} # optional report factors Next-pipeline items come from ``np_export.py`` (answer type ``np:``, ``scoring`` is the scorer from ``embodied_pipeline.prover.scoring``); see ``np_answers.py``. Truth (``truth.jsonl``, private, kept separate and only read when scoring):: {"item_id": "...", "truth": [x, y] | number | option index, "magnitude": number (optional override)} Settings (track) select the input mode, mirroring the benchmarks surveyed: ``frames`` with ``frames=N`` (VSI-Bench/Video-MME ``nframes``), ``fps`` with ``rate``/``max_frames`` (Qwen/Gemini style), ``video`` (native video API), and ``text_only`` (question-only blind baseline). ``budget`` is ``per_view`` or ``total`` for multi-recording items (plan section 7). Outputs go to a fresh run directory: ``responses.jsonl`` (one line per item, append-only, so an interrupted run resumes), ``run.json`` (endpoint, settings, item set hash) and, after ``score``, ``scores.jsonl`` and ``summary.json``. """ import argparse import concurrent.futures import hashlib import json import re import sys import threading import time from pathlib import Path if __package__ in (None, ''): sys.path.insert(0, str(Path(__file__).resolve().parent)) import media, np_answers, prompts, providers, scoring # noqa: E401 else: from . import media, np_answers, prompts, providers, scoring TRUNCATED = {'length', 'max_tokens', 'MAX_TOKENS'} SETTINGS_KEYS = {'mode', 'frames', 'rate', 'max_frames', 'budget', 'max_side', 'lang', 'text_only', 'max_tokens', 'temperature', 'seed', 'video_fallback_frames', 'frame_labels', 'images_in_budget'} def read_jsonl(path): rows = [] with open(path, encoding='utf-8') as fh: for n, line in enumerate(fh, 1): if line.strip(): try: rows.append(json.loads(line)) except json.JSONDecodeError as exc: raise ValueError(f'{path}:{n}: {exc}') from None return rows def file_sha256(path): h = hashlib.sha256() with open(path, 'rb') as fh: for chunk in iter(lambda: fh.read(1 << 20), b''): h.update(chunk) return h.hexdigest() def load_items(path): path = Path(path) items = read_jsonl(path) seen = set() for item in items: for key in ('item_id', 'version_id', 'question', 'answer', 'videos'): if key not in item: raise ValueError(f"item {item.get('item_id')!r} lacks {key}") if item['item_id'] in seen: raise ValueError(f"duplicate item_id {item['item_id']!r}") seen.add(item['item_id']) if 'truth' in item or 'private_truth' in item: raise ValueError(f"item {item['item_id']!r} carries truth; keep it in truth.jsonl") prompts.answer_spec(item) for v in item['videos']: v['path'] = str((path.parent / v['path']).resolve()) if not item.get('images'): # 平面图题的图出题时就写进 presentation.images(label 可缺);map_choice 的由导出现画进 images item['images'] = [dict(image) for image in (item.get('presentation') or {}).get('images') or []] for image in item.get('images') or []: image['path'] = str((path.parent / image['path']).resolve()) return items def normalize_settings(raw): unknown = set(raw) - SETTINGS_KEYS if unknown: raise ValueError(f'unknown settings: {sorted(unknown)}') s = {'mode': 'frames', 'frames': 16, 'rate': None, 'max_frames': None, 'budget': 'per_view', 'max_side': 768, 'lang': 'zh', 'text_only': False, 'max_tokens': 16384, 'temperature': 0.0, 'seed': 0, 'video_fallback_frames': None, # True labels every frame with its index and time and states the duration (11-02). Off by default so # earlier runs keep their prompt wording when resumed; new runs opt in. 'frame_labels': False, **raw} # images_in_budget (11-09, opt-in, no default key so earlier run.json files still resume): a total frame # budget also counts the item's attached images (floor plans, option maps), so an endpoint capped at # N images per request (aigw: 50) gets N-1 frames plus the map. if s['mode'] not in media.MODES: raise ValueError(f"mode must be one of {media.MODES}") if s['budget'] not in media.BUDGETS: raise ValueError(f"budget must be one of {media.BUDGETS}") if s['lang'] not in ('zh', 'en'): raise ValueError('lang must be zh or en') if s.get('images_in_budget') and (s['mode'] == 'video' or s['budget'] != 'total' or (s['mode'] == 'fps' and s['max_frames'] is None)): raise ValueError('images_in_budget needs budget total and a frame cap (frames, or fps with max_frames)') return s def frame_budget(item, settings): """(frames, max_frames, attached images) for this item; the cap shrinks by the attached images when ``images_in_budget`` is set.""" frames, cap = settings['frames'], settings['max_frames'] n = len(item.get('images') or []) if settings.get('images_in_budget') else 0 if n: if settings['mode'] == 'fps': cap -= n else: frames -= n left = cap if settings['mode'] == 'fps' else frames if left < len(item['videos']): raise ValueError(f"item {item['item_id']!r}: {n} attached images leave {left} frames " f"for {len(item['videos'])} views") return frames, cap, n def build_request(item, settings, cache_dir): if settings['text_only']: views, access = [], {'mode': 'text_only', 'views': []} else: if prompts.is_np(item) and not item['videos']: raise ValueError(f"item {item['item_id']!r} has no recordings; only text_only settings can run it") frames, max_frames, attached = frame_budget(item, settings) views, access = media.build_inputs( item['videos'], settings['mode'], cache_dir, frames=frames, rate=settings['rate'], max_frames=max_frames, budget=settings['budget'], max_side=settings['max_side']) if settings.get('images_in_budget'): access['images_in_budget'] = attached if settings['mode'] == 'video' and settings['video_fallback_frames']: # Providers without native video (Anthropic) expand to these frames. framed, _ = media.build_inputs(item['videos'], 'frames', cache_dir, frames=settings['video_fallback_frames'], budget=settings['budget'], max_side=settings['max_side']) for v, f in zip(views, framed): v['fallback_frames'] = [{'type': 'image', 'path': x['path'], 'mime': 'image/jpeg'} for x in f['frames']] parts = prompts.build_parts(item, views, settings['lang'], settings['mode'], settings['text_only'], settings['frame_labels']) request = {'system': prompts.SYSTEM[settings['lang']], 'parts': parts, 'max_tokens': settings['max_tokens'], 'temperature': settings['temperature'], 'seed': settings['seed']} return request, access def prompt_text(request): """Text-only view of a request, stored for audit (media replaced by markers).""" out = [] for part in request['parts']: if part['type'] == 'text': out.append(part['text']) elif part['type'] == 'image': out.append('') elif part['type'] == 'video': out.append(f"