Certainly! Below is a Python script that transforms the provided Gradio-based application into a command-line interface (CLI) using argparse for parsing user inputs and plotly for displaying the generated images. The script adheres to PEP-8 standards, includes type hints, optimizes performance, and incorporates comprehensive error handling to ensure robustness and maintainability.
Overview:
-
Argument Parsing: Utilizes Python's built-in argparse module to parse command-line arguments, allowing users to input prompts and configure image generation parameters.
-
Model Initialization: Loads the Stable Diffusion model using the diffusers library, automatically selecting the appropriate device (GPU if available) and data type.
-
Image Generation: Generates images based on user-provided prompts and settings. It includes options to randomize the seed for varied outputs.
-
Image Display: Uses plotly to display the generated image in a web browser by creating an interactive HTML plot.
-
Error Handling: Implements comprehensive error handling to catch and report issues during model loading, image generation, and display processes.
Prerequisites:
Ensure you have the following packages installed:
pip install diffusers torch plotly numpy
Code:
import argparse
import sys
import random
from typing import Optional, Tuple
import numpy as np
import torch
from diffusers import DiffusionPipeline
from PIL import Image
import plotly.graph_objects as go
import plotly.io as pio
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
DEFAULT_MODEL_REPO_ID = "stabilityai/stable-diffusion-3.5-large"
def parse_arguments() -> argparse.Namespace:
"""
Parses command-line arguments.
Returns:
argparse.Namespace: Parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Generate images using Stable Diffusion from text prompts."
)
parser.add_argument(
"prompt",
type=str,
help="The text prompt to generate an image."
)
parser.add_argument(
"--negative_prompt",
type=str,
default="",
help="A negative text prompt to guide the image generation."
)
parser.add_argument(
"--seed",
type=int,
default=42,
help=f"Seed for reproducibility (0 to {MAX_SEED})."
)
parser.add_argument(
"--randomize_seed",
action="store_true",
help="Randomize the seed for each generation."
)
parser.add_argument(
"--width",
type=int,
default=1024,
help=f"Width of the generated image (minimum 512, maximum {MAX_IMAGE_SIZE})."
)
parser.add_argument(
"--height",
type=int,
default=1024,
help=f"Height of the generated image (minimum 512, maximum {MAX_IMAGE_SIZE})."
)
parser.add_argument(
"--guidance_scale",
type=float,
default=4.5,
help="Guidance scale for the image generation."
)
parser.add_argument(
"--num_inference_steps",
type=int,
default=40,
help="Number of inference steps for image generation."
)
parser.add_argument(
"--model_repo_id",
type=str,
default=DEFAULT_MODEL_REPO_ID,
help="Model repository ID from Hugging Face."
)
return parser.parse_args()
def validate_arguments(args: argparse.Namespace) -> None:
"""
Validates the command-line arguments.
Args:
args (argparse.Namespace): Parsed arguments.
Raises:
ValueError: If any argument is out of its allowed range.
"""
if not (0 <= args.seed <= MAX_SEED):
raise ValueError(f"Seed must be between 0 and {MAX_SEED}.")
if not (512 <= args.width <= MAX_IMAGE_SIZE):
raise ValueError(f"Width must be between 512 and {MAX_IMAGE_SIZE}.")
if not (512 <= args.height <= MAX_IMAGE_SIZE):
raise ValueError(f"Height must be between 512 and {MAX_IMAGE_SIZE}.")
if args.guidance_scale < 0.0:
raise ValueError("Guidance scale must be non-negative.")
if args.num_inference_steps < 1:
raise ValueError("Number of inference steps must be at least 1.")
def initialize_pipeline(model_repo_id: str) -> DiffusionPipeline:
"""
Initializes the diffusion pipeline.
Args:
model_repo_id (str): The model repository ID.
Returns:
DiffusionPipeline: The initialized pipeline.
Raises:
RuntimeError: If the pipeline cannot be loaded.
"""
try:
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = (
torch.bfloat16 if device == "cuda" else torch.float32
)
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype
)
pipeline = pipeline.to(device)
return pipeline
except Exception as e:
raise RuntimeError(f"Failed to load the model pipeline: {e}")
def generate_image(
pipeline: DiffusionPipeline,
prompt: str,
negative_prompt: str,
seed: int,
randomize_seed: bool,
width: int,
height: int,
guidance_scale: float,
num_inference_steps: int
) -> Tuple[Image.Image, int]:
"""
Generates an image using the diffusion pipeline.
Args:
pipeline (DiffusionPipeline): The diffusion pipeline.
prompt (str): The text prompt.
negative_prompt (str): The negative text prompt.
seed (int): The seed for randomness.
randomize_seed (bool): Whether to randomize the seed.
width (int): Image width.
height (int): Image height.
guidance_scale (float): Guidance scale.
num_inference_steps (int): Number of inference steps.
Returns:
Tuple[Image.Image, int]: Generated image and the seed used.
Raises:
RuntimeError: If image generation fails.
"""
try:
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator(device=pipeline.device).manual_seed(seed)
output = pipeline(
prompt=prompt,
negative_prompt=negative_prompt if negative_prompt else None,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator
)
image = output.images[0]
return image, seed
except Exception as e:
raise RuntimeError(f"Image generation failed: {e}")
def display_image(image: Image.Image, seed: int) -> None:
"""
Displays the image using plotly.
Args:
image (Image.Image): The PIL image to display.
seed (int): The seed used for generation.
"""
try:
image_rgb = image.convert("RGB")
np_image = np.array(image_rgb)
fig = go.Figure(
go.Image(z=np_image)
)
fig.update_layout(
title=f"Generated Image (Seed: {seed})",
title_x=0.5,
autosize=True
)
pio.show(fig)
except Exception as e:
print(f"Failed to display image: {e}", file=sys.stderr)
def main() -> None:
"""
Main function to execute the CLI application.
"""
try:
args = parse_arguments()
validate_arguments(args)
except Exception as e:
print(f"Argument Error: {e}", file=sys.stderr)
sys.exit(1)
try:
pipeline = initialize_pipeline(args.model_repo_id)
except RuntimeError as e:
print(e, file=sys.stderr)
sys.exit(1)
try:
image, used_seed = generate_image(
pipeline=pipeline,
prompt=args.prompt,
negative_prompt=args.negative_prompt,
seed=args.seed,
randomize_seed=args.randomize_seed,
width=args.width,
height=args.height,
guidance_scale=args.guidance_scale,
num_inference_steps=args.num_inference_steps
)
except RuntimeError as e:
print(e, file=sys.stderr)
sys.exit(1)
try:
display_image(image, used_seed)
except Exception as e:
print(f"Display Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Usage Example:
To generate an image with the prompt "A capybara wearing a suit holding a sign that reads Hello World" and display it, run the following command in your terminal:
python generate_image.py "A capybara wearing a suit holding a sign that reads Hello World"
Additional Options:
-
Specify a negative prompt:
python generate_image.py "A capybara wearing a suit holding a sign that reads Hello World" --negative_prompt "No text, no signs"
-
Randomize seed:
python generate_image.py "A capybara wearing a suit holding a sign that reads Hello World" --randomize_seed
-
Adjust image dimensions:
python generate_image.py "A capybara wearing a suit holding a sign that reads Hello World" --width 800 --height 800
-
Change guidance scale and inference steps:
python generate_image.py "A capybara wearing a suit holding a sign that reads Hello World" --guidance_scale 7.0 --num_inference_steps 50
Notes:
-
Model Repository: By default, the script uses the stabilityai/stable-diffusion-3.5-large model. You can specify a different model repository from Hugging Face using the --model_repo_id argument.
-
Device Utilization: The script automatically utilizes a GPU if available. Ensure that the appropriate CUDA drivers are installed for GPU acceleration.
-
Plotly Display: The generated image will open in your default web browser via Plotly's interactive viewer. Ensure that your environment supports opening web pages from Python scripts.
-
Error Messages: The script provides meaningful error messages for issues related to argument parsing, model loading, image generation, and display processes, enhancing robustness and user experience.
This script provides a maintainable, efficient, and user-friendly way to generate and display images using Stable Diffusion directly from the command line, adhering to best practices and coding standards.