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)