Spaces:
Runtime error
Runtime error
File size: 25,890 Bytes
a2a83e2 | 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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 | """
Image Creation Studio - Gradio 6 Application
A comprehensive image generation app with prompt enhancement and LoRA support from civitai.com
"""
import gradio as gr
import json
import time
from datetime import datetime
# ============================================
# UTILITY FUNCTIONS
# ============================================
def enhance_prompt(prompt: str, enhancement_level: str) -> str:
"""
Enhance a prompt with additional descriptive elements.
"""
if not prompt.strip():
return "Please enter a prompt first."
enhancements = {
"subtle": [
"high quality", "detailed", "professional photography"
],
"moderate": [
"masterpiece", "best quality", "highly detailed",
"ultra detailed", "8k wallpaper", "professional"
],
"extreme": [
"masterpiece", "best quality", "highly detailed",
"ultra detailed", "8k wallpaper", "professional photography",
"intricate details", "beautiful composition", "soft lighting",
"depth of field", "cinematic", "award winning"
]
}
enhancement_terms = enhancements.get(enhancement_level, enhancements["moderate"])
enhanced = f"{prompt}, {', '.join(enhancement_terms)}"
return enhanced
def search_loras(query: str, page: int = 1):
"""
Simulate searching LoRAs from civitai.com
In production, this would use the civitai API
"""
# Mock LoRA data - in production, fetch from civitai API
mock_loras = [
{"name": "Beautiful Realistic Face", "type": "Detail", "baseModel": "SD 1.5", "downloads": "2.5M", "rating": "98%"},
{"name": "Anime Style", "type": "Style", "baseModel": "SD 1.5", "downloads": "1.8M", "rating": "95%"},
{"name": "Cyberpunk City", "type": "Style", "baseModel": "SDXL", "downloads": "890K", "rating": "92%"},
{"name": "Fantasy Character", "type": "Character", "baseModel": "SD 1.5", "downloads": "1.2M", "rating": "96%"},
{"name": "Photorealistic Portrait", "type": "Detail", "baseModel": "SD 1.5", "downloads": "3.1M", "rating": "99%"},
{"name": "Mech Design", "type": "Concept", "baseModel": "SDXL", "downloads": "450K", "rating": "88%"},
{"name": "Watercolor Style", "type": "Style", "baseModel": "SD 1.5", "downloads": "670K", "rating": "91%"},
{"name": "3D Render Style", "type": "Style", "baseModel": "SDXL", "downloads": "780K", "rating": "94%"},
]
if query:
filtered = [l for l in mock_loras if query.lower() in l["name"].lower()]
else:
filtered = mock_loras
return filtered[:8]
def generate_image(
prompt: str,
negative_prompt: str,
model: str,
width: int,
height: int,
steps: int,
guidance: float,
seed: int,
loras: list,
enable_hr: bool,
hr_scale: float,
denoising_strength: float
):
"""
Generate image with specified parameters.
This is a mock function - in production, connect to a real image generation API
"""
if not prompt.strip():
raise gr.Error("Please enter a prompt!")
# Build enhanced prompt with LoRAs
final_prompt = prompt
if loras:
lora_text = ", ".join([f"<lora:{lora}>" for lora in loras])
final_prompt = f"{final_prompt}, {lora_text}"
# Simulate generation delay
time.sleep(2)
# Return placeholder - in production return actual generated image
# For demo, return a placeholder message
return {
"prompt": final_prompt,
"negative_prompt": negative_prompt,
"parameters": {
"model": model,
"width": width,
"height": height,
"steps": steps,
"guidance": guidance,
"seed": seed,
"loras": loras,
"hires_fix": enable_hr
},
"message": "Image generation would happen here with a real API connection."
}
def get_available_models():
"""Get list of available Stable Diffusion models"""
return [
"Stable Diffusion 1.5",
"Stable Diffusion 2.1",
"Stable Diffusion XL 1.0",
"DreamShaper 8",
"Realistic Vision V5",
"MeinaMix V11",
"Counterfeit V3",
"Animagine XL 3.1",
]
def get_aspect_ratios():
"""Get common aspect ratios"""
return {
"Square (1:1)": (512, 512),
"Portrait (3:4)": (512, 683),
"Landscape (4:3)": (683, 512),
"Portrait (9:16)": (512, 907),
"Landscape (16:9)": (907, 512),
"Standard (4:5)": (512, 640),
"Ultrawide (21:9)": (768, 320),
}
# ============================================
# MAIN APPLICATION
# ============================================
# Create custom theme
custom_theme = gr.themes.Soft(
primary_hue="blue",
secondary_hue="indigo",
neutral_hue="slate",
font=gr.themes.GoogleFont("Inter"),
text_size="lg",
spacing_size="lg",
radius_size="md"
).set(
button_primary_background_fill="*primary_600",
button_primary_background_fill_hover="*primary_700",
block_title_text_weight="600",
)
with gr.Blocks(theme=custom_theme, title="Image Creation Studio") as demo:
# Header with anycoder link
gr.HTML("""
<div style="text-align: center; padding: 10px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 20px;">
<h1 style="color: white; margin: 0; font-size: 2.5em;">π¨ Image Creation Studio</h1>
<p style="color: white; opacity: 0.9; margin: 10px 0 0 0;">Create stunning images with AI - Enhanced Prompts & LoRA Support</p>
</div>
<div style="text-align: center; margin-bottom: 20px;">
<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #667eea; text-decoration: none; font-weight: 600;">
π Built with anycoder
</a>
</div>
""")
with gr.Tabs():
# ============================================
# TAB 1: TEXT TO IMAGE
# ============================================
with gr.Tab("π¨ Text to Image"):
with gr.Row():
# Left Panel - Input
with gr.Column(scale=1):
gr.Markdown("### π Prompt")
prompt_input = gr.Textbox(
label="Prompt",
placeholder="Enter your image description...",
lines=4,
interactive=True
)
# Prompt Enhancement Section
with gr.Accordion("β¨ Prompt Enhancement", open=True):
enhancement_level = gr.Radio(
["subtle", "moderate", "extreme"],
label="Enhancement Level",
value="moderate"
)
enhance_btn = gr.Button("β¨ Enhance Prompt", variant="secondary")
enhanced_prompt = gr.Textbox(
label="Enhanced Prompt",
lines=4,
interactive=True
)
copy_enhanced_btn = gr.Button("π Copy to Main Prompt")
gr.Markdown("### π« Negative Prompt")
negative_prompt = gr.Textbox(
label="What to avoid",
placeholder="bad quality, blurry, distorted...",
lines=3
)
# Right Panel - Settings & Output
with gr.Column(scale=1):
# Generation Settings
with gr.Accordion("βοΈ Generation Settings", open=True):
with gr.Row():
model_select = gr.Dropdown(
choices=get_available_models(),
label="Model",
value="Stable Diffusion XL 1.0"
)
aspect_ratio = gr.Dropdown(
choices=list(get_aspect_ratios().keys()),
label="Aspect Ratio",
value="Square (1:1)"
)
with gr.Row():
steps_slider = gr.Slider(
minimum=1, maximum=150, value=30,
step=1, label="Steps"
)
guidance_slider = gr.Slider(
minimum=1, maximum=30, value=7.5,
step=0.5, label="Guidance Scale"
)
seed_input = gr.Number(
label="Seed (-1 for random)",
value=-1,
precision=0
)
# LoRA Selection
with gr.Accordion("π LoRA Settings", open=True):
lora_search = gr.Textbox(
label="Search LoRAs",
placeholder="Search on civitai.com..."
)
search_lora_btn = gr.Button("π Search civitai.com")
lora_results = gr.Dataframe(
headers=["Name", "Type", "Base Model", "Downloads", "Rating"],
label="Available LoRAs",
row_count=5,
col_count=5
)
selected_loras = gr.CheckboxGroup(
choices=[],
label="Selected LoRAs"
)
# Hi-Res Fix
with gr.Accordion("π² Hi-Res Fix", open=False):
enable_hires = gr.Checkbox(
label="Enable Hi-Res Fix",
value=False
)
hr_scale_slider = gr.Slider(
minimum=1, maximum=4, value=2,
step=0.1, label="Upscale Scale"
)
denoising_strength_slider = gr.Slider(
minimum=0.1, maximum=1, value=0.5,
step=0.05, label="Denoising Strength"
)
# Generate Button
generate_btn = gr.Button("π¨ Generate Image", variant="primary", size="lg")
# Output Section
gr.Markdown("### πΌοΈ Generated Image")
with gr.Row():
output_image = gr.Image(
label="Output",
type="filepath",
height=400
)
output_info = gr.JSON(
label="Generation Info"
)
# ============================================
# TAB 2: IMAGE TO IMAGE
# ============================================
with gr.Tab("π Image to Image"):
with gr.Row():
with gr.Column():
input_image = gr.Image(
label="Input Image",
type="filepath",
height=300
)
strength_slider = gr.Slider(
minimum=0, maximum=1, value=0.75,
step=0.05, label="Denoising Strength"
)
with gr.Column():
i2i_prompt = gr.Textbox(
label="Prompt",
placeholder="Describe the desired output...",
lines=3
)
i2i_negative = gr.Textbox(
label="Negative Prompt",
placeholder="What to avoid...",
lines=2
)
i2i_btn = gr.Button("π Transform", variant="primary")
i2i_output = gr.Image(label="Result", height=400)
# ============================================
# TAB 3: INPAINTING
# ============================================
with gr.Tab("ποΈ Inpainting"):
with gr.Row():
with gr.Column():
base_image = gr.Image(
label="Base Image",
type="filepath",
height=300
)
mask_image = gr.Image(
label="Mask (white = keep, black = regenerate)",
type="filepath",
height=300
)
with gr.Column():
inpaint_prompt = gr.Textbox(
label="What to add/edit",
placeholder="Describe what to add in the masked area...",
lines=3
)
inpaint_btn = gr.Button("π¨ Inpaint", variant="primary")
inpaint_output = gr.Image(label="Inpainted Result", height=400)
# ============================================
# TAB 4: LoRA BROWSEr
# ============================================
with gr.Tab("π LoRA Browser"):
gr.Markdown("""
### π Browse LoRAs from civitai.com
Search and discover LoRAs to enhance your image generation.
""")
with gr.Row():
lora_search_input = gr.Textbox(
label="Search LoRAs",
placeholder="Enter keywords (e.g., anime, realistic, portrait)...",
scale=2
)
lora_category = gr.Dropdown(
choices=["All", "Style", "Character", "Concept", "Detail"],
label="Category",
value="All"
)
lora_search_btn = gr.Button("π Search", variant="primary")
with gr.Row():
lora_gallery = gr.Gallery(
label="LoRA Results",
columns=4,
height=500
)
lora_details = gr.JSON(label="Selected LoRA Details")
add_to_prompt_btn = gr.Button("β Add to Current Prompt")
# ============================================
# TAB 5: PROMPT BUILDER
# ============================================
with gr.Tab("π Prompt Builder"):
gr.Markdown("### π― Interactive Prompt Builder")
with gr.Row():
with gr.Column():
# Subject
gr.Markdown("#### Subject")
subject_type = gr.Radio(
["Person", "Animal", "Object", "Landscape", "Abstract"],
label="Subject Type"
)
subject_details = gr.Textbox(
label="Subject Details",
placeholder="e.g., young woman, golden retriever, vintage car..."
)
# Style
gr.Markdown("#### Art Style")
style_choice = gr.Dropdown(
choices=[
"Photorealistic", "Anime/Manga", "Digital Art",
"Oil Painting", "Watercolor", "3D Render",
"Concept Art", "Illustration", "Pixel Art"
],
label="Art Style"
)
custom_style = gr.Textbox(
label="Custom Style",
placeholder="Any additional style keywords..."
)
# Lighting
gr.Markdown("#### Lighting")
lighting = gr.CheckboxGroup(
choices=[
"Natural Light", "Golden Hour", "Blue Hour",
"Studio Lighting", "Neon Lights", "Volumetric Lighting",
"Rembrandt Lighting", "Soft Lighting"
],
label="Lighting"
)
# Camera/Composition
gr.Markdown("#### Camera & Composition")
camera = gr.Dropdown(
choices=[
"Wide Shot", "Medium Shot", "Close-up", "Extreme Close-up",
"Birds Eye View", "Worm's Eye View", "Over the Shoulder"
],
label="Camera Angle"
)
composition = gr.Dropdown(
choices=["Centered", "Rule of Thirds", "Diagonal", "Symmetrical"],
label="Composition"
)
# Quality Tags
gr.Markdown("#### Quality")
quality = gr.CheckboxGroup(
choices=[
"Masterpiece", "Best Quality", "High Detail",
"8K", "4K", "Ultra Detailed", "Professional"
],
label="Quality Tags"
)
build_prompt_btn = gr.Button("ποΈ Build Prompt", variant="primary")
with gr.Column():
built_prompt = gr.Textbox(
label="Generated Prompt",
lines=15,
interactive=True
)
copy_prompt_btn = gr.Button("π Copy Prompt")
use_in_generation_btn = gr.Button("π¨ Use in Generation")
# Example prompts
gr.Markdown("### π‘ Example Prompts")
gr.Examples(
examples=[
["masterpiece, best quality, a beautiful woman, portrait, soft lighting, golden hour, 8k, professional photography"],
["anime style, colorful, vibrant city, neon lights, cyberpunk, detailed, illustration"],
["3d render, cute cat, fluffy, big eyes, soft lighting, cute, adorable, Pixar style"],
["oil painting, landscape, mountains, sunset, dramatic clouds, golden hour, detailed brushstrokes"],
],
inputs=[built_prompt],
label="Example Prompts"
)
# ============================================
# TAB 6: SETTINGS
# ============================================
with gr.Tab("βοΈ Settings"):
gr.Markdown("### π§ Application Settings")
with gr.Row():
with gr.Column():
gr.Markdown("#### API Configuration")
api_endpoint = gr.Textbox(
label="API Endpoint",
placeholder="https://api.example.com/v1",
value="http://localhost:7860"
)
api_key = gr.Textbox(
label="API Key",
type="password",
placeholder="Enter your API key..."
)
test_connection_btn = gr.Button("π Test Connection")
with gr.Column():
gr.Markdown("#### Default Settings")
default_model = gr.Dropdown(
choices=get_available_models(),
label="Default Model",
value="Stable Diffusion XL 1.0"
)
default_steps = gr.Slider(
minimum=1, maximum=150, value=30,
label="Default Steps"
)
default_guidance = gr.Slider(
minimum=1, maximum=30, value=7.5,
label="Default Guidance"
)
auto_enhance = gr.Checkbox(
label="Auto-enhance prompts",
value=False
)
save_settings_btn = gr.Button("πΎ Save Settings")
status_output = gr.Textbox(label="Status", interactive=False)
# Footer
gr.HTML("""
<div style="text-align: center; padding: 20px; margin-top: 20px; border-top: 1px solid #e0e0e0;">
<p style="color: #666;">
Image Creation Studio |
<a href="https://civitai.com" target="_blank" style="color: #667eea;">LoRAs from civitai.com</a> |
<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #667eea;">Built with anycoder</a>
</p>
</div>
""")
# ============================================
# EVENT HANDLERS
# ============================================
# Prompt Enhancement
enhance_btn.click(
fn=enhance_prompt,
inputs=[prompt_input, enhancement_level],
outputs=[enhanced_prompt]
)
copy_enhanced_btn.click(
fn=lambda x: x,
inputs=[enhanced_prompt],
outputs=[prompt_input]
)
# LoRA Search
search_lora_btn.click(
fn=search_loras,
inputs=[lora_search],
outputs=[lora_results]
)
# Update aspect ratio when selected
def update_size(aspect_name):
w, h = get_aspect_ratios()[aspect_name]
return w, h
aspect_ratio.change(
fn=update_size,
inputs=[aspect_ratio],
outputs=[steps_slider, guidance_slider] # Placeholder - would need separate components
)
# Generate Image
def get_selected_loras(selected, all_loras):
return selected if selected else []
generate_btn.click(
fn=generate_image,
inputs=[
prompt_input,
negative_prompt,
model_select,
steps_slider,
guidance_slider,
seed_input,
selected_loras,
enable_hires,
hr_scale_slider,
denoising_strength_slider
],
outputs=[output_image, output_info]
)
# LoRA Browser Tab
lora_search_btn.click(
fn=lambda q: search_loras(q),
inputs=[lora_search_input],
outputs=[lora_gallery]
)
# Prompt Builder
def build_prompt_fn(subject_type, subject, style, custom_style, lighting, camera, composition, quality):
parts = []
# Subject
if subject:
parts.append(subject)
# Quality tags (add first)
if quality:
parts = list(quality) + parts
# Style
if style:
parts.append(style)
if custom_style:
parts.append(custom_style)
# Lighting
if lighting:
parts.append(", ".join(lighting))
# Camera
if camera:
parts.append(camera)
# Composition
if composition:
parts.append(composition)
return ", ".join(parts)
build_prompt_btn.click(
fn=build_prompt_fn,
inputs=[
subject_type, subject_details, style_choice, custom_style,
lighting, camera, composition, quality
],
outputs=[built_prompt]
)
copy_prompt_btn.click(
fn=lambda x: x,
inputs=[built_prompt],
outputs=[prompt_input]
)
use_in_generation_btn.click(
fn=lambda x: x,
inputs=[built_prompt],
outputs=[prompt_input]
)
# Test Connection
test_connection_btn.click(
fn=lambda: "β
Connection successful! (Demo mode)",
inputs=None,
outputs=[status_output]
)
# Save Settings
save_settings_btn.click(
fn=lambda: "β
Settings saved successfully!",
inputs=None,
outputs=[status_output]
)
# ============================================
# LAUNCH APPLICATION
# ============================================
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
title="Image Creation Studio",
theme=custom_theme,
css="""
.gradio-container {
max-width: 1400px !important;
}
.main-title {
font-size: 2.5em;
font-weight: bold;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
""",
footer_links=[
{"label": "civitai.com", "url": "https://civitai.com"},
{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
]
) |