|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import base64 |
| 4 | +import json |
| 5 | +import os |
| 6 | +import time |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any, Optional |
| 9 | + |
| 10 | +import requests as http_requests |
| 11 | +from PIL import Image |
| 12 | + |
| 13 | +from lmms_eval.api.instance import Instance |
| 14 | +from lmms_eval.api.model import lmms |
| 15 | +from lmms_eval.api.registry import register_model |
| 16 | + |
| 17 | + |
| 18 | +@register_model("openrouter_image_gen") |
| 19 | +class OpenRouterImageGen(lmms): |
| 20 | + is_simple = True |
| 21 | + |
| 22 | + def __init__( |
| 23 | + self, |
| 24 | + model_version: str = "openai/gpt-5-image-mini", |
| 25 | + output_dir: str = "./logs/openrouter_image_gen", |
| 26 | + max_new_tokens: int = 1024, |
| 27 | + temperature: Optional[float] = None, |
| 28 | + image_size: str = "1024x1024", |
| 29 | + max_retries: int = 3, |
| 30 | + timeout: int = 180, |
| 31 | + **_: Any, |
| 32 | + ) -> None: |
| 33 | + super().__init__() |
| 34 | + self.model_version = model_version |
| 35 | + self.output_dir = output_dir |
| 36 | + self.max_new_tokens = max_new_tokens |
| 37 | + self.temperature = None if temperature is None else float(temperature) |
| 38 | + self.image_size = image_size |
| 39 | + self.max_retries = max_retries |
| 40 | + self.timeout = timeout |
| 41 | + |
| 42 | + self.api_key = os.getenv("OPENROUTER_API_KEY") |
| 43 | + if not self.api_key: |
| 44 | + raise EnvironmentError("OPENROUTER_API_KEY is required for openrouter_image_gen") |
| 45 | + |
| 46 | + self.base_url = "https://openrouter.ai/api/v1/chat/completions" |
| 47 | + self.session = http_requests.Session() |
| 48 | + self.session.headers.update( |
| 49 | + { |
| 50 | + "Authorization": f"Bearer {self.api_key}", |
| 51 | + "Content-Type": "application/json", |
| 52 | + } |
| 53 | + ) |
| 54 | + |
| 55 | + Path(self.output_dir).mkdir(parents=True, exist_ok=True) |
| 56 | + |
| 57 | + def _encode_image(self, image: Image.Image) -> str: |
| 58 | + from io import BytesIO |
| 59 | + |
| 60 | + buf = BytesIO() |
| 61 | + image.convert("RGB").save(buf, format="PNG") |
| 62 | + return base64.b64encode(buf.getvalue()).decode("utf-8") |
| 63 | + |
| 64 | + def _decode_data_url(self, data_url: str) -> bytes: |
| 65 | + marker = "base64," |
| 66 | + idx = data_url.find(marker) |
| 67 | + if idx == -1: |
| 68 | + raise ValueError("Image data URL missing base64 payload") |
| 69 | + payload = data_url[idx + len(marker) :] |
| 70 | + return base64.b64decode(payload) |
| 71 | + |
| 72 | + def _extract_images(self, payload: dict[str, Any]) -> list[str]: |
| 73 | + out: list[str] = [] |
| 74 | + try: |
| 75 | + images = payload["choices"][0]["message"].get("images", []) |
| 76 | + except (KeyError, IndexError, TypeError): |
| 77 | + return out |
| 78 | + |
| 79 | + for item in images: |
| 80 | + if not isinstance(item, dict): |
| 81 | + continue |
| 82 | + image_url = item.get("image_url", {}) |
| 83 | + if not isinstance(image_url, dict): |
| 84 | + continue |
| 85 | + url = image_url.get("url") |
| 86 | + if isinstance(url, str) and url.startswith("data:image"): |
| 87 | + out.append(url) |
| 88 | + return out |
| 89 | + |
| 90 | + def _request_generation(self, prompt: str, visuals: list[Image.Image]) -> dict[str, Any]: |
| 91 | + content: list[dict[str, Any]] = [{"type": "text", "text": prompt}] |
| 92 | + for img in visuals: |
| 93 | + b64 = self._encode_image(img) |
| 94 | + content.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}) |
| 95 | + |
| 96 | + payload: dict[str, Any] = { |
| 97 | + "model": self.model_version, |
| 98 | + "messages": [{"role": "user", "content": content}], |
| 99 | + "modalities": ["text", "image"], |
| 100 | + "image": {"size": self.image_size}, |
| 101 | + "max_tokens": self.max_new_tokens, |
| 102 | + } |
| 103 | + if self.temperature is not None: |
| 104 | + payload["temperature"] = self.temperature |
| 105 | + |
| 106 | + for attempt in range(1, self.max_retries + 1): |
| 107 | + try: |
| 108 | + resp = self.session.post(self.base_url, json=payload, timeout=self.timeout) |
| 109 | + resp.raise_for_status() |
| 110 | + return resp.json() |
| 111 | + except http_requests.HTTPError as exc: |
| 112 | + detail = "" |
| 113 | + if exc.response is not None: |
| 114 | + detail = exc.response.text |
| 115 | + if attempt == self.max_retries: |
| 116 | + raise RuntimeError(f"OpenRouter HTTPError: {detail}") from exc |
| 117 | + time.sleep(min(2 * attempt, 8)) |
| 118 | + except Exception: |
| 119 | + if attempt == self.max_retries: |
| 120 | + raise |
| 121 | + time.sleep(min(2 * attempt, 8)) |
| 122 | + raise RuntimeError("Unreachable retry loop") |
| 123 | + |
| 124 | + def _save_images(self, image_data_urls: list[str], task: str, doc_id: int) -> list[str]: |
| 125 | + task_dir = Path(self.output_dir) / str(task).replace("/", "_") |
| 126 | + task_dir.mkdir(parents=True, exist_ok=True) |
| 127 | + |
| 128 | + saved_paths: list[str] = [] |
| 129 | + for idx, data_url in enumerate(image_data_urls): |
| 130 | + raw = self._decode_data_url(data_url) |
| 131 | + path = task_dir / f"{doc_id}_{idx}.png" |
| 132 | + path.write_bytes(raw) |
| 133 | + saved_paths.append(str(path)) |
| 134 | + return saved_paths |
| 135 | + |
| 136 | + def generate_until(self, requests: list[Instance]) -> list[str]: |
| 137 | + outputs: list[str] = [] |
| 138 | + for req in requests: |
| 139 | + args = req.args |
| 140 | + if len(args) < 6: |
| 141 | + outputs.append(json.dumps({"text": "", "images": []}, ensure_ascii=False)) |
| 142 | + continue |
| 143 | + ctx, gen_kwargs, doc_to_visual, doc_id, task, split = args[:6] |
| 144 | + prompt = str(ctx) |
| 145 | + local_gen_kwargs = dict(gen_kwargs or {}) |
| 146 | + |
| 147 | + visuals_raw = doc_to_visual(self.task_dict[task][split][doc_id]) |
| 148 | + visuals: list[Image.Image] = [] |
| 149 | + for item in visuals_raw: |
| 150 | + if isinstance(item, Image.Image): |
| 151 | + visuals.append(item) |
| 152 | + |
| 153 | + if "max_new_tokens" in local_gen_kwargs: |
| 154 | + self.max_new_tokens = int(local_gen_kwargs["max_new_tokens"]) |
| 155 | + if "temperature" in local_gen_kwargs: |
| 156 | + value = local_gen_kwargs["temperature"] |
| 157 | + self.temperature = None if value is None else float(value) |
| 158 | + |
| 159 | + try: |
| 160 | + data = self._request_generation(prompt=prompt, visuals=visuals) |
| 161 | + except Exception: |
| 162 | + data = self._request_generation(prompt=prompt, visuals=[]) |
| 163 | + image_urls = self._extract_images(data) |
| 164 | + saved_images = self._save_images(image_urls, task=str(task), doc_id=int(doc_id)) |
| 165 | + |
| 166 | + text = "" |
| 167 | + try: |
| 168 | + text = data["choices"][0]["message"].get("content", "") |
| 169 | + except (KeyError, IndexError, TypeError): |
| 170 | + text = "" |
| 171 | + |
| 172 | + result = {"text": text, "images": saved_images} |
| 173 | + outputs.append(json.dumps(result, ensure_ascii=False)) |
| 174 | + self.cache_hook.add_partial("generate_until", (ctx, local_gen_kwargs), outputs[-1]) |
| 175 | + |
| 176 | + return outputs |
| 177 | + |
| 178 | + def loglikelihood(self, requests: list[Instance]) -> list[tuple[float, bool]]: |
| 179 | + raise NotImplementedError("openrouter_image_gen does not support loglikelihood") |
| 180 | + |
| 181 | + def generate_until_multi_round(self, requests: list[Instance]) -> list[str]: |
| 182 | + raise NotImplementedError("openrouter_image_gen does not support multi-round generation") |
0 commit comments