File size: 11,773 Bytes
adb8450
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

"""Run the benchmark against a multimodal model behind an OpenAI-compatible API.

For each question the model receives, as a multi-turn conversation, every session
before the one in which the question is asked, plus the turns of that session up to
the question's turn cutoff. The first user turn of each session carries the session's
clip: frames spread evenly across the ten seconds, then the audio. The question
follows with its four options in a fixed per-item shuffle, and the model is asked to
give its choice after the token <final_answer>.

Results are appended to <out-dir>/<user_id>.jsonl after every item, so an interrupted
run resumes where it stopped. Score them with eval/score.py.

Media comes from scripts/fetch_clips.py. A session whose clip could not be fetched
is given its date marker and dialogue without media.

Requires the openai package and ffmpeg on PATH.

Usage:
    export OPENAI_API_KEY=...
    python eval/run_eval.py --model <model> --data-dir data --media-dir media \\
        --out-dir results/<model> [--base-url https://...] [--users 001,002]
"""

from __future__ import annotations

import argparse
import base64
import json
import os
import random
import re
import subprocess
import sys
import time
from pathlib import Path
from typing import Any

from openai import OpenAI

SYSTEM_PROMPT = (
    "You are a wearable hearing assistant worn by one user. You talk with the user in "
    "separate sessions spread over several years. Each session begins with a 10-second "
    "audio-visual clip of what you perceived at that moment: ordered frames sampled evenly "
    "across the clip, followed "
    "by the audio. That clip describes the environment for the whole session, until the "
    "next clip appears. Each session is marked with its date."
)

SYSTEM_PROMPT_NO_AUDIO = (
    "You are a wearable assistant worn by one user. You talk with the user in separate "
    "sessions spread over several years. Each session begins with ordered frames of "
    "what you saw at that moment. Those frames describe the environment for the whole "
    "session, until the next set appears. Each session is marked with its date."
)

ANSWER_INSTRUCTIONS = (
    "Find the most appropriate answer and give your final answer (a), (b), (c), or (d) "
    "after the special token <final_answer>. Before that, in at most two sentences, "
    "state your reasons."
)

FRAME_WIDTH = 384
AUDIO_RATE = 16000
AUDIO_BITRATE = "64k"
# A second ask only covers a reply that came back whole without naming a choice.
ANSWER_ATTEMPTS = 2


def load_record(path: Path) -> dict[str, Any]:
    data = json.loads(path.read_text())
    return data[0] if isinstance(data, list) else data


def prepare_clip(media_dir: Path, cache_dir: Path, asset_id: str) -> Path | None:
    """Downscale a clip's frames and compress its audio once, so a long history fits
    in one request. Returns None when the clip was not fetched."""
    source = media_dir / asset_id
    if not (source / "audio.wav").exists():
        return None
    target = cache_dir / asset_id
    frames = sorted((source / "frames").glob("*.jpg"))
    if (target / "audio.mp3").exists() and len(list((target / "frames").glob("*.jpg"))) == len(frames):
        return target
    (target / "frames").mkdir(parents=True, exist_ok=True)
    for frame in frames:
        subprocess.run(
            ["ffmpeg", "-y", "-loglevel", "error", "-i", str(frame),
             "-vf", f"scale={FRAME_WIDTH}:-2", "-q:v", "6", str(target / "frames" / frame.name)],
            check=True,
        )
    subprocess.run(
        ["ffmpeg", "-y", "-loglevel", "error", "-i", str(source / "audio.wav"),
         "-ac", "1", "-ar", str(AUDIO_RATE), "-b:a", AUDIO_BITRATE, str(target / "audio.mp3")],
        check=True,
    )
    return target


def spread(frames: list[Path], count: int) -> list[Path]:
    """Pick ``count`` frames reaching from the first to the last."""
    if count >= len(frames):
        return frames
    if count <= 1:
        return frames[:count]
    last = len(frames) - 1
    return [frames[round(step * last / (count - 1))] for step in range(count)]


def clip_blocks(clip: Path | None, session: dict[str, Any], args: argparse.Namespace) -> list[dict]:
    blocks: list[dict] = [{"type": "text", "text": f"[{session['session_id']} | {session['timestamp']}]"}]
    if clip is None:
        return blocks
    for frame in spread(sorted((clip / "frames").glob("*.jpg")), args.frame_count):
        encoded = base64.b64encode(frame.read_bytes()).decode()
        blocks.append({"type": "image_url",
                       "image_url": {"url": f"data:image/jpeg;base64,{encoded}", "detail": args.image_detail}})
    if not args.no_audio:
        encoded = base64.b64encode((clip / "audio.mp3").read_bytes()).decode()
        blocks.append({"type": "input_audio", "input_audio": {"data": encoded, "format": "mp3"}})
    return blocks


