PosterText-30K / code /postereval /openrouter_client.py
HGTasd's picture
Initial clean release
ec21fa4 verified
#!/usr/bin/env python3
"""Small OpenRouter JSON client used by the public PosterEval scripts."""
import base64
import hashlib
import json
import os
import re
import threading
from io import BytesIO
from pathlib import Path
from typing import Any, Dict, Optional
from PIL import Image
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
MODEL_MAP = {
"qwen3-vl-235b": "qwen/qwen3-vl-235b-a22b-instruct",
"gpt-4o": "openai/gpt-4o",
"claude-3.5-sonnet": "anthropic/claude-3.5-sonnet",
}
_CACHE_LOCK = threading.Lock()
def resolve_model(model: str) -> str:
return MODEL_MAP.get(model, model)
def clean_json_string(text: str) -> str:
text = (text or "").strip()
if "```json" in text:
match = re.search(r"```json\s*([\s\S]*?)\s*```", text)
if match:
text = match.group(1)
elif text.startswith("```"):
text = re.sub(r"^```\w*\n?", "", text)
text = re.sub(r"\n?```$", "", text)
start = text.find("{")
end = text.rfind("}")
if start != -1 and end != -1 and end > start:
text = text[start : end + 1]
text = text.replace("\r", " ").replace("\n", " ")
text = re.sub(r"[\x00-\x1f]", " ", text)
return re.sub(r"\s+", " ", text).strip()
def parse_json_response(text: str) -> Dict[str, Any]:
try:
payload = json.loads(clean_json_string(text))
if isinstance(payload, dict):
return payload
except json.JSONDecodeError:
pass
return {
"parse_error": True,
"raw_response": text,
"error": "Could not parse a JSON object from the model response.",
}
def encode_image_data_url(
image_path: Path,
max_edge: int = 1600,
jpeg_quality: int = 85,
) -> str:
image = Image.open(image_path)
width, height = image.size
if max(width, height) > max_edge:
ratio = max_edge / float(max(width, height))
image = image.resize(
(max(1, int(width * ratio)), max(1, int(height * ratio))),
Image.LANCZOS,
)
if image.mode != "RGB":
image = image.convert("RGB")
buffer = BytesIO()
image.save(buffer, format="JPEG", quality=jpeg_quality)
encoded = base64.b64encode(buffer.getvalue()).decode("utf-8")
return "data:image/jpeg;base64," + encoded
def _cache_path(model: str, prompt: str, image_path: Optional[Path]) -> Optional[Path]:
cache_dir = os.getenv("POSTEREVAL_LLM_CACHE_DIR", "").strip()
if not cache_dir:
return None
digest = hashlib.sha256()
digest.update(model.encode("utf-8"))
digest.update(b"\0")
digest.update(prompt.encode("utf-8"))
if image_path is not None:
digest.update(b"\0")
digest.update(str(image_path.name).encode("utf-8"))
try:
digest.update(image_path.read_bytes())
except OSError:
digest.update(str(image_path).encode("utf-8"))
return Path(cache_dir) / (digest.hexdigest() + ".json")
def _read_cache(path: Optional[Path]) -> Optional[Dict[str, Any]]:
if path is None or not path.exists():
return None
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return None
return payload if isinstance(payload, dict) else None
def _write_cache(path: Optional[Path], payload: Dict[str, Any]) -> None:
if path is None or payload.get("parse_error"):
return
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_suffix("." + str(threading.get_ident()) + ".tmp")
with _CACHE_LOCK:
if path.exists():
return
temp_path.write_text(
json.dumps(payload, ensure_ascii=False) + "\n",
encoding="utf-8",
)
os.replace(temp_path, path)
def call_openrouter_json(
prompt: str,
model: str = "qwen3-vl-235b",
image_path: Optional[Path] = None,
max_tokens: int = 16384,
temperature: float = 0.0,
response_format_json: bool = True,
) -> Dict[str, Any]:
"""Call OpenRouter and parse a JSON response.
Set `OPENROUTER_API_KEY` in the environment. `POSTEREVAL_LLM_CACHE_DIR` is
optional and stores parsed JSON responses keyed by model, prompt, and image.
"""
from openai import OpenAI
model_name = resolve_model(model)
cache_path = _cache_path(model_name, prompt, image_path)
cached = _read_cache(cache_path)
if cached is not None:
return cached
api_key = os.getenv("OPENROUTER_API_KEY", "").strip()
if not api_key:
raise RuntimeError("OPENROUTER_API_KEY is not set.")
content: Any
if image_path is None:
content = prompt
else:
content = [
{"type": "image_url", "image_url": {"url": encode_image_data_url(image_path)}},
{"type": "text", "text": prompt},
]
client = OpenAI(
base_url=os.getenv("OPENROUTER_BASE_URL", OPENROUTER_BASE_URL),
api_key=api_key,
default_headers={
"HTTP-Referer": "https://postereval.local",
"X-Title": "PosterEval",
},
)
kwargs: Dict[str, Any] = {
"model": model_name,
"messages": [{"role": "user", "content": content}],
"temperature": temperature,
"max_tokens": max_tokens,
}
if response_format_json:
kwargs["response_format"] = {"type": "json_object"}
response = client.chat.completions.create(**kwargs)
raw_text = response.choices[0].message.content or ""
payload = parse_json_response(raw_text)
_write_cache(cache_path, payload)
return payload