|
| 1 | +"""OpenRouter image generation provider — uses any image model via the OpenAI-compatible API.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import base64 |
| 6 | +import re |
| 7 | +from io import BytesIO |
| 8 | +from typing import Optional |
| 9 | + |
| 10 | +import structlog |
| 11 | +from PIL import Image |
| 12 | +from tenacity import retry, stop_after_attempt, wait_exponential |
| 13 | + |
| 14 | +from paperbanana.providers.base import ImageGenProvider |
| 15 | + |
| 16 | +logger = structlog.get_logger() |
| 17 | + |
| 18 | + |
| 19 | +class OpenRouterImageGen(ImageGenProvider): |
| 20 | + """Image generation routed through OpenRouter. |
| 21 | +
|
| 22 | + Talks to models that support ``modalities: ["image", "text"]`` |
| 23 | + (e.g. google/gemini-3-pro-image-preview) and returns a PIL Image |
| 24 | + decoded from the base64 response. |
| 25 | +
|
| 26 | + Get an API key at https://openrouter.ai/keys |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, |
| 31 | + api_key: Optional[str] = None, |
| 32 | + model: str = "google/gemini-3-pro-image-preview", |
| 33 | + ): |
| 34 | + self._api_key = api_key |
| 35 | + self._model = model |
| 36 | + self._client = None |
| 37 | + |
| 38 | + @property |
| 39 | + def name(self) -> str: |
| 40 | + return "openrouter_imagen" |
| 41 | + |
| 42 | + @property |
| 43 | + def model_name(self) -> str: |
| 44 | + return self._model |
| 45 | + |
| 46 | + def _get_client(self): |
| 47 | + """Lazy-init an async httpx client pointed at the OpenRouter API.""" |
| 48 | + if self._client is None: |
| 49 | + import httpx |
| 50 | + |
| 51 | + self._client = httpx.AsyncClient( |
| 52 | + base_url="https://openrouter.ai/api/v1", |
| 53 | + headers={ |
| 54 | + "Authorization": f"Bearer {self._api_key}", |
| 55 | + "HTTP-Referer": "https://github.com/llmsresearch/paperbanana", |
| 56 | + "X-Title": "PaperBanana", |
| 57 | + }, |
| 58 | + # Image generation can take a while |
| 59 | + timeout=180.0, |
| 60 | + ) |
| 61 | + return self._client |
| 62 | + |
| 63 | + def is_available(self) -> bool: |
| 64 | + return self._api_key is not None |
| 65 | + |
| 66 | + def _aspect_ratio_hint(self, width: int, height: int) -> str: |
| 67 | + """Turn pixel dimensions into a human-readable aspect ratio hint for the prompt.""" |
| 68 | + ratio = width / height |
| 69 | + if ratio > 1.5: |
| 70 | + return "wide landscape format (16:9)" |
| 71 | + if ratio > 1.2: |
| 72 | + return "landscape format (3:2)" |
| 73 | + if ratio < 0.67: |
| 74 | + return "tall portrait format (9:16)" |
| 75 | + if ratio < 0.83: |
| 76 | + return "portrait format (2:3)" |
| 77 | + return "square format (1:1)" |
| 78 | + |
| 79 | + @retry(stop=stop_after_attempt(3), wait=wait_exponential(min=2, max=30)) |
| 80 | + async def generate( |
| 81 | + self, |
| 82 | + prompt: str, |
| 83 | + negative_prompt: Optional[str] = None, |
| 84 | + width: int = 1024, |
| 85 | + height: int = 1024, |
| 86 | + seed: Optional[int] = None, |
| 87 | + ) -> Image.Image: |
| 88 | + client = self._get_client() |
| 89 | + |
| 90 | + # OpenRouter doesn't have native aspect-ratio params like the Google SDK, |
| 91 | + # so we bake the desired format into the prompt itself. |
| 92 | + aspect_hint = self._aspect_ratio_hint(width, height) |
| 93 | + full_prompt = f"{prompt}\n\nGenerate this as a {aspect_hint} image." |
| 94 | + if negative_prompt: |
| 95 | + full_prompt += f"\n\nAvoid: {negative_prompt}" |
| 96 | + |
| 97 | + payload = { |
| 98 | + "model": self._model, |
| 99 | + "messages": [ |
| 100 | + {"role": "user", "content": full_prompt}, |
| 101 | + ], |
| 102 | + # This tells OpenRouter we want an image back, not just text |
| 103 | + "modalities": ["image", "text"], |
| 104 | + } |
| 105 | + |
| 106 | + if seed is not None: |
| 107 | + payload["seed"] = seed |
| 108 | + |
| 109 | + response = await client.post("/chat/completions", json=payload) |
| 110 | + response.raise_for_status() |
| 111 | + data = response.json() |
| 112 | + |
| 113 | + message = data["choices"][0]["message"] |
| 114 | + |
| 115 | + # Primary path: images come as base64 data-URLs in the "images" array |
| 116 | + images = message.get("images", []) |
| 117 | + if images: |
| 118 | + for img_entry in images: |
| 119 | + url = img_entry.get("image_url", {}).get("url", "") |
| 120 | + if url.startswith("data:image/"): |
| 121 | + b64_data = url.split(",", 1)[1] |
| 122 | + image_bytes = base64.b64decode(b64_data) |
| 123 | + return Image.open(BytesIO(image_bytes)) |
| 124 | + |
| 125 | + # Fallback: some models inline the base64 data directly in the text content |
| 126 | + content = message.get("content", "") |
| 127 | + if "data:image/" in content: |
| 128 | + match = re.search(r"data:image/[^;]+;base64,([A-Za-z0-9+/=]+)", content) |
| 129 | + if match: |
| 130 | + image_bytes = base64.b64decode(match.group(1)) |
| 131 | + return Image.open(BytesIO(image_bytes)) |
| 132 | + |
| 133 | + logger.error("No image data in OpenRouter response", model=self._model) |
| 134 | + raise ValueError( |
| 135 | + f"OpenRouter response for {self._model} did not contain image data. " |
| 136 | + f"Content preview: {content[:200]}" |
| 137 | + ) |
0 commit comments