Upload bench_eval_code/bench_utils.py with huggingface_hub
Browse files
bench_eval_code/bench_utils.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shared utilities for CPI-Bench evaluation scripts.
|
| 3 |
+
Includes: API key pool, image helpers, retry-wrapped VLM caller.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import base64
|
| 7 |
+
import io
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
|
| 14 |
+
MAX_RETRIES = 3
|
| 15 |
+
RETRY_DELAY_BASE = 2 # exponential backoff base (seconds)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ApiKeyPool:
|
| 19 |
+
"""Thread-safe round-robin API key pool (supports multiple keys for higher QPS)."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, keys: list):
|
| 22 |
+
if not keys:
|
| 23 |
+
raise ValueError("At least one API key must be provided.")
|
| 24 |
+
self._keys = list(keys)
|
| 25 |
+
self._index = 0
|
| 26 |
+
self._lock = threading.Lock()
|
| 27 |
+
|
| 28 |
+
def next_key(self) -> str:
|
| 29 |
+
with self._lock:
|
| 30 |
+
key = self._keys[self._index % len(self._keys)]
|
| 31 |
+
self._index += 1
|
| 32 |
+
return key
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def pil_to_base64(img: Image.Image, fmt: str = "PNG") -> str:
|
| 36 |
+
"""Encode a PIL image (already RGB) to base64 string."""
|
| 37 |
+
if img.mode == "RGBA":
|
| 38 |
+
# flatten transparency onto white background
|
| 39 |
+
white_bg = Image.new("RGB", img.size, (255, 255, 255))
|
| 40 |
+
white_bg.paste(img, mask=img.split()[3])
|
| 41 |
+
img = white_bg
|
| 42 |
+
elif img.mode != "RGB":
|
| 43 |
+
img = img.convert("RGB")
|
| 44 |
+
buffer = io.BytesIO()
|
| 45 |
+
img.save(buffer, format=fmt)
|
| 46 |
+
return base64.b64encode(buffer.getvalue()).decode("utf-8")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_local_image(path: str) -> Image.Image:
|
| 50 |
+
"""Load a locally-saved result image (produced by the model being evaluated)."""
|
| 51 |
+
img = Image.open(path)
|
| 52 |
+
img.load()
|
| 53 |
+
if img.mode == "RGBA":
|
| 54 |
+
white_bg = Image.new("RGB", img.size, (255, 255, 255))
|
| 55 |
+
white_bg.paste(img, mask=img.split()[3])
|
| 56 |
+
return white_bg
|
| 57 |
+
return img.convert("RGB")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def call_vlm_with_retries(
|
| 61 |
+
content_parts: list,
|
| 62 |
+
api_key_pool: ApiKeyPool,
|
| 63 |
+
base_url: str,
|
| 64 |
+
model: str,
|
| 65 |
+
max_tokens: int = 8192,
|
| 66 |
+
temperature: float = 0.1,
|
| 67 |
+
top_p: float = 0.95,
|
| 68 |
+
extra_body: dict | None = None,
|
| 69 |
+
tag: str = "",
|
| 70 |
+
) -> str:
|
| 71 |
+
"""
|
| 72 |
+
Call an OpenAI-compatible chat completions endpoint with retries.
|
| 73 |
+
Returns the raw text content, or a string starting with 'Error' on failure.
|
| 74 |
+
"""
|
| 75 |
+
last_error = None
|
| 76 |
+
for attempt in range(1, MAX_RETRIES + 1):
|
| 77 |
+
api_key = api_key_pool.next_key()
|
| 78 |
+
client = OpenAI(api_key=api_key, base_url=base_url)
|
| 79 |
+
try:
|
| 80 |
+
kwargs = dict(
|
| 81 |
+
model=model,
|
| 82 |
+
messages=[{"role": "user", "content": content_parts}],
|
| 83 |
+
timeout=120,
|
| 84 |
+
max_tokens=max_tokens,
|
| 85 |
+
temperature=temperature,
|
| 86 |
+
top_p=top_p,
|
| 87 |
+
)
|
| 88 |
+
if extra_body:
|
| 89 |
+
kwargs["extra_body"] = extra_body
|
| 90 |
+
response = client.chat.completions.create(**kwargs)
|
| 91 |
+
return response.choices[0].message.content
|
| 92 |
+
except Exception as e:
|
| 93 |
+
last_error = e
|
| 94 |
+
if attempt < MAX_RETRIES:
|
| 95 |
+
delay = RETRY_DELAY_BASE * (2 ** (attempt - 1))
|
| 96 |
+
print(f"[{tag}] Attempt {attempt} failed: {e}. Retrying in {delay}s...")
|
| 97 |
+
time.sleep(delay)
|
| 98 |
+
return f"Error after {MAX_RETRIES} retries: {last_error}"
|