Onise commited on
Commit
e009c22
·
verified ·
1 Parent(s): 9536671

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +338 -4
app.py CHANGED
@@ -1,4 +1,338 @@
1
- A cyberpunk city at night, neon lights, rain, highly detailed, 8k
2
- Portrait of a fantasy elf warrior, intricate armor, forest background
3
- Magical library with floating books, mystical atmosphere, warm lighting
4
- Steampunk airship flying through clouds, detailed mechanical parts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import AutoPipelineForText2Image
4
+ from huggingface_hub import hf_hub_download
5
+ import os
6
+ from utils import load_lora_weights, get_available_loras, generate_image
7
+
8
+ # Global model cache
9
+ pipeline = None
10
+ current_lora = None
11
+
12
+ def load_model():
13
+ """Load the Magic-Wan-Image-V2 model"""
14
+ global pipeline
15
+ if pipeline is None:
16
+ print("Loading Magic-Wan-Image-V2 model...")
17
+ pipeline = AutoPipelineForText2Image.from_pretrained(
18
+ "wikeeyang/Magic-Wan-Image-V2",
19
+ torch_dtype=torch.float16,
20
+ variant="fp16"
21
+ )
22
+ if torch.cuda.is_available():
23
+ pipeline = pipeline.to("cuda")
24
+ print("Model loaded successfully!")
25
+ return pipeline
26
+
27
+ def generate(
28
+ prompt,
29
+ negative_prompt,
30
+ lora_name,
31
+ lora_scale,
32
+ width,
33
+ height,
34
+ num_inference_steps,
35
+ guidance_scale,
36
+ seed,
37
+ randomize_seed
38
+ ):
39
+ """Generate image from text prompt with optional LoRA"""
40
+ global pipeline, current_lora
41
+
42
+ try:
43
+ # Load model if not already loaded
44
+ pipe = load_model()
45
+
46
+ # Handle LoRA loading
47
+ if lora_name and lora_name != "None":
48
+ if current_lora != lora_name:
49
+ # Unload previous LoRA if exists
50
+ if current_lora:
51
+ pipe.unload_lora_weights()
52
+
53
+ # Load new LoRA
54
+ lora_path = get_available_loras().get(lora_name)
55
+ if lora_path:
56
+ load_lora_weights(pipe, lora_path)
57
+ current_lora = lora_name
58
+ print(f"Loaded LoRA: {lora_name}")
59
+
60
+ # Set LoRA scale
61
+ if hasattr(pipe, 'set_adapters'):
62
+ pipe.set_adapters(["default"], [lora_scale])
63
+ else:
64
+ # Unload LoRA if "None" selected
65
+ if current_lora:
66
+ pipe.unload_lora_weights()
67
+ current_lora = None
68
+
69
+ # Handle seed
70
+ if randomize_seed:
71
+ seed = torch.randint(0, 2**32 - 1, (1,)).item()
72
+
73
+ generator = torch.Generator(device=pipeline.device).manual_seed(seed) if seed != -1 else None
74
+
75
+ # Generate image
76
+ image = pipe(
77
+ prompt=prompt,
78
+ negative_prompt=negative_prompt if negative_prompt else None,
79
+ width=width,
80
+ height=height,
81
+ num_inference_steps=num_inference_steps,
82
+ guidance_scale=guidance_scale,
83
+ generator=generator,
84
+ ).images[0]
85
+
86
+ return image, str(seed)
87
+
88
+ except Exception as e:
89
+ raise gr.Error(f"Generation failed: {str(e)}")
90
+
91
+ # Get available LoRAs
92
+ available_loras = get_available_loras()
93
+ lora_choices = ["None"] + list(available_loras.keys())
94
+
95
+ # Create Gradio 6 app with modern theme
96
+ with gr.Blocks() as demo:
97
+ # Header with anycoder link
98
+ gr.HTML("""
99
+ <div style="text-align: center; margin-bottom: 20px;">
100
+ <h1>🎨 Magic Wan Image V2 - Text to Image</h1>
101
+ <p>Generate stunning images from text prompts with LoRA support</p>
102
+ <p style="font-size: 14px;">
103
+ <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #FF9D00; text-decoration: none;">
104
+ <strong>Built with anycoder</strong> 🚀
105
+ </a>
106
+ </p>
107
+ </div>
108
+ """)
109
+
110
+ with gr.Row():
111
+ # Left column - Controls
112
+ with gr.Column(scale=1):
113
+ gr.Markdown("### 📝 Prompt")
114
+ prompt = gr.Textbox(
115
+ label="Prompt",
116
+ placeholder="Describe the image you want to generate...",
117
+ lines=3,
118
+ value="A beautiful sunset over mountains, highly detailed, 8k"
119
+ )
120
+
121
+ negative_prompt = gr.Textbox(
122
+ label="Negative Prompt (Optional)",
123
+ placeholder="What to avoid in the image...",
124
+ lines=2,
125
+ value="blurry, low quality, distorted"
126
+ )
127
+
128
+ gr.Markdown("### 🎭 LoRA Style")
129
+ lora_dropdown = gr.Dropdown(
130
+ choices=lora_choices,
131
+ value="None",
132
+ label="Select LoRA Adapter",
133
+ info="Choose a style adapter or leave as None for base model"
134
+ )
135
+
136
+ lora_scale = gr.Slider(
137
+ minimum=0.0,
138
+ maximum=2.0,
139
+ value=1.0,
140
+ step=0.1,
141
+ label="LoRA Scale",
142
+ info="Strength of LoRA effect (0.0 = no effect)"
143
+ )
144
+
145
+ gr.Markdown("### ⚙️ Generation Settings")
146
+ with gr.Row():
147
+ width = gr.Slider(
148
+ minimum=256,
149
+ maximum=1024,
150
+ value=512,
151
+ step=64,
152
+ label="Width"
153
+ )
154
+ height = gr.Slider(
155
+ minimum=256,
156
+ maximum=1024,
157
+ value=512,
158
+ step=64,
159
+ label="Height"
160
+ )
161
+
162
+ with gr.Row():
163
+ num_inference_steps = gr.Slider(
164
+ minimum=10,
165
+ maximum=100,
166
+ value=30,
167
+ step=1,
168
+ label="Inference Steps"
169
+ )
170
+ guidance_scale = gr.Slider(
171
+ minimum=1.0,
172
+ maximum=20.0,
173
+ value=7.5,
174
+ step=0.5,
175
+ label="Guidance Scale"
176
+ )
177
+
178
+ gr.Markdown("### 🎲 Seed Settings")
179
+ with gr.Row():
180
+ seed = gr.Number(
181
+ value=-1,
182
+ label="Seed (-1 for random)",
183
+ precision=0
184
+ )
185
+ randomize_seed = gr.Checkbox(
186
+ value=True,
187
+ label="Randomize Seed"
188
+ )
189
+
190
+ generate_btn = gr.Button(
191
+ "🚀 Generate Image",
192
+ variant="primary",
193
+ size="lg"
194
+ )
195
+
196
+ # Right column - Output
197
+ with gr.Column(scale=1):
198
+ gr.Markdown("### 🖼️ Generated Image")
199
+ output_image = gr.Image(
200
+ label="Generated Image",
201
+ type="pil",
202
+ height=512
203
+ )
204
+
205
+ seed_output = gr.Textbox(
206
+ label="Used Seed",
207
+ interactive=False
208
+ )
209
+
210
+ gr.Markdown("### 💡 Tips")
211
+ gr.Markdown("""
212
+ - **Prompt**: Be descriptive and specific
213
+ - **LoRA**: Try different style adapters for unique looks
214
+ - **Steps**: More steps = better quality but slower
215
+ - **Guidance**: Higher = more prompt adherence
216
+ - **Seed**: Use same seed for reproducible results
217
+ """)
218
+
219
+ # Examples section
220
+ gr.Markdown("### 📚 Examples")
221
+ examples = gr.Examples(
222
+ examples=[
223
+ [
224
+ "A cyberpunk city at night, neon lights, rain, highly detailed",
225
+ "blurry, low quality",
226
+ "None",
227
+ 1.0,
228
+ 512,
229
+ 512,
230
+ 30,
231
+ 7.5,
232
+ -1,
233
+ True
234
+ ],
235
+ [
236
+ "Portrait of a fantasy elf warrior, intricate armor, forest background",
237
+ "deformed, ugly, bad anatomy",
238
+ "None",
239
+ 1.0,
240
+ 512,
241
+ 768,
242
+ 30,
243
+ 7.5,
244
+ -1,
245
+ True
246
+ ],
247
+ [
248
+ "Magical library with floating books, mystical atmosphere, warm lighting",
249
+ "dark, scary",
250
+ "None",
251
+ 1.0,
252
+ 768,
253
+ 512,
254
+ 30,
255
+ 7.5,
256
+ -1,
257
+ True
258
+ ],
259
+ [
260
+ "Steampunk airship flying through clouds, detailed mechanical parts",
261
+ "modern, electronic",
262
+ "None",
263
+ 1.0,
264
+ 512,
265
+ 512,
266
+ 30,
267
+ 7.5,
268
+ -1,
269
+ True
270
+ ],
271
+ ],
272
+ inputs=[
273
+ prompt,
274
+ negative_prompt,
275
+ lora_dropdown,
276
+ lora_scale,
277
+ width,
278
+ height,
279
+ num_inference_steps,
280
+ guidance_scale,
281
+ seed,
282
+ randomize_seed
283
+ ],
284
+ label="Click an example to load settings"
285
+ )
286
+
287
+ # Connect generate button
288
+ generate_btn.click(
289
+ fn=generate,
290
+ inputs=[
291
+ prompt,
292
+ negative_prompt,
293
+ lora_dropdown,
294
+ lora_scale,
295
+ width,
296
+ height,
297
+ num_inference_steps,
298
+ guidance_scale,
299
+ seed,
300
+ randomize_seed
301
+ ],
302
+ outputs=[output_image, seed_output],
303
+ api_visibility="public"
304
+ )
305
+
306
+ # Footer
307
+ gr.HTML("""
308
+ <div style="text-align: center; margin-top: 30px; padding: 20px; border-top: 1px solid #e0e0e0;">
309
+ <p style="color: #666; font-size: 12px;">
310
+ Model: <a href="https://huggingface.co/wikeeyang/Magic-Wan-Image-V2" target="_blank">Magic-Wan-Image-V2</a> |
311
+ Powered by Gradio 6
312
+ </p>
313
+ </div>
314
+ """)
315
+
316
+ # Launch with Gradio 6 syntax - theme goes in launch(), not Blocks!
317
+ if __name__ == "__main__":
318
+ demo.launch(
319
+ theme=gr.themes.Soft(
320
+ primary_hue="indigo",
321
+ secondary_hue="purple",
322
+ neutral_hue="slate",
323
+ font=gr.themes.GoogleFont("Inter"),
324
+ text_size="md",
325
+ spacing_size="md",
326
+ radius_size="md"
327
+ ).set(
328
+ button_primary_background_fill="*primary_600",
329
+ button_primary_background_fill_hover="*primary_700",
330
+ block_title_text_weight="600",
331
+ ),
332
+ footer_links=[
333
+ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
334
+ {"label": "Model Card", "url": "https://huggingface.co/wikeeyang/Magic-Wan-Image-V2"},
335
+ "api"
336
+ ],
337
+ allow_flagging="never"
338
+ )