def build_messages(
    item: dict[str, Any], sessions: list[dict[str, Any]], clips: dict[str, Path | None], args: argparse.Namespace
) -> tuple[list[dict], str, list[str]]:
    order = [session["session_id"] for session in sessions]
    location = item["question_location"]
    stop = order.index(location["session_id"])
    messages: list[dict] = [{"role": "system", "content": SYSTEM_PROMPT_NO_AUDIO if args.no_audio else SYSTEM_PROMPT}]

    def add_session(session: dict[str, Any], turns: list[dict]) -> list[dict] | None:
        pending: list[dict] | None = clip_blocks(clips[session["selected_asset_id"]], session, args)
        for turn in turns:
            if turn["role"] == "user" and pending is not None:
                messages.append({"role": "user", "content": pending + [{"type": "text", "text": turn["content"]}]})
                pending = None
            else:
                messages.append({"role": turn["role"], "content": turn["content"]})
        return pending

    for index in range(stop):
        add_session(sessions[index], sessions[index]["dialogue"])
    pending = add_session(sessions[stop], sessions[stop]["dialogue"][: location["turn_cutoff"]])

    correct = item["Correct_Answer"]
    options = [correct] + list(item["Incorrect_Answers"])
    random.Random(f"{item['candidate_id']}:{args.seed}").shuffle(options)
    gold = "abcd"[options.index(correct)]
    labelled = [f"({'abcd'[i]}) {option}" for i, option in enumerate(options)]
    text = f"{item['Question']}\n\n{ANSWER_INSTRUCTIONS}\n\n" + "\n".join(labelled)
    messages.append({"role": "user", "content": pending + [{"type": "text", "text": text}] if pending else text})
    return messages, gold, labelled


def parse_choice(reply: str) -> set[str]:
    """The choice after <final_answer>; only the parenthesised form counts, and only
    when exactly one letter is named."""
    if "<final_answer>" not in reply:
        return set()
    found = set(re.findall(r"\(([a-d])\)", reply.rsplit("<final_answer>", 1)[1].lower()))
    return found if len(found) == 1 else set()


def classify(picked: set[str], gold: str) -> str:
    if not picked:
        return "parse_failure"
    return "correct" if picked == {gold} else "wrong"


def ask(client: OpenAI, messages: list[dict], args: argparse.Namespace) -> str:
    for attempt in range(args.request_attempts):
        try:
            response = client.chat.completions.create(
                model=args.model, messages=messages, max_tokens=args.max_tokens
            )
            return (response.choices[0].message.content or "").strip()
        except Exception as error:  # noqa: BLE001 - retried, then recorded
            if attempt + 1 == args.request_attempts:
                raise
            print(f"request failed ({error}); retrying", file=sys.stderr)
            time.sleep(min(2 ** attempt * 2, 30))
    raise RuntimeError("unreachable")


def evaluate_user(client: OpenAI, user_dir: Path, args: argparse.Namespace) -> None:
    user_id = user_dir.name
    out_path = args.out_dir / f"{user_id}.jsonl"
    done: set[str] = set()
    if out_path.exists():
        for line in out_path.read_text().splitlines():
            record = json.loads(line)
            if record["outcome"] != "error":
                done.add(record["candidate_id"])

    sessions = load_record(user_dir / "7.1_dialogue_enhanced.json")["sessions"]
    items = load_record(user_dir / "10_benchmark_qa.json")["qa"]
    if args.limit:
        items = items[: args.limit]
    clips = {s["selected_asset_id"]: prepare_clip(args.media_dir, args.cache_dir, s["selected_asset_id"])
             for s in sessions}

    with out_path.open("a") as out:
        for number, item in enumerate(items, start=1):
            if item["candidate_id"] in done:
                continue
            messages, gold, labelled = build_messages(item, sessions, clips, args)
            record: dict[str, Any] = {"user_id": user_id, "candidate_id": item["candidate_id"],
                                      "type": item["Type"], "options": labelled, "gold": gold}
            started = time.time()
            try:
                reply, picked = "", set()
                for _ in range(ANSWER_ATTEMPTS):
                    reply = ask(client, messages, args)
                    picked = parse_choice(reply)
                    if picked:
                        break
                record.update(picked=sorted(picked), outcome=classify(picked, gold), reply=reply)
            except Exception as error:  # noqa: BLE001 - kept so a resumed run retries it
                record.update(picked=[], outcome="error", error=f"{type(error).__name__}: {error}"[:500])
            record["latency_s"] = round(time.time() - started, 1)
            out.write(json.dumps(record) + "\n")
            out.flush()
            print(f"{user_id} [{number}/{len(items)}] {record['outcome']}", file=sys.stderr)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--model", required=True)
    parser.add_argument("--base-url", default=None, help="OpenAI-compatible endpoint (default: OpenAI)")
    parser.add_argument("--data-dir", type=Path, default=Path("data"))
    parser.add_argument("--media-dir", type=Path, default=Path("media"))
    parser.add_argument("--cache-dir", type=Path, default=Path("media_cache"))
    parser.add_argument("--out-dir", type=Path, required=True)
    parser.add_argument("--users", default="", help="Comma-separated user IDs (default: all)")
    parser.add_argument("--frame-count", type=int, default=10, help="Frames sent per clip")
    parser.add_argument("--image-detail", choices=("low", "high", "auto"), default="high")
    parser.add_argument("--no-audio", action="store_true", help="Frames only, for models without audio input")
    parser.add_argument("--max-tokens", type=int, default=4096)
    parser.add_argument("--request-attempts", type=int, default=3)
    parser.add_argument("--seed", type=int, default=0, help="Seed for the option shuffle")
    parser.add_argument("--limit", type=int, default=0, help="First N questions per user")
    args = parser.parse_args()

    client = OpenAI(base_url=args.base_url, api_key=os.environ.get("OPENAI_API_KEY"))
    args.out_dir.mkdir(parents=True, exist_ok=True)
    users = {u.strip() for u in args.users.split(",") if u.strip()}
    for user_dir in sorted(p.parent for p in args.data_dir.glob("*/10_benchmark_qa.json")):
        if not users or user_dir.name in users:
            evaluate_user(client, user_dir, args)


if __name__ == "__main__":
    main()