CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-webuiapi

Python API client for AUTOMATIC1111/stable-diffusion-webui enabling programmatic Stable Diffusion image generation

Overview
Eval results
Files

configuration.mddocs/

Configuration

WebUI configuration management, option retrieval and modification, system status monitoring, and utility functions for managing the API client and server settings.

Capabilities

Options Management

Retrieve and modify WebUI configuration settings and options.

def get_options() -> Dict:
    """
    Get all current WebUI configuration options.

    Returns:
    Dictionary containing all WebUI settings including:
    - Model settings (default model, VAE, etc.)
    - Generation defaults (sampler, steps, CFG scale)
    - UI preferences and behavior
    - Extension settings
    - System configuration
    """

def set_options(options: Dict) -> None:
    """
    Update WebUI configuration options.

    Parameters:
    - options: Dictionary of option names and values to update
    
    Example options:
    - "sd_model_checkpoint": Model to load
    - "CLIP_stop_at_last_layers": CLIP skip value
    - "eta_noise_seed_delta": Noise seed delta
    - "samples_save": Save generated images
    - "grid_save": Save image grids
    """

def get_cmd_flags() -> Dict:
    """
    Get command line flags used to start WebUI.

    Returns:
    Dictionary containing startup flags and their values
    """

System Status and Control

Monitor system status and control generation processes.

def get_progress() -> Dict:
    """
    Get current generation progress information.

    Returns:
    Dictionary containing:
    - progress: Progress percentage (0.0-1.0)
    - eta_relative: Estimated time remaining (seconds)
    - state: Current processing state
    - job_count: Number of jobs in queue
    - job_no: Current job number
    - sampling_step: Current sampling step
    - sampling_steps: Total sampling steps
    """

def interrupt() -> None:
    """
    Interrupt the current generation process.
    
    Stops the currently running txt2img, img2img, or processing task.
    """

def skip() -> None:
    """
    Skip the current generation and move to next in queue.
    
    Completes current step but skips remaining steps in generation.
    """

def get_memory() -> Dict:
    """
    Get system memory usage information.

    Returns:
    Dictionary containing GPU and system memory statistics
    """

Authentication

Configure API authentication for secured WebUI instances.

def set_auth(username: str, password: str) -> None:
    """
    Set HTTP Basic Authentication credentials.

    Parameters:
    - username: Authentication username
    - password: Authentication password
    
    Used when WebUI is started with --api-auth option.
    Note: Credentials are sent in cleartext over HTTP.
    Use HTTPS for secure transmission.
    """

Utility and Status Functions

Helper functions for API management and status checking.

def util_wait_for_ready(check_interval: float = 5.0) -> bool:
    """
    Wait for WebUI to be ready and responsive.

    Parameters:
    - check_interval: Interval between readiness checks in seconds

    Returns:
    True if WebUI becomes ready, False on error
    
    Note: This function polls continuously until WebUI is ready.
    Use with caution in production environments.
    """

def custom_get(endpoint: str, **kwargs) -> requests.Response:
    """
    Perform custom GET request to WebUI API.

    Parameters:
    - endpoint: API endpoint path (without base URL)
    - **kwargs: Additional parameters for requests.get()

    Returns:
    Raw requests.Response object
    """

def custom_post(endpoint: str, **kwargs) -> requests.Response:
    """
    Perform custom POST request to WebUI API.

    Parameters:
    - endpoint: API endpoint path (without base URL)
    - **kwargs: Additional parameters for requests.post()

    Returns:
    Raw requests.Response object
    """

Usage Examples:

import webuiapi
import time

# Initialize API with custom configuration
api = webuiapi.WebUIApi(
    host='192.168.1.100',
    port=7860,
    use_https=True,
    username='admin',
    password='secret'
)

# Wait for WebUI to be ready
if api.util_wait_for_ready(check_interval=2.0):
    print("WebUI is ready!")
else:
    print("WebUI failed to start within timeout")
    exit(1)

