Quickly create an API to generate comic illustrations

更新时间:
复制 MD 格式

Create an API from scratch to generate comic illustrations.

This tutorial guides you through creating an API to generate comic illustrations from scratch.

Solution overview

You can create an application in the SpeedPix console, debug the required workflow, and publish it as a callable API. Then, you can integrate the software development kit (SDK) for your preferred language and call the API to retrieve the results of the ComfyUI task. Using the SpeedPix console and the provided SDKs, you can quickly debug your workflow and deploy it as an API.

image

Overview

You can use the Intelligent Creation Workshop platform to:

  • Create and debug ComfyUI workflows

  • Publish workflows as callable APIs

  • Quickly integrate with your applications using the Python SDK

Estimated completion time: 15 minutes

Prerequisites

Before you begin, ensure you have:

  • An Alibaba Cloud account

  • Enable Intelligent Creation Workshop service

  • Install Python 3.8+

Step 1: Create a new workflow

  1. Go to the ComfyUI Workflow Management page in the Intelligent Creation Workshop console.

  2. Click New Workflow.image

  3. Enter the workflow information, select the Text-to-Image Template, and click OK.

  4. You are redirected to the workflow editing page. Wait for the page to load. The page appears as shown in the following figure:image

Step 2: Test the workflow

  1. Modify the positive prompt and negative prompt in the node. Click Run Workflow in the upper-right corner to view the result.image

  2. Wait for the workflow to run.

  3. After the run is complete, the result is displayed as shown in the following figure.

Step 3: Publish the API

Publish the workflow

  1. After you confirm that the workflow runs successfully, click Publish to open the publish menu.

  2. Enter a Version Description, such as Simple text-to-image test.

  3. Set the Workflow input parameters. These are the parameters that the API will expose. Unexposed parameters use the default values from the workflow. If you do not pass a value for an exposed parameter during an API call, its default value from the workflow is used.

    1. Click the Add button below to add a new parameter.

    2. After you add the parameter, confirm the settings. The parameters are described as follows. Note: The node ID, such as #3, is displayed in the upper-right corner of the node in the workflow for easy reference.image

    3. To modify a parameter:

      1. Click Edit next to the field to edit the parameter alias.image

      2. Edit mode:image

      3. After editing, press Enter to save.

  4. Set the Workflow output parameters. Here, you can specify the content that the API returns.

    1. Click the Add button below to add a new output parameter.imageimage

    2. After you add the parameter, confirm the settings. You can see a preview of the corresponding output.image

  5. Publish the workflow. After you confirm the settings, click Submit and Publish.image

  6. After publishing, you can view the generated API version management information.image

Assign an alias to the workflow

  1. Click the Alias Management tab, click the New Alias button, enter an Alias Name for the API call, and select the version to associate with the alias. When you update the API version later, you can simply update the version that the alias points to. This lets you keep the alias name in your code unchanged.image

  2. Click OK. The result is shown in the following figure:image

  3. Copy the alias for later use. In this example, it is t2i_0821.

Step 4: Get API credentials

  1. After you publish the API, you must create an application to obtain an AccessKey ID and AccessKey secret. You can then use the SDK to call the API. Open the Application Management tab in the SpeedPix console.

  2. In the upper-right corner, click Create Application.image

  3. Enter an Application Name and select an Application Type, then click OK.image

  4. You are automatically redirected to the application details page. Copy the AccessKey ID and AccessKey secret for later use.image

Step 5: Python SDK integration

Install the SDK

# Recommended to install with uv
uv add speedpix

# Or install with pip
pip install speedpix

Set environment variables

export SPEEDPIX_APP_KEY="your-app-key"
export SPEEDPIX_APP_SECRET="your-app-secret"
# Optional
export SPEEDPIX_ENDPOINT="https://openai.edu-aliyun.com"

Basic call example

Create a file named cartoon_generator.py:

from speedpix import Client
import os

