Z-Image-Turbo-API / USAGE_EXAMPLES.md
mohamedislegend4's picture
Upload 9 files
d6e90da verified
|
Raw
History Blame Contribute Delete
8.55 kB

Z-Image-Turbo API Wrapper - Usage Examples

Setup

1. Install Dependencies

pip install -r requirements.txt

2. Run the Server

python app.py

Or with Gunicorn (production):

gunicorn -w 4 -b 0.0.0.0:5000 app:app

The server will start on http://localhost:5000


API Endpoints

Health Check

curl http://localhost:5000/health

Response:

{"status": "ok"}

Get API Info

curl http://localhost:5000/api/info

Response:

{
  "api_name": "Z-Image-Turbo API Wrapper",
  "version": "1.0.0",
  "endpoints": [...]
}

Generate Image

Method 1: Curl (Simple)

curl -X POST http://localhost:5000/api/generate \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A beautiful sunset over mountains"
  }'

Method 2: Curl (With all parameters)

curl -X POST http://localhost:5000/api/generate \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A futuristic city with neon lights",
    "steps": 30,
    "height": 512,
    "width": 512
  }'

Method 3: Curl (Save response to file)

curl -X POST http://localhost:5000/api/generate \
  -H "Content-Type: application/json" \
  -d '{"prompt": "A cat wearing sunglasses"}' \
  | jq . > response.json

Method 4: Curl (Extract image URL and download)

# Generate image and extract URL
RESPONSE=$(curl -s -X POST http://localhost:5000/api/generate \
  -H "Content-Type: application/json" \
  -d '{"prompt": "A dragon flying over a castle"}')

echo "Response: $RESPONSE"

# Extract image URL
IMAGE_URL=$(echo $RESPONSE | jq -r '.image_url')
echo "Image URL: $IMAGE_URL"

# Download the image
if [ ! -z "$IMAGE_URL" ] && [ "$IMAGE_URL" != "null" ]; then
  curl -o generated_image.png "$IMAGE_URL"
  echo "Image saved to generated_image.png"
else
  echo "No image URL found"
fi

Python Examples

Method 1: Simple Python Request

import requests
import json

# API endpoint
url = "http://localhost:5000/api/generate"

# Request payload
payload = {
    "prompt": "A beautiful sunset over mountains",
    "steps": 20,
    "height": 512,
    "width": 512
}

# Make request
response = requests.post(url, json=payload)
result = response.json()

print(json.dumps(result, indent=2))

# Get the image URL
if result.get("success"):
    image_url = result.get("image_url")
    print(f"Image URL: {image_url}")

Method 2: Download the Image

import requests
import json

url = "http://localhost:5000/api/generate"
payload = {
    "prompt": "A futuristic city with neon lights",
    "steps": 25,
    "height": 512,
    "width": 512
}

# Generate image
response = requests.post(url, json=payload)
result = response.json()

print("Generation result:")
print(json.dumps(result, indent=2))

# Download image if URL is available
if result.get("success") and result.get("image_url"):
    image_url = result["image_url"]
    print(f"\nDownloading image from: {image_url}")
    
    # Download the image
    img_response = requests.get(image_url)
    with open("downloaded_image.png", "wb") as f:
        f.write(img_response.content)
    print("Image saved to downloaded_image.png")

Method 3: Complete Class Wrapper

import requests
import json
from typing import Optional, Dict

class ZImageTurboClient:
    def __init__(self, base_url: str = "http://localhost:5000"):
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
    
    def generate(self, prompt: str, steps: int = 20, 
                height: int = 512, width: int = 512) -> Optional[Dict]:
        """Generate an image"""
        url = f"{self.base_url}/api/generate"
        payload = {
            "prompt": prompt,
            "steps": steps,
            "height": height,
            "width": width
        }
        
        try:
            response = self.session.post(url, json=payload, timeout=300)
            return response.json()
        except Exception as e:
            print(f"Error: {e}")
            return None
    
    def get_image_url(self, result: Dict) -> Optional[str]:
        """Extract image URL from result"""
        if result and result.get("success"):
            return result.get("image_url")
        return None
    
    def download_image(self, url: str, filepath: str) -> bool:
        """Download image from URL"""
        try:
            response = requests.get(url)
            with open(filepath, "wb") as f:
                f.write(response.content)
            return True
        except Exception as e:
            print(f"Download error: {e}")
            return False

