File size: 9,542 Bytes
1836fe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# 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)