def generate_cartoon(prompt, negative_prompt=""):
    """
    Generate a comic illustration.
    
    Args:
        prompt (str): Positive prompt, describing the desired content.
        negative_prompt (str): Negative prompt, describing unwanted elements.
    
    Returns:
        str: The path where the generated image is saved.
    """
    try:
        # Initialize the client.
        client = Client()
        
        # Call the workflow.
        result = client.run(
            workflow_id="your_workflow_id",  # Replace with your workflow ID.
            input={
                "prompt": prompt,
                "negative_prompt": negative_prompt
            },
            alias_id="cartoon_v1"  # Replace with your alias.
        )
        
        # Save the generated image.
        output_path = f"cartoon_{hash(prompt) % 10000}.png"
        result['images']['url'].save(output_path)
        
        print(f"Image generated successfully: {output_path}")
        return output_path
        
    except Exception as e:
        print(f"Generation failed: {e}")
        return None

# Test function.
if __name__ == "__main__":
    # Generate a comic illustration.
    image_path = generate_cartoon(
        prompt="Sun Wukong comic ascending to heaven and starting to wreak havoc, comic style, color",
        negative_prompt="blurry, low quality, black and white"
    )
    
    if image_path and os.path.exists(image_path):
        print(f"File size: {os.path.getsize(image_path)} bytes")

Step 6: Verification and testing

Run the test

# Test basic functionality.
python cartoon_generator.py

# Check the generated file.
ls -la cartoon_*.png

View the generated result

Example of a generated comic illustration:

Input prompt

Generated result

"Sun Wukong comic ascending to heaven and starting to wreak havoc"

p838803

Advanced features

Error handling best practices

from speedpix import Client, PredictionError, SpeedPixException
import logging

# Configure logging.
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def robust_generate(prompt, max_retries=3):
    """Generation function with a retry mechanism."""
    client = Client()
    
    for attempt in range(max_retries):
        try:
            result = client.run(
                workflow_id="your_workflow_id",
                input={"prompt": prompt},
                alias_id="cartoon_v1"
            )
            
            output_path = f"cartoon_{attempt}_{hash(prompt) % 10000}.png"
            result['images']['url'].save(output_path)
            
            logger.info(f"Generation successful: {output_path}")
            return output_path
            
        except PredictionError as e:
            logger.error(f"Prediction error (attempt {attempt + 1}): {e}")
            if attempt == max_retries - 1:
                raise
                
        except SpeedPixException as e:
            logger.error(f"API error (attempt {attempt + 1}): {e}")
            if e.status_code == 429:  # Rate limit
                time.sleep(2 ** attempt)  # Exponential backoff
            elif attempt == max_retries - 1:
                raise
                
        except Exception as e:
            logger.error(f"Unknown error (attempt {attempt + 1}): {e}")
            if attempt == max_retries - 1:
                raise
    
    return None

Performance optimization configuration

from speedpix import Client

# High-performance configuration
client = Client(
    timeout=60.0,                    # Increase the timeout period.
    endpoint="https://your-region.com",  # Use a nearby region.
)

# Use dedicated resources (recommended for production environments).
result = client.run(
    workflow_id="your_workflow_id",
    input={"prompt": "High-quality comic generation"},
    resource_config_id="your-dedicated-resource-id"  # Dedicated resource ID
)

Troubleshooting

FAQ

Problem

Cause

Solution

Authentication failed

Invalid API credentials

Check the app_key and app_secret.

Workflow not found

Incorrect workflow ID

Confirm the workflow ID and alias.

Timeout

Request timed out

Increase the timeout parameter or use dedicated resources.

Rate limit exceeded

Request frequency is too high

Add a request interval or upgrade your quota.

Debugging tips

import logging
from speedpix import Client

# Enable detailed logging.
logging.basicConfig(level=logging.DEBUG)

client = Client()

# Check the connection.
try:
    # Simple test.
    result = client.run(
        workflow_id="your_workflow_id",
        input={"prompt": "test"},
        alias_id="cartoon_v1"
    )
    print("Connection is normal")
except Exception as e:
    print(f"Connection failed: {e}")

Related resources