# Usage
client = ZImageTurboClient()

# Generate image
result = client.generate(
    prompt="A peaceful mountain landscape",
    steps=20,
    height=768,
    width=768
)

print("Result:")
print(json.dumps(result, indent=2))

# Get URL
image_url = client.get_image_url(result)
if image_url:
    print(f"Image URL: {image_url}")
    # Download it
    client.download_image(image_url, "my_image.png")

Method 4: Async/Concurrent Requests

import requests
import json
import asyncio
from concurrent.futures import ThreadPoolExecutor

def generate_image(prompt: str, steps: int = 20) -> Optional[Dict]:
    """Generate image (blocking)"""
    url = "http://localhost:5000/api/generate"
    payload = {"prompt": prompt, "steps": steps}
    try:
        response = requests.post(url, json=payload, timeout=300)
        return response.json()
    except Exception as e:
        print(f"Error: {e}")
        return None

# Generate multiple images in parallel
prompts = [
    "A beautiful sunset",
    "A futuristic city",
    "A magical forest",
    "A serene ocean view"
]

with ThreadPoolExecutor(max_workers=2) as executor:
    results = list(executor.map(generate_image, prompts))

# Process results
for i, result in enumerate(results):
    if result and result.get("success"):
        print(f"Image {i+1}: {result.get('image_url')}")
    else:
        print(f"Image {i+1}: Failed")

Response Format

Success Response

{
  "success": true,
  "prompt": "A beautiful sunset over mountains",
  "steps": 20,
  "height": 512,
  "width": 512,
  "image_url": "https://...",
  "image_path": "/path/to/image",
  "size": 123456,
  "mime_type": "image/png",
  "filename": "image.png"
}

Error Response

{
  "success": false,
  "error": "Error message here"
}

Common Parameters

Parameter Type Default Range Description
prompt string (required) - Text description of the image
steps integer 20 1-50 Number of inference steps
height integer 512 - Image height in pixels
width integer 512 - Image width in pixels

Tips

  1. First request is slow: The Gradio API needs time to initialize
  2. Steps vs Quality: Higher steps = better quality but slower
    • 8-15: Fast, lower quality
    • 20-30: Recommended (good balance)
    • 40-50: High quality but slower
  3. Image size: Larger images take longer to generate
  4. Timeout: Default timeout is 300 seconds (5 minutes)
  5. Prompts: More detailed prompts = better results

Troubleshooting

"Connection refused"

  • Make sure the Flask server is running: python app.py

"Failed to get result"

  • The Gradio API might be slow or down
  • Try again with fewer steps or smaller image size

Timeout error

  • The image is taking too long to generate
  • Try reducing steps or image dimensions

Empty image URL

  • The API didn't return the image data
  • Check the Flask logs for details

Deploying to Production

Using Gunicorn (Recommended)

gunicorn -w 4 -b 0.0.0.0:5000 --timeout 300 app:app

Using Docker

FROM python:3.10-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY app.py .

EXPOSE 5000

CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "--timeout", "300", "app:app"]

Build and run:

docker build -t z-image-api .
docker run -p 5000:5000 z-image-api

Using Environment Variables

Create .env file:

GRADIO_API_URL=https://mohamedislegend4-z-image-turbo-api.hf.space
PORT=5000
DEBUG=False

Then modify app.py to load them:

from dotenv import load_dotenv
import os

load_dotenv()
GRADIO_API_URL = os.getenv("GRADIO_API_URL", "https://...")
PORT = int(os.getenv("PORT", 5000))