Quiho commited on
Commit
dc366cf
·
verified ·
1 Parent(s): e5ca988

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +302 -83
app.py CHANGED
@@ -1,27 +1,73 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
  import torch
 
 
8
 
 
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "dhead/wai-nsfw-illustrious-sdxl-v140-sdxl" # Replace to the model you would like to use
 
 
 
 
 
11
 
 
 
 
12
  if torch.cuda.is_available():
13
  torch_dtype = torch.float16
 
 
 
 
 
 
14
  else:
15
  torch_dtype = torch.float32
 
 
 
 
 
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
 
18
  pipe = pipe.to(device)
19
 
 
 
 
 
 
20
  MAX_SEED = np.iinfo(np.int32).max
21
  MAX_IMAGE_SIZE = 1024
 
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
  def infer(
26
  prompt,
27
  negative_prompt,
@@ -31,110 +77,241 @@ def infer(
31
  height,
32
  guidance_scale,
33
  num_inference_steps,
 
34
  progress=gr.Progress(track_tqdm=True),
35
  ):
 
 
36
  if randomize_seed:
37
  seed = random.randint(0, MAX_SEED)
38
 
39
  generator = torch.Generator().manual_seed(seed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
 
 
 
 
 
 
 
 
 
 
 
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  examples = [
55
  "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
  "An astronaut riding a green horse",
57
  "A delicious ceviche cheesecake slice",
 
 
58
  ]
59
 
60
  css = """
61
  #col-container {
62
  margin: 0 auto;
63
- max-width: 640px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
  """
66
 
67
- with gr.Blocks(css=css) as demo:
68
  with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
 
 
 
71
  with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
  )
 
 
110
 
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
 
 
 
 
 
117
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=4.0, # Replace with defaults that work for your model
126
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=24, # Replace with defaults that work for your model
134
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  triggers=[run_button.click, prompt.submit],
139
  fn=infer,
140
  inputs=[
@@ -146,9 +323,51 @@ with gr.Blocks(css=css) as demo:
146
  height,
147
  guidance_scale,
148
  num_inference_steps,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  ],
150
- outputs=[result, seed],
 
 
 
 
 
 
151
  )
152
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
+ import os
5
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
 
6
  import torch
7
+ from PIL import Image
8
+ import time
9
 
10
+ # Ustawienia środowiska dla lepszej wydajności na CPU
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
12
+ torch.set_grad_enabled(False) # Wyłącz gradienty dla inferencji
13
+
14
+ # Optymalizacje dla CPU
15
+ if device == "cpu":
16
+ os.environ["OMP_NUM_THREADS"] = str(os.cpu_count())
17
+ torch.set_num_threads(os.cpu_count())
18
 
19
+ model_repo_id = "dhead/wai-nsfw-illustrious-sdxl-v140-sdxl"
20
+
21
+ # Optymalizacje typu danych
22
  if torch.cuda.is_available():
23
  torch_dtype = torch.float16
24
+ pipe = DiffusionPipeline.from_pretrained(
25
+ model_repo_id,
26
+ torch_dtype=torch_dtype,
27
+ use_safetensors=True,
28
+ variant="fp16"
29
+ )
30
  else:
31
  torch_dtype = torch.float32
32
+ pipe = DiffusionPipeline.from_pretrained(
33
+ model_repo_id,
34
+ torch_dtype=torch_dtype,
35
+ use_safetensors=True
36
+ )
37
 
38
+ # Optymalizacje potoku
39
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
40
  pipe = pipe.to(device)
41
 
42
+ # Dodatkowe optymalizacje dla CPU
43
+ if device == "cpu":
44
+ pipe.enable_attention_slicing()
45
+ pipe.enable_sequential_cpu_offload() # Dla systemów z małą ilością RAM
46
+
47
  MAX_SEED = np.iinfo(np.int32).max
48
  MAX_IMAGE_SIZE = 1024
49
+ DEFAULT_IMAGE_SIZE = 768 # Zmniejszony domyślny rozmiar dla CPU
50
 
51
+ def optimize_for_prompt(prompt, width, height):
52
+ """Automatyczna optymalizacja parametrów na podstawie promptu"""
53
+ prompt_lower = prompt.lower()
54
+
55
+ # Dostosuj liczbę kroków na podstawie złożoności promptu
56
+ complex_keywords = ['detailed', 'intricate', 'complex', '8k', 'ultra detailed']
57
+ if any(keyword in prompt_lower for keyword in complex_keywords):
58
+ steps = min(30, 25) # Więcej kroków dla złożonych promptów
59
+ else:
60
+ steps = min(20, 25) # Mniej kroków dla prostych promptów
61
+
62
+ # Dostosuj rozmiar na podstawie dostępnej pamięci
63
+ total_pixels = width * height
64
+ if total_pixels > 1024 * 1024:
65
+ width = min(width, 768)
66
+ height = min(height, 768)
67
+ steps = min(steps, 20)
68
+
69
+ return steps, width, height
70
 
 
71
  def infer(
72
  prompt,
73
  negative_prompt,
 
77
  height,
78
  guidance_scale,
79
  num_inference_steps,
80
+ enable_optimizations=True,
81
  progress=gr.Progress(track_tqdm=True),
82
  ):
