File size: 3,720 Bytes
2c76448
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared helpers for VisSlideBench evaluation.

The judge is any OpenAI-compatible chat endpoint. Configure it with
environment variables; nothing is hard-coded:

    export OPENAI_API_KEY=...
    export OPENAI_BASE_URL=...      # optional, defaults to the official endpoint
    export VISSLIDEBENCH_JUDGE=gpt-4.1   # optional
"""

import base64
import json
import os
import re
import time
from io import BytesIO
from pathlib import Path

from PIL import Image

BENCH_ROOT = Path(__file__).resolve().parents[1]
PROMPT_DIR = Path(__file__).resolve().parent / "prompts"
JUDGE_MODEL = os.environ.get("VISSLIDEBENCH_JUDGE", "gpt-4.1")
MAX_RETRIES = 3


def load_jsonl(path):
    with open(path, "r", encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def write_jsonl(path, rows):
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        for row in rows:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")


def load_prompt(name):
    return (PROMPT_DIR / name).read_text(encoding="utf-8")


def bench_path(rel):
    return str(BENCH_ROOT / rel)


def get_client():
    from openai import OpenAI

    return OpenAI()  # credentials and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL


def image_to_data_uri(path, max_size=1600):
    """JPEG-encode an image with its long side capped at `max_size` pixels."""
    img = Image.open(path).convert("RGB")
    w, h = img.size
    if max(w, h) > max_size:
        r = max_size / max(w, h)
        img = img.resize((int(w * r), int(h * r)), Image.LANCZOS)
    buf = BytesIO()
    img.save(buf, format="JPEG", quality=85)
    return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("utf-8")


def image_part(path):
    return {"type": "image_url", "image_url": {"url": image_to_data_uri(path), "detail": "high"}}


def text_part(text):
    return {"type": "text", "text": text}


def parse_json_block(text):
    """Return the first JSON object or array found in a model reply."""
    text = text.strip()
    m = re.search(r"```(?:json)?\s*\n(.*?)```", text, re.DOTALL)
    if m:
        text = m.group(1).strip()
    else:
        starts = [i for i in (text.find("{"), text.find("[")) if i >= 0]
        if starts:
            s = min(starts)
            e = max(text.rfind("}"), text.rfind("]"))
            if e > s:
                text = text[s : e + 1]
    return json.loads(text)


def chat(client, system, user_content, temperature, max_tokens):
    """Call the judge with retries; returns the parsed JSON reply."""
    err = None
    for attempt in range(1, MAX_RETRIES + 1):
        try:
            resp = client.chat.completions.create(
                model=JUDGE_MODEL,
                messages=([{"role": "system", "content": system}] if system else [])
                + [{"role": "user", "content": user_content}],
                temperature=temperature,
                max_tokens=max_tokens,
            )
            return parse_json_block(resp.choices[0].message.content)
        except Exception as e:  # network errors, rate limits, unparsable replies
            err = e
            if attempt < MAX_RETRIES:
                time.sleep(2 ** attempt)
    raise RuntimeError(f"judge call failed after {MAX_RETRIES} attempts: {err}")


def mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs) if xs else None


def subdimension_mean(result):
    """Unweighted mean of the per-dimension `score` fields of a judge reply.

    The judge also returns an `overall_score`; it is not used.
    """
    scores = [v["score"] for v in result.values() if isinstance(v, dict) and "score" in v]
    return mean(float(s) for s in scores)