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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provider abstraction for eval scripts.
|
| 2 |
+
|
| 3 |
+
Defaults to HuggingFace Inference API using the HF_TOKEN from .env.
|
| 4 |
+
Override via environment variables if needed:
|
| 5 |
+
|
| 6 |
+
PROVIDER=anthropic → direct Anthropic SDK
|
| 7 |
+
PROVIDER=openrouter → OpenRouter (Claude, GPT-4V, Gemini, ...)
|
| 8 |
+
PROVIDER=hf → HuggingFace Inference API (default)
|
| 9 |
+
|
| 10 |
+
EVAL_MODEL=<model_id> → override the default model for any provider
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import base64
|
| 14 |
+
import io
|
| 15 |
+
import os
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
from PIL import Image
|
| 19 |
+
|
| 20 |
+
# Load .env from repo root so HF_TOKEN etc. are available without manual export.
|
| 21 |
+
_env_path = Path(__file__).resolve().parents[2] / ".env"
|
| 22 |
+
if _env_path.exists():
|
| 23 |
+
from dotenv import load_dotenv
|
| 24 |
+
load_dotenv(_env_path, override=False) # don't clobber already-set vars
|
| 25 |
+
|
| 26 |
+
# ── defaults ──────────────────────────────────────────────────────────────────
|
| 27 |
+
|
| 28 |
+
# HF model options by backend:
|
| 29 |
+
# hf-inference (free tier): meta-llama/Llama-3.2-11B-Vision-Instruct
|
| 30 |
+
# novita / together backends: Qwen/Qwen2-VL-7B-Instruct (set HF_BACKEND=novita)
|
| 31 |
+
#
|
| 32 |
+
# To use a different model: export EVAL_MODEL=<model_id>
|
| 33 |
+
# To use a different backend: export HF_BACKEND=novita (or together, fireworks-ai)
|
| 34 |
+
HF_BACKEND = os.environ.get("HF_BACKEND", "together")
|
| 35 |
+
HF_MODEL = "google/gemma-4-31B-it"
|
| 36 |
+
|
| 37 |
+
DEFAULTS = {
|
| 38 |
+
"anthropic": "claude-opus-4-5",
|
| 39 |
+
"openrouter": "anthropic/claude-opus-4-5",
|
| 40 |
+
"hf": HF_MODEL,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# Auto-detect provider: prefer whatever key is present.
|
| 44 |
+
def _default_provider() -> str:
|
| 45 |
+
if os.environ.get("ANTHROPIC_API_KEY"):
|
| 46 |
+
return "anthropic"
|
| 47 |
+
if os.environ.get("OPENROUTER_API_KEY"):
|
| 48 |
+
return "openrouter"
|
| 49 |
+
return "hf" # HF_TOKEN loaded from .env
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_provider() -> str:
|
| 53 |
+
return os.environ.get("PROVIDER", _default_provider()).lower()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_model() -> str:
|
| 57 |
+
return os.environ.get("EVAL_MODEL", DEFAULTS[get_provider()])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_client():
|
| 61 |
+
"""Return a client for the configured provider."""
|
| 62 |
+
provider = get_provider()
|
| 63 |
+
print(f"[provider] {provider} / {get_model()}")
|
| 64 |
+
|
| 65 |
+
if provider == "anthropic":
|
| 66 |
+
import anthropic
|
| 67 |
+
return _AnthropicWrapper(
|
| 68 |
+
anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
from openai import OpenAI
|
| 72 |
+
|
| 73 |
+
if provider == "openrouter":
|
| 74 |
+
return OpenAI(
|
| 75 |
+
base_url="https://openrouter.ai/api/v1",
|
| 76 |
+
api_key=os.environ["OPENROUTER_API_KEY"],
|
| 77 |
+
default_headers={
|
| 78 |
+
"HTTP-Referer": "https://github.com/midah/patent-wireframes",
|
| 79 |
+
"X-Title": "patent-wireframes-eval",
|
| 80 |
+
},
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if provider == "hf":
|
| 84 |
+
token = os.environ.get("HF_TOKEN")
|
| 85 |
+
if not token:
|
| 86 |
+
raise RuntimeError("HF_TOKEN not set. Add it to .env or export it.")
|
| 87 |
+
backend = os.environ.get("HF_BACKEND", HF_BACKEND)
|
| 88 |
+
return OpenAI(
|
| 89 |
+
base_url=f"https://router.huggingface.co/{backend}/v1",
|
| 90 |
+
api_key=token,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
raise ValueError(f"Unknown PROVIDER={provider!r}. Choose: anthropic, openrouter, hf")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# ── image encoding ────────────────────────────────────────────────────────────
|
| 97 |
+
|
| 98 |
+
def encode_image(path: Path, max_long_edge: int = 1024) -> tuple[str, str]:
|
| 99 |
+
"""Return (base64_str, media_type) for an image file, resized to fit."""
|
| 100 |
+
img = Image.open(path).convert("RGB")
|
| 101 |
+
w, h = img.size
|
| 102 |
+
scale = min(max_long_edge / max(w, h), 1.0)
|
| 103 |
+
if scale < 1.0:
|
| 104 |
+
img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
|
| 105 |
+
buf = io.BytesIO()
|
| 106 |
+
img.save(buf, format="JPEG", quality=85)
|
| 107 |
+
return base64.standard_b64encode(buf.getvalue()).decode(), "image/jpeg"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ── unified message API ───────────────────────────────────────────────────────
|
| 111 |
+
|
| 112 |
+
_NOTHINK_PREFIX = "/nothink\n"
|
| 113 |
+
|
| 114 |
+
def _inject_nothink(messages: list[dict]) -> list[dict]:
|
| 115 |
+
"""Prepend /nothink to any text block so thinking models skip CoT."""
|
| 116 |
+
if get_provider() != "hf" or "gemma" not in get_model().lower():
|
| 117 |
+
return messages
|
| 118 |
+
import copy
|
| 119 |
+
msgs = copy.deepcopy(messages)
|
| 120 |
+
content = msgs[0].get("content", "")
|
| 121 |
+
|
| 122 |
+
# Plain string content — prepend directly
|
| 123 |
+
if isinstance(content, str):
|
| 124 |
+
if not content.startswith("/nothink"):
|
| 125 |
+
msgs[0]["content"] = _NOTHINK_PREFIX + content
|
| 126 |
+
return msgs
|
| 127 |
+
|
| 128 |
+
# List of blocks — find first text block
|
| 129 |
+
for block in content:
|
| 130 |
+
if isinstance(block, dict) and block.get("type") == "text" and block.get("text", "").strip():
|
| 131 |
+
if not block["text"].startswith("/nothink"):
|
| 132 |
+
block["text"] = _NOTHINK_PREFIX + block["text"]
|
| 133 |
+
return msgs
|
| 134 |
+
|
| 135 |
+
# No text block found — append one
|
| 136 |
+
content.append({"type": "text", "text": _NOTHINK_PREFIX})
|
| 137 |
+
return msgs
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def chat(client, messages: list[dict], max_tokens: int = 200) -> str:
|
| 141 |
+
"""Send messages and return the text response.
|
| 142 |
+
|
| 143 |
+
Works with both the Anthropic wrapper and OpenAI-compatible clients.
|
| 144 |
+
"""
|
| 145 |
+
if isinstance(client, _AnthropicWrapper):
|
| 146 |
+
return client.chat(messages, max_tokens)
|
| 147 |
+
|
| 148 |
+
# OpenAI-compatible (OpenRouter, HF) with exponential backoff on rate limits
|
| 149 |
+
import time
|
| 150 |
+
messages = _inject_nothink(messages)
|
| 151 |
+
for attempt in range(4):
|
| 152 |
+
try:
|
| 153 |
+
resp = client.chat.completions.create(
|
| 154 |
+
model=get_model(),
|
| 155 |
+
messages=messages,
|
| 156 |
+
max_tokens=max(max_tokens, 600),
|
| 157 |
+
)
|
| 158 |
+
return (resp.choices[0].message.content or "").strip()
|
| 159 |
+
except Exception as e:
|
| 160 |
+
if "429" in str(e) or "rate" in str(e).lower():
|
| 161 |
+
wait = 4 ** attempt # 1, 4, 16, 64 seconds
|
| 162 |
+
print(f" Rate limit, retrying in {wait}s...")
|
| 163 |
+
time.sleep(wait)
|
| 164 |
+
else:
|
| 165 |
+
raise
|
| 166 |
+
return ""
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def image_message(b64: str, media_type: str, text: str) -> list[dict]:
|
| 170 |
+
"""Build a user message with one image + text, in OpenAI vision format."""
|
| 171 |
+
return [{
|
| 172 |
+
"role": "user",
|
| 173 |
+
"content": [
|
| 174 |
+
{"type": "image_url",
|
| 175 |
+
"image_url": {"url": f"data:{media_type};base64,{b64}"}},
|
| 176 |
+
{"type": "text", "text": text},
|
| 177 |
+
],
|
| 178 |
+
}]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def multi_image_message(
|
| 182 |
+
images: list[tuple[str, str]], # list of (b64, media_type)
|
| 183 |
+
text_before: str = "",
|
| 184 |
+
text_after: str = "",
|
| 185 |
+
labels: list[str] | None = None,
|
| 186 |
+
) -> list[dict]:
|
| 187 |
+
"""Build a user message with multiple images, interleaved with labels."""
|
| 188 |
+
content = []
|
| 189 |
+
if text_before:
|
| 190 |
+
content.append({"type": "text", "text": text_before})
|
| 191 |
+
for i, (b64, media_type) in enumerate(images):
|
| 192 |
+
if labels:
|
| 193 |
+
content.append({"type": "text", "text": labels[i]})
|
| 194 |
+
content.append({"type": "image_url",
|
| 195 |
+
"image_url": {"url": f"data:{media_type};base64,{b64}"}})
|
| 196 |
+
if text_after:
|
| 197 |
+
content.append({"type": "text", "text": text_after})
|
| 198 |
+
return [{"role": "user", "content": content}]
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# ── Anthropic SDK wrapper (translates to OpenAI message format) ───────────────
|
| 202 |
+
|
| 203 |
+
class _AnthropicWrapper:
|
| 204 |
+
"""Wraps anthropic.Anthropic to accept OpenAI-format image_url content."""
|
| 205 |
+
|
| 206 |
+
def __init__(self, client):
|
| 207 |
+
self._client = client
|
| 208 |
+
|
| 209 |
+
def chat(self, messages: list[dict], max_tokens: int) -> str:
|
| 210 |
+
converted = self._convert_messages(messages)
|
| 211 |
+
resp = self._client.messages.create(
|
| 212 |
+
model=get_model(),
|
| 213 |
+
max_tokens=max_tokens,
|
| 214 |
+
messages=converted,
|
| 215 |
+
)
|
| 216 |
+
return resp.content[0].text.strip()
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def _convert_messages(messages: list[dict]) -> list[dict]:
|
| 220 |
+
"""Convert OpenAI image_url format → Anthropic base64 format."""
|
| 221 |
+
out = []
|
| 222 |
+
for msg in messages:
|
| 223 |
+
role = msg["role"]
|
| 224 |
+
content = msg["content"]
|
| 225 |
+
if isinstance(content, str):
|
| 226 |
+
out.append({"role": role, "content": content})
|
| 227 |
+
continue
|
| 228 |
+
new_content = []
|
| 229 |
+
for block in content:
|
| 230 |
+
if block["type"] == "image_url":
|
| 231 |
+
url = block["image_url"]["url"]
|
| 232 |
+
# data:image/jpeg;base64,<data>
|
| 233 |
+
if url.startswith("data:"):
|
| 234 |
+
meta, data = url.split(",", 1)
|
| 235 |
+
media_type = meta.split(":")[1].split(";")[0]
|
| 236 |
+
new_content.append({
|
| 237 |
+
"type": "image",
|
| 238 |
+
"source": {
|
| 239 |
+
"type": "base64",
|
| 240 |
+
"media_type": media_type,
|
| 241 |
+
"data": data,
|
| 242 |
+
},
|
| 243 |
+
})
|
| 244 |
+
else:
|
| 245 |
+
new_content.append({
|
| 246 |
+
"type": "image",
|
| 247 |
+
"source": {"type": "url", "url": url},
|
| 248 |
+
})
|
| 249 |
+
else:
|
| 250 |
+
new_content.append(block)
|
| 251 |
+
out.append({"role": role, "content": new_content})
|
| 252 |
+
return out
|