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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Trouter-Imagine-1 Comprehensive Examples
|
| 4 |
+
Apache 2.0 License
|
| 5 |
+
|
| 6 |
+
This file contains extensive examples demonstrating various use cases
|
| 7 |
+
and advanced techniques for the Trouter-Imagine-1 model.
|
| 8 |
+
|
| 9 |
+
Topics Covered:
|
| 10 |
+
- Basic text-to-image generation
|
| 11 |
+
- Advanced parameter tuning
|
| 12 |
+
- Batch processing workflows
|
| 13 |
+
- Style transfer techniques
|
| 14 |
+
- Prompt engineering strategies
|
| 15 |
+
- Memory optimization
|
| 16 |
+
- Multi-resolution generation
|
| 17 |
+
- Quality comparison testing
|
| 18 |
+
- Scheduler comparison
|
| 19 |
+
- Automated prompt generation
|
| 20 |
+
- Image series creation
|
| 21 |
+
- Professional workflows
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
|
| 26 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 27 |
+
import random
|
| 28 |
+
import json
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from typing import List, Dict, Tuple
|
| 31 |
+
import time
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ============================================================================
|
| 35 |
+
# EXAMPLE 1: Basic Text-to-Image Generation
|
| 36 |
+
# ============================================================================
|
| 37 |
+
|
| 38 |
+
def example_basic_generation():
|
| 39 |
+
"""
|
| 40 |
+
Simplest example of generating an image from text
|
| 41 |
+
Perfect for beginners getting started with the model
|
| 42 |
+
"""
|
| 43 |
+
print("\n" + "="*70)
|
| 44 |
+
print("EXAMPLE 1: Basic Text-to-Image Generation")
|
| 45 |
+
print("="*70)
|
| 46 |
+
|
| 47 |
+
# Load the model
|
| 48 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 49 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 50 |
+
model_id,
|
| 51 |
+
torch_dtype=torch.float16
|
| 52 |
+
)
|
| 53 |
+
pipe = pipe.to("cuda")
|
| 54 |
+
|
| 55 |
+
# Define your prompt
|
| 56 |
+
prompt = "a beautiful sunset over mountains, vibrant colors, professional photography"
|
| 57 |
+
|
| 58 |
+
# Generate the image
|
| 59 |
+
print(f"Generating: {prompt}")
|
| 60 |
+
image = pipe(prompt).images[0]
|
| 61 |
+
|
| 62 |
+
# Save the result
|
| 63 |
+
image.save("example1_basic.png")
|
| 64 |
+
print("✓ Image saved to example1_basic.png")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ============================================================================
|
| 68 |
+
# EXAMPLE 2: Using Negative Prompts for Better Quality
|
| 69 |
+
# ============================================================================
|
| 70 |
+
|
| 71 |
+
def example_negative_prompts():
|
| 72 |
+
"""
|
| 73 |
+
Demonstrates how negative prompts improve image quality
|
| 74 |
+
by specifying what NOT to include in the generation
|
| 75 |
+
"""
|
| 76 |
+
print("\n" + "="*70)
|
| 77 |
+
print("EXAMPLE 2: Using Negative Prompts")
|
| 78 |
+
print("="*70)
|
| 79 |
+
|
| 80 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 81 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 82 |
+
model_id,
|
| 83 |
+
torch_dtype=torch.float16
|
| 84 |
+
).to("cuda")
|
| 85 |
+
|
| 86 |
+
prompt = "portrait of a young woman, elegant dress, studio lighting"
|
| 87 |
+
|
| 88 |
+
# Without negative prompt
|
| 89 |
+
print("Generating WITHOUT negative prompt...")
|
| 90 |
+
image_without = pipe(prompt, num_inference_steps=30).images[0]
|
| 91 |
+
image_without.save("example2_without_negative.png")
|
| 92 |
+
|
| 93 |
+
# With negative prompt
|
| 94 |
+
negative_prompt = "blurry, low quality, distorted, bad anatomy, ugly, deformed"
|
| 95 |
+
print("Generating WITH negative prompt...")
|
| 96 |
+
image_with = pipe(
|
| 97 |
+
prompt,
|
| 98 |
+
negative_prompt=negative_prompt,
|
| 99 |
+
num_inference_steps=30
|
| 100 |
+
).images[0]
|
| 101 |
+
image_with.save("example2_with_negative.png")
|
| 102 |
+
|
| 103 |
+
print("✓ Compare example2_without_negative.png vs example2_with_negative.png")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ============================================================================
|
| 107 |
+
# EXAMPLE 3: Parameter Exploration
|
| 108 |
+
# ============================================================================
|
| 109 |
+
|
| 110 |
+
def example_parameter_exploration():
|
| 111 |
+
"""
|
| 112 |
+
Shows how different parameters affect the output
|
| 113 |
+
Tests guidance scale and inference steps
|
| 114 |
+
"""
|
| 115 |
+
print("\n" + "="*70)
|
| 116 |
+
print("EXAMPLE 3: Parameter Exploration")
|
| 117 |
+
print("="*70)
|
| 118 |
+
|
| 119 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 120 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 121 |
+
model_id,
|
| 122 |
+
torch_dtype=torch.float16
|
| 123 |
+
).to("cuda")
|
| 124 |
+
|
| 125 |
+
prompt = "a cozy cabin in snowy mountains, winter scene, warm lights"
|
| 126 |
+
|
| 127 |
+
# Test different guidance scales
|
| 128 |
+
guidance_scales = [5.0, 7.5, 10.0, 15.0]
|
| 129 |
+
|
| 130 |
+
print("Testing different guidance scales...")
|
| 131 |
+
for guidance in guidance_scales:
|
| 132 |
+
print(f" Generating with guidance_scale={guidance}")
|
| 133 |
+
image = pipe(
|
| 134 |
+
prompt,
|
| 135 |
+
guidance_scale=guidance,
|
| 136 |
+
num_inference_steps=30
|
| 137 |
+
).images[0]
|
| 138 |
+
image.save(f"example3_guidance_{guidance}.png")
|
| 139 |
+
|
| 140 |
+
# Test different step counts
|
| 141 |
+
step_counts = [15, 25, 35, 50]
|
| 142 |
+
|
| 143 |
+
print("\nTesting different step counts...")
|
| 144 |
+
for steps in step_counts:
|
| 145 |
+
print(f" Generating with {steps} steps")
|
| 146 |
+
start_time = time.time()
|
| 147 |
+
image = pipe(
|
| 148 |
+
prompt,
|
| 149 |
+
num_inference_steps=steps,
|
| 150 |
+
guidance_scale=7.5
|
| 151 |
+
).images[0]
|
| 152 |
+
elapsed = time.time() - start_time
|
| 153 |
+
image.save(f"example3_steps_{steps}.png")
|
| 154 |
+
print(f" Completed in {elapsed:.2f}s")
|
| 155 |
+
|
| 156 |
+
print("✓ Parameter exploration complete")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# ============================================================================
|
| 160 |
+
# EXAMPLE 4: Multiple Resolution Generation
|
| 161 |
+
# ============================================================================
|
| 162 |
+
|
| 163 |
+
def example_multi_resolution():
|
| 164 |
+
"""
|
| 165 |
+
Generate the same prompt at different resolutions
|
| 166 |
+
Demonstrates quality vs speed tradeoffs
|
| 167 |
+
"""
|
| 168 |
+
print("\n" + "="*70)
|
| 169 |
+
print("EXAMPLE 4: Multi-Resolution Generation")
|
| 170 |
+
print("="*70)
|
| 171 |
+
|
| 172 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 173 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 174 |
+
model_id,
|
| 175 |
+
torch_dtype=torch.float16
|
| 176 |
+
).to("cuda")
|
| 177 |
+
|
| 178 |
+
prompt = "futuristic cyberpunk city at night, neon lights, detailed"
|
| 179 |
+
|
| 180 |
+
resolutions = [
|
| 181 |
+
(512, 512, "standard"),
|
| 182 |
+
(768, 768, "high"),
|
| 183 |
+
(1024, 1024, "ultra"),
|
| 184 |
+
(768, 512, "landscape"),
|
| 185 |
+
(512, 768, "portrait")
|
| 186 |
+
]
|
| 187 |
+
|
| 188 |
+
for width, height, desc in resolutions:
|
| 189 |
+
print(f"Generating {width}x{height} ({desc})...")
|
| 190 |
+
start_time = time.time()
|
| 191 |
+
|
| 192 |
+
image = pipe(
|
| 193 |
+
prompt,
|
| 194 |
+
width=width,
|
| 195 |
+
height=height,
|
| 196 |
+
num_inference_steps=30,
|
| 197 |
+
guidance_scale=7.5
|
| 198 |
+
).images[0]
|
| 199 |
+
|
| 200 |
+
elapsed = time.time() - start_time
|
| 201 |
+
filename = f"example4_{desc}_{width}x{height}.png"
|
| 202 |
+
image.save(filename)
|
| 203 |
+
print(f" ✓ Saved {filename} ({elapsed:.2f}s)")
|
| 204 |
+
|
| 205 |
+
print("✓ Multi-resolution generation complete")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# ============================================================================
|
| 209 |
+
# EXAMPLE 5: Batch Generation with Different Seeds
|
| 210 |
+
# ============================================================================
|
| 211 |
+
|
| 212 |
+
def example_seed_variations():
|
| 213 |
+
"""
|
| 214 |
+
Generate variations of the same prompt using different seeds
|
| 215 |
+
Useful for exploring different interpretations
|
| 216 |
+
"""
|
| 217 |
+
print("\n" + "="*70)
|
| 218 |
+
print("EXAMPLE 5: Seed Variations")
|
| 219 |
+
print("="*70)
|
| 220 |
+
|
| 221 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 222 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 223 |
+
model_id,
|
| 224 |
+
torch_dtype=torch.float16
|
| 225 |
+
).to("cuda")
|
| 226 |
+
|
| 227 |
+
prompt = "a magical forest with glowing mushrooms, fairy lights, enchanted atmosphere"
|
| 228 |
+
|
| 229 |
+
seeds = [42, 123, 456, 789, 1337, 9999]
|
| 230 |
+
|
| 231 |
+
print(f"Generating {len(seeds)} variations...")
|
| 232 |
+
for i, seed in enumerate(seeds):
|
| 233 |
+
generator = torch.Generator("cuda").manual_seed(seed)
|
| 234 |
+
|
| 235 |
+
image = pipe(
|
| 236 |
+
prompt,
|
| 237 |
+
generator=generator,
|
| 238 |
+
num_inference_steps=30,
|
| 239 |
+
guidance_scale=7.5
|
| 240 |
+
).images[0]
|
| 241 |
+
|
| 242 |
+
image.save(f"example5_seed_{seed}.png")
|
| 243 |
+
print(f" ✓ Variation {i+1}/6 (seed: {seed})")
|
| 244 |
+
|
| 245 |
+
print("✓ Seed variations complete")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# ============================================================================
|
| 249 |
+
# EXAMPLE 6: Style Comparison
|
| 250 |
+
# ============================================================================
|
| 251 |
+
|
| 252 |
+
def example_style_comparison():
|
| 253 |
+
"""
|
| 254 |
+
Generate the same subject in different artistic styles
|
| 255 |
+
Shows the model's versatility across styles
|
| 256 |
+
"""
|
| 257 |
+
print("\n" + "="*70)
|
| 258 |
+
print("EXAMPLE 6: Style Comparison")
|
| 259 |
+
print("="*70)
|
| 260 |
+
|
| 261 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 262 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 263 |
+
model_id,
|
| 264 |
+
torch_dtype=torch.float16
|
| 265 |
+
).to("cuda")
|
| 266 |
+
|
| 267 |
+
base_subject = "a majestic lion"
|
| 268 |
+
|
| 269 |
+
styles = {
|
| 270 |
+
"photorealistic": "photorealistic, 4k photography, national geographic",
|
| 271 |
+
"oil_painting": "oil painting, classical art style, detailed brushstrokes",
|
| 272 |
+
"watercolor": "watercolor painting, soft colors, artistic",
|
| 273 |
+
"digital_art": "digital art, concept art, highly detailed illustration",
|
| 274 |
+
"anime": "anime style, cel shaded, vibrant colors, manga art",
|
| 275 |
+
"cyberpunk": "cyberpunk style, neon colors, futuristic, tech-enhanced",
|
| 276 |
+
"fantasy": "fantasy art style, magical, ethereal, mystical atmosphere",
|
| 277 |
+
"minimalist": "minimalist art, simple shapes, clean design, modern"
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
for style_name, style_desc in styles.items():
|
| 281 |
+
prompt = f"{base_subject}, {style_desc}"
|
| 282 |
+
print(f"Generating {style_name} style...")
|
| 283 |
+
|
| 284 |
+
image = pipe(
|
| 285 |
+
prompt,
|
| 286 |
+
num_inference_steps=35,
|
| 287 |
+
guidance_scale=8.0
|
| 288 |
+
).images[0]
|
| 289 |
+
|
| 290 |
+
image.save(f"example6_style_{style_name}.png")
|
| 291 |
+
print(f" ✓ {style_name}")
|
| 292 |
+
|
| 293 |
+
print("✓ Style comparison complete")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
# ============================================================================
|
| 297 |
+
# EXAMPLE 7: Scheduler Comparison
|
| 298 |
+
# ============================================================================
|
| 299 |
+
|
| 300 |
+
def example_scheduler_comparison():
|
| 301 |
+
"""
|
| 302 |
+
Compare different schedulers (samplers) and their outputs
|
| 303 |
+
Helps understand which scheduler works best for different use cases
|
| 304 |
+
"""
|
| 305 |
+
print("\n" + "="*70)
|
| 306 |
+
print("EXAMPLE 7: Scheduler Comparison")
|
| 307 |
+
print("="*70)
|
| 308 |
+
|
| 309 |
+
from diffusers import (
|
| 310 |
+
DPMSolverMultistepScheduler,
|
| 311 |
+
EulerAncestralDiscreteScheduler,
|
| 312 |
+
DDIMScheduler,
|
| 313 |
+
PNDMScheduler
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 317 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 318 |
+
model_id,
|
| 319 |
+
torch_dtype=torch.float16
|
| 320 |
+
).to("cuda")
|
| 321 |
+
|
| 322 |
+
prompt = "ancient temple in jungle, overgrown with vines, mystical atmosphere"
|
| 323 |
+
|
| 324 |
+
schedulers = {
|
| 325 |
+
"DPM": DPMSolverMultistepScheduler,
|
| 326 |
+
"Euler": EulerAncestralDiscreteScheduler,
|
| 327 |
+
"DDIM": DDIMScheduler,
|
| 328 |
+
"PNDM": PNDMScheduler
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
# Use same seed for fair comparison
|
| 332 |
+
seed = 42
|
| 333 |
+
|
| 334 |
+
for name, scheduler_class in schedulers.items():
|
| 335 |
+
print(f"Testing {name} scheduler...")
|
| 336 |
+
|
| 337 |
+
pipe.scheduler = scheduler_class.from_config(pipe.scheduler.config)
|
| 338 |
+
generator = torch.Generator("cuda").manual_seed(seed)
|
| 339 |
+
|
| 340 |
+
start_time = time.time()
|
| 341 |
+
image = pipe(
|
| 342 |
+
prompt,
|
| 343 |
+
generator=generator,
|
| 344 |
+
num_inference_steps=30,
|
| 345 |
+
guidance_scale=7.5
|
| 346 |
+
).images[0]
|
| 347 |
+
elapsed = time.time() - start_time
|
| 348 |
+
|
| 349 |
+
image.save(f"example7_scheduler_{name}.png")
|
| 350 |
+
print(f" ✓ {name} completed in {elapsed:.2f}s")
|
| 351 |
+
|
| 352 |
+
print("✓ Scheduler comparison complete")
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
# ============================================================================
|
| 356 |
+
# EXAMPLE 8: Memory-Optimized Generation
|
| 357 |
+
# ============================================================================
|
| 358 |
+
|
| 359 |
+
def example_memory_optimization():
|
| 360 |
+
"""
|
| 361 |
+
Demonstrates memory optimization techniques for limited VRAM
|
| 362 |
+
Useful for running on consumer GPUs
|
| 363 |
+
"""
|
| 364 |
+
print("\n" + "="*70)
|
| 365 |
+
print("EXAMPLE 8: Memory-Optimized Generation")
|
| 366 |
+
print("="*70)
|
| 367 |
+
|
| 368 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 369 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 370 |
+
model_id,
|
| 371 |
+
torch_dtype=torch.float16
|
| 372 |
+
).to("cuda")
|
| 373 |
+
|
| 374 |
+
# Enable all memory optimizations
|
| 375 |
+
print("Enabling memory optimizations...")
|
| 376 |
+
pipe.enable_attention_slicing()
|
| 377 |
+
pipe.enable_vae_slicing()
|
| 378 |
+
|
| 379 |
+
# For very limited VRAM, enable CPU offload
|
| 380 |
+
# pipe.enable_model_cpu_offload()
|
| 381 |
+
|
| 382 |
+
# Try xformers if available
|
| 383 |
+
try:
|
| 384 |
+
pipe.enable_xformers_memory_efficient_attention()
|
| 385 |
+
print(" ✓ xformers enabled")
|
| 386 |
+
except:
|
| 387 |
+
print(" ℹ xformers not available")
|
| 388 |
+
|
| 389 |
+
prompt = "detailed cityscape at sunset, skyscrapers, urban photography"
|
| 390 |
+
|
| 391 |
+
# Generate high resolution with optimizations
|
| 392 |
+
print("Generating 1024x1024 image with optimizations...")
|
| 393 |
+
image = pipe(
|
| 394 |
+
prompt,
|
| 395 |
+
width=1024,
|
| 396 |
+
height=1024,
|
| 397 |
+
num_inference_steps=30,
|
| 398 |
+
guidance_scale=7.5
|
| 399 |
+
).images[0]
|
| 400 |
+
|
| 401 |
+
image.save("example8_optimized_1024.png")
|
| 402 |
+
print("✓ High-resolution generation with optimizations complete")
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
# ============================================================================
|
| 406 |
+
# EXAMPLE 9: Automated Prompt Generation and Testing
|
| 407 |
+
# ============================================================================
|
| 408 |
+
|
| 409 |
+
def example_automated_prompts():
|
| 410 |
+
"""
|
| 411 |
+
Automatically generate and test multiple prompt combinations
|
| 412 |
+
Useful for finding optimal prompt formulations
|
| 413 |
+
"""
|
| 414 |
+
print("\n" + "="*70)
|
| 415 |
+
print("EXAMPLE 9: Automated Prompt Generation")
|
| 416 |
+
print("="*70)
|
| 417 |
+
|
| 418 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 419 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 420 |
+
model_id,
|
| 421 |
+
torch_dtype=torch.float16
|
| 422 |
+
).to("cuda")
|
| 423 |
+
|
| 424 |
+
# Build prompts from components
|
| 425 |
+
subjects = ["a dragon", "a spaceship", "a castle"]
|
| 426 |
+
settings = ["in space", "on a mountain", "underwater"]
|
| 427 |
+
styles = ["cyberpunk style", "fantasy art", "photorealistic"]
|
| 428 |
+
qualities = ["highly detailed", "4k", "masterpiece"]
|
| 429 |
+
|
| 430 |
+
print("Generating combinations...")
|
| 431 |
+
output_dir = Path("example9_automated")
|
| 432 |
+
output_dir.mkdir(exist_ok=True)
|
| 433 |
+
|
| 434 |
+
for i, subject in enumerate(subjects):
|
| 435 |
+
for j, setting in enumerate(settings):
|
| 436 |
+
style = random.choice(styles)
|
| 437 |
+
quality = random.choice(qualities)
|
| 438 |
+
|
| 439 |
+
prompt = f"{subject} {setting}, {style}, {quality}"
|
| 440 |
+
print(f" Generating: {prompt[:60]}...")
|
| 441 |
+
|
| 442 |
+
image = pipe(
|
| 443 |
+
prompt,
|
| 444 |
+
num_inference_steps=25,
|
| 445 |
+
guidance_scale=7.5
|
| 446 |
+
).images[0]
|
| 447 |
+
|
| 448 |
+
filename = output_dir / f"combo_{i}_{j}.png"
|
| 449 |
+
image.save(filename)
|
| 450 |
+
|
| 451 |
+
print(f"✓ Generated {len(subjects) * len(settings)} combinations")
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
# ============================================================================
|
| 455 |
+
# EXAMPLE 10: Image Series Generation (Storytelling)
|
| 456 |
+
# ============================================================================
|
| 457 |
+
|
| 458 |
+
def example_image_series():
|
| 459 |
+
"""
|
| 460 |
+
Generate a series of related images telling a story
|
| 461 |
+
Demonstrates consistency in sequential generation
|
| 462 |
+
"""
|
| 463 |
+
print("\n" + "="*70)
|
| 464 |
+
print("EXAMPLE 10: Image Series (Storytelling)")
|
| 465 |
+
print("="*70)
|
| 466 |
+
|
| 467 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 468 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 469 |
+
model_id,
|
| 470 |
+
torch_dtype=torch.float16
|
| 471 |
+
).to("cuda")
|
| 472 |
+
|
| 473 |
+
# Story sequence
|
| 474 |
+
story_prompts = [
|
| 475 |
+
"a young wizard finding a mysterious glowing orb in a cave, fantasy art, dramatic lighting",
|
| 476 |
+
"the wizard holding the glowing orb as magic energy swirls around him, fantasy art, detailed",
|
| 477 |
+
"the wizard casting a powerful spell with the orb, energy beams, magical effects, fantasy art",
|
| 478 |
+
"the wizard standing victorious as the orb floats above his hand, epic scene, fantasy art"
|
| 479 |
+
]
|
| 480 |
+
|
| 481 |
+
output_dir = Path("example10_story_series")
|
| 482 |
+
output_dir.mkdir(exist_ok=True)
|
| 483 |
+
|
| 484 |
+
print(f"Generating {len(story_prompts)}-part story sequence...")
|
| 485 |
+
|
| 486 |
+
for i, prompt in enumerate(story_prompts, 1):
|
| 487 |
+
print(f" Scene {i}/{len(story_prompts)}: {prompt[:50]}...")
|
| 488 |
+
|
| 489 |
+
image = pipe(
|
| 490 |
+
prompt,
|
| 491 |
+
num_inference_steps=35,
|
| 492 |
+
guidance_scale=8.0
|
| 493 |
+
).images[0]
|
| 494 |
+
|
| 495 |
+
# Add scene number to image
|
| 496 |
+
draw = ImageDraw.Draw(image)
|
| 497 |
+
try:
|
| 498 |
+
# Try to load a font, fall back to default if not available
|
| 499 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 40)
|
| 500 |
+
except:
|
| 501 |
+
font = ImageFont.load_default()
|
| 502 |
+
|
| 503 |
+
draw.text((20, 20), f"Scene {i}", fill="white", font=font)
|
| 504 |
+
|
| 505 |
+
filename = output_dir / f"scene_{i:02d}.png"
|
| 506 |
+
image.save(filename)
|
| 507 |
+
|
| 508 |
+
print("✓ Story series generation complete")
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# ============================================================================
|
| 512 |
+
# EXAMPLE 11: Quality vs Speed Benchmark
|
| 513 |
+
# ============================================================================
|
| 514 |
+
|
| 515 |
+
def example_quality_speed_benchmark():
|
| 516 |
+
"""
|
| 517 |
+
Benchmark different quality settings and their generation times
|
| 518 |
+
Helps users choose optimal settings for their use case
|
| 519 |
+
"""
|
| 520 |
+
print("\n" + "="*70)
|
| 521 |
+
print("EXAMPLE 11: Quality vs Speed Benchmark")
|
| 522 |
+
print("="*70)
|
| 523 |
+
|
| 524 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 525 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 526 |
+
model_id,
|
| 527 |
+
torch_dtype=torch.float16
|
| 528 |
+
).to("cuda")
|
| 529 |
+
|
| 530 |
+
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
| 531 |
+
|
| 532 |
+
prompt = "detailed portrait of a knight in armor, medieval, dramatic lighting"
|
| 533 |
+
|
| 534 |
+
presets = {
|
| 535 |
+
"draft": {"steps": 15, "resolution": 512, "guidance": 6.0},
|
| 536 |
+
"balanced": {"steps": 25, "resolution": 512, "guidance": 7.5},
|
| 537 |
+
"quality": {"steps": 40, "resolution": 768, "guidance": 8.0},
|
| 538 |
+
"maximum": {"steps": 50, "resolution": 1024, "guidance": 9.0}
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
results = {}
|
| 542 |
+
|
| 543 |
+
for preset_name, settings in presets.items():
|
| 544 |
+
print(f"\nTesting {preset_name} preset:")
|
| 545 |
+
print(f" Resolution: {settings['resolution']}x{settings['resolution']}")
|
| 546 |
+
print(f" Steps: {settings['steps']}")
|
| 547 |
+
print(f" Guidance: {settings['guidance']}")
|
| 548 |
+
|
| 549 |
+
start_time = time.time()
|
| 550 |
+
|
| 551 |
+
image = pipe(
|
| 552 |
+
prompt,
|
| 553 |
+
width=settings['resolution'],
|
| 554 |
+
height=settings['resolution'],
|
| 555 |
+
num_inference_steps=settings['steps'],
|
| 556 |
+
guidance_scale=settings['guidance']
|
| 557 |
+
).images[0]
|
| 558 |
+
|
| 559 |
+
elapsed = time.time() - start_time
|
| 560 |
+
results[preset_name] = elapsed
|
| 561 |
+
|
| 562 |
+
image.save(f"example11_preset_{preset_name}.png")
|
| 563 |
+
print(f" ✓ Generated in {elapsed:.2f}s")
|
| 564 |
+
|
| 565 |
+
print("\n" + "="*70)
|
| 566 |
+
print("BENCHMARK RESULTS:")
|
| 567 |
+
print("="*70)
|
| 568 |
+
for preset, time_taken in results.items():
|
| 569 |
+
print(f"{preset:>12}: {time_taken:>6.2f}s")
|
| 570 |
+
|
| 571 |
+
print("✓ Quality vs speed benchmark complete")
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
# ============================================================================
|
| 575 |
+
# EXAMPLE 12: Professional Workflow - Product Photography
|
| 576 |
+
# ============================================================================
|
| 577 |
+
|
| 578 |
+
def example_product_photography():
|
| 579 |
+
"""
|
| 580 |
+
Generate professional product photography shots
|
| 581 |
+
Demonstrates commercial use case
|
| 582 |
+
"""
|
| 583 |
+
print("\n" + "="*70)
|
| 584 |
+
print("EXAMPLE 12: Professional Product Photography")
|
| 585 |
+
print("="*70)
|
| 586 |
+
|
| 587 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 588 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 589 |
+
model_id,
|
| 590 |
+
torch_dtype=torch.float16
|
| 591 |
+
).to("cuda")
|
| 592 |
+
|
| 593 |
+
products = [
|
| 594 |
+
"luxury watch with leather strap on marble surface",
|
| 595 |
+
"modern smartphone with sleek design on white background",
|
| 596 |
+
"artisanal coffee cup with latte art on wooden table",
|
| 597 |
+
"designer sunglasses with reflection of sunset",
|
| 598 |
+
"premium headphones with soft studio lighting"
|
| 599 |
+
]
|
| 600 |
+
|
| 601 |
+
base_prompt_additions = "professional product photography, commercial, high-end, 4k, studio lighting, detailed"
|
| 602 |
+
negative_prompt = "low quality, blurry, amateur, cluttered, distorted, watermark"
|
| 603 |
+
|
| 604 |
+
output_dir = Path("example12_product_photos")
|
| 605 |
+
output_dir.mkdir(exist_ok=True)
|
| 606 |
+
|
| 607 |
+
print("Generating professional product photos...")
|
| 608 |
+
|
| 609 |
+
for i, product in enumerate(products, 1):
|
| 610 |
+
full_prompt = f"{product}, {base_prompt_additions}"
|
| 611 |
+
print(f" Product {i}/{len(products)}: {product}")
|
| 612 |
+
|
| 613 |
+
image = pipe(
|
| 614 |
+
prompt=full_prompt,
|
| 615 |
+
negative_prompt=negative_prompt,
|
| 616 |
+
width=768,
|
| 617 |
+
height=768,
|
| 618 |
+
num_inference_steps=40,
|
| 619 |
+
guidance_scale=8.5
|
| 620 |
+
).images[0]
|
| 621 |
+
|
| 622 |
+
filename = output_dir / f"product_{i:02d}.png"
|
| 623 |
+
image.save(filename)
|
| 624 |
+
|
| 625 |
+
print("✓ Professional product photography complete")
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
# ============================================================================
|
| 629 |
+
# EXAMPLE 13: Advanced - Image Grid Comparison
|
| 630 |
+
# ============================================================================
|
| 631 |
+
|
| 632 |
+
def example_image_grid():
|
| 633 |
+
"""
|
| 634 |
+
Create comparison grids showing different parameters
|
| 635 |
+
Useful for presentations and documentation
|
| 636 |
+
"""
|
| 637 |
+
print("\n" + "="*70)
|
| 638 |
+
print("EXAMPLE 13: Image Grid Comparison")
|
| 639 |
+
print("="*70)
|
| 640 |
+
|
| 641 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 642 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 643 |
+
model_id,
|
| 644 |
+
torch_dtype=torch.float16
|
| 645 |
+
).to("cuda")
|
| 646 |
+
|
| 647 |
+
prompt = "a red sports car on mountain road, sunset"
|
| 648 |
+
guidance_scales = [5.0, 7.5, 10.0, 12.5]
|
| 649 |
+
|
| 650 |
+
print("Generating images for grid...")
|
| 651 |
+
images = []
|
| 652 |
+
|
| 653 |
+
for guidance in guidance_scales:
|
| 654 |
+
print(f" Guidance scale: {guidance}")
|
| 655 |
+
image = pipe(
|
| 656 |
+
prompt,
|
| 657 |
+
guidance_scale=guidance,
|
| 658 |
+
num_inference_steps=30,
|
| 659 |
+
width=512,
|
| 660 |
+
height=512
|
| 661 |
+
).images[0]
|
| 662 |
+
|
| 663 |
+
# Add label
|
| 664 |
+
draw = ImageDraw.Draw(image)
|
| 665 |
+
draw.text((10, 10), f"Guidance: {guidance}", fill="white")
|
| 666 |
+
images.append(image)
|
| 667 |
+
|
| 668 |
+
# Create 2x2 grid
|
| 669 |
+
grid = Image.new('RGB', (1024, 1024))
|
| 670 |
+
for i, img in enumerate(images):
|
| 671 |
+
x = (i % 2) * 512
|
| 672 |
+
y = (i // 2) * 512
|
| 673 |
+
grid.paste(img, (x, y))
|
| 674 |
+
|
| 675 |
+
grid.save("example13_comparison_grid.png")
|
| 676 |
+
print("✓ Comparison grid created")
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
# ============================================================================
|
| 680 |
+
# EXAMPLE 14: Batch Processing from JSON Config
|
| 681 |
+
# ============================================================================
|
| 682 |
+
|
| 683 |
+
def example_json_batch_processing():
|
| 684 |
+
"""
|
| 685 |
+
Process multiple generations from a JSON configuration file
|
| 686 |
+
Useful for automated workflows and reproducible results
|
| 687 |
+
"""
|
| 688 |
+
print("\n" + "="*70)
|
| 689 |
+
print("EXAMPLE 14: JSON Batch Processing")
|
| 690 |
+
print("="*70)
|
| 691 |
+
|
| 692 |
+
# Create example config
|
| 693 |
+
config = {
|
| 694 |
+
"model_id": "OpenTrouter/Trouter-Imagine-1",
|
| 695 |
+
"output_dir": "example14_json_batch",
|
| 696 |
+
"default_params": {
|
| 697 |
+
"num_inference_steps": 30,
|
| 698 |
+
"guidance_scale": 7.5,
|
| 699 |
+
"width": 512,
|
| 700 |
+
"height": 512
|
| 701 |
+
},
|
| 702 |
+
"generations": [
|
| 703 |
+
{
|
| 704 |
+
"prompt": "sunset over ocean, peaceful scene",
|
| 705 |
+
"negative_prompt": "stormy, dark, gloomy",
|
| 706 |
+
"filename": "peaceful_sunset.png"
|
| 707 |
+
},
|
| 708 |
+
{
|
| 709 |
+
"prompt": "cyberpunk alley with neon signs",
|
| 710 |
+
"negative_prompt": "daytime, bright, clean",
|
| 711 |
+
"guidance_scale": 8.5,
|
| 712 |
+
"filename": "cyberpunk_alley.png"
|
| 713 |
+
},
|
| 714 |
+
{
|
| 715 |
+
"prompt": "fantasy castle on floating island",
|
| 716 |
+
"negative_prompt": "modern, realistic",
|
| 717 |
+
"width": 768,
|
| 718 |
+
"height": 768,
|
| 719 |
+
"num_inference_steps": 40,
|
| 720 |
+
"filename": "floating_castle.png"
|
| 721 |
+
}
|
| 722 |
+
]
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
# Save config
|
| 726 |
+
config_path = "example14_config.json"
|
| 727 |
+
with open(config_path, 'w') as f:
|
| 728 |
+
json.dump(config, indent=2, fp=f)
|
| 729 |
+
print(f"Config saved to {config_path}")
|
| 730 |
+
|
| 731 |
+
# Load and process
|
| 732 |
+
model_id = config["model_id"]
|
| 733 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 734 |
+
model_id,
|
| 735 |
+
torch_dtype=torch.float16
|
| 736 |
+
).to("cuda")
|
| 737 |
+
|
| 738 |
+
output_dir = Path(config["output_dir"])
|
| 739 |
+
output_dir.mkdir(exist_ok=True)
|
| 740 |
+
|
| 741 |
+
default_params = config["default_params"]
|
| 742 |
+
|
| 743 |
+
print(f"\nProcessing {len(config['generations'])} generations...")
|
| 744 |
+
|
| 745 |
+
for i, gen_config in enumerate(config["generations"], 1):
|
| 746 |
+
# Merge with defaults
|
| 747 |
+
params = {**default_params, **gen_config}
|
| 748 |
+
|
| 749 |
+
prompt = params.pop("prompt")
|
| 750 |
+
filename = params.pop("filename")
|
| 751 |
+
negative_prompt = params.pop("negative_prompt", "")
|
| 752 |
+
|
| 753 |
+
print(f" {i}/{len(config['generations'])}: {filename}")
|
| 754 |
+
|
| 755 |
+
image = pipe(
|
| 756 |
+
prompt=prompt,
|
| 757 |
+
negative_prompt=negative_prompt,
|
| 758 |
+
**params
|
| 759 |
+
).images[0]
|
| 760 |
+
|
| 761 |
+
image.save(output_dir / filename)
|
| 762 |
+
|
| 763 |
+
print("✓ JSON batch processing complete")
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
# ============================================================================
|
| 767 |
+
# EXAMPLE 15: Advanced - Reproducible Research Workflow
|
| 768 |
+
# ============================================================================
|
| 769 |
+
|
| 770 |
+
def example_reproducible_research():
|
| 771 |
+
"""
|
| 772 |
+
Demonstrates best practices for reproducible research
|
| 773 |
+
Includes logging, seed management, and metadata storage
|
| 774 |
+
"""
|
| 775 |
+
print("\n" + "="*70)
|
| 776 |
+
print("EXAMPLE 15: Reproducible Research Workflow")
|
| 777 |
+
print("="*70)
|
| 778 |
+
|
| 779 |
+
import hashlib
|
| 780 |
+
from datetime import datetime
|
| 781 |
+
|
| 782 |
+
model_id = "OpenTrouter/Trouter-Imagine-1"
|
| 783 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 784 |
+
model_id,
|
| 785 |
+
torch_dtype=torch.float16
|
| 786 |
+
).to("cuda")
|
| 787 |
+
|
| 788 |
+
output_dir = Path("example15_research")
|
| 789 |
+
output_dir.mkdir(exist_ok=True)
|
| 790 |
+
|
| 791 |
+
# Experiment configuration
|
| 792 |
+
experiment = {
|
| 793 |
+
"experiment_id": hashlib.md5(str(datetime.now()).encode()).hexdigest()[:8],
|
| 794 |
+
"timestamp": datetime.now().isoformat(),
|
| 795 |
+
"model": model_id,
|
| 796 |
+
"hypothesis": "Testing effect of guidance scale on image fidelity",
|
| 797 |
+
"prompt": "a scientist in a laboratory, professional photography",
|
| 798 |
+
"negative_prompt": "blurry, low quality, distorted",
|
| 799 |
+
"fixed_seed": 12345,
|
| 800 |
+
"variable_parameter": "guidance_scale",
|
| 801 |
+
"test_values": [5.0, 7.5, 10.0, 12.5, 15.0],
|
| 802 |
+
"fixed_parameters": {
|
| 803 |
+
"width": 512,
|
| 804 |
+
"height": 512,
|
| 805 |
+
"num_inference_steps": 35
|
| 806 |
+
}
|
| 807 |
+
}
|
| 808 |
+
|
| 809 |
+
# Save experiment config
|
| 810 |
+
config_file = output_dir / f"experiment_{experiment['experiment_id']}.json"
|
| 811 |
+
with open(config_file, 'w') as f:
|
| 812 |
+
json.dump(experiment, indent=2, fp=f)
|
| 813 |
+
|
| 814 |
+
print(f"Experiment ID: {experiment['experiment_id']}")
|
| 815 |
+
print(f"Testing: {experiment['hypothesis']}")
|
| 816 |
+
|
| 817 |
+
# Run experiment
|
| 818 |
+
results = []
|
| 819 |
+
|
| 820 |
+
for value in experiment['test_values']:
|
| 821 |
+
print(f"\n Testing {experiment['variable_parameter']} = {value}")
|
| 822 |
+
|
| 823 |
+
generator = torch.Generator("cuda").manual_seed(experiment['fixed_seed'])
|
| 824 |
+
|
| 825 |
+
start_time = time.time()
|
| 826 |
+
|
| 827 |
+
image = pipe(
|
| 828 |
+
prompt=experiment['prompt'],
|
| 829 |
+
negative_prompt=experiment['negative_prompt'],
|
| 830 |
+
guidance_scale=value,
|
| 831 |
+
generator=generator,
|
| 832 |
+
**experiment['fixed_parameters']
|
| 833 |
+
).images[0]
|
| 834 |
+
|
| 835 |
+
generation_time = time.time() - start_time
|
| 836 |
+
|
| 837 |
+
# Save with metadata
|
| 838 |
+
filename = f"{experiment['experiment_id']}_guidance_{value}.png"
|
| 839 |
+
image.save(output_dir / filename)
|
| 840 |
+
|
| 841 |
+
result = {
|
| 842 |
+
"parameter_value": value,
|
| 843 |
+
"filename": filename,
|
| 844 |
+
"generation_time": generation_time,
|
| 845 |
+
"seed_used": experiment['fixed_seed']
|
| 846 |
+
}
|
| 847 |
+
results.append(result)
|
| 848 |
+
|
| 849 |
+
print(f" Generated in {generation_time:.2f}s")
|
| 850 |
+
|
| 851 |
+
# Save results
|
| 852 |
+
experiment['results'] = results
|
| 853 |
+
with open(config_file, 'w') as f:
|
| 854 |
+
json.dump(experiment, indent=2, fp=f)
|
| 855 |
+
|
| 856 |
+
print(f"\n✓ Experiment complete. Results saved to {config_file}")
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
# ============================================================================
|
| 860 |
+
# Main Function - Run All Examples
|
| 861 |
+
# ============================================================================
|
| 862 |
+
|
| 863 |
+
def run_all_examples():
|
| 864 |
+
"""Run all examples (warning: this will take a long time!)"""
|
| 865 |
+
examples = [
|
| 866 |
+
("Basic Generation", example_basic_generation),
|
| 867 |
+
("Negative Prompts", example_negative_prompts),
|
| 868 |
+
("Parameter Exploration", example_parameter_exploration),
|
| 869 |
+
("Multi-Resolution", example_multi_resolution),
|
| 870 |
+
("Seed Variations", example_seed_variations),
|
| 871 |
+
("Style Comparison", example_style_comparison),
|
| 872 |
+
("Scheduler Comparison", example_scheduler_comparison),
|
| 873 |
+
("Memory Optimization", example_memory_optimization),
|
| 874 |
+
("Automated Prompts", example_automated_prompts),
|
| 875 |
+
("Image Series", example_image_series),
|
| 876 |
+
("Quality/Speed Benchmark", example_quality_speed_benchmark),
|
| 877 |
+
("Product Photography", example_product_photography),
|
| 878 |
+
("Image Grid", example_image_grid),
|
| 879 |
+
("JSON Batch Processing", example_json_batch_processing),
|
| 880 |
+
("Reproducible Research", example_reproducible_research)
|
| 881 |
+
]
|
| 882 |
+
|
| 883 |
+
print("\n" + "="*70)
|
| 884 |
+
print("TROUTER-IMAGINE-1 COMPREHENSIVE EXAMPLES")
|
| 885 |
+
print("="*70)
|
| 886 |
+
print(f"\nTotal examples: {len(examples)}")
|
| 887 |
+
print("Warning: Running all examples will take considerable time and GPU resources")
|
| 888 |
+
print("="*70)
|
| 889 |
+
|
| 890 |
+
for i, (name, func) in enumerate(examples, 1):
|
| 891 |
+
try:
|
| 892 |
+
print(f"\n[{i}/{len(examples)}] Running: {name}")
|
| 893 |
+
func()
|
| 894 |
+
except Exception as e:
|
| 895 |
+
print(f"ERROR in {name}: {e}")
|
| 896 |
+
continue
|
| 897 |
+
|
| 898 |
+
print("\n" + "="*70)
|
| 899 |
+
print("ALL EXAMPLES COMPLETED")
|
| 900 |
+
print("="*70)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
if __name__ == "__main__":
|
| 904 |
+
import sys
|
| 905 |
+
|
| 906 |
+
if len(sys.argv) > 1:
|
| 907 |
+
example_num = sys.argv[1]
|
| 908 |
+
|
| 909 |
+
examples_map = {
|
| 910 |
+
"1": example_basic_generation,
|
| 911 |
+
"2": example_negative_prompts,
|
| 912 |
+
"3": example_parameter_exploration,
|
| 913 |
+
"4": example_multi_resolution,
|
| 914 |
+
"5": example_seed_variations,
|
| 915 |
+
"6": example_style_comparison,
|
| 916 |
+
"7": example_scheduler_comparison,
|
| 917 |
+
"8": example_memory_optimization,
|
| 918 |
+
"9": example_automated_prompts,
|
| 919 |
+
"10": example_image_series,
|
| 920 |
+
"11": example_quality_speed_benchmark,
|
| 921 |
+
"12": example_product_photography,
|
| 922 |
+
"13": example_image_grid,
|
| 923 |
+
"14": example_json_batch_processing,
|
| 924 |
+
"15": example_reproducible_research,
|
| 925 |
+
"all": run_all_examples
|
| 926 |
+
}
|
| 927 |
+
|
| 928 |
+
if example_num in examples_map:
|
| 929 |
+
examples_map[example_num]()
|
| 930 |
+
else:
|
| 931 |
+
print(f"Unknown example: {example_num}")
|
| 932 |
+
print("Available examples: 1-15, all")
|
| 933 |
+
else:
|
| 934 |
+
print("\nUsage: python examples.py <example_number>")
|
| 935 |
+
print("\nAvailable examples:")
|
| 936 |
+
print(" 1 - Basic Generation")
|
| 937 |
+
print(" 2 - Negative Prompts")
|
| 938 |
+
print(" 3 - Parameter Exploration")
|
| 939 |
+
print(" 4 - Multi-Resolution")
|
| 940 |
+
print(" 5 - Seed Variations")
|
| 941 |
+
print(" 6 - Style Comparison")
|
| 942 |
+
print(" 7 - Scheduler Comparison")
|
| 943 |
+
print(" 8 - Memory Optimization")
|
| 944 |
+
print(" 9 - Automated Prompts")
|
| 945 |
+
print(" 10 - Image Series (Storytelling)")
|
| 946 |
+
print(" 11 - Quality vs Speed Benchmark")
|
| 947 |
+
print(" 12 - Professional Product Photography")
|
| 948 |
+
print(" 13 - Image Grid Comparison")
|
| 949 |
+
print(" 14 - JSON Batch Processing")
|
| 950 |
+
print(" 15 - Reproducible Research Workflow")
|
| 951 |
+
print(" all - Run all examples (takes a long time!)")
|
| 952 |
+
print("\nExample: python examples.py 1")
|