Spaces:
Sleeping
Sleeping
File size: 15,950 Bytes
df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 4ec0c37 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da 18a9cc5 df4d2da |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
"""
Gradio Web Interface for Stencil Image Generator
This module provides a web-based UI for the Stencil Generator using Gradio.
Run this file to launch the interactive web interface.
"""
import gradio as gr
from Stencil import StencilGenerator
from StencilCV import StencilCV
import torch
from typing import Optional
import numpy as np
import os
MAX_IMAGES = 4
class StencilApp:
"""Wrapper class for the Gradio application."""
def __init__(self):
"""Initialize the Stencil Generator."""
self.generator = None
self.current_model_type = None
self.original_images = [] # Store original images for toggling
self.outlined_status = [] # Track which images have outline applied
def load_model(self, model_type: str = "Standard SD 2.1"):
"""
Lazy load the model when first needed or reload if model type changed.
Args:
model_type: Type of model to load ("Standard SD 2.1", "Checkpoint-500", "Checkpoint-1000")
"""
# Reload if model type changed or first load
if self.generator is None or self.current_model_type != model_type:
print(f"Initializing Stencil Generator with {model_type}...")
# Determine checkpoint path based on model type
# Can be local path or HuggingFace Hub model ID
checkpoint_path = None
if model_type == "Checkpoint-500":
# Try local path first, fallback to HuggingFace Hub
checkpoint_path = "./Fine-tuning/checkpoint-500"
if not os.path.exists(checkpoint_path):
checkpoint_path = "mrpink925/stencilai-checkpoint-500"
elif model_type == "Checkpoint-1000":
# Try local path first, fallback to HuggingFace Hub
checkpoint_path = "./Fine-tuning/checkpoint-1000"
if not os.path.exists(checkpoint_path):
checkpoint_path = "mrpink925/stencilai-checkpoint-1000"
self.generator = StencilGenerator(
model_id="Manojb/stable-diffusion-2-1-base",
checkpoint_path=checkpoint_path,
use_fp16=torch.cuda.is_available()
)
self.current_model_type = model_type
return self.generator
def generate_stencil(
self,
prompt: str,
model_type: str,
negative_prompt: Optional[str],
num_images: int,
num_inference_steps: int,
guidance_scale: float,
width: int,
height: int,
seed: int,
use_seed: bool,
add_stencil_suffix: bool,
clean_background: bool
):
"""
Generate stencil images based on user inputs.
This is the main function called by the Gradio interface.
"""
if not prompt or prompt.strip() == "":
return [], "Please enter a prompt!"
try:
# Load model (will reload if model type changed)
generator = self.load_model(model_type)
# Generate the image(s)
images = generator.generate(
prompt=prompt,
negative_prompt=negative_prompt if negative_prompt else None,
num_images=num_images,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
width=width,
height=height,
seed=seed if use_seed else None,
add_stencil_suffix=add_stencil_suffix,
clean_background=clean_background
)
# Ensure images is a list
if not isinstance(images, list):
images = [images]
# Store original images and reset outlined status
self.original_images = [img.copy() for img in images]
self.outlined_status = [False] * len(images)
return images, f"Generation successful! Created {len(images)} image(s)."
except Exception as e:
return [], f"Error: {str(e)}"
def apply_outline(self, gallery_data, selected_index):
"""
Toggle outline processing on a selected image using StencilCV.
If the image has outline applied, revert to original. Otherwise, apply outline.
Args:
gallery_data: Gallery data from Gradio (list of images or tuples)
selected_index: Index of the selected image (from gr.Gallery select event)
Returns:
Updated gallery and status message
"""
# print(f"DEBUG: apply_outline called")
# print(f"DEBUG: gallery_data type: {type(gallery_data)}")
# print(f"DEBUG: gallery_data length: {len(gallery_data) if gallery_data else 0}")
# print(f"DEBUG: selected_index: {selected_index}")
if not gallery_data:
return gallery_data, "No images to process!"
# If there's only 1 image and no selection, default to index 0
if selected_index is None:
if len(self.original_images) == 1:
selected_index = 0
else:
return gallery_data, "Please select an image first by clicking on it!"
if selected_index >= len(self.original_images):
return gallery_data, "Error: Image index out of range!"
try:
# Create a copy of the gallery data
updated_gallery = list(gallery_data)
# Check if this image already has outline applied
if self.outlined_status[selected_index]:
# Revert to original
# print(f"DEBUG: Reverting image {selected_index} to original")
updated_gallery[selected_index] = self.original_images[selected_index].copy()
self.outlined_status[selected_index] = False
return updated_gallery, f"Reverted image {selected_index + 1} to original."
else:
# Apply outline
# print(f"DEBUG: Applying outline to image {selected_index}")
# Initialize StencilCV processor
processor = StencilCV()
# Get the original image (not the gallery one, to ensure consistency)
original_img = self.original_images[selected_index]
# print(f"DEBUG: Applying edge_stencil...")
# Apply outline to the original image
outlined = processor.edge_stencil(original_img)
# print(f"DEBUG: Outline applied successfully!")
# Update gallery with outlined version
updated_gallery[selected_index] = outlined
self.outlined_status[selected_index] = True
return updated_gallery, f"Applied outline to image {selected_index + 1}. Click again to revert."
except Exception as e:
import traceback
print("DEBUG: Exception occurred:")
traceback.print_exc()
return gallery_data, f"Error applying outline: {str(e)}"
def create_interface():
"""Create and configure the Gradio interface."""
app = StencilApp()
# Define the interface
with gr.Blocks(title="Stencil Image Generator", theme=gr.themes.Soft()) as interface:
gr.Markdown(
"""
# 🎨 Stencil Image Generator
Generate black and white stencil-style images using AI. Perfect for creating
cutting templates, vector art, and silhouette designs.
"""
)
with gr.Row():
with gr.Column(scale=1):
# Input controls
prompt = gr.Textbox(
label="Prompt",
placeholder="e.g., a cat sitting, a tree with spreading branches...",
lines=3
)
model_selector = gr.Radio(
choices=["Standard SD 2.1", "Checkpoint-500", "Checkpoint-1000"],
value="Checkpoint-1000",
label="Model Type",
info="Choose between standard model or fine-tuned checkpoints (trained on sketch-style images)"
)
num_images = gr.Slider(
minimum=1,
maximum=MAX_IMAGES,
value=2,
step=1,
label="Number of Images",
info="Generate multiple variations to choose from"
)
with gr.Accordion("Advanced Settings", open=False):
negative_prompt = gr.Textbox(
label="Negative Prompt (optional)",
placeholder="Things to avoid in the generation...",
lines=2
)
add_stencil_suffix = gr.Checkbox(
label="Add stencil styling suffix(recommended)",
value=True,
info="Automatically adds stencil-specific styling to your prompt (prompt decorations)"
)
clean_background = gr.Checkbox(
label="Clean white background (recommended)",
value=True,
info="Post-process to ensure pure white background and remove artifacts"
)
num_inference_steps = gr.Slider(
minimum=10,
maximum=50,
value=25,
step=5,
label="Inference Steps",
info="Higher = better quality but slower"
)
guidance_scale = gr.Slider(
minimum=1,
maximum=15,
value=7.5,
step=0.5,
label="Guidance Scale",
info="How closely to follow the prompt (7-8 recommended)"
)
with gr.Row():
width = gr.Slider(
minimum=256,
maximum=1024,
value=512,
step=64,
label="Width"
)
height = gr.Slider(
minimum=256,
maximum=1024,
value=512,
step=64,
label="Height"
)
with gr.Row():
use_seed = gr.Checkbox(
label="Use fixed seed",
value=False,
info="Enable for reproducible results"
)
seed = gr.Number(
label="Seed",
value=42,
precision=0
)
generate_btn = gr.Button("Generate Stencil", variant="primary", size="lg")
# Example prompts
gr.Examples(
examples=[
["a cat sitting"],
["a tree with spreading branches"],
["a bicycle"],
["a coffee cup"],
["a bird in flight"],
["a deer with antlers"],
["a mountain landscape"],
["a lighthouse by the sea"]
],
inputs=prompt,
label="Example Prompts"
)
with gr.Column(scale=1):
# Output - Gallery for multiple images
output_gallery = gr.Gallery(
label="Generated Stencils (click to select)",
show_label=True,
columns=2,
rows=2,
height="auto",
object_fit="contain"
)
status_text = gr.Textbox(
label="Status",
interactive=False,
lines=1
)
# Hidden state to track selected image
selected_image_index = gr.State(value=None)
# Post-processing section
with gr.Accordion("Post-Processing Options", open=False):
gr.Markdown(
"""
**Outline Generation**: Click an image above to select it, then click the button below
to toggle outline processing. This creates a line-art effect and works best on images
with clear subjects. Click the button again to revert to the original.
You can toggle outline on/off for each image independently to compare styles.
"""
)
apply_outline_btn = gr.Button("Toggle Outline on Selected Image", variant="secondary")
gr.Markdown(
"""
### Tips for Best Results:
- Keep prompts simple and descriptive
- **Standard SD 2.1**: Best for general stencils with detailed prompt engineering
- **Checkpoint models**: Fine-tuned for sketch-style stencils (automatically adds "sketch of" prefix)
- Generate multiple images to see variations
- Use negative prompts to avoid unwanted features (works best with Standard SD 2.1)
- Try the outline option after generation for different styles
- Higher inference steps = better quality (but slower)
"""
)
# Connect the generate button
generate_btn.click(
fn=app.generate_stencil,
inputs=[
prompt,
model_selector,
negative_prompt,
num_images,
num_inference_steps,
guidance_scale,
width,
height,
seed,
use_seed,
add_stencil_suffix,
clean_background
],
outputs=[output_gallery, status_text]
)
# Track when user selects an image in the gallery
def update_selection(evt: gr.SelectData):
print(f"DEBUG: Gallery selection event - index: {evt.index}")
return evt.index
output_gallery.select(
fn=update_selection,
outputs=selected_image_index
)
# Connect the outline button
apply_outline_btn.click(
fn=app.apply_outline,
inputs=[output_gallery, selected_image_index],
outputs=[output_gallery, status_text]
)
gr.Markdown(
"""
---
Built with [Stable Diffusion](https://stability.ai/) and [Gradio](https://gradio.app/)
"""
)
return interface
def launch(
share: bool = False,
server_name: str = "0.0.0.0",
server_port: int = 7860,
**kwargs
):
"""
Launch the Gradio interface.
Args:
share: Whether to create a public shareable link
server_name: Server host (0.0.0.0 for public access)
server_port: Port to run the server on
**kwargs: Additional arguments passed to gradio.launch()
"""
interface = create_interface()
interface.launch(
share=share,
server_name=server_name,
server_port=server_port,
**kwargs
)
if __name__ == "__main__":
# Launch with default settings
# Set share=True to create a public link
launch(share=True, pwa=True)
|