Datasets:
Download code/evaluation/_api.py from nvidia/VESPER: direct link, hf CLI and curl.
- Browser
- Download file 9.54 kB
-
https://huggingface.co/datasets/nvidia/VESPER/resolve/main/code/evaluation/_api.py
- Command line
-
hf download hf://datasets/nvidia/VESPER/code/evaluation/_api.py
-
curl -L -o _api.py https://huggingface.co/datasets/nvidia/VESPER/resolve/main/code/evaluation/_api.py
9.54 kB
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | |
| # SPDX-License-Identifier: LicenseRef-NVIDIA-OneWay-Noncommercial | |
| """OpenAI-compatible chat-completions client for the evaluated models and the judge. | |
| A clip is sent in one of two ways: | |
| * ``gemini_video``: the whole clip as one ``image_url`` part holding a | |
| ``data:video/mp4;base64,...`` URL. | |
| * ``openai_frames``: JPEG frames spread evenly across the clip, one | |
| ``image_url`` part each. | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import importlib.util | |
| import json | |
| import os | |
| import socket | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| CHAT_COMPLETIONS_URL = (os.environ.get("VLM_API_BASE", "").rstrip("/") + "/v1/chat/completions") if os.environ.get("VLM_API_BASE", "") else "" | |
| # HTTP statuses worth retrying: server errors, gateway failures and rate limits. | |
| # A failed request is dropped from the run, so transient errors must be retried. | |
| RETRYABLE_STATUS = frozenset({429, 500, 502, 503, 504}) | |
| # Socket timeout for every chat-completions POST. Without one, urlopen can block | |
| # forever on a dead connection. | |
| HTTP_TIMEOUT_SEC = float(os.environ.get("VLM_HTTP_TIMEOUT_SEC", "600")) | |
| # Attempts per request to an evaluated model (retryable errors only), and the | |
| # wait between attempts. | |
| API_MAX_ATTEMPTS = 10 | |
| API_RETRY_WAIT_SEC = 5 | |
| def post_chat_completion( | |
| url: str, | |
| api_key: str, | |
| payload: dict, | |
| server_error_max_attempts: int, | |
| server_error_wait_sec: int, | |
| ) -> dict: | |
| headers = { | |
| "Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json", | |
| } | |
| data = json.dumps(payload).encode("utf-8") | |
| attempts = max(1, server_error_max_attempts) | |
| for attempt in range(1, attempts + 1): | |
| req = urllib.request.Request(url, data=data, headers=headers, method="POST") | |
| body = "" | |
| try: | |
| with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SEC) as resp: | |
| if resp.status < 200 or resp.status >= 300: | |
| print(f"Request failed with HTTP {resp.status}: {url}", file=sys.stderr) | |
| sys.exit(1) | |
| body = resp.read().decode("utf-8") | |
| except urllib.error.HTTPError as e: | |
| err_body = e.read().decode("utf-8", errors="replace") | |
| if e.code in RETRYABLE_STATUS and attempt < attempts: | |
| print( | |
| f"HTTP {e.code} on POST {url} " | |
| f"(attempt {attempt}/{attempts}), retrying in {server_error_wait_sec}s...", | |
| file=sys.stderr, | |
| ) | |
| time.sleep(server_error_wait_sec) | |
| continue | |
| print(f"Request failed with HTTP {e.code}: {url}", file=sys.stderr) | |
| if err_body: | |
| print(err_body[:2000], file=sys.stderr) | |
| sys.exit(1) | |
| except (TimeoutError, socket.timeout, urllib.error.URLError) as e: | |
| # MUST stay below the HTTPError clause: HTTPError subclasses URLError, | |
| # so ordering it first would swallow every HTTP status here. | |
| # A stalled connection is retried exactly like a 5xx. | |
| if attempt < attempts: | |
| print( | |
| f"{type(e).__name__} on POST {url} " | |
| f"(attempt {attempt}/{attempts}), retrying in {server_error_wait_sec}s...", | |
| file=sys.stderr, | |
| ) | |
| time.sleep(server_error_wait_sec) | |
| continue | |
| print( | |
| f"Request failed after {attempts} attempts ({type(e).__name__}): {url}", | |
| file=sys.stderr, | |
| ) | |
| sys.exit(1) | |
| if not body: | |
| return {} | |
| return json.loads(body) | |
| sys.exit(1) | |
| def video_mime_from_path(path: str) -> str: | |
| lower = path.lower() | |
| if lower.endswith(".mp4"): | |
| return "video/mp4" | |
| if lower.endswith(".webm"): | |
| return "video/webm" | |
| if lower.endswith(".mov"): | |
| return "video/quicktime" | |
| if lower.endswith(".mpeg") or lower.endswith(".mpg"): | |
| return "video/mpeg" | |
| print( | |
| "Unsupported video extension (use .mp4, .webm, .mov, .mpeg, .mpg): " | |
| f"{path}", | |
| file=sys.stderr, | |
| ) | |
| sys.exit(1) | |
| def video_data_uri_from_file(video_path: str) -> str: | |
| p = video_path if os.path.isabs(video_path) else os.path.abspath(video_path) | |
| if not os.path.isfile(p): | |
| print(f"Video file not found: {p}", file=sys.stderr) | |
| sys.exit(1) | |
| with open(p, "rb") as f: | |
| raw = f.read() | |
| if not raw: | |
| print(f"Video file is empty: {p}", file=sys.stderr) | |
| sys.exit(1) | |
| b64 = base64.standard_b64encode(raw).decode("ascii") | |
| return f"data:{video_mime_from_path(p)};base64,{b64}" | |
| def build_messages_gemini_video(question: str, video_data_uri: str) -> list[dict]: | |
| """Question text plus one image_url part holding the whole clip.""" | |
| return [ | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "text", "text": question}, | |
| { | |
| "type": "image_url", | |
| "image_url": {"url": video_data_uri}, | |
| }, | |
| ], | |
| } | |
| ] | |
| def load_cv2(): | |
| if importlib.util.find_spec("cv2") is None: | |
| print( | |
| "Frame mode needs OpenCV: pip install opencv-python-headless", | |
| file=sys.stderr, | |
| ) | |
| sys.exit(1) | |
| import cv2 | |
| return cv2 | |
| def extract_jpeg_base64_frames(video_path: str, max_frames: int) -> list[str]: | |
| """Return up to ``max_frames`` JPEG frames spread evenly from the first to the last frame.""" | |
| cv2 = load_cv2() | |
| cap = cv2.VideoCapture(video_path) | |
| if not cap.isOpened(): | |
| print(f"Cannot open video for frame extraction: {video_path}", file=sys.stderr) | |
| sys.exit(1) | |
| total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) | |
| out: list[str] = [] | |
| if total <= 0: | |
| # Frame count unavailable: decode everything, then subsample evenly. | |
| frames = [] | |
| while True: | |
| ok, fr = cap.read() | |
| if not ok: | |
| break | |
| frames.append(fr) | |
| cap.release() | |
| if not frames: | |
| return out | |
| n = min(max_frames, len(frames)) | |
| idxs = [round(i * (len(frames) - 1) / max(1, n - 1)) for i in range(n)] if n > 1 else [0] | |
| for i in idxs: | |
| ok, buf = cv2.imencode(".jpg", frames[i]) | |
| if ok: | |
| out.append(base64.standard_b64encode(buf.tobytes()).decode("ascii")) | |
| return out | |
| n = min(max_frames, total) | |
| idxs = [round(i * (total - 1) / max(1, n - 1)) for i in range(n)] if n > 1 else [0] | |
| for i in idxs: | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, i) | |
| ok, fr = cap.read() | |
| if not ok: | |
| continue | |
| enc_ok, buf = cv2.imencode(".jpg", fr) | |
| if enc_ok: | |
| out.append(base64.standard_b64encode(buf.tobytes()).decode("ascii")) | |
| cap.release() | |
| return out | |
| def build_messages_openai_frames(question: str, jpeg_base64_frames: list[str]) -> list[dict]: | |
| """Question text plus one data:image/jpeg;base64,... part per frame.""" | |
| parts: list[dict] = [{"type": "text", "text": question}] | |
| for b64 in jpeg_base64_frames: | |
| parts.append( | |
| { | |
| "type": "image_url", | |
| "image_url": {"url": f"data:image/jpeg;base64,{b64}"}, | |
| } | |
| ) | |
| return [{"role": "user", "content": parts}] | |
| def resolve_input_mode(flag: str, model: str) -> str: | |
| """``auto`` sends frames to GPT models and the whole clip to every other model.""" | |
| if flag in ("openai_frames", "gemini_video"): | |
| return flag | |
| m = (model or "").lower() | |
| if "gpt-" in m or "/gpt" in m: | |
| return "openai_frames" | |
| return "gemini_video" | |
| def extract_assistant_text(response: dict) -> str: | |
| choices = response.get("choices") | |
| if not isinstance(choices, list) or not choices: | |
| return "" | |
| ch0 = choices[0] | |
| if not isinstance(ch0, dict): | |
| return "" | |
| msg = ch0.get("message") | |
| if not isinstance(msg, dict): | |
| return "" | |
| content = msg.get("content") | |
| if isinstance(content, str): | |
| return content.strip() | |
| if isinstance(content, list): | |
| parts: list[str] = [] | |
| for part in content: | |
| if not isinstance(part, dict): | |
| continue | |
| if part.get("type") == "text": | |
| t = (part.get("text") or "").strip() | |
| if t: | |
| parts.append(t) | |
| return "\n".join(parts).strip() | |
| return "" | |
| def query_model( | |
| video_path: str, | |
| question: str, | |
| model: str, | |
| api_url: str, | |
| api_key: str, | |
| input_mode: str, | |
| max_frames: int, | |
| robot_type: str = "", | |
| ) -> str: | |
| """Send the clip and question to a model and return its answer text.""" | |
| if resolve_input_mode(input_mode, model) == "openai_frames": | |
| messages = build_messages_openai_frames( | |
| question, extract_jpeg_base64_frames(video_path, max_frames), | |
| ) | |
| else: | |
| messages = build_messages_gemini_video(question, video_data_uri_from_file(video_path)) | |
| if robot_type: | |
| messages = [ | |
| {"role": "system", "content": f"You are a {robot_type}."}, | |
| *messages, | |
| ] | |
| payload = {"model": model, "messages": messages} | |
| response = post_chat_completion( | |
| api_url, api_key, payload, API_MAX_ATTEMPTS, API_RETRY_WAIT_SEC, | |
| ) | |
| return extract_assistant_text(response) | |