lastwarning commited on
Commit
6a198b1
·
verified ·
1 Parent(s): 75b4451

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +439 -99
app.py CHANGED
@@ -1,147 +1,487 @@
1
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
- import numpy as np
4
- import random
5
- import spaces
6
  import torch
 
7
 
8
  from diffusers import DiffusionPipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- model_repo_id = "stabilityai/sdxl-turbo"
 
 
 
11
 
12
- MAX_SEED = np.iinfo(np.int32).max
13
- MAX_IMAGE_SIZE = 1024
 
 
 
14
 
15
- pipe = DiffusionPipeline.from_pretrained(
16
- model_repo_id,
17
- torch_dtype=torch.float16
18
- )
19
 
20
- pipe = pipe.to("cuda")
21
 
 
 
 
22
 
23
  @spaces.GPU
24
- def infer(
25
  prompt,
26
  negative_prompt,
27
- seed,
28
- randomize_seed,
29
  width,
30
  height,
31
- guidance_scale,
32
- num_inference_steps,
33
- progress=gr.Progress(track_tqdm=True),
34
  ):
35
- if randomize_seed:
36
- seed = random.randint(0, MAX_SEED)
37
-
38
- generator = torch.Generator(
39
- device="cuda"
40
- ).manual_seed(seed)
41
-
42
- image = pipe(
43
- prompt=prompt,
44
- negative_prompt=negative_prompt,
45
- guidance_scale=guidance_scale,
46
- num_inference_steps=num_inference_steps,
47
- width=width,
48
- height=height,
49
- generator=generator,
50
- ).images[0]
51
-
52
- return image, seed
53
-
54
-
55
- examples = [
56
- "Astronaut in a jungle, cinematic lighting",
57
- "An astronaut riding a green horse",
58
- "A futuristic beautiful city at sunset",
59
- ]
60
-
61
- css = """
62
- #col-container {
63
- margin: 0 auto;
64
- max-width: 640px;
65
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  """
67
 
68
- with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- with gr.Column(elem_id="col-container"):
71
 
72
- gr.Markdown("# Tasting AI Image Generator")
73
 
74
- prompt = gr.Textbox(
75
- label="Prompt",
76
- placeholder="Describe your image..."
77
  )
78
 
79
- run_button = gr.Button(
80
- "Generate Image",
81
- variant="primary"
 
 
82
  )
83
 
84
- result = gr.Image(label="Generated Image")
85
 
86
- with gr.Accordion("Advanced Settings"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  negative_prompt = gr.Textbox(
89
- label="Negative Prompt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
91
 
92
- seed = gr.Slider(
93
- 0, MAX_SEED, value=0,
94
- step=1, label="Seed"
 
95
  )
96
 
97
- randomize_seed = gr.Checkbox(
98
  value=True,
99
- label="Randomize Seed"
100
  )
101
 
102
- width = gr.Slider(
103
- 256, MAX_IMAGE_SIZE,
104
- value=1024, step=32,
105
- label="Width"
106
  )
107
 
108
- height = gr.Slider(
109
- 256, MAX_IMAGE_SIZE,
110
- value=1024, step=32,
111
- label="Height"
112
  )
113
 
114
- guidance_scale = gr.Slider(
115
- 0, 10, value=0,
116
- step=0.1,
117
- label="Guidance Scale"
118
  )
119
 
120
- num_inference_steps = gr.Slider(
121
- 1, 50, value=2,
122
- step=1,
123
- label="Inference Steps"
 
 
 
 
 
 
 
 
 
 
 
 
124
  )
125
 
126
- gr.Examples(
127
- examples=examples,
128
- inputs=[prompt]
129
- )
 
 
 
 
 
 
 
 
 
130
 
131
- run_button.click(
132
- fn=infer,
133
- inputs=[
134
- prompt,
135
- negative_prompt,
136
- seed,
137
- randomize_seed,
138
- width,
139
- height,
140
- guidance_scale,
141
- num_inference_steps,
142
- ],
143
- outputs=[result, seed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  )
145
 
 
 
 
 
 
146
  if __name__ == "__main__":
147
- demo.launch()
 
 
 
1
 
2
+ import os
3
+
4
+ # Disable automatic authentication.
5
+ os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
6
+ os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
7
+
8
+ import gc
9
+ import threading
10
  import gradio as gr
 
 
 
11
  import torch
12
+ import spaces
13
 
14
  from diffusers import DiffusionPipeline
15
+ from transformers import AutoTokenizer, AutoModelForCausalLM
16
+
17
+
18
+ # ==========================================
19
+ # APP CONFIG
20
+ # ==========================================
21
+
22
+ APP_NAME = "Tasting AI Studio"
23
+
24
+ IMAGE_MODELS = {
25
+ "SDXL Turbo": "stabilityai/sdxl-turbo",
26
+ "Stable Diffusion 1.5":
27
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
28
+ }
29
+
30
+ CODE_MODELS = {
31
+ "Qwen Coder 0.5B":
32
+ "Qwen/Qwen2.5-Coder-0.5B-Instruct",
33
+
34
+ "Qwen Coder 1.5B":
35
+ "Qwen/Qwen2.5-Coder-1.5B-Instruct",
36
+
37
+ "DeepSeek Coder 1.3B":
38
+ "deepseek-ai/deepseek-coder-1.3b-instruct",
39
+ }
40
 
41
+ image_cache = {
42
+ "name": None,
43
+ "pipe": None,
44
+ }
45
 
46
+ code_cache = {
47
+ "name": None,
48
+ "tokenizer": None,
49
+ "model": None,
50
+ }
51
 
52
+ image_lock = threading.Lock()
53
+ code_lock = threading.Lock()
 
 
54
 
 
55
 
56
+ # ==========================================
57
+ # IMAGE GENERATION
58
+ # ==========================================
59
 
60
  @spaces.GPU
61
+ def generate_image(
62
  prompt,
63
  negative_prompt,
64
+ model_name,
 
65
  width,
66
  height,
67
+ steps,
68
+ seed,
69
+ random_seed
70
  ):
71
+ if not prompt.strip():
72
+ raise gr.Error("Enter an image prompt.")
73
+
74
+ if model_name not in IMAGE_MODELS:
75
+ raise gr.Error("Invalid image model.")
76
+
77
+ if not torch.cuda.is_available():
78
+ raise gr.Error("GPU is unavailable.")
79
+
80
+ model_id = IMAGE_MODELS[model_name]
81
+
82
+ if random_seed:
83
+ seed = int.from_bytes(os.urandom(4), "big") % 2147483647
84
+
85
+ with image_lock:
86
+ try:
87
+ if image_cache["name"] != model_id:
88
+
89
+ if image_cache["pipe"] is not None:
90
+ del image_cache["pipe"]
91
+ image_cache["pipe"] = None
92
+ image_cache["name"] = None
93
+
94
+ gc.collect()
95
+ torch.cuda.empty_cache()
96
+
97
+ pipe = DiffusionPipeline.from_pretrained(
98
+ model_id,
99
+ torch_dtype=torch.float16,
100
+ token=False,
101
+ )
102
+
103
+ pipe = pipe.to("cuda")
104
+
105
+ image_cache["pipe"] = pipe
106
+ image_cache["name"] = model_id
107
+
108
+ pipe = image_cache["pipe"]
109
+
110
+ generator = torch.Generator(
111
+ device="cuda"
112
+ ).manual_seed(int(seed))
113
+
114
+ if model_name == "SDXL Turbo":
115
+ guidance = 0.0
116
+ actual_steps = min(max(int(steps), 1), 4)
117
+ else:
118
+ guidance = 7.5
119
+ actual_steps = max(int(steps), 20)
120
+
121
+ result = pipe(
122
+ prompt=prompt,
123
+ negative_prompt=negative_prompt or None,
124
+ width=int(width),
125
+ height=int(height),
126
+ num_inference_steps=actual_steps,
127
+ guidance_scale=guidance,
128
+ generator=generator,
129
+ )
130
+
131
+ return result.images[0], int(seed)
132
+
133
+ except Exception as error:
134
+ raise gr.Error(
135
+ "Image generation failed: " + str(error)
136
+ )
137
+
138
+
139
+ # ==========================================
140
+ # LOAD PUBLIC CODING MODEL
141
+ # ==========================================
142
+
143
+ def load_code_model(model_name):
144
+
145
+ model_id = CODE_MODELS[model_name]
146
+
147
+ with code_lock:
148
+
149
+ if code_cache["name"] == model_id:
150
+ return (
151
+ code_cache["tokenizer"],
152
+ code_cache["model"]
153
+ )
154
+
155
+ if code_cache["model"] is not None:
156
+ del code_cache["model"]
157
+ del code_cache["tokenizer"]
158
+
159
+ code_cache["model"] = None
160
+ code_cache["tokenizer"] = None
161
+ code_cache["name"] = None
162
+
163
+ gc.collect()
164
+
165
+ tokenizer = AutoTokenizer.from_pretrained(
166
+ model_id,
167
+ token=False,
168
+ )
169
+
170
+ model = AutoModelForCausalLM.from_pretrained(
171
+ model_id,
172
+ token=False,
173
+ torch_dtype=torch.float32,
174
+ low_cpu_mem_usage=True,
175
+ )
176
+
177
+ model.to("cpu")
178
+ model.eval()
179
+
180
+ code_cache["name"] = model_id
181
+ code_cache["tokenizer"] = tokenizer
182
+ code_cache["model"] = model
183
+
184
+ return tokenizer, model
185
+
186
+
187
+ # ==========================================
188
+ # CODING ASSISTANT
189
+ # ==========================================
190
+
191
+ SYSTEM_PROMPT = """
192
+ You are Tasting AI, an advanced coding assistant.
193
+
194
+ Your responsibilities:
195
+
196
+ 1. Write Python, Kotlin, Java, HTML, CSS and JavaScript.
197
+ 2. Create Android applications.
198
+ 3. Analyze programming errors.
199
+ 4. Fix bugs in supplied code.
200
+ 5. Optimize existing code.
201
+ 6. Explain source code.
202
+ 7. Generate complete project files when requested.
203
+ 8. Preserve existing features when modifying projects.
204
+ 9. Never invent successful test results.
205
+ 10. Use clear Markdown formatting.
206
+
207
+ Always understand the user's requirements before generating code.
208
  """
209
 
210
+ def coding_assistant(
211
+ prompt,
212
+ model_name,
213
+ max_tokens,
214
+ temperature,
215
+ ):
216
+ if not prompt.strip():
217
+ raise gr.Error("Enter your coding request.")
218
+
219
+ if model_name not in CODE_MODELS:
220
+ raise gr.Error("Invalid coding model.")
221
+
222
+ try:
223
+ tokenizer, model = load_code_model(model_name)
224
+
225
+ messages = [
226
+ {
227
+ "role": "system",
228
+ "content": SYSTEM_PROMPT,
229
+ },
230
+ {
231
+ "role": "user",
232
+ "content": prompt,
233
+ }
234
+ ]
235
+
236
+ if hasattr(tokenizer, "apply_chat_template"):
237
+ formatted_prompt = tokenizer.apply_chat_template(
238
+ messages,
239
+ tokenize=False,
240
+ add_generation_prompt=True,
241
+ )
242
+ else:
243
+ formatted_prompt = (
244
+ SYSTEM_PROMPT
245
+ + "\n\nUser: "
246
+ + prompt
247
+ + "\n\nAssistant:"
248
+ )
249
+
250
+ inputs = tokenizer(
251
+ formatted_prompt,
252
+ return_tensors="pt",
253
+ truncation=True,
254
+ max_length=4096,
255
+ )
256
+
257
+ with torch.inference_mode():
258
+
259
+ outputs = model.generate(
260
+ **inputs,
261
+ max_new_tokens=int(max_tokens),
262
+ do_sample=float(temperature) > 0.05,
263
+ temperature=max(float(temperature), 0.05),
264
+ pad_token_id=tokenizer.eos_token_id,
265
+ )
266
 
267
+ input_length = inputs["input_ids"].shape[1]
268
 
269
+ new_tokens = outputs[0][input_length:]
270
 
271
+ answer = tokenizer.decode(
272
+ new_tokens,
273
+ skip_special_tokens=True,
274
  )
275
 
276
+ return answer or "No response generated."
277
+
278
+ except Exception as error:
279
+ raise gr.Error(
280
+ "Coding error: " + str(error)
281
  )
282
 
 
283
 
284
+ # ==========================================
285
+ # GRADIO INTERFACE
286
+ # ==========================================
287
+
288
+ CSS = """
289
+ .gradio-container {
290
+ max-width: 1100px !important;
291
+ margin: auto !important;
292
+ }
293
+
294
+ #heading {
295
+ text-align: center;
296
+ }
297
+
298
+ button.primary {
299
+ min-height: 48px;
300
+ }
301
+ """
302
+
303
+ with gr.Blocks(
304
+ theme=gr.themes.Soft(),
305
+ css=CSS,
306
+ title=APP_NAME,
307
+ ) as demo:
308
+
309
+ gr.Markdown(
310
+ """
311
+ # ⚡ Tasting AI Studio
312
+
313
+ ### Public Open-Source AI Models
314
+
315
+ No API key required for public model downloads.
316
+ """,
317
+ elem_id="heading",
318
+ )
319
+
320
+ with gr.Tabs():
321
+
322
+ # ----------------------------------
323
+ # IMAGE GENERATOR
324
+ # ----------------------------------
325
+
326
+ with gr.Tab("🎨 Image Generator"):
327
+
328
+ gr.Markdown("## Text to Image")
329
+
330
+ image_model = gr.Dropdown(
331
+ choices=list(IMAGE_MODELS.keys()),
332
+ value="SDXL Turbo",
333
+ label="Choose Image Model",
334
+ )
335
+
336
+ image_prompt = gr.Textbox(
337
+ label="Image Prompt",
338
+ placeholder="Describe your image...",
339
+ lines=4,
340
+ )
341
 
342
  negative_prompt = gr.Textbox(
343
+ label="Negative Prompt",
344
+ lines=2,
345
+ )
346
+
347
+ with gr.Row():
348
+
349
+ width = gr.Slider(
350
+ 256, 768, value=512,
351
+ step=32, label="Width"
352
+ )
353
+
354
+ height = gr.Slider(
355
+ 256, 768, value=512,
356
+ step=32, label="Height"
357
+ )
358
+
359
+ steps = gr.Slider(
360
+ 1, 30, value=4,
361
+ step=1,
362
+ label="Inference Steps"
363
  )
364
 
365
+ seed = gr.Number(
366
+ value=0,
367
+ precision=0,
368
+ label="Seed"
369
  )
370
 
371
+ random_seed = gr.Checkbox(
372
  value=True,
373
+ label="Random Seed"
374
  )
375
 
376
+ generate_button = gr.Button(
377
+ "✨ Generate Image",
378
+ variant="primary",
 
379
  )
380
 
381
+ image_output = gr.Image(
382
+ label="Generated Image",
383
+ type="pil",
 
384
  )
385
 
386
+ seed_output = gr.Number(
387
+ label="Generated Seed",
388
+ precision=0,
 
389
  )
390
 
391
+ generate_button.click(
392
+ fn=generate_image,
393
+ inputs=[
394
+ image_prompt,
395
+ negative_prompt,
396
+ image_model,
397
+ width,
398
+ height,
399
+ steps,
400
+ seed,
401
+ random_seed,
402
+ ],
403
+ outputs=[
404
+ image_output,
405
+ seed_output,
406
+ ],
407
  )
408
 
409
+ # ----------------------------------
410
+ # CODING ASSISTANT
411
+ # ----------------------------------
412
+
413
+ with gr.Tab("💻 AI Coding"):
414
+
415
+ gr.Markdown(
416
+ """
417
+ ## AI Coding Assistant
418
+
419
+ Generate, explain, debug and optimize code.
420
+ """
421
+ )
422
 
423
+ code_model = gr.Dropdown(
424
+ choices=list(CODE_MODELS.keys()),
425
+ value="Qwen Coder 0.5B",
426
+ label="Choose Coding Model",
427
+ )
428
+
429
+ code_prompt = gr.Textbox(
430
+ label="Your Coding Request",
431
+ placeholder="Create a Python application...",
432
+ lines=7,
433
+ )
434
+
435
+ with gr.Row():
436
+
437
+ max_tokens = gr.Slider(
438
+ 128, 1024,
439
+ value=512,
440
+ step=128,
441
+ label="Maximum New Tokens",
442
+ )
443
+
444
+ temperature = gr.Slider(
445
+ 0.1, 1.0,
446
+ value=0.3,
447
+ step=0.1,
448
+ label="Temperature",
449
+ )
450
+
451
+ coding_button = gr.Button(
452
+ "⚡ Generate Code",
453
+ variant="primary",
454
+ )
455
+
456
+ coding_output = gr.Markdown(
457
+ label="AI Response"
458
+ )
459
+
460
+ coding_button.click(
461
+ fn=coding_assistant,
462
+ inputs=[
463
+ code_prompt,
464
+ code_model,
465
+ max_tokens,
466
+ temperature,
467
+ ],
468
+ outputs=coding_output,
469
+ )
470
+
471
+ gr.Markdown(
472
+ """
473
+ ---
474
+ **Tasting AI Studio**
475
+ Public models · Local inference · No API key
476
+ """
477
  )
478
 
479
+
480
+ # ==========================================
481
+ # START
482
+ # ==========================================
483
+
484
  if __name__ == "__main__":
485
+ demo.queue(
486
+ default_concurrency_limit=1
487
+ ).launch()