Generate a single image via the pollinations.ai image API.
(prompt: str, token: str, width: int = 2048, height: int = 2048, index: int = 0, model: str = None)
| 356 | |
| 357 | |
| 358 | def generate_image(prompt: str, token: str, width: int = 2048, height: int = 2048, index: int = 0, model: str = None) -> tuple[Optional[bytes], Optional[str]]: |
| 359 | """Generate a single image via the pollinations.ai image API.""" |
| 360 | use_model = model or IMAGE_MODEL |
| 361 | |
| 362 | # Append character descriptions if not already present (loaded from prompt file) |
| 363 | if "bee mascot" not in prompt.lower(): |
| 364 | bee_desc = load_shared("bee") |
| 365 | if bee_desc: |
| 366 | prompt = f"{prompt} {bee_desc}" |
| 367 | |
| 368 | # Always append style suffix — forces consistent pixel art rendering |
| 369 | prompt = f"{prompt} {IMAGE_STYLE_SUFFIX}" |
| 370 | |
| 371 | # Strip single quotes — they cause 400 errors from the image API even when URL-encoded |
| 372 | sanitized = prompt.replace("'", "") |
| 373 | encoded_prompt = quote(sanitized) |
| 374 | base_url = f"{POLLINATIONS_IMAGE_BASE}/{encoded_prompt}" |
| 375 | |
| 376 | print(f"\n Generating image {index + 1} (model={use_model}): {prompt[:80]}...") |
| 377 | |
| 378 | last_error = None |
| 379 | |
| 380 | for attempt in range(MAX_RETRIES): |
| 381 | seed = random.randint(0, MAX_SEED) |
| 382 | |
| 383 | params = { |
| 384 | "model": use_model, |
| 385 | "width": width, |
| 386 | "height": height, |
| 387 | "quality": "hd", |
| 388 | "seed": seed, |
| 389 | "key": token, |
| 390 | "image": "https://raw.githubusercontent.com/pollinations/pollinations/main/social/prompts/brand/characters-ref.jpg", |
| 391 | } |
| 392 | |
| 393 | if attempt == 0: |
| 394 | print(f" Using seed: {seed}") |
| 395 | else: |
| 396 | backoff_delay = INITIAL_RETRY_DELAY * (2 ** attempt) |
| 397 | print(f" Retry {attempt}/{MAX_RETRIES - 1} with new seed: {seed} (waiting {backoff_delay}s)") |
| 398 | time.sleep(backoff_delay) |
| 399 | |
| 400 | try: |
| 401 | response = requests.get(base_url, params=params, timeout=300) |
| 402 | |
| 403 | if response.status_code == 200: |
| 404 | content_type = response.headers.get('content-type', '') |
| 405 | if 'image' in content_type: |
| 406 | image_bytes = response.content |
| 407 | |
| 408 | if len(image_bytes) < 1000: |
| 409 | last_error = f"Image too small ({len(image_bytes)} bytes)" |
| 410 | print(f" {last_error}") |
| 411 | continue |
| 412 | |
| 413 | # Check valid image format |
| 414 | is_jpeg = image_bytes[:2] == b'\xff\xd8' |
| 415 | is_png = image_bytes[:8] == b'\x89PNG\r\n\x1a\n' |
no test coverage detected