83
+ start_time = time.time()
84
+
85
  if randomize_seed:
86
  seed = random.randint(0, MAX_SEED)
87
 
88
  generator = torch.Generator().manual_seed(seed)
89
+
90
+ # Automatyczne optymalizacje
91
+ if enable_optimizations:
92
+ num_inference_steps, width, height = optimize_for_prompt(prompt, width, height)
93
+
94
+ try:
95
+ image = pipe(
96
+ prompt=prompt,
97
+ negative_prompt=negative_prompt,
98
+ guidance_scale=guidance_scale,
99
+ num_inference_steps=num_inference_steps,
100
+ width=width,
101
+ height=height,
102
+ generator=generator,
103
+ ).images[0]
104
+
105
+ generation_time = time.time() - start_time
106
+
107
+ return image, seed, f"Generation time: {generation_time:.2f}s | Steps: {num_inference_steps} | Size: {width}x{height}"
108
+
109
+ except Exception as e:
110
+ return None, seed, f"Error: {str(e)}"
111
 
112
+ def save_image(image, prompt, seed):
113
+ """Zapisz wygenerowany obraz"""
114
+ if image is None:
115
+ return "No image to save"
116
+
117
+ timestamp = int(time.time())
118
+ filename = f"generated_{timestamp}_{seed}.png"
119
+
120
+ # Tworzenie folderu jeśli nie istnieje
121
+ os.makedirs("generated_images", exist_ok=True)
122
+ filepath = os.path.join("generated_images", filename)
123
+
124
+ image.save(filepath)
125
+
126
+ # Zapisz metadane
127
+ metadata_file = f"generated_images/metadata_{timestamp}.txt"
128
+ with open(metadata_file, "w") as f:
129
+ f.write(f"Prompt: {prompt}\n")
130
+ f.write(f"Seed: {seed}\n")
131
+ f.write(f"Timestamp: {timestamp}\n")
132
+
133
+ return f"Image saved as {filename}"
134
 
135
+ def batch_generate(prompts, num_images, **kwargs):
136
+ """Funkcja do generowania wielu obrazów"""
137
+ results = []
138
+ for prompt in prompts.split('\n'):
139
+ prompt = prompt.strip()
140
+ if prompt:
141
+ for i in range(num_images):
142
+ kwargs['prompt'] = prompt
143
+ kwargs['randomize_seed'] = True
144
+ image, seed, info = infer(**kwargs)
145
+ if image:
146
+ results.append((image, prompt, seed, info))
147
+ return results
148
 
149
  examples = [
150
  "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
151
  "An astronaut riding a green horse",
152
  "A delicious ceviche cheesecake slice",
153
+ "Cyberpunk cityscape at night, neon lights, rain",
154
+ "Majestic dragon flying over medieval castle",
155
  ]
156
 
157
  css = """
158
  #col-container {
159
  margin: 0 auto;
160
+ max-width: 800px;
161
+ }
162
+ .gallery-container {
163
+ display: grid;
164
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
165
+ gap: 10px;
166
+ margin-top: 20px;
167
+ }
168
+ .gallery-item {
169
+ border-radius: 8px;
170
+ overflow: hidden;
171
+ }
172
+ .performance-info {
173
+ background: #f0f0f0;
174
+ padding: 10px;
175
+ border-radius: 5px;
176
+ margin: 10px 0;
177
  }
178
  """
179
 
180
+ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
181
  with gr.Column(elem_id="col-container"):
182
+ gr.Markdown("""
183
+ # 🎨 Advanced Text-to-Image Generator
184
+ *Optimized for CPU performance with 18GB RAM*
185
+ """)
186
+
187
  with gr.Row():
188
+ with gr.Column(scale=4):
189
+ prompt = gr.Text(
190
+ label="Prompt",
191
+ show_label=False,
192
+ max_lines=2,
193
+ placeholder="Enter your detailed prompt here...",
194
+ container=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  )
196
+ with gr.Column(scale=1):
197
+ run_button = gr.Button("Generate 🚀", variant="primary", size="lg")
198
 
199
+ with gr.Row():
200
+ with gr.Column():
201
+ result = gr.Image(label="Generated Image", show_label=True, height=512)
202
+ with gr.Row():
203
+ save_btn = gr.Button("💾 Save Image")
204
+ clear_btn = gr.Button("🗑️ Clear")
205
+
206
+ performance_info = gr.Textbox(
207
+ label="Generation Info",
208
+ interactive=False,
209
+ max_lines=2
210
  )
