File size: 8,343 Bytes
8796918
 
 
73a5a3c
8796918
 
 
 
 
 
 
 
 
 
 
 
 
73a5a3c
 
8796918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73a5a3c
 
8796918
 
 
 
73a5a3c
8796918
 
 
 
 
 
 
 
 
 
 
 
 
73a5a3c
8796918
 
 
73a5a3c
 
 
 
8796918
73a5a3c
8796918
 
 
 
 
 
 
 
73a5a3c
8796918
 
 
 
 
73a5a3c
8796918
73a5a3c
 
 
 
 
 
 
 
8796918
 
 
73a5a3c
8796918
 
4afd7dd
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

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)