Code

Python: Generate Images with Replicate

Generate featured images programmatically using Replicate API. Optimize and upload images to S3 storage automatically.

Python: Generate Images with Replicate

Overview

Automate image generation for your programmatic SEO pages using Replicate API. This example shows how to generate images, optimize them, and upload to S3 storage.

The Code

import os
import replicate
from io import BytesIO
from pathlib import Path
from PIL import Image
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Replicate expects REPLICATE_API_TOKEN
if os.environ.get("REPLICATE_API_KEY"):
    os.environ["REPLICATE_API_TOKEN"] = os.environ["REPLICATE_API_KEY"]

def generate_image_from_replicate(prompt: str) -> BytesIO:
    """
    Generate an image using Replicate API.
    
    Args:
        prompt: The full image generation prompt
        
    Returns:
        BytesIO object containing the generated image
    """
    print(f"Calling Replicate API...")
    
    output = replicate.run(
        "google/nano-banana-pro",
        input={
            "prompt": prompt,
            "resolution": "1K",
            "image_input": [],
            "aspect_ratio": "16:9",
            "output_format": "png",
            "safety_filter_level": "block_only_high"
        }
    )
    
    # Read the image into a BytesIO buffer
    image_data = BytesIO(output.read())
    image_data.seek(0)
    
    return image_data

def optimize_image(image_data: BytesIO, max_width: int = 1200, quality: int = 85) -> BytesIO:
    """
    Optimize image: resize if needed, convert to WebP, compress.
    """
    img = Image.open(image_data)
    
    # Convert RGBA to RGB if needed
    if img.mode in ('RGBA', 'LA', 'P'):
        background = Image.new('RGB', img.size, (255, 255, 255))
        if img.mode == 'P':
            img = img.convert('RGBA')
        background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
        img = background
    elif img.mode != 'RGB':
        img = img.convert('RGB')
    
    # Resize if larger than max_width
    if img.width > max_width:
        ratio = max_width / img.width
        new_height = int(img.height * ratio)
        img = img.resize((max_width, new_height), Image.Resampling.LANCZOS)
    
    # Save to buffer as WebP
    output = BytesIO()
    img.save(output, format='WEBP', quality=quality, method=6)
    output.seek(0)
    
    return output

def generate_and_optimize_image(prompt: str, slug: str) -> dict:
    """
    Complete workflow: generate, optimize, and return image data.
    """
    # Generate image
    raw_image = generate_image_from_replicate(prompt)
    
    # Optimize
    optimized_image = optimize_image(raw_image)
    
    # Get file size
    optimized_image.seek(0, 2)  # Seek to end
    file_size = optimized_image.tell()
    optimized_image.seek(0)  # Reset
    
    print(f"Generated and optimized: {file_size / 1024:.1f} KB")
    
    return {
        'data': optimized_image,
        'size': file_size,
        'format': 'webp'
    }

# Example usage
prompt = (
    "Clean minimalist vector illustration, isometric perspective. "
    "Magnifying glass hovering over a grid of interconnected keyword bubbles. "
    "Dark charcoal background (#0a0a0b), bright green accent (#22c55e). "
    "Modern SaaS aesthetic, 16:9, no text, high contrast"
)

result = generate_and_optimize_image(prompt, "keyword-research")

# Save locally or upload to S3
with open(f"{result['format']}_image.webp", "wb") as f:
    f.write(result['data'].read())

Key Features

  • Replicate Integration: Uses Replicate API for image generation
  • Image Optimization: Resizes and converts to WebP format
  • Memory Efficient: Uses BytesIO for in-memory processing
  • Brand Guidelines: Includes brand colors and style in prompts
  • Batch Processing: Can generate multiple images in a loop

Usage Tips

  • Create prompt templates for consistent style
  • Cache generated images to avoid regenerating
  • Upload to S3/CDN for production use
  • Monitor Replicate API costs
  • Test different models for best results

More Templates