Download eval/common.py from InfoVis/VisSlideBench: direct link, hf CLI and curl.
- Browser
- Download file 3.72 kB
-
https://huggingface.co/datasets/InfoVis/VisSlideBench/resolve/main/eval/common.py
- Command line
-
hf download hf://datasets/InfoVis/VisSlideBench/eval/common.py
-
curl -L -o common.py https://huggingface.co/datasets/InfoVis/VisSlideBench/resolve/main/eval/common.py
3.72 kB
| """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) | |