spac333's picture
Update app.py
4afd7dd verified
import gradio as gr
import torch
from diffusers import StableDiffusionPipeline
import random
print("๐ŸŽฎ Loading Game Character Generator...")
# Modello ottimizzato per character design
MODEL_ID = "Lykon/dreamshaper-8"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
pipe = StableDiffusionPipeline.from_pretrained(
MODEL_ID,
torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
safety_checker=None,
)
# Usa lo scheduler di default del modello (no cambio necessario)
pipe.to(DEVICE)
if DEVICE == "cuda":
pipe.enable_model_cpu_offload()
pipe.enable_vae_slicing()
print(f"โœ… Model loaded on {DEVICE}")
# Preset per diversi stili di gioco
GAME_STYLES = {
"RPG Fantasy": "fantasy rpg character, detailed armor, character sheet, concept art, white background",
"Anime JRPG": "anime style character, vibrant colors, jrpg aesthetic, character design, official art",
"Pixel Art Retro": "pixel art character sprite, 16-bit style, retro game, clean pixel art",
"3D Realistic": "3d character render, realistic, game character, unreal engine, highly detailed",
"Cartoon Mobile": "cute cartoon character, mobile game style, colorful, simple design",
"Dark Souls": "dark fantasy character, souls-like, detailed armor, dramatic lighting",
"Cyberpunk": "cyberpunk character, neon lights, futuristic, sci-fi game character",
"Platformer": "platformer game character, mascot, fun design, action pose"
}
NEGATIVE_BASE = "blurry, low quality, distorted, ugly, bad anatomy, extra limbs, text, watermark, signature"
def generate_character(
character_description,
game_style,
character_type,
custom_prompt="",
width=512,
height=768,
steps=30,
guidance=7.5,
seed=-1,
progress=gr.Progress()
):
"""Genera un personaggio da videogioco"""
if not character_description or len(character_description.strip()) == 0:
return None, "โŒ Please describe your character!"
try:
progress(0, desc="๐ŸŽจ Preparing...")
# Costruisci prompt completo
style_suffix = GAME_STYLES.get(game_style, "")
full_prompt = f"{character_description}, {character_type}, {style_suffix}"
if custom_prompt:
full_prompt += f", {custom_prompt}"
negative = NEGATIVE_BASE
if seed == -1:
seed = random.randint(0, 999999)
generator = torch.Generator(DEVICE).manual_seed(seed)
print(f"๐ŸŽจ Generating: {full_prompt[:80]}...")
progress(0.3, desc="๐Ÿ–ผ๏ธ Generating character...")
result = pipe(
prompt=full_prompt,
negative_prompt=negative,
num_inference_steps=steps,
guidance_scale=guidance,
width=width,
height=height,
generator=generator,
)
progress(1.0, desc="โœ… Complete!")
info = f"""
โœ… **Character Generated Successfully!**
๐Ÿ“Š **Details:**
- **Style:** {game_style}
- **Type:** {character_type}
- **Seed:** {seed}
- **Resolution:** {width}x{height}
- **Steps:** {steps}
๐Ÿ“ **Prompt Used:**
{full_prompt}
๐Ÿ’ก **Tip:** Save the seed to recreate similar characters!
"""
return result.images[0], info
except Exception as e:
error_msg = f"""
โŒ **Generation Failed**
**Error:** {str(e)}
๐Ÿ’ก **Try:**
- Simplify the description
- Reduce image size
- Lower quality steps
"""
print(f"Error: {e}")
return None, error_msg
# Character type presets
CHARACTER_TYPES = [
"full body character",
"character portrait",
"character turnaround",
"action pose",
"idle stance",
"character sheet",
"battle stance"
]
# UI Gradio
with gr.Blocks(
title="๐ŸŽฎ Game Character Generator",
theme=gr.themes.Soft(primary_hue="purple", secondary_hue="pink")
) as demo:
gr.Markdown("""
# ๐ŸŽฎ Game Character Generator
### Create Professional Characters for Your Video Game
Generate high-quality character designs for RPGs, platformers, mobile games, and more!
Powered by **DreamShaper 8** - optimized for game character creation.
""")
with gr.Row():
# Left column - Input
with gr.Column(scale=1):
gr.Markdown("### ๐ŸŽจ Character Design")
character_desc = gr.Textbox(
label="๐Ÿ’ฌ Character Description",
placeholder="Example: female warrior with red hair and golden armor",
lines=3,
value="knight with silver armor"
)
game_style = gr.Dropdown(
choices=list(GAME_STYLES.keys()),
value="RPG Fantasy",
label="๐ŸŽฎ Game Style"
)
character_type = gr.Dropdown(
choices=CHARACTER_TYPES,
value="full body character",
label="๐Ÿ“ Character View"
)
custom_prompt = gr.Textbox(
label="โœจ Additional Details (optional)",
placeholder="Example: holding magic sword, blue cape, heroic",
lines=2
)
with gr.Accordion("โš™๏ธ Advanced Settings", open=False):
with gr.Row():
width = gr.Slider(256, 768, 512, step=64, label="Width")
height = gr.Slider(256, 1024, 768, step=64, label="Height")
steps = gr.Slider(15, 50, 30, step=5, label="Quality Steps")
guidance = gr.Slider(5, 15, 7.5, step=0.5, label="Guidance")
seed = gr.Number(value=-1, label="Seed (-1 = random)")
generate_btn = gr.Button(
"๐ŸŽจ Generate Character",
variant="primary",
size="lg"
)
gr.Markdown("""
### ๐Ÿ’ก Tips for Best Results
โœ… **Do:**
- Be specific about appearance
- Mention colors and clothing
- Try different game styles
โŒ **Avoid:**
- Vague descriptions
- Too many details
""")
# Right column - Output
with gr.Column(scale=1):
output_image = gr.Image(
label="๐ŸŽฎ Generated Character",
height=600
)
output_info = gr.Markdown(
"๐Ÿ‘† Describe your character and click Generate!"
)
# Examples
gr.Markdown("### ๐ŸŽจ Example Characters")
gr.Examples(
examples=[
["knight with silver armor and red cape", "RPG Fantasy", "full body character", "holding sword, heroic", 512, 768, 30, 7.5, 42],
["cute anime girl with pink hair", "Anime JRPG", "character portrait", "smiling, cheerful", 512, 512, 30, 8.0, 123],
["cyberpunk hacker with neon visor", "Cyberpunk", "full body character", "tech gear, glowing", 512, 768, 30, 7.5, 456],
["dwarf warrior with battle axe", "RPG Fantasy", "full body character", "red beard, armor", 512, 768, 30, 7.5, 789],
],
inputs=[character_desc, game_style, character_type, custom_prompt, width, height, steps, guidance, seed],
outputs=[output_image, output_info],
fn=generate_character,
cache_examples=False
)
# Event handler
generate_btn.click(
fn=generate_character,
inputs=[character_desc, game_style, character_type, custom_prompt, width, height, steps, guidance, seed],
outputs=[output_image, output_info]
)
gr.Markdown("""
---
### ๐ŸŽฎ Supported Game Styles
- **RPG Fantasy**: Medieval, D&D style
- **Anime JRPG**: Japanese RPG aesthetic
- **Pixel Art**: Retro 8-bit/16-bit
- **3D Realistic**: AAA game quality
- **Cartoon Mobile**: Casual games
- **Dark Souls**: Gothic fantasy
- **Cyberpunk**: Futuristic sci-fi
- **Platformer**: Action game mascots
---
**Model:** DreamShaper 8 | **Framework:** Diffusers
""")
demo.queue(max_size=20).launch(server_name="0.0.0.0", share=False)