211
+
212
+ with gr.Column():
213
+ with gr.Accordion("🎛️ Advanced Settings", open=False):
214
+ with gr.Tab("Basic"):
215
+ negative_prompt = gr.Text(
216
+ label="Negative Prompt",
217
+ max_lines=2,
218
+ placeholder="What to exclude from the image...",
219
+ value="blurry, low quality, distorted"
220
+ )
221
+
222
+ with gr.Row():
223
+ seed = gr.Number(
224
+ label="Seed",
225
+ value=0,
226
+ precision=0
227
+ )
228
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
229
+
230
+ enable_optimizations = gr.Checkbox(
231
+ label="Enable Auto-Optimizations",
232
+ value=True,
233
+ info="Automatically adjust settings for better performance"
234
+ )
235
 
236
+ with gr.Tab("Dimensions & Quality"):
237
+ with gr.Row():
238
+ width = gr.Slider(
239
+ label="Width",
240
+ minimum=256,
241
+ maximum=MAX_IMAGE_SIZE,
242
+ step=32,
243
+ value=DEFAULT_IMAGE_SIZE,
244
+ )
245
+ height = gr.Slider(
246
+ label="Height",
247
+ minimum=256,
248
+ maximum=MAX_IMAGE_SIZE,
249
+ step=32,
250
+ value=DEFAULT_IMAGE_SIZE,
251
+ )
252
+
253
+ with gr.Row():
254
+ guidance_scale = gr.Slider(
255
+ label="Guidance Scale",
256
+ minimum=1.0,
257
+ maximum=10.0,
258
+ step=0.1,
259
+ value=5.0,
260
+ )
261
+ num_inference_steps = gr.Slider(
262
+ label="Inference Steps",
263
+ minimum=10,
264
+ maximum=40,
265
+ step=1,
266
+ value=20,
267
+ )
268
 
269
+ with gr.Accordion("🔄 Batch Generation", open=False):
270
+ batch_prompts = gr.Textbox(
271
+ label="Batch Prompts (one per line)",
272
+ lines=3,
273
+ placeholder="Enter multiple prompts, one per line..."
274
+ )
275
+ num_images_per_prompt = gr.Slider(
276
+ label="Images per prompt",
277
+ minimum=1,
278
+ maximum=5,
279
+ step=1,
280
+ value=1
281
+ )
282
+ batch_button = gr.Button("Generate Batch", variant="secondary")
283
+
284
+ batch_gallery = gr.Gallery(
285
+ label="Batch Results",
286
+ show_label=True,
287
+ columns=3,
288
+ height="auto"
289
+ )
290
 
291
+ # Przykłady
292
+ gr.Examples(
293
+ examples=examples,
294
+ inputs=[prompt],
295
+ label="Click any example to load it ↑"
296
+ )
297
+
298
+ # Sekcja informacyjna
299
+ with gr.Accordion("ℹ️ Usage Tips", open=False):
300
+ gr.Markdown("""
301
+ **Performance Tips for CPU:**
302
+ - Use 512x512 or 768x768 resolutions for faster generation
303
+ - Keep inference steps between 15-25
304
+ - Enable auto-optimizations for best results
305
+ - Use clear, descriptive prompts for better quality
306
+
307
+ **Recommended Settings for 18GB RAM:**
308
+ - Max resolution: 1024x1024
309
+ - Steps: 15-25
310
+ - Guidance scale: 4.0-7.0
311
+ """)
312
+
313
+ # Główne zdarzenia
314
+ run_event = gr.on(
315
  triggers=[run_button.click, prompt.submit],
316
  fn=infer,
317
  inputs=[
 
323
  height,
324
  guidance_scale,
325
  num_inference_steps,
326
+ enable_optimizations,
327
+ ],
328
+ outputs=[result, seed, performance_info]
329
+ )
330
+
331
+ # Zdarzenia dodatkowe
332
+ save_btn.click(
333
+ fn=save_image,
334
+ inputs=[result, prompt, seed],
335
+ outputs=[performance_info]
336
+ )
337
+
338
+ clear_btn.click(
339
+ fn=lambda: [None, 0, "Cleared"],
340
+ outputs=[result, seed, performance_info]
341
+ )
342
+
343
+ batch_button.click(
344
+ fn=batch_generate,
345
+ inputs=[
346
+ batch_prompts,
347
+ num_images_per_prompt,
348
+ negative_prompt,
349
+ seed,
350
+ randomize_seed,
351
+ width,
352
+ height,
353
+ guidance_scale,
354
+ num_inference_steps,
355
+ enable_optimizations,
356
  ],
357
+ outputs=[batch_gallery]
358
+ )
359
+
360
+ # Automatyczne czyszczenie przy zmianie promptu
361
+ prompt.change(
362
+ fn=lambda: [None, 0, "Enter new prompt and click Generate"],
363
+ outputs=[result, seed, performance_info]
364
  )
365
 
366
  if __name__ == "__main__":
367
+ # Konfiguracja launch dla lepszej wydajności
368
+ demo.launch(
369
+ server_name="0.0.0.0",
370
+ share=False,
371
+ show_error=True,
372
+ max_file_size="100MB"
373
+ )