Generate Images

Mirako's image generation capabilities allow you to create stunning images featuring your custom avatars, all based on the text prompts you provide.

The image generation API takes the following inputs:

  • Prompt: A detailed description of the image you want to create, including description of the scene, style, and the avatar you want to include.

  • Avatar ID: The unique identifier of the avatar you want to feature in the image. If you don't specify an avatar, a generic avatar will be used.

  • Aspect Ratio: The desired aspect ratio for the image (e.g. 16:9, 1:1)

  • Seed: An optional seed value for reproducibility. If not provided, a random seed will be used.

Quick Start

Using the CLI Tool

To quickly generating images, you can use the Mirako CLI tool and run in termina

sh
mirako image generate -p "A professional headshot of middle-aged man in a modern office environment, wearing a business suit, with soft lighting, arm-crossed." --aspect-ratio 1:1

This command will start the image generation process with the specified prompt and aspect ratio. The CLI will handle the API calls and provide you with the generated image once it's ready.

Generate Images with Avatar

To generate images featuring a specific avatar, just embed the actual avatar Id in you prompt. Like we can modify the prompt if we want to swap the subject of the above image with the desired avatar:

sh
# Replace <my_avatar_id> with your actual avatar ID (i.e. in UUID format)
mirako image generate -p "A professional headshot of <my_avatar_id> in a modern office environment, wearing a business suit, with soft lighting, arm-crossed." --aspect-ratio 1:1

You can run mirako image generate --help to see all available options.

Generating Images with API

You may also use the Mirako API directly in your application to generate images.

python
import requests
import time

# API configuration
API_KEY = "your_api_key_here"
BASE_URL = "https://mirako.co"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

def generate_avatar_image(prompt, aspect_ratio="16:9", seed=None):
    """Generate image with avatar using text prompt"""
    
    payload = {
        "prompt": prompt,
        "aspect_ratio": aspect_ratio
    }
    
    if seed:
        payload["seed"] = seed
    
    response = requests.post(
        f"{BASE_URL}/v1/image/async_generate",
        headers=headers,
        json=payload
    )
    
    if response.status_code == 200:
        result = response.json()
        task_id = result['data']['task_id']
        print(f"✅ Image generation started!")
        print(f"Task ID: {task_id}")
        return task_id
    else:
        print(f"❌ Error: {response.status_code}")
        print(response.text)
        return None

# Generate an image
avatar_id = "your_avatar_id"  # Replace with your actual avatar ID

task_id = generate_avatar_image(
    f"A professional headshot of {avatar_id} in a modern office environment, wearing a business suit, with soft lighting",
    aspect_ratio="1:1"
)

Checkout the API Reference - Image Generation for more details on the available parameters and options.

Monitoring Image Generation

Image Generation is an asynchronous process, so we need to check the status of the task to see when it is completed. You can do this by polling the status endpoint.

python
def check_image_status(task_id):
    """Check image generation status"""
    
    response = requests.get(
        f"{BASE_URL}/v1/image/async_generate/{task_id}/status",
        headers=headers
    )
    
    if response.status_code == 200:
        result = response.json()['data']
        status = result['status']
        
        print(f"Status: {status}")
        
        if status == "COMPLETED":
            image_data = result.get('image')
            print("🎉 Image generation completed!")
            return {"status": "completed", "image": image_data}
        
        elif status in ["IN_QUEUE", "IN_PROGRESS"]:
            print("⏳ Image generation in progress...")
            return {"status": "processing"}
        
        elif status in ["FAILED", "CANCELED", "TIMED_OUT"]:
            print(f"❌ Image generation failed: {status}")
            return {"status": "failed"}
        
        else:
            print(f"Unknown status: {status}")
            return {"status": "unknown"}
    else:
        print(f"Error checking status: {response.text}")
        return {"status": "error"}

def wait_for_image_completion(task_id, max_wait_time=180):  # 3 minutes
    """Wait for image generation to complete"""
    
    start_time = time.time()
    
    while time.time() - start_time < max_wait_time:
        result = check_image_status(task_id)
        
        if result["status"] == "completed":
            return result["image"]
        elif result["status"] == "failed":
            return None
        
        # Wait 5 seconds before next check
        time.sleep(5)
    
    print("⏰ Timeout: Image didn't complete within time limit")
    return None

# Wait for completion
if task_id:
    image_data = wait_for_image_completion(task_id)
    
    if image_data:
        print("✅ Image generated successfully!")
        # image_data is base64 encoded JPG
    else:
        print("❌ Image generation failed or timed out")

Aspect Ratios and Formats

Supported Aspect Ratios

Image generation supports the following aspect ratios:

Aspect Ratio Description
16:9 Widescreen - Great for presentations, banners
1:1 Square - Perfect for social media posts, profile pictures
4:3 Standard - Good for presentations, displays
3:2 Photo format - Natural photo proportions, good for prints
2:3 Portrait photo - Vertical photo format, good for portraits
3:4 Portrait - Good for mobile screens, vertical content
9:16 Vertical - Perfect for stories, mobile content

Output Formats

Generated images are returned in JPEG format, which is widely supported and suitable for most applications. The images are base64 encoded for easy transmission over the network.

Best Practices

1. Effective Prompting

  • Be specific about lighting, pose, and setting
  • Include style descriptors (professional, casual, creative)
  • Specify background preferences
  • Use consistent terminology for better results

2. Avatar Integration

  • Always include avatar ID for consistent appearance
  • Test prompts with different avatars
  • Consider avatar characteristics when writing prompts

3. Aspect Ratio Selection

  • Choose ratios based on intended use
  • Generate multiple ratios for versatile content
  • Consider platform requirements (social media, web, print)

4. Quality Control

python
def validate_generation_quality(image_results):
    """Basic quality validation for generated images"""
    
    quality_report = {
        "total": len(image_results),
        "successful": 0,
        "failed": 0,
        "issues": []
    }
    
    for result in image_results:
        if result["success"]:
            quality_report["successful"] += 1
            
            # Check file size (basic quality indicator)
            if os.path.exists(result["filepath"]):
                file_size = os.path.getsize(result["filepath"])
                if file_size < 50000:  # Less than 50KB might indicate issues
                    quality_report["issues"].append(f"Small file size: {result['filepath']}")
        else:
            quality_report["failed"] += 1
    
    return quality_report

Note

Image generation consumes credits based on resolution and complexity. Higher quality images and complex prompts require more processing resources.

Dive Deeper