# Get current configuration
current_options = api.get_options()
print(f"Current model: {current_options.get('sd_model_checkpoint')}")
print(f"Default sampler: {current_options.get('sampler_index')}")
print(f"CLIP skip: {current_options.get('CLIP_stop_at_last_layers')}")

# Update configuration
new_options = {
    "sd_model_checkpoint": "realisticVisionV40_v40VAE.safetensors",
    "CLIP_stop_at_last_layers": 2,
    "samples_save": True,
    "samples_format": "png"
}

api.set_options(new_options)
print("Configuration updated!")

# Monitor generation progress
result_future = api.txt2img(
    prompt="detailed landscape painting",
    steps=50,
    width=1024,
    height=768
)

# Poll progress while generating
while True:
    progress = api.get_progress()
    
    if progress.get('progress', 0) == 0:
        break
    
    current_step = progress.get('sampling_step', 0)
    total_steps = progress.get('sampling_steps', 1)
    eta = progress.get('eta_relative', 0)
    
    print(f"Progress: {current_step}/{total_steps} steps, ETA: {eta:.1f}s")
    time.sleep(1)

print("Generation completed!")

# Check system memory
memory_info = api.get_memory()
print(f"GPU Memory: {memory_info}")

# Get command line flags
cmd_flags = api.get_cmd_flags()
print(f"WebUI started with flags: {cmd_flags}")

# Custom API calls for advanced usage
# Get available scripts
scripts_response = api.custom_get("/sdapi/v1/scripts")
scripts = scripts_response.json()
print(f"Available scripts: {list(scripts.keys())}")

# Custom endpoint access
custom_response = api.custom_post("/sdapi/v1/extra-single-image", json={
    "image": "base64_image_data",
    "upscaler_1": "R-ESRGAN 4x+",
    "upscaling_resize": 2.0
})

# Emergency controls
# Interrupt current generation if taking too long
api.interrupt()

# Or skip to next in queue
api.skip()

# Authentication examples
# Set auth after initialization
api.set_auth("newuser", "newpassword")

# Or provide during initialization
secure_api = webuiapi.WebUIApi(
    host='secure.example.com',
    port=443,
    use_https=True,
    username='admin',
    password='secretkey'
)

# Configuration backup and restore
# Backup current settings
backup_options = api.get_options()

# Make temporary changes
temp_options = {
    "samples_save": False,
    "save_images_before_face_restoration": False
}
api.set_options(temp_options)

# Do some work...
result = api.txt2img(prompt="test image")

# Restore original settings
api.set_options(backup_options)

Advanced Configuration

Batch Processing Configuration

import webuiapi

api = webuiapi.WebUIApi()

# Configure for batch processing
batch_options = {
    "samples_save": True,
    "save_images_before_face_restoration": True,
    "save_images_before_highres_fix": True,
    "save_init_img": True,
    "outdir_samples": "/output/samples",
    "outdir_txt2img_samples": "/output/txt2img",
    "outdir_img2img_samples": "/output/img2img"
}

api.set_options(batch_options)

# Batch generate with automatic saving
for i in range(10):
    result = api.txt2img(
        prompt=f"landscape variation {i}",
        seed=1000 + i,
        save_images=True
    )

Performance Optimization

# Optimize for speed
speed_options = {
    "do_not_show_images": True,
    "show_progress_every_n_steps": 10,
    "samples_save": False,
    "grid_save": False
}

api.set_options(speed_options)

# Optimize for quality
quality_options = {
    "do_not_show_images": False,
    "show_progress_every_n_steps": 1,
    "samples_save": True,
    "jpeg_quality": 95
}

api.set_options(quality_options)

Types

# Configuration and status types are primarily dictionaries
# returned by the WebUI API with varying structures

class WebUIApi:
    """Main API class with configuration attributes."""
    has_controlnet: bool  # ControlNet extension availability
    has_adetailer: bool  # ADetailer extension availability
    has_animatediff: bool  # AnimateDiff extension availability

Install with Tessl CLI

npx tessl i tessl/pypi-webuiapi

docs

configuration.md

controlnet.md

extensions.md

image-generation.md

image-processing.md

index.md

interfaces.md

model-management.md

tile.json