lastwarning commited on
Commit
ea34782
·
verified ·
1 Parent(s): ab35ebc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1370 -333
app.py CHANGED
@@ -1,39 +1,113 @@
1
 
2
  import os
3
  import gc
4
- import threading
5
  import random
 
 
 
 
 
 
 
6
 
7
  os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
8
  os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
 
9
 
 
10
  import gradio as gr
11
  import torch
12
- import spaces
13
 
14
- from diffusers import DiffusionPipeline
 
 
 
 
 
 
15
  from transformers import (
16
  AutoTokenizer,
17
  AutoModelForCausalLM,
18
  TextIteratorStreamer,
 
 
19
  )
20
 
21
  from threading import Thread, Event
22
 
23
 
24
  # ==========================================
25
- # CONFIGURATION
26
  # ==========================================
27
 
28
  APP_NAME = "Tasting AI Studio"
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  IMAGE_MODELS = {
31
- "SDXL Turbo": "stabilityai/sdxl-turbo",
32
- "Stable Diffusion 1.5":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  "stable-diffusion-v1-5/stable-diffusion-v1-5",
 
34
  }
35
 
 
 
 
 
 
36
  CODE_MODELS = {
 
 
 
37
  "Qwen Coder 0.5B":
38
  "Qwen/Qwen2.5-Coder-0.5B-Instruct",
39
 
@@ -42,11 +116,29 @@ CODE_MODELS = {
42
 
43
  "DeepSeek Coder 1.3B":
44
  "deepseek-ai/deepseek-coder-1.3b-instruct",
 
 
 
 
 
 
 
 
 
 
 
 
45
  }
46
 
 
 
 
 
 
47
  image_cache = {
48
  "name": None,
49
  "pipe": None,
 
50
  }
51
 
52
  code_cache = {
@@ -55,466 +147,1219 @@ code_cache = {
55
  "model": None,
56
  }
57
 
58
- image_lock = threading.Lock()
59
- code_lock = threading.Lock()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- stop_events = {}
62
 
 
63
 
64
- # ==========================================
65
- # IMAGE MODEL
66
- # ==========================================
67
 
68
- @spaces.GPU(duration=120)
69
- def generate_image(
70
- prompt,
71
- negative_prompt,
72
- model_name,
73
- width,
74
- height,
75
- steps,
76
- seed,
77
- random_seed,
78
- ):
79
- if not prompt.strip():
80
- raise gr.Error("Enter an image prompt.")
81
 
82
- if not torch.cuda.is_available():
83
- raise gr.Error("GPU is unavailable.")
84
 
85
- if model_name not in IMAGE_MODELS:
86
- raise gr.Error("Invalid image model.")
87
 
88
- model_id = IMAGE_MODELS[model_name]
89
 
90
- if random_seed:
91
- seed = random.randint(0, 2147483647)
92
 
93
- with image_lock:
94
- try:
95
- if image_cache["name"] != model_id:
96
 
97
- if image_cache["pipe"] is not None:
98
- del image_cache["pipe"]
99
 
100
- image_cache["pipe"] = None
101
- image_cache["name"] = None
102
 
103
- gc.collect()
104
- torch.cuda.empty_cache()
105
 
106
- pipe = DiffusionPipeline.from_pretrained(
107
- model_id,
108
- torch_dtype=torch.float16,
109
- token=False,
110
- )
111
 
112
- pipe = pipe.to("cuda")
113
 
114
- image_cache["pipe"] = pipe
115
- image_cache["name"] = model_id
116
 
117
- pipe = image_cache["pipe"]
118
 
119
- generator = torch.Generator(
120
- device="cuda"
121
- ).manual_seed(int(seed))
122
 
123
- if model_name == "SDXL Turbo":
124
- guidance = 0.0
125
- actual_steps = min(max(int(steps), 1), 4)
126
- else:
127
- guidance = 7.5
128
- actual_steps = max(int(steps), 20)
129
 
130
- result = pipe(
131
- prompt=prompt,
132
- negative_prompt=negative_prompt or None,
133
- width=int(width),
134
- height=int(height),
135
- num_inference_steps=actual_steps,
136
- guidance_scale=guidance,
137
- generator=generator,
138
- )
139
 
140
- return result.images[0], int(seed)
141
 
142
- except Exception as error:
143
- gc.collect()
144
- torch.cuda.empty_cache()
145
 
146
- raise gr.Error(
147
- f"Image generation failed: {error}"
148
- )
149
 
 
150
 
151
- # ==========================================
152
- # LOAD CODING MODEL
153
- # ==========================================
154
 
155
- def load_code_model(model_name):
156
 
157
- model_id = CODE_MODELS[model_name]
158
 
159
- with code_lock:
160
 
161
- if code_cache["name"] == model_id:
162
- return (
163
- code_cache["tokenizer"],
164
- code_cache["model"],
165
- )
 
166
 
167
- if code_cache["model"] is not None:
168
 
169
- del code_cache["model"]
170
- del code_cache["tokenizer"]
171
 
172
- code_cache["model"] = None
173
- code_cache["tokenizer"] = None
174
- code_cache["name"] = None
175
 
176
- gc.collect()
177
 
178
- tokenizer = AutoTokenizer.from_pretrained(
179
- model_id,
180
- token=False,
181
- )
182
 
183
- model = AutoModelForCausalLM.from_pretrained(
184
- model_id,
185
- token=False,
186
- torch_dtype=torch.float32,
187
- low_cpu_mem_usage=True,
188
- )
189
 
190
- model.to("cpu")
191
- model.eval()
192
 
193
- code_cache["name"] = model_id
194
- code_cache["tokenizer"] = tokenizer
195
- code_cache["model"] = model
196
 
197
- return tokenizer, model
198
 
 
199
 
200
- # ==========================================
201
- # CODING SYSTEM PROMPT
202
- # ==========================================
203
 
204
- SYSTEM_PROMPT = """
205
- You are Tasting AI, an advanced software coding assistant.
206
 
207
- You specialize in:
208
 
209
- - Python
210
- - Kotlin
211
- - Java
212
- - Android development
213
- - JavaScript
214
- - HTML
215
- - CSS
216
- - React
217
- - APIs
218
- - Databases
219
- - Debugging
220
- - Code optimization
221
- - Software architecture
222
 
223
- RULES:
224
 
225
- 1. Understand the complete user request.
226
- 2. Generate practical working code.
227
- 3. Never intentionally omit important code.
228
- 4. Preserve existing features when fixing code.
229
- 5. Explain important changes.
230
- 6. Return complete files when requested.
231
- 7. Identify dependencies.
232
- 8. Never claim code was tested unless actually tested.
233
- 9. Use Markdown formatting.
234
- 10. Prioritize correctness over unnecessary explanations.
235
- """
236
 
 
237
 
238
- # ==========================================
239
- # REAL-TIME CODING STREAM
240
- # ==========================================
241
 
242
- def coding_assistant(
243
- prompt,
244
- model_name,
245
- max_tokens,
246
- temperature,
247
- history,
248
- ):
249
 
250
- if not prompt.strip():
251
- yield "Please enter your coding request."
252
- return
253
 
254
- if model_name not in CODE_MODELS:
255
- yield "Invalid coding model."
256
- return
257
 
258
- stop_event = Event()
259
- stop_events["current"] = stop_event
260
 
261
- try:
262
 
263
- yield "⏳ Loading coding model..."
264
 
265
- tokenizer, model = load_code_model(model_name)
266
 
267
- messages = [
268
- {
269
- "role": "system",
270
- "content": SYSTEM_PROMPT,
271
- }
272
- ]
273
 
274
- # Previous conversation context.
275
- if history:
276
- for item in history[-6:]:
277
 
278
- if not isinstance(item, dict):
279
- continue
280
 
281
- role = item.get("role")
282
- content = item.get("content")
283
 
284
- if role in ["user", "assistant"]:
285
- if isinstance(content, str):
286
- messages.append({
287
- "role": role,
288
- "content": content,
289
- })
290
 
291
- messages.append({
292
- "role": "user",
293
- "content": prompt,
294
- })
295
 
296
- formatted_prompt = tokenizer.apply_chat_template(
297
- messages,
298
- tokenize=False,
299
- add_generation_prompt=True,
300
- )
301
 
302
- inputs = tokenizer(
303
- formatted_prompt,
304
- return_tensors="pt",
305
- truncation=True,
306
- max_length=4096,
307
- )
308
 
309
- streamer = TextIteratorStreamer(
310
- tokenizer,
311
- skip_prompt=True,
312
- skip_special_tokens=True,
313
- timeout=120,
314
- )
315
 
316
- class StopOnRequest(
317
- torch.nn.Module
318
- ):
319
- def __init__(self, event):
320
- super().__init__()
321
- self.event = event
322
 
323
- def forward(self, input_ids, scores, **kwargs):
324
- return self.event.is_set()
325
 
326
- class StreamStoppingCriteria(
327
- torch.nn.Module
328
- ):
329
- def __init__(self, event):
330
- super().__init__()
331
- self.event = event
332
 
333
- def __call__(self, input_ids, scores, **kwargs):
334
- return self.event.is_set()
335
 
336
- from transformers import StoppingCriteria, StoppingCriteriaList
337
 
338
- class StopCriteria(StoppingCriteria):
339
- def __init__(self, event):
340
- self.event = event
341
 
342
- def __call__(self, input_ids, scores, **kwargs):
343
- return self.event.is_set()
344
 
345
- generation_kwargs = {
346
- **inputs,
347
- "streamer": streamer,
348
- "max_new_tokens": int(max_tokens),
349
- "do_sample": float(temperature) > 0.05,
350
- "temperature": max(float(temperature), 0.05),
351
- "pad_token_id": tokenizer.eos_token_id,
352
- "stopping_criteria": StoppingCriteriaList([
353
- StopCriteria(stop_event)
354
- ]),
355
- }
356
 
357
- def generate():
358
- try:
359
- with torch.inference_mode():
360
- model.generate(**generation_kwargs)
361
- except Exception as error:
362
- print("Generation error:", error)
363
 
364
- thread = Thread(
365
- target=generate,
366
- daemon=True,
367
- )
368
 
369
- thread.start()
370
 
371
- response = ""
372
 
373
- for token in streamer:
374
 
375
- if stop_event.is_set():
376
- break
377
 
378
- response += token
379
 
380
- # Update Gradio immediately.
381
- yield response
 
382
 
383
- thread.join(timeout=5)
384
 
385
- if stop_event.is_set():
386
- yield response + "\n\n⏹ Generation stopped."
387
- elif response:
388
- yield response
389
- else:
390
- yield "No response generated."
391
 
392
- except Exception as error:
393
- yield f"**Coding error:** {str(error)}"
 
 
 
 
 
394
 
395
- finally:
396
- stop_events.pop("current", None)
397
 
 
398
 
399
- # ==========================================
400
- # STOP GENERATION
401
- # ==========================================
402
 
403
- def stop_generation():
404
 
405
- event = stop_events.get("current")
406
 
407
- if event:
408
- event.set()
409
 
410
- return "⏹ Stop requested."
411
 
 
412
 
413
- # ==========================================
414
- # USER INTERFACE
415
- # ==========================================
 
 
 
 
416
 
417
- CSS = """
418
- .gradio-container {
419
- max-width: 1100px !important;
420
- margin: auto !important;
421
- }
 
 
422
 
423
- #heading {
424
- text-align: center;
425
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
 
427
- .primary-button {
428
- min-height: 48px;
429
- }
430
  """
431
 
 
 
 
 
 
432
  with gr.Blocks(
433
- theme=gr.themes.Soft(),
 
 
 
 
434
  css=CSS,
435
  title=APP_NAME,
436
  ) as demo:
437
 
 
 
438
  gr.Markdown(
439
  """
440
- # ⚡ Tasting AI Studio
441
-
442
- ### Image Generation + Real-Time AI Coding
443
-
444
- Public open-source models.
445
- """,
446
- elem_id="heading",
447
  )
448
 
 
 
 
 
449
  with gr.Tabs():
450
 
451
  # ==================================
452
- # IMAGE TAB
453
  # ==================================
454
 
455
- with gr.Tab("🎨 Image Generation"):
456
 
457
- gr.Markdown("## AI Image Generator")
 
 
458
 
459
  image_model = gr.Dropdown(
460
  choices=list(IMAGE_MODELS.keys()),
461
  value="SDXL Turbo",
462
- label="Choose Image Model",
463
  )
464
 
465
  image_prompt = gr.Textbox(
466
  label="Image Prompt",
467
- placeholder="Describe your image...",
 
 
 
468
  lines=4,
469
  )
470
 
471
  negative_prompt = gr.Textbox(
472
  label="Negative Prompt",
 
473
  lines=2,
474
  )
475
 
476
  with gr.Row():
477
 
478
  width = gr.Slider(
479
- 256, 768,
 
480
  value=512,
481
- step=32,
482
- label="Width",
483
  )
484
 
485
  height = gr.Slider(
486
- 256, 768,
 
487
  value=512,
488
- step=32,
489
- label="Height",
490
  )
491
 
492
  steps = gr.Slider(
493
- 1, 30,
 
494
  value=4,
495
  step=1,
496
  label="Inference Steps",
497
  )
498
 
499
- seed = gr.Number(
500
- value=0,
501
- precision=0,
502
- label="Seed",
503
- )
504
 
505
- random_seed = gr.Checkbox(
506
- value=True,
507
- label="Random Seed",
508
- )
 
 
 
 
 
 
509
 
510
  generate_button = gr.Button(
511
  "✨ Generate Image",
512
  variant="primary",
 
513
  )
514
 
515
  image_output = gr.Image(
516
- label="Generated Image",
517
  type="pil",
 
518
  )
519
 
520
  seed_output = gr.Number(
@@ -541,47 +1386,193 @@ with gr.Blocks(
541
  )
542
 
543
  # ==================================
544
- # CODING TAB
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545
  # ==================================
546
 
547
  with gr.Tab("💻 AI Coding"):
548
 
549
  gr.Markdown(
550
  """
551
- ## Real-Time Coding Assistant
552
 
553
- Watch your code being generated live.
 
 
554
  """
555
  )
556
 
557
  code_model = gr.Dropdown(
558
  choices=list(CODE_MODELS.keys()),
559
  value="Qwen Coder 0.5B",
560
- label="Choose Coding Model",
561
  )
562
 
563
  code_prompt = gr.Textbox(
564
  label="Your Coding Request",
565
- placeholder="Create a complete Python application...",
566
- lines=7,
 
 
567
  )
568
 
569
  with gr.Row():
570
 
571
  max_tokens = gr.Slider(
572
- 128, 1024,
 
573
  value=512,
574
  step=128,
575
  label="Maximum Output Tokens",
576
  )
577
 
578
  temperature = gr.Slider(
579
- 0.1, 1.0,
 
580
  value=0.3,
581
  step=0.1,
582
  label="Temperature",
583
  )
584
 
 
 
 
 
 
 
 
 
 
585
  with gr.Row():
586
 
587
  generate_code = gr.Button(
@@ -590,12 +1581,18 @@ with gr.Blocks(
590
  )
591
 
592
  stop_button = gr.Button(
593
- "⏹ Stop Generation",
594
  variant="stop",
595
  )
596
 
597
- coding_output = gr.Markdown(
598
- label="Live AI Response",
 
 
 
 
 
 
599
  )
600
 
601
  generate_code.click(
@@ -605,21 +1602,59 @@ with gr.Blocks(
605
  code_model,
606
  max_tokens,
607
  temperature,
608
- gr.State([]),
609
  ],
610
- outputs=coding_output,
 
 
 
 
 
 
611
  )
612
 
613
  stop_button.click(
614
  fn=stop_generation,
615
- outputs=coding_output,
616
  )
617
 
618
- gr.Markdown(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619
  """
620
- ---
621
- **Tasting AI Studio**
622
- Local inference · Live code streaming · Public models
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
  """
624
  )
625
 
@@ -632,6 +1667,8 @@ if __name__ == "__main__":
632
 
633
  demo.queue(
634
  default_concurrency_limit=1,
 
635
  ).launch(
636
  show_error=True,
 
637
  )
 
1
 
2
  import os
3
  import gc
 
4
  import random
5
+ import threading
6
+ import traceback
7
+
8
+ # ==========================================
9
+ # ENVIRONMENT
10
+ # IMPORTANT: spaces before torch
11
+ # ==========================================
12
 
13
  os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
14
  os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
15
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
16
 
17
+ import spaces
18
  import gradio as gr
19
  import torch
 
20
 
21
+ from PIL import Image, ImageOps
22
+
23
+ from diffusers import (
24
+ DiffusionPipeline,
25
+ AutoPipelineForImage2Image,
26
+ )
27
+
28
  from transformers import (
29
  AutoTokenizer,
30
  AutoModelForCausalLM,
31
  TextIteratorStreamer,
32
+ StoppingCriteria,
33
+ StoppingCriteriaList,
34
  )
35
 
36
  from threading import Thread, Event
37
 
38
 
39
  # ==========================================
40
+ # APP CONFIGURATION
41
  # ==========================================
42
 
43
  APP_NAME = "Tasting AI Studio"
44
 
45
+ APP_VERSION = "2.0 Premium"
46
+
47
+ DEVICE = "cuda"
48
+
49
+ IMAGE_DTYPE = torch.float16
50
+
51
+ MAX_INPUT_LENGTH = 4096
52
+
53
+ MAX_HISTORY_MESSAGES = 10
54
+
55
+ # ==========================================
56
+ # TEXT TO IMAGE MODELS
57
+ # ==========================================
58
+
59
  IMAGE_MODELS = {
60
+
61
+ "SDXL Turbo": {
62
+ "id": "stabilityai/sdxl-turbo",
63
+ "steps": 4,
64
+ "guidance": 0.0,
65
+ "max_steps": 4,
66
+ },
67
+
68
+ "Stable Diffusion 1.5": {
69
+ "id": "stable-diffusion-v1-5/stable-diffusion-v1-5",
70
+ "steps": 25,
71
+ "guidance": 7.5,
72
+ "max_steps": 30,
73
+ },
74
+
75
+ "SD Turbo": {
76
+ "id": "stabilityai/sd-turbo",
77
+ "steps": 4,
78
+ "guidance": 0.0,
79
+ "max_steps": 4,
80
+ },
81
+
82
+ "Tiny SD": {
83
+ "id": "segmind/tiny-sd",
84
+ "steps": 20,
85
+ "guidance": 7.5,
86
+ "max_steps": 30,
87
+ },
88
+ }
89
+
90
+
91
+ # ==========================================
92
+ # IMAGE TO IMAGE MODELS
93
+ # ==========================================
94
+
95
+ IMAGE_TO_IMAGE_MODELS = {
96
+
97
+ "Stable Diffusion 1.5 Img2Img":
98
  "stable-diffusion-v1-5/stable-diffusion-v1-5",
99
+
100
  }
101
 
102
+
103
+ # ==========================================
104
+ # CODING MODELS
105
+ # ==========================================
106
+
107
  CODE_MODELS = {
108
+
109
+ # ORIGINAL MODELS
110
+
111
  "Qwen Coder 0.5B":
112
  "Qwen/Qwen2.5-Coder-0.5B-Instruct",
113
 
 
116
 
117
  "DeepSeek Coder 1.3B":
118
  "deepseek-ai/deepseek-coder-1.3b-instruct",
119
+
120
+ # ADDITIONAL MODELS
121
+
122
+ "Qwen Coder 3B":
123
+ "Qwen/Qwen2.5-Coder-3B-Instruct",
124
+
125
+ "StarCoder2 3B":
126
+ "bigcode/starcoder2-3b",
127
+
128
+ "CodeGen 350M":
129
+ "Salesforce/codegen-350M-mono",
130
+
131
  }
132
 
133
+
134
+ # ==========================================
135
+ # MODEL CACHES
136
+ # ==========================================
137
+
138
  image_cache = {
139
  "name": None,
140
  "pipe": None,
141
+ "mode": None,
142
  }
143
 
144
  code_cache = {
 
147
  "model": None,
148
  }
149
 
150
+ image_lock = threading.RLock()
151
+
152
+ code_lock = threading.RLock()
153
+
154
+ generation_events = {}
155
+
156
+ generation_events_lock = threading.Lock()
157
+
158
+
159
+ # ==========================================
160
+ # MEMORY MANAGEMENT
161
+ # ==========================================
162
+
163
+ def clear_image_cache():
164
+
165
+ with image_lock:
166
+
167
+ old_pipe = image_cache.get("pipe")
168
+
169
+ image_cache["pipe"] = None
170
+ image_cache["name"] = None
171
+ image_cache["mode"] = None
172
+
173
+ if old_pipe is not None:
174
+ del old_pipe
175
+
176
+ gc.collect()
177
+
178
+ if torch.cuda.is_available():
179
+ torch.cuda.empty_cache()
180
+
181
+
182
+ def clear_code_cache():
183
+
184
+ with code_lock:
185
+
186
+ old_model = code_cache.get("model")
187
+ old_tokenizer = code_cache.get("tokenizer")
188
+
189
+ code_cache["model"] = None
190
+ code_cache["tokenizer"] = None
191
+ code_cache["name"] = None
192
+
193
+ if old_model is not None:
194
+ del old_model
195
+
196
+ if old_tokenizer is not None:
197
+ del old_tokenizer
198
+
199
+ gc.collect()
200
+
201
+
202
+ # ==========================================
203
+ # IMAGE PIPELINE LOADER
204
+ # ==========================================
205
+
206
+ def load_image_pipeline(model_id, mode):
207
+
208
+ cache_key = f"{mode}:{model_id}"
209
+
210
+ with image_lock:
211
+
212
+ if (
213
+ image_cache["name"] == cache_key
214
+ and image_cache["pipe"] is not None
215
+ ):
216
+
217
+ return image_cache["pipe"]
218
+
219
+ clear_image_cache()
220
+
221
+ if mode == "text":
222
+
223
+ pipe = DiffusionPipeline.from_pretrained(
224
+ model_id,
225
+ torch_dtype=IMAGE_DTYPE,
226
+ token=False,
227
+ safety_checker=None,
228
+ requires_safety_checker=False,
229
+ )
230
+
231
+ elif mode == "image":
232
+
233
+ pipe = AutoPipelineForImage2Image.from_pretrained(
234
+ model_id,
235
+ torch_dtype=IMAGE_DTYPE,
236
+ token=False,
237
+ )
238
+
239
+ else:
240
+
241
+ raise ValueError("Unsupported image generation mode.")
242
+
243
+ pipe = pipe.to(DEVICE)
244
+
245
+ # Optional memory optimization.
246
+ if hasattr(pipe, "enable_attention_slicing"):
247
+ pipe.enable_attention_slicing()
248
+
249
+ image_cache["pipe"] = pipe
250
+ image_cache["name"] = cache_key
251
+ image_cache["mode"] = mode
252
+
253
+ return pipe
254
+
255
+
256
+ # ==========================================
257
+ # TEXT TO IMAGE GENERATION
258
+ # ==========================================
259
+
260
+ @spaces.GPU(duration=120)
261
+ def generate_image(
262
+ prompt,
263
+ negative_prompt,
264
+ model_name,
265
+ width,
266
+ height,
267
+ steps,
268
+ seed,
269
+ random_seed,
270
+ ):
271
+
272
+ if not prompt or not prompt.strip():
273
+
274
+ raise gr.Error("Please enter an image prompt.")
275
+
276
+ if model_name not in IMAGE_MODELS:
277
+
278
+ raise gr.Error("Invalid image model.")
279
+
280
+ config = IMAGE_MODELS[model_name]
281
+
282
+ if random_seed:
283
+ seed = random.randint(0, 2147483647)
284
+
285
+ seed = int(seed)
286
+
287
+ width = int(width)
288
+ height = int(height)
289
+
290
+ # Avoid unsupported dimensions.
291
+
292
+ width = max(256, min(width, 768))
293
+ height = max(256, min(height, 768))
294
+
295
+ width = (width // 8) * 8
296
+ height = (height // 8) * 8
297
+
298
+ actual_steps = min(
299
+ max(int(steps), 1),
300
+ config["max_steps"],
301
+ )
302
+
303
+ if model_name in ["SDXL Turbo", "SD Turbo"]:
304
+
305
+ actual_steps = min(actual_steps, 4)
306
+
307
+ else:
308
+
309
+ actual_steps = max(actual_steps, 1)
310
+
311
+ try:
312
+
313
+ pipe = load_image_pipeline(
314
+ config["id"],
315
+ "text",
316
+ )
317
+
318
+ generator = torch.Generator(
319
+ device=DEVICE
320
+ ).manual_seed(seed)
321
+
322
+ result = pipe(
323
+ prompt=prompt.strip(),
324
+ negative_prompt=negative_prompt or None,
325
+ width=width,
326
+ height=height,
327
+ num_inference_steps=actual_steps,
328
+ guidance_scale=config["guidance"],
329
+ generator=generator,
330
+ )
331
+
332
+ output = result.images[0]
333
+
334
+ return output, seed
335
+
336
+ except Exception as error:
337
+
338
+ traceback.print_exc()
339
+
340
+ raise gr.Error(
341
+ f"Text-to-image failed: {str(error)}"
342
+ )
343
+
344
+
345
+ # ==========================================
346
+ # IMAGE TO IMAGE GENERATION
347
+ # ==========================================
348
+
349
+ @spaces.GPU(duration=120)
350
+ def generate_image_to_image(
351
+ input_image,
352
+ prompt,
353
+ negative_prompt,
354
+ model_name,
355
+ strength,
356
+ steps,
357
+ guidance,
358
+ seed,
359
+ random_seed,
360
+ ):
361
+
362
+ if input_image is None:
363
+
364
+ raise gr.Error("Please upload an image.")
365
+
366
+ if not prompt or not prompt.strip():
367
+
368
+ raise gr.Error("Please enter a transformation prompt.")
369
+
370
+ if model_name not in IMAGE_TO_IMAGE_MODELS:
371
+
372
+ raise gr.Error("Invalid image-to-image model.")
373
+
374
+ if random_seed:
375
+ seed = random.randint(0, 2147483647)
376
+
377
+ seed = int(seed)
378
+
379
+ strength = float(strength)
380
+ strength = max(0.05, min(strength, 0.95))
381
+
382
+ steps = max(1, min(int(steps), 30))
383
+
384
+ try:
385
+
386
+ # Convert uploaded image to RGB.
387
+
388
+ if isinstance(input_image, Image.Image):
389
+
390
+ image = input_image.convert("RGB")
391
+
392
+ else:
393
+
394
+ image = Image.open(input_image).convert("RGB")
395
+
396
+ # Preserve image proportions.
397
+
398
+ image.thumbnail(
399
+ (768, 768),
400
+ Image.Resampling.LANCZOS,
401
+ )
402
+
403
+ # Make dimensions compatible with Stable Diffusion.
404
+
405
+ new_width = max(256, (image.width // 8) * 8)
406
+ new_height = max(256, (image.height // 8) * 8)
407
+
408
+ image = image.resize(
409
+ (new_width, new_height),
410
+ Image.Resampling.LANCZOS,
411
+ )
412
+
413
+ model_id = IMAGE_TO_IMAGE_MODELS[model_name]
414
+
415
+ pipe = load_image_pipeline(
416
+ model_id,
417
+ "image",
418
+ )
419
+
420
+ generator = torch.Generator(
421
+ device=DEVICE
422
+ ).manual_seed(seed)
423
+
424
+ result = pipe(
425
+ prompt=prompt.strip(),
426
+ image=image,
427
+ negative_prompt=negative_prompt or None,
428
+ strength=strength,
429
+ num_inference_steps=steps,
430
+ guidance_scale=float(guidance),
431
+ generator=generator,
432
+ )
433
+
434
+ return result.images[0], seed
435
+
436
+ except Exception as error:
437
+
438
+ traceback.print_exc()
439
+
440
+ raise gr.Error(
441
+ f"Image-to-image failed: {str(error)}"
442
+ )
443
+
444
+
445
+ # ==========================================
446
+ # CODING SYSTEM PROMPT
447
+ # ==========================================
448
+
449
+ SYSTEM_PROMPT = """
450
+ You are Tasting AI, a professional software engineering
451
+ and advanced coding assistant.
452
+
453
+ YOUR SPECIALIZATIONS:
454
+
455
+ - Python
456
+ - Kotlin
457
+ - Java
458
+ - Android development
459
+ - Android Studio
460
+ - Gradle
461
+ - AAPT2
462
+ - JavaScript
463
+ - TypeScript
464
+ - HTML
465
+ - CSS
466
+ - React
467
+ - APIs
468
+ - Databases
469
+ - Backend development
470
+ - Frontend development
471
+ - Hugging Face
472
+ - Gradio
473
+ - PyTorch
474
+ - Diffusers
475
+ - Transformers
476
+ - Machine learning
477
+ - Debugging
478
+ - Code optimization
479
+ - Software architecture
480
+
481
+ CORE RULES:
482
+
483
+ 1. Understand the complete user request.
484
+
485
+ 2. Generate practical, working code.
486
+
487
+ 3. Never intentionally omit important code.
488
+
489
+ 4. Preserve existing features when modifying projects.
490
+
491
+ 5. Explain important changes.
492
+
493
+ 6. Return complete files when requested.
494
+
495
+ 7. Identify required dependencies.
496
+
497
+ 8. Never claim code was tested unless actually tested.
498
+
499
+ 9. Use Markdown formatting.
500
+
501
+ 10. Prioritize correctness.
502
+
503
+ 11. Analyze error messages before proposing fixes.
504
+
505
+ 12. Avoid unnecessary code changes.
506
+
507
+ 13. Maintain compatibility with the requested environment.
508
+
509
+ 14. Clearly explain any limitations.
510
+
511
+ 15. When asked for a complete application,
512
+ return the complete implementation rather than pseudocode.
513
+ """
514
+
515
+
516
+ # ==========================================
517
+ # LOAD CODING MODEL
518
+ # ==========================================
519
+
520
+ def load_code_model(model_name):
521
+
522
+ if model_name not in CODE_MODELS:
523
+
524
+ raise ValueError("Invalid coding model.")
525
+
526
+ model_id = CODE_MODELS[model_name]
527
+
528
+ with code_lock:
529
+
530
+ if (
531
+ code_cache["name"] == model_id
532
+ and code_cache["model"] is not None
533
+ ):
534
+
535
+ return (
536
+ code_cache["tokenizer"],
537
+ code_cache["model"],
538
+ )
539
+
540
+ clear_code_cache()
541
+
542
+ tokenizer = AutoTokenizer.from_pretrained(
543
+ model_id,
544
+ token=False,
545
+ )
546
+
547
+ model = AutoModelForCausalLM.from_pretrained(
548
+ model_id,
549
+ token=False,
550
+ torch_dtype=torch.float32,
551
+ low_cpu_mem_usage=True,
552
+ )
553
+
554
+ model.to("cpu")
555
+ model.eval()
556
+
557
+ code_cache["name"] = model_id
558
+ code_cache["tokenizer"] = tokenizer
559
+ code_cache["model"] = model
560
+
561
+ return tokenizer, model
562
+
563
+
564
+ # ==========================================
565
+ # STOPPING CRITERIA
566
+ # ==========================================
567
+
568
+ class StopCriteria(StoppingCriteria):
569
+
570
+ def __init__(self, event):
571
+
572
+ self.event = event
573
+
574
+ def __call__(
575
+ self,
576
+ input_ids,
577
+ scores,
578
+ **kwargs,
579
+ ):
580
+
581
+ return self.event.is_set()
582
+
583
+
584
+ # ==========================================
585
+ # REAL TIME CODING ASSISTANT
586
+ # ==========================================
587
+
588
+ def coding_assistant(
589
+ prompt,
590
+ model_name,
591
+ max_tokens,
592
+ temperature,
593
+ history,
594
+ request: gr.Request,
595
+ ):
596
+
597
+ if not prompt or not prompt.strip():
598
+
599
+ yield history or [], history or []
600
+
601
+ return
602
+
603
+ session_id = (
604
+ request.session_hash
605
+ if request
606
+ else "default"
607
+ )
608
+
609
+ stop_event = Event()
610
+
611
+ with generation_events_lock:
612
+
613
+ old_event = generation_events.get(session_id)
614
+
615
+ if old_event:
616
+ old_event.set()
617
+
618
+ generation_events[session_id] = stop_event
619
+
620
+ history = list(history or [])
621
+
622
+ conversation = history[-MAX_HISTORY_MESSAGES:]
623
+
624
+ messages = [
625
+ {
626
+ "role": "system",
627
+ "content": SYSTEM_PROMPT,
628
+ }
629
+ ]
630
+
631
+ # Preserve previous conversation.
632
+
633
+ for item in conversation:
634
+
635
+ if not isinstance(item, dict):
636
+ continue
637
+
638
+ role = item.get("role")
639
+ content = item.get("content")
640
+
641
+ if (
642
+ role in ["user", "assistant"]
643
+ and isinstance(content, str)
644
+ ):
645
+
646
+ messages.append({
647
+ "role": role,
648
+ "content": content,
649
+ })
650
+
651
+ messages.append({
652
+ "role": "user",
653
+ "content": prompt.strip(),
654
+ })
655
+
656
+ updated_history = history + [
657
+ {
658
+ "role": "user",
659
+ "content": prompt.strip(),
660
+ },
661
+ {
662
+ "role": "assistant",
663
+ "content": "⏳ Loading coding model...",
664
+ },
665
+ ]
666
+
667
+ try:
668
+
669
+ yield updated_history, updated_history
670
+
671
+ tokenizer, model = load_code_model(model_name)
672
+
673
+ formatted_prompt = tokenizer.apply_chat_template(
674
+ messages,
675
+ tokenize=False,
676
+ add_generation_prompt=True,
677
+ )
678
+
679
+ inputs = tokenizer(
680
+ formatted_prompt,
681
+ return_tensors="pt",
682
+ truncation=True,
683
+ max_length=MAX_INPUT_LENGTH,
684
+ )
685
+
686
+ streamer = TextIteratorStreamer(
687
+ tokenizer,
688
+ skip_prompt=True,
689
+ skip_special_tokens=True,
690
+ )
691
+
692
+ generation_kwargs = {
693
+
694
+ **inputs,
695
+
696
+ "streamer": streamer,
697
+
698
+ "max_new_tokens": int(max_tokens),
699
+
700
+ "do_sample": float(temperature) > 0.05,
701
+
702
+ "temperature": max(
703
+ float(temperature),
704
+ 0.05,
705
+ ),
706
+
707
+ "pad_token_id": (
708
+ tokenizer.pad_token_id
709
+ if tokenizer.pad_token_id is not None
710
+ else tokenizer.eos_token_id
711
+ ),
712
+
713
+ "stopping_criteria": StoppingCriteriaList([
714
+ StopCriteria(stop_event)
715
+ ]),
716
+ }
717
+
718
+ generation_error = []
719
+
720
+ def generate():
721
+
722
+ try:
723
+
724
+ with torch.inference_mode():
725
+
726
+ model.generate(
727
+ **generation_kwargs
728
+ )
729
+
730
+ except Exception as error:
731
+
732
+ generation_error.append(str(error))
733
+
734
+ traceback.print_exc()
735
+
736
+ # Ensure the streamer can finish.
737
+
738
+ try:
739
+ streamer.end()
740
+ except Exception:
741
+ pass
742
+
743
+ thread = Thread(
744
+ target=generate,
745
+ daemon=True,
746
+ )
747
+
748
+ thread.start()
749
+
750
+ response = ""
751
+
752
+ for token in streamer:
753
+
754
+ if stop_event.is_set():
755
+ break
756
+
757
+ response += token
758
+
759
+ current_history = history + [
760
+ {
761
+ "role": "user",
762
+ "content": prompt.strip(),
763
+ },
764
+ {
765
+ "role": "assistant",
766
+ "content": response,
767
+ },
768
+ ]
769
+
770
+ yield current_history, current_history
771
+
772
+ thread.join(timeout=10)
773
+
774
+ if generation_error:
775
+
776
+ raise RuntimeError(
777
+ generation_error[0]
778
+ )
779
+
780
+ if stop_event.is_set():
781
+
782
+ response += "\n\n⏹ Generation stopped."
783
+
784
+ elif not response.strip():
785
+
786
+ response = "No response generated."
787
+
788
+ final_history = history + [
789
+ {
790
+ "role": "user",
791
+ "content": prompt.strip(),
792
+ },
793
+ {
794
+ "role": "assistant",
795
+ "content": response,
796
+ },
797
+ ]
798
+
799
+ yield final_history, final_history
800
+
801
+ except Exception as error:
802
+
803
+ error_text = (
804
+ f"**Coding error:** {str(error)}"
805
+ )
806
+
807
+ final_history = history + [
808
+ {
809
+ "role": "user",
810
+ "content": prompt.strip(),
811
+ },
812
+ {
813
+ "role": "assistant",
814
+ "content": error_text,
815
+ },
816
+ ]
817
+
818
+ yield final_history, final_history
819
+
820
+ finally:
821
+
822
+ with generation_events_lock:
823
+
824
+ if generation_events.get(session_id) is stop_event:
825
+
826
+ generation_events.pop(
827
+ session_id,
828
+ None,
829
+ )
830
+
831
+
832
+ # ==========================================
833
+ # STOP GENERATION
834
+ # ==========================================
835
+
836
+ def stop_generation(request: gr.Request):
837
+
838
+ session_id = (
839
+ request.session_hash
840
+ if request
841
+ else "default"
842
+ )
843
+
844
+ with generation_events_lock:
845
+
846
+ event = generation_events.get(session_id)
847
+
848
+ if event:
849
+ event.set()
850
+
851
+ return "⏹ Stop requested."
852
+
853
+
854
+ # ==========================================
855
+ # CLEAR CODING HISTORY
856
+ # ==========================================
857
+
858
+ def clear_history():
859
+
860
+ return [], "Conversation cleared."
861
+
862
+
863
+ # ==========================================
864
+ # PREMIUM CSS
865
+ # ==========================================
866
+
867
+ CSS = r"""
868
+
869
+ @import url(
870
+ 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap'
871
+ );
872
+
873
+ :root {
874
+
875
+ --bg: #080b14;
876
+
877
+ --panel: #101727;
878
+
879
+ --accent: #8b5cf6;
880
+
881
+ --cyan: #06d6e9;
882
+
883
+ --text: #f5f7ff;
884
+
885
+ }
886
+
887
+ body {
888
+
889
+ background:
890
+ radial-gradient(
891
+ circle at 15% 10%,
892
+ rgba(105, 64, 255, .15),
893
+ transparent 35%
894
+ ),
895
+ radial-gradient(
896
+ circle at 90% 80%,
897
+ rgba(0, 205, 255, .10),
898
+ transparent 35%
899
+ ),
900
+ var(--bg) !important;
901
+
902
+ font-family: Inter, sans-serif !important;
903
+
904
+ }
905
+
906
+ .gradio-container {
907
+
908
+ max-width: 1250px !important;
909
+
910
+ margin: auto !important;
911
+
912
+ background: transparent !important;
913
+
914
+ }
915
+
916
+ footer {
917
+
918
+ display: none !important;
919
+
920
+ }
921
+
922
+ #main-header {
923
+
924
+ position: relative;
925
+
926
+ overflow: hidden;
927
+
928
+ text-align: center;
929
+
930
+ padding: 55px 20px;
931
+
932
+ border: 1px solid rgba(139, 92, 246, .35);
933
+
934
+ border-radius: 25px;
935
+
936
+ background:
937
+ linear-gradient(
938
+ 120deg,
939
+ rgba(45, 26, 90, .95),
940
+ rgba(9, 35, 57, .95),
941
+ rgba(30, 17, 70, .95)
942
+ );
943
+
944
+ box-shadow:
945
+ 0 0 30px rgba(139, 92, 246, .16),
946
+ inset 0 0 35px rgba(6, 214, 233, .07);
947
+
948
+ animation: bannerGlow 5s ease-in-out infinite alternate;
949
+
950
+ }
951
+
952
+ @keyframes bannerGlow {
953
+
954
+ from {
955
+
956
+ box-shadow:
957
+ 0 0 15px rgba(139, 92, 246, .15);
958
+
959
+ }
960
+
961
+ to {
962
+
963
+ box-shadow:
964
+ 0 0 38px rgba(6, 214, 233, .24),
965
+ 0 0 65px rgba(139, 92, 246, .17);
966
+
967
+ }
968
+
969
+ }
970
+
971
+ .hero-title {
972
+
973
+ font-size: clamp(30px, 6vw, 58px);
974
+
975
+ font-weight: 900;
976
+
977
+ letter-spacing: -2px;
978
+
979
+ background:
980
+ linear-gradient(
981
+ 90deg,
982
+ #ffffff,
983
+ #b8a5ff,
984
+ #56e8ff,
985
+ #ffffff
986
+ );
987
+
988
+ background-size: 300%;
989
+
990
+ -webkit-background-clip: text;
991
+
992
+ -webkit-text-fill-color: transparent;
993
+
994
+ animation: textGradient 5s linear infinite;
995
+
996
+ }
997
+
998
+ @keyframes textGradient {
999
+
1000
+ 0% { background-position: 0%; }
1001
+
1002
+ 100% { background-position: 300%; }
1003
+
1004
+ }
1005
+
1006
+ .hero-subtitle {
1007
+
1008
+ color: #bdc7df;
1009
+
1010
+ font-size: 15px;
1011
+
1012
+ letter-spacing: 1px;
1013
+
1014
+ animation: fadeIn 1.5s ease;
1015
+
1016
+ }
1017
+
1018
+ @keyframes fadeIn {
1019
+
1020
+ from {
1021
+
1022
+ opacity: 0;
1023
 
1024
+ transform: translateY(12px);
1025
 
1026
+ }
1027
 
1028
+ to {
 
 
1029
 
1030
+ opacity: 1;
 
 
 
 
 
 
 
 
 
 
 
 
1031
 
1032
+ transform: translateY(0);
 
1033
 
1034
+ }
 
1035
 
1036
+ }
1037
 
1038
+ .section-title {
 
1039
 
1040
+ font-size: 23px;
 
 
1041
 
1042
+ font-weight: 800;
 
1043
 
1044
+ color: #ffffff;
 
1045
 
1046
+ }
 
1047
 
1048
+ .gradio-container .tab-nav {
 
 
 
 
1049
 
1050
+ border: 1px solid rgba(139, 92, 246, .25);
1051
 
1052
+ border-radius: 15px;
 
1053
 
1054
+ background: rgba(18, 24, 40, .8);
1055
 
1056
+ padding: 7px;
 
 
1057
 
1058
+ }
 
 
 
 
 
1059
 
1060
+ .gradio-container button {
 
 
 
 
 
 
 
 
1061
 
1062
+ border-radius: 12px !important;
1063
 
1064
+ transition: all .25s ease !important;
 
 
1065
 
1066
+ }
 
 
1067
 
1068
+ .gradio-container button:hover {
1069
 
1070
+ transform: translateY(-2px);
 
 
1071
 
1072
+ box-shadow: 0 0 20px rgba(139, 92, 246, .35);
1073
 
1074
+ }
1075
 
1076
+ .primary {
1077
 
1078
+ background:
1079
+ linear-gradient(
1080
+ 100deg,
1081
+ #7045ed,
1082
+ #168edb
1083
+ ) !important;
1084
 
1085
+ border: 1px solid rgba(255,255,255,.15) !important;
1086
 
1087
+ color: white !important;
 
1088
 
1089
+ font-weight: 800 !important;
 
 
1090
 
1091
+ }
1092
 
1093
+ textarea, input {
 
 
 
1094
 
1095
+ border-radius: 12px !important;
 
 
 
 
 
1096
 
1097
+ }
 
1098
 
1099
+ .gradio-container .block {
 
 
1100
 
1101
+ border-color: rgba(139, 92, 246, .16) !important;
1102
 
1103
+ }
1104
 
1105
+ .output-markdown {
 
 
1106
 
1107
+ border-radius: 15px;
 
1108
 
1109
+ }
1110
 
1111
+ #coding-output {
 
 
 
 
 
 
 
 
 
 
 
 
1112
 
1113
+ min-height: 350px;
1114
 
1115
+ padding: 18px;
 
 
 
 
 
 
 
 
 
 
1116
 
1117
+ border: 1px solid rgba(6, 214, 233, .22);
1118
 
1119
+ border-radius: 15px;
 
 
1120
 
1121
+ background: rgba(9, 15, 28, .8);
 
 
 
 
 
 
1122
 
1123
+ }
 
 
1124
 
1125
+ #coding-output code {
 
 
1126
 
1127
+ color: #70e7ff;
 
1128
 
1129
+ }
1130
 
1131
+ #footer {
1132
 
1133
+ text-align: center;
1134
 
1135
+ color: #8390ad;
 
 
 
 
 
1136
 
1137
+ padding: 20px;
 
 
1138
 
1139
+ }
 
1140
 
1141
+ .status-label {
 
1142
 
1143
+ color: #61e5f3;
 
 
 
 
 
1144
 
1145
+ font-weight: 600;
 
 
 
1146
 
1147
+ }
 
 
 
 
1148
 
1149
+ @media(max-width: 650px) {
 
 
 
 
 
1150
 
1151
+ .gradio-container {
 
 
 
 
 
1152
 
1153
+ padding: 8px !important;
 
 
 
 
 
1154
 
1155
+ }
 
1156
 
1157
+ #main-header {
 
 
 
 
 
1158
 
1159
+ padding: 35px 12px;
 
1160
 
1161
+ border-radius: 18px;
1162
 
1163
+ }
 
 
1164
 
1165
+ .hero-title {
 
1166
 
1167
+ font-size: 32px;
 
 
 
 
 
 
 
 
 
 
1168
 
1169
+ }
 
 
 
 
 
1170
 
1171
+ .hero-subtitle {
 
 
 
1172
 
1173
+ font-size: 12px;
1174
 
1175
+ }
1176
 
1177
+ }
1178
 
1179
+ """
 
1180
 
 
1181
 
1182
+ # ==========================================
1183
+ # PREMIUM HEADER
1184
+ # ==========================================
1185
 
1186
+ HEADER = """
1187
 
1188
+ <div id="main-header">
 
 
 
 
 
1189
 
1190
+ <div style="
1191
+ font-size:13px;
1192
+ color:#83eaff;
1193
+ letter-spacing:4px;
1194
+ font-weight:800;
1195
+ margin-bottom:12px;
1196
+ ">
1197
 
1198
+ NEXT GENERATION ARTIFICIAL INTELLIGENCE
 
1199
 
1200
+ </div>
1201
 
1202
+ <div class="hero-title">
 
 
1203
 
1204
+ ⚡ TASTING AI STUDIO
1205
 
1206
+ </div>
1207
 
1208
+ <div class="hero-subtitle">
 
1209
 
1210
+ CREATE · TRANSFORM · CODE · INNOVATE
1211
 
1212
+ </div>
1213
 
1214
+ <div style="
1215
+ display:flex;
1216
+ justify-content:center;
1217
+ flex-wrap:wrap;
1218
+ gap:9px;
1219
+ margin-top:25px;
1220
+ ">
1221
 
1222
+ <span style="
1223
+ background:#ffffff15;
1224
+ padding:8px 15px;
1225
+ border-radius:30px;
1226
+ color:#d8d5ff;
1227
+ font-size:12px;
1228
+ ">🎨 AI Art</span>
1229
 
1230
+ <span style="
1231
+ background:#ffffff15;
1232
+ padding:8px 15px;
1233
+ border-radius:30px;
1234
+ color:#d8d5ff;
1235
+ font-size:12px;
1236
+ ">🖼 Image Transform</span>
1237
+
1238
+ <span style="
1239
+ background:#ffffff15;
1240
+ padding:8px 15px;
1241
+ border-radius:30px;
1242
+ color:#d8d5ff;
1243
+ font-size:12px;
1244
+ ">💻 AI Coding</span>
1245
+
1246
+ </div>
1247
+
1248
+ </div>
1249
 
 
 
 
1250
  """
1251
 
1252
+
1253
+ # ==========================================
1254
+ # GRADIO APPLICATION
1255
+ # ==========================================
1256
+
1257
  with gr.Blocks(
1258
+ theme=gr.themes.Soft(
1259
+ primary_hue="violet",
1260
+ secondary_hue="cyan",
1261
+ neutral_hue="slate",
1262
+ ),
1263
  css=CSS,
1264
  title=APP_NAME,
1265
  ) as demo:
1266
 
1267
+ gr.HTML(HEADER)
1268
+
1269
  gr.Markdown(
1270
  """
1271
+ <div style="text-align:center;color:#9ba9c5;padding:12px">
1272
+ Premium AI workspace · Public open models · Live generation
1273
+ </div>
1274
+ """
 
 
 
1275
  )
1276
 
1277
+ # ======================================
1278
+ # MAIN TABS
1279
+ # ======================================
1280
+
1281
  with gr.Tabs():
1282
 
1283
  # ==================================
1284
+ # TEXT TO IMAGE
1285
  # ==================================
1286
 
1287
+ with gr.Tab("🎨 Text to Image"):
1288
 
1289
+ gr.Markdown(
1290
+ "## Create Images with AI"
1291
+ )
1292
 
1293
  image_model = gr.Dropdown(
1294
  choices=list(IMAGE_MODELS.keys()),
1295
  value="SDXL Turbo",
1296
+ label="Select Image Model",
1297
  )
1298
 
1299
  image_prompt = gr.Textbox(
1300
  label="Image Prompt",
1301
+ placeholder=(
1302
+ "A beautiful fantasy landscape, "
1303
+ "cinematic lighting, detailed artwork..."
1304
+ ),
1305
  lines=4,
1306
  )
1307
 
1308
  negative_prompt = gr.Textbox(
1309
  label="Negative Prompt",
1310
+ placeholder="Blurry, low quality, distorted...",
1311
  lines=2,
1312
  )
1313
 
1314
  with gr.Row():
1315
 
1316
  width = gr.Slider(
1317
+ 256,
1318
+ 768,
1319
  value=512,
1320
+ step=64,
1321
+ label="Image Width",
1322
  )
1323
 
1324
  height = gr.Slider(
1325
+ 256,
1326
+ 768,
1327
  value=512,
1328
+ step=64,
1329
+ label="Image Height",
1330
  )
1331
 
1332
  steps = gr.Slider(
1333
+ 1,
1334
+ 30,
1335
  value=4,
1336
  step=1,
1337
  label="Inference Steps",
1338
  )
1339
 
1340
+ with gr.Row():
 
 
 
 
1341
 
1342
+ seed = gr.Number(
1343
+ value=0,
1344
+ precision=0,
1345
+ label="Seed",
1346
+ )
1347
+
1348
+ random_seed = gr.Checkbox(
1349
+ value=True,
1350
+ label="Random Seed",
1351
+ )
1352
 
1353
  generate_button = gr.Button(
1354
  "✨ Generate Image",
1355
  variant="primary",
1356
+ elem_classes=["primary-button"],
1357
  )
1358
 
1359
  image_output = gr.Image(
1360
+ label="Generated Artwork",
1361
  type="pil",
1362
+ height=450,
1363
  )
1364
 
1365
  seed_output = gr.Number(
 
1386
  )
1387
 
1388
  # ==================================
1389
+ # IMAGE TO IMAGE
1390
+ # ==================================
1391
+
1392
+ with gr.Tab("🖼 Image to Image"):
1393
+
1394
+ gr.Markdown(
1395
+ """
1396
+ ## Transform Your Images
1397
+
1398
+ Upload a picture and describe the transformation.
1399
+ """
1400
+ )
1401
+
1402
+ input_image = gr.Image(
1403
+ label="Upload Original Image",
1404
+ type="pil",
1405
+ height=350,
1406
+ )
1407
+
1408
+ gr.Markdown(
1409
+ """
1410
+ **Example transformation prompts**
1411
+
1412
+ - Whimsical hand-painted anime illustration
1413
+ - Soft watercolor fantasy artwork
1414
+ - Colorful cartoon illustration
1415
+ - Cinematic digital painting
1416
+ - Dreamy illustrated landscape
1417
+ """
1418
+ )
1419
+
1420
+ img2img_model = gr.Dropdown(
1421
+ choices=list(IMAGE_TO_IMAGE_MODELS.keys()),
1422
+ value="Stable Diffusion 1.5 Img2Img",
1423
+ label="Image-to-Image Model",
1424
+ )
1425
+
1426
+ img2img_prompt = gr.Textbox(
1427
+ label="Transformation Prompt",
1428
+ placeholder=(
1429
+ "Transform this photograph into "
1430
+ "a beautiful hand-painted anime illustration..."
1431
+ ),
1432
+ lines=4,
1433
+ )
1434
+
1435
+ img2img_negative = gr.Textbox(
1436
+ label="Negative Prompt",
1437
+ placeholder="Blurry, distorted, low quality...",
1438
+ lines=2,
1439
+ )
1440
+
1441
+ strength = gr.Slider(
1442
+ 0.05,
1443
+ 0.95,
1444
+ value=0.70,
1445
+ step=0.05,
1446
+ label="Transformation Strength",
1447
+ info=(
1448
+ "Lower values preserve more of the original image. "
1449
+ "Higher values create bigger changes."
1450
+ ),
1451
+ )
1452
+
1453
+ with gr.Row():
1454
+
1455
+ img2img_steps = gr.Slider(
1456
+ 1,
1457
+ 30,
1458
+ value=25,
1459
+ step=1,
1460
+ label="Inference Steps",
1461
+ )
1462
+
1463
+ img2img_guidance = gr.Slider(
1464
+ 1,
1465
+ 15,
1466
+ value=7.5,
1467
+ step=0.5,
1468
+ label="Guidance Scale",
1469
+ )
1470
+
1471
+ with gr.Row():
1472
+
1473
+ img2img_seed = gr.Number(
1474
+ value=0,
1475
+ precision=0,
1476
+ label="Seed",
1477
+ )
1478
+
1479
+ img2img_random = gr.Checkbox(
1480
+ value=True,
1481
+ label="Random Seed",
1482
+ )
1483
+
1484
+ img2img_button = gr.Button(
1485
+ "🪄 Transform Image",
1486
+ variant="primary",
1487
+ )
1488
+
1489
+ img2img_output = gr.Image(
1490
+ label="Transformed Image",
1491
+ type="pil",
1492
+ height=450,
1493
+ )
1494
+
1495
+ img2img_seed_output = gr.Number(
1496
+ label="Used Seed",
1497
+ precision=0,
1498
+ )
1499
+
1500
+ img2img_button.click(
1501
+ fn=generate_image_to_image,
1502
+ inputs=[
1503
+ input_image,
1504
+ img2img_prompt,
1505
+ img2img_negative,
1506
+ img2img_model,
1507
+ strength,
1508
+ img2img_steps,
1509
+ img2img_guidance,
1510
+ img2img_seed,
1511
+ img2img_random,
1512
+ ],
1513
+ outputs=[
1514
+ img2img_output,
1515
+ img2img_seed_output,
1516
+ ],
1517
+ )
1518
+
1519
+ # ==================================
1520
+ # AI CODING
1521
  # ==================================
1522
 
1523
  with gr.Tab("💻 AI Coding"):
1524
 
1525
  gr.Markdown(
1526
  """
1527
+ ## Advanced AI Coding Assistant
1528
 
1529
+ <div style="color:#7ddfff">
1530
+ Real-time token streaming · Multiple coding models
1531
+ </div>
1532
  """
1533
  )
1534
 
1535
  code_model = gr.Dropdown(
1536
  choices=list(CODE_MODELS.keys()),
1537
  value="Qwen Coder 0.5B",
1538
+ label="Select Coding Model",
1539
  )
1540
 
1541
  code_prompt = gr.Textbox(
1542
  label="Your Coding Request",
1543
+ placeholder=(
1544
+ "Build a complete Android application..."
1545
+ ),
1546
+ lines=6,
1547
  )
1548
 
1549
  with gr.Row():
1550
 
1551
  max_tokens = gr.Slider(
1552
+ 128,
1553
+ 1024,
1554
  value=512,
1555
  step=128,
1556
  label="Maximum Output Tokens",
1557
  )
1558
 
1559
  temperature = gr.Slider(
1560
+ 0.1,
1561
+ 1.0,
1562
  value=0.3,
1563
  step=0.1,
1564
  label="Temperature",
1565
  )
1566
 
1567
+ coding_history = gr.State([])
1568
+
1569
+ coding_chat = gr.Chatbot(
1570
+ label="Live AI Conversation",
1571
+ type="messages",
1572
+ height=450,
1573
+ elem_id="coding-output",
1574
+ )
1575
+
1576
  with gr.Row():
1577
 
1578
  generate_code = gr.Button(
 
1581
  )
1582
 
1583
  stop_button = gr.Button(
1584
+ "⏹ Stop",
1585
  variant="stop",
1586
  )
1587
 
1588
+ clear_button = gr.Button(
1589
+ "🗑 Clear History",
1590
+ variant="secondary",
1591
+ )
1592
+
1593
+ coding_status = gr.Markdown(
1594
+ "Ready to generate.",
1595
+ elem_classes=["status-label"],
1596
  )
1597
 
1598
  generate_code.click(
 
1602
  code_model,
1603
  max_tokens,
1604
  temperature,
1605
+ coding_history,
1606
  ],
1607
+ outputs=[
1608
+ coding_chat,
1609
+ coding_history,
1610
+ ],
1611
+ ).then(
1612
+ fn=lambda: "Generation completed.",
1613
+ outputs=coding_status,
1614
  )
1615
 
1616
  stop_button.click(
1617
  fn=stop_generation,
1618
+ outputs=coding_status,
1619
  )
1620
 
1621
+ clear_button.click(
1622
+ fn=clear_history,
1623
+ outputs=[
1624
+ coding_chat,
1625
+ coding_status,
1626
+ ],
1627
+ ).then(
1628
+ fn=lambda: [],
1629
+ outputs=coding_history,
1630
+ )
1631
+
1632
+ # ======================================
1633
+ # FOOTER
1634
+ # ======================================
1635
+
1636
+ gr.HTML(
1637
  """
1638
+ <div id="footer">
1639
+
1640
+ <div style="
1641
+ font-size:19px;
1642
+ font-weight:800;
1643
+ color:#c7b7ff;
1644
+ margin-bottom:8px;
1645
+ ">
1646
+ ⚡ TASTING AI STUDIO
1647
+ </div>
1648
+
1649
+ <div>
1650
+ Premium AI Workspace · Version 2.0
1651
+ </div>
1652
+
1653
+ <div style="margin-top:8px;font-size:11px">
1654
+ Powered by open-source models and Hugging Face
1655
+ </div>
1656
+
1657
+ </div>
1658
  """
1659
  )
1660
 
 
1667
 
1668
  demo.queue(
1669
  default_concurrency_limit=1,
1670
+ max_size=20,
1671
  ).launch(
1672
  show_error=True,
1673
+ share=False,
1674
  )