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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +320 -576
app.py CHANGED
@@ -1,14 +1,8 @@
 
1
  import os
2
  import gc
3
  import threading
4
  import random
5
- import secrets
6
- import string
7
- import json
8
- import asyncio
9
- from datetime import datetime
10
- from threading import Thread, Event
11
- from typing import Optional
12
 
13
  os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
14
  os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
@@ -22,16 +16,9 @@ from transformers import (
22
  AutoTokenizer,
23
  AutoModelForCausalLM,
24
  TextIteratorStreamer,
25
- StoppingCriteria,
26
- StoppingCriteriaList,
27
  )
28
 
29
- # FastAPI for API server
30
- from fastapi import FastAPI, HTTPException, Header, Request
31
- from fastapi.middleware.cors import CORSMiddleware
32
- from fastapi.responses import StreamingResponse, JSONResponse
33
- from pydantic import BaseModel
34
- import uvicorn
35
 
36
 
37
  # ==========================================
@@ -39,89 +26,99 @@ import uvicorn
39
  # ==========================================
40
 
41
  APP_NAME = "Tasting AI Studio"
42
- BASE_URL = "http://localhost:7860" # will be updated at runtime
43
 
44
  IMAGE_MODELS = {
45
  "SDXL Turbo": "stabilityai/sdxl-turbo",
46
- "Stable Diffusion 1.5": "stable-diffusion-v1-5/stable-diffusion-v1-5",
 
47
  }
48
 
49
  CODE_MODELS = {
50
- "Qwen Coder 0.5B": "Qwen/Qwen2.5-Coder-0.5B-Instruct",
51
- "Qwen Coder 1.5B": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
52
- "DeepSeek Coder 1.3B": "deepseek-ai/deepseek-coder-1.3b-instruct",
53
- }
54
-
55
- ALL_MODELS = {
56
- **{k: {"type": "image", "id": v} for k, v in IMAGE_MODELS.items()},
57
- **{k: {"type": "text", "id": v} for k, v in CODE_MODELS.items()},
58
- }
59
-
60
- # ==========================================
61
- # API KEY STORE (in-memory)
62
- # ==========================================
63
-
64
- api_keys: set = set()
65
-
66
 
67
- def generate_api_key() -> str:
68
- prefix = "tai-"
69
- body = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(48))
70
- key = prefix + body
71
- api_keys.add(key)
72
- return key
73
-
74
-
75
- def validate_api_key(key: str) -> bool:
76
- return key in api_keys
77
 
 
 
 
78
 
79
- # ==========================================
80
- # MODEL CACHES
81
- # ==========================================
 
82
 
83
- image_cache = {"name": None, "pipe": None}
84
- code_cache = {"name": None, "tokenizer": None, "model": None}
 
 
 
85
 
86
  image_lock = threading.Lock()
87
  code_lock = threading.Lock()
 
88
  stop_events = {}
89
 
90
 
91
  # ==========================================
92
- # IMAGE GENERATION
93
  # ==========================================
94
 
95
  @spaces.GPU(duration=120)
96
- def generate_image(prompt, negative_prompt, model_name, width, height, steps, seed, random_seed):
 
 
 
 
 
 
 
 
 
97
  if not prompt.strip():
98
  raise gr.Error("Enter an image prompt.")
 
99
  if not torch.cuda.is_available():
100
  raise gr.Error("GPU is unavailable.")
 
101
  if model_name not in IMAGE_MODELS:
102
  raise gr.Error("Invalid image model.")
103
 
104
  model_id = IMAGE_MODELS[model_name]
 
105
  if random_seed:
106
  seed = random.randint(0, 2147483647)
107
 
108
  with image_lock:
109
  try:
110
  if image_cache["name"] != model_id:
 
111
  if image_cache["pipe"] is not None:
112
  del image_cache["pipe"]
 
113
  image_cache["pipe"] = None
114
  image_cache["name"] = None
 
115
  gc.collect()
116
  torch.cuda.empty_cache()
117
 
118
- pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, token=False)
 
 
 
 
 
119
  pipe = pipe.to("cuda")
 
120
  image_cache["pipe"] = pipe
121
  image_cache["name"] = model_id
122
 
123
  pipe = image_cache["pipe"]
124
- generator = torch.Generator(device="cuda").manual_seed(int(seed))
 
 
 
125
 
126
  if model_name == "SDXL Turbo":
127
  guidance = 0.0
@@ -139,12 +136,16 @@ def generate_image(prompt, negative_prompt, model_name, width, height, steps, se
139
  guidance_scale=guidance,
140
  generator=generator,
141
  )
 
142
  return result.images[0], int(seed)
143
 
144
  except Exception as error:
145
  gc.collect()
146
  torch.cuda.empty_cache()
147
- raise gr.Error(f"Image generation failed: {error}")
 
 
 
148
 
149
 
150
  # ==========================================
@@ -152,23 +153,40 @@ def generate_image(prompt, negative_prompt, model_name, width, height, steps, se
152
  # ==========================================
153
 
154
  def load_code_model(model_name):
 
155
  model_id = CODE_MODELS[model_name]
 
156
  with code_lock:
 
157
  if code_cache["name"] == model_id:
158
- return code_cache["tokenizer"], code_cache["model"]
 
 
 
159
 
160
  if code_cache["model"] is not None:
 
161
  del code_cache["model"]
162
  del code_cache["tokenizer"]
 
163
  code_cache["model"] = None
164
  code_cache["tokenizer"] = None
165
  code_cache["name"] = None
 
166
  gc.collect()
167
 
168
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=False)
 
 
 
 
169
  model = AutoModelForCausalLM.from_pretrained(
170
- model_id, token=False, torch_dtype=torch.float32, low_cpu_mem_usage=True
 
 
 
171
  )
 
172
  model.to("cpu")
173
  model.eval()
174
 
@@ -180,19 +198,30 @@ def load_code_model(model_name):
180
 
181
 
182
  # ==========================================
183
- # SYSTEM PROMPT
184
  # ==========================================
185
 
186
  SYSTEM_PROMPT = """
187
  You are Tasting AI, an advanced software coding assistant.
188
 
189
  You specialize in:
190
- - Python, Kotlin, Java, Android development
191
- - JavaScript, HTML, CSS, React
192
- - APIs, Databases, Debugging
193
- - Code optimization, Software architecture
 
 
 
 
 
 
 
 
 
 
194
 
195
  RULES:
 
196
  1. Understand the complete user request.
197
  2. Generate practical working code.
198
  3. Never intentionally omit important code.
@@ -207,13 +236,21 @@ RULES:
207
 
208
 
209
  # ==========================================
210
- # CODING STREAM (Gradio)
211
  # ==========================================
212
 
213
- def coding_assistant(prompt, model_name, max_tokens, temperature, history):
 
 
 
 
 
 
 
214
  if not prompt.strip():
215
  yield "Please enter your coding request."
216
  return
 
217
  if model_name not in CODE_MODELS:
218
  yield "Invalid coding model."
219
  return
@@ -222,34 +259,82 @@ def coding_assistant(prompt, model_name, max_tokens, temperature, history):
222
  stop_events["current"] = stop_event
223
 
224
  try:
 
225
  yield "⏳ Loading coding model..."
 
226
  tokenizer, model = load_code_model(model_name)
227
 
228
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
 
 
 
 
 
229
 
 
230
  if history:
231
  for item in history[-6:]:
 
232
  if not isinstance(item, dict):
233
  continue
 
234
  role = item.get("role")
235
  content = item.get("content")
236
- if role in ["user", "assistant"] and isinstance(content, str):
237
- messages.append({"role": role, "content": content})
238
 
239
- messages.append({"role": "user", "content": prompt})
 
 
 
 
 
 
 
 
 
 
240
 
241
  formatted_prompt = tokenizer.apply_chat_template(
242
- messages, tokenize=False, add_generation_prompt=True
 
 
243
  )
244
 
245
  inputs = tokenizer(
246
- formatted_prompt, return_tensors="pt", truncation=True, max_length=4096
 
 
 
247
  )
248
 
249
  streamer = TextIteratorStreamer(
250
- tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120
 
 
 
251
  )
252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  class StopCriteria(StoppingCriteria):
254
  def __init__(self, event):
255
  self.event = event
@@ -264,7 +349,9 @@ def coding_assistant(prompt, model_name, max_tokens, temperature, history):
264
  "do_sample": float(temperature) > 0.05,
265
  "temperature": max(float(temperature), 0.05),
266
  "pad_token_id": tokenizer.eos_token_id,
267
- "stopping_criteria": StoppingCriteriaList([StopCriteria(stop_event)]),
 
 
268
  }
269
 
270
  def generate():
@@ -274,14 +361,23 @@ def coding_assistant(prompt, model_name, max_tokens, temperature, history):
274
  except Exception as error:
275
  print("Generation error:", error)
276
 
277
- thread = Thread(target=generate, daemon=True)
 
 
 
 
278
  thread.start()
279
 
280
  response = ""
 
281
  for token in streamer:
 
282
  if stop_event.is_set():
283
  break
 
284
  response += token
 
 
285
  yield response
286
 
287
  thread.join(timeout=5)
@@ -295,199 +391,27 @@ def coding_assistant(prompt, model_name, max_tokens, temperature, history):
295
 
296
  except Exception as error:
297
  yield f"**Coding error:** {str(error)}"
 
298
  finally:
299
  stop_events.pop("current", None)
300
 
301
 
302
- def stop_generation():
303
- event = stop_events.get("current")
304
- if event:
305
- event.set()
306
- return "⏹ Stop requested."
307
-
308
-
309
  # ==========================================
310
- # FASTAPI — OpenAI-Compatible API Server
311
  # ==========================================
312
 
313
- api_app = FastAPI(title="Tasting AI API", version="1.0.0")
314
-
315
- api_app.add_middleware(
316
- CORSMiddleware,
317
- allow_origins=["*"],
318
- allow_credentials=True,
319
- allow_methods=["*"],
320
- allow_headers=["*"],
321
- )
322
-
323
-
324
- def check_auth(authorization: Optional[str]) -> bool:
325
- if not authorization:
326
- return False
327
- if not authorization.startswith("Bearer "):
328
- return False
329
- key = authorization[len("Bearer "):]
330
- return validate_api_key(key)
331
-
332
-
333
- @api_app.get("/v1/models")
334
- async def list_models(authorization: Optional[str] = Header(None)):
335
- if not check_auth(authorization):
336
- raise HTTPException(status_code=401, detail="Invalid or missing API key.")
337
-
338
- model_list = []
339
- for name, info in ALL_MODELS.items():
340
- model_list.append({
341
- "id": name,
342
- "object": "model",
343
- "created": int(datetime.now().timestamp()),
344
- "owned_by": "tasting-ai",
345
- "type": info["type"],
346
- "huggingface_id": info["id"],
347
- })
348
-
349
- return {
350
- "object": "list",
351
- "data": model_list,
352
- }
353
-
354
-
355
- class ChatMessage(BaseModel):
356
- role: str
357
- content: str
358
-
359
-
360
- class ChatCompletionRequest(BaseModel):
361
- model: str
362
- messages: list[ChatMessage]
363
- max_tokens: Optional[int] = 512
364
- temperature: Optional[float] = 0.3
365
- stream: Optional[bool] = False
366
-
367
-
368
- @api_app.post("/v1/chat/completions")
369
- async def chat_completions(
370
- request: ChatCompletionRequest,
371
- authorization: Optional[str] = Header(None),
372
- ):
373
- if not check_auth(authorization):
374
- raise HTTPException(status_code=401, detail="Invalid or missing API key.")
375
-
376
- model_name = request.model
377
- if model_name not in CODE_MODELS:
378
- raise HTTPException(
379
- status_code=400,
380
- detail=f"Model '{model_name}' not found or not a text model. Available: {list(CODE_MODELS.keys())}",
381
- )
382
-
383
- try:
384
- tokenizer, model = load_code_model(model_name)
385
- except Exception as e:
386
- raise HTTPException(status_code=500, detail=f"Failed to load model: {e}")
387
-
388
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
389
- for msg in request.messages:
390
- messages.append({"role": msg.role, "content": msg.content})
391
-
392
- formatted_prompt = tokenizer.apply_chat_template(
393
- messages, tokenize=False, add_generation_prompt=True
394
- )
395
-
396
- inputs = tokenizer(
397
- formatted_prompt, return_tensors="pt", truncation=True, max_length=4096
398
- )
399
-
400
- if request.stream:
401
- streamer = TextIteratorStreamer(
402
- tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120
403
- )
404
-
405
- generation_kwargs = {
406
- **inputs,
407
- "streamer": streamer,
408
- "max_new_tokens": request.max_tokens or 512,
409
- "do_sample": (request.temperature or 0.3) > 0.05,
410
- "temperature": max(request.temperature or 0.3, 0.05),
411
- "pad_token_id": tokenizer.eos_token_id,
412
- }
413
-
414
- def generate():
415
- with torch.inference_mode():
416
- model.generate(**generation_kwargs)
417
-
418
- thread = Thread(target=generate, daemon=True)
419
- thread.start()
420
-
421
- async def stream_generator():
422
- chunk_id = f"chatcmpl-{secrets.token_hex(8)}"
423
- for token in streamer:
424
- chunk = {
425
- "id": chunk_id,
426
- "object": "chat.completion.chunk",
427
- "created": int(datetime.now().timestamp()),
428
- "model": model_name,
429
- "choices": [{
430
- "index": 0,
431
- "delta": {"content": token},
432
- "finish_reason": None,
433
- }],
434
- }
435
- yield f"data: {json.dumps(chunk)}\n\n"
436
- await asyncio.sleep(0)
437
-
438
- yield f"data: [DONE]\n\n"
439
-
440
- return StreamingResponse(stream_generator(), media_type="text/event-stream")
441
-
442
- else:
443
- with torch.inference_mode():
444
- output = model.generate(
445
- **inputs,
446
- max_new_tokens=request.max_tokens or 512,
447
- do_sample=(request.temperature or 0.3) > 0.05,
448
- temperature=max(request.temperature or 0.3, 0.05),
449
- pad_token_id=tokenizer.eos_token_id,
450
- )
451
-
452
- input_len = inputs["input_ids"].shape[1]
453
- generated = output[0][input_len:]
454
- response_text = tokenizer.decode(generated, skip_special_tokens=True)
455
-
456
- return {
457
- "id": f"chatcmpl-{secrets.token_hex(8)}",
458
- "object": "chat.completion",
459
- "created": int(datetime.now().timestamp()),
460
- "model": model_name,
461
- "choices": [{
462
- "index": 0,
463
- "message": {"role": "assistant", "content": response_text},
464
- "finish_reason": "stop",
465
- }],
466
- "usage": {
467
- "prompt_tokens": input_len,
468
- "completion_tokens": len(generated),
469
- "total_tokens": input_len + len(generated),
470
- },
471
- }
472
-
473
-
474
- # ==========================================
475
- # KEY MANAGEMENT (Gradio side)
476
- # ==========================================
477
 
478
- def handle_generate_key():
479
- key = generate_api_key()
480
- return key, f"✅ API Key generated: `{key}`"
481
 
 
 
482
 
483
- def handle_list_keys():
484
- if not api_keys:
485
- return "No keys generated yet."
486
- return "\n".join([f"• `{k}`" for k in sorted(api_keys)])
487
 
488
 
489
  # ==========================================
490
- # GRADIO UI
491
  # ==========================================
492
 
493
  CSS = """
@@ -496,241 +420,27 @@ CSS = """
496
  margin: auto !important;
497
  }
498
 
499
- #heading { text-align: center; }
500
-
501
- /* Sidebar overlay */
502
- #sidebar-overlay {
503
- display: none;
504
- position: fixed;
505
- top: 0; left: 0;
506
- width: 100vw; height: 100vh;
507
- background: rgba(0,0,0,0.4);
508
- z-index: 1000;
509
- }
510
-
511
- #sidebar-panel {
512
- display: none;
513
- position: fixed;
514
- top: 0; right: 0;
515
- width: 340px;
516
- height: 100vh;
517
- background: #1e1e2e;
518
- color: #cdd6f4;
519
- z-index: 1001;
520
- padding: 24px 20px;
521
- box-shadow: -4px 0 24px rgba(0,0,0,0.5);
522
- overflow-y: auto;
523
- font-family: monospace;
524
- }
525
-
526
- #sidebar-panel h2 {
527
- color: #cba6f7;
528
- margin-bottom: 20px;
529
- font-size: 1.1rem;
530
- }
531
-
532
- .sidebar-label {
533
- font-size: 0.75rem;
534
- color: #a6adc8;
535
- text-transform: uppercase;
536
- letter-spacing: 0.05em;
537
- margin-bottom: 6px;
538
- }
539
-
540
- .sidebar-row {
541
- display: flex;
542
- align-items: center;
543
- gap: 8px;
544
- background: #313244;
545
- border-radius: 8px;
546
- padding: 10px 12px;
547
- margin-bottom: 16px;
548
- word-break: break-all;
549
- font-size: 0.82rem;
550
  }
551
 
552
- .copy-btn {
553
- cursor: pointer;
554
- padding: 4px 10px;
555
- background: #89b4fa;
556
- color: #1e1e2e;
557
- border: none;
558
- border-radius: 6px;
559
- font-size: 0.75rem;
560
- font-weight: bold;
561
- white-space: nowrap;
562
  }
563
-
564
- .copy-btn:hover { background: #74c7ec; }
565
-
566
- .close-btn {
567
- position: absolute;
568
- top: 16px; right: 16px;
569
- background: none;
570
- border: none;
571
- color: #f38ba8;
572
- font-size: 1.4rem;
573
- cursor: pointer;
574
- }
575
-
576
- .gen-key-btn {
577
- width: 100%;
578
- padding: 10px;
579
- background: #a6e3a1;
580
- color: #1e1e2e;
581
- border: none;
582
- border-radius: 8px;
583
- font-weight: bold;
584
- cursor: pointer;
585
- margin-top: 8px;
586
- font-size: 0.9rem;
587
- }
588
-
589
- .gen-key-btn:hover { background: #94e2d5; }
590
-
591
- #hamburger-btn {
592
- position: fixed;
593
- top: 16px;
594
- right: 20px;
595
- z-index: 999;
596
- background: #313244;
597
- border: none;
598
- color: #cdd6f4;
599
- font-size: 1.4rem;
600
- cursor: pointer;
601
- padding: 8px 12px;
602
- border-radius: 8px;
603
- line-height: 1;
604
- }
605
-
606
- #hamburger-btn:hover { background: #45475a; }
607
-
608
- #key-display {
609
- background: #313244;
610
- border-radius: 8px;
611
- padding: 10px;
612
- font-size: 0.75rem;
613
- word-break: break-all;
614
- color: #a6e3a1;
615
- margin-top: 10px;
616
- min-height: 40px;
617
- }
618
-
619
- .primary-button { min-height: 48px; }
620
  """
621
 
622
- # HTML only — no <script> tags (Gradio 6 blocks innerHTML script execution)
623
- SIDEBAR_HTML = """
624
- <button id="hamburger-btn" title="API Settings">☰</button>
625
-
626
- <div id="sidebar-overlay"></div>
627
-
628
- <div id="sidebar-panel">
629
- <button class="close-btn" id="sidebar-close-btn">✕</button>
630
- <h2>⚙ API Access</h2>
631
-
632
- <div class="sidebar-label">Base URL</div>
633
- <div class="sidebar-row">
634
- <span id="base-url-text" style="flex:1">Loading...</span>
635
- <button class="copy-btn" id="copy-base-url-btn">Copy</button>
636
- </div>
637
-
638
- <div class="sidebar-label">API Key</div>
639
- <div id="key-display">No key generated yet.</div>
640
- <button class="copy-btn" id="copy-key-btn" style="margin-top:8px; width:100%">Copy Key</button>
641
-
642
- <button class="gen-key-btn" id="gen-key-sidebar-btn">🔑 Generate New API Key</button>
643
-
644
- <div style="margin-top:24px; padding-top:16px; border-top:1px solid #45475a">
645
- <div class="sidebar-label" style="margin-bottom:8px">Available Endpoints</div>
646
- <div style="font-size:0.78rem; color:#89dceb; line-height:1.8">
647
- GET &nbsp;<span style="color:#a6e3a1">/v1/models</span><br>
648
- POST <span style="color:#a6e3a1">/v1/chat/completions</span>
649
- </div>
650
- <div style="margin-top:12px; font-size:0.75rem; color:#6c7086">
651
- Use <code>Authorization: Bearer &lt;key&gt;</code>
652
- </div>
653
- </div>
654
- </div>
655
- """
656
-
657
- # JS injected via js_on_load — executes properly in Gradio 6
658
- SIDEBAR_JS = """
659
- () => {
660
- function attachSidebarEvents() {
661
- const hamburger = document.getElementById('hamburger-btn');
662
- const overlay = document.getElementById('sidebar-overlay');
663
- const panel = document.getElementById('sidebar-panel');
664
- const closeBtn = document.getElementById('sidebar-close-btn');
665
- const copyBaseBtn = document.getElementById('copy-base-url-btn');
666
- const copyKeyBtn = document.getElementById('copy-key-btn');
667
- const genKeyBtn = document.getElementById('gen-key-sidebar-btn');
668
-
669
- if (!hamburger) {
670
- setTimeout(attachSidebarEvents, 300);
671
- return;
672
- }
673
-
674
- function openSidebar() {
675
- overlay.style.display = 'block';
676
- panel.style.display = 'block';
677
- document.getElementById('base-url-text').textContent = window.location.origin;
678
- }
679
-
680
- function closeSidebar() {
681
- overlay.style.display = 'none';
682
- panel.style.display = 'none';
683
- }
684
-
685
- function copyText(elemId, btn) {
686
- const el = document.getElementById(elemId);
687
- const text = el.textContent.trim();
688
- navigator.clipboard.writeText(text).then(() => {
689
- const orig = btn.textContent;
690
- btn.textContent = '✓ Copied';
691
- setTimeout(() => { btn.textContent = orig; }, 1500);
692
- });
693
- }
694
-
695
- hamburger.addEventListener('click', openSidebar);
696
- overlay.addEventListener('click', closeSidebar);
697
- closeBtn.addEventListener('click', closeSidebar);
698
-
699
- copyBaseBtn.addEventListener('click', () => copyText('base-url-text', copyBaseBtn));
700
- copyKeyBtn.addEventListener('click', () => copyText('key-display', copyKeyBtn));
701
-
702
- genKeyBtn.addEventListener('click', async () => {
703
- genKeyBtn.textContent = '⏳ Generating...';
704
- genKeyBtn.disabled = true;
705
- try {
706
- const resp = await fetch('/generate_key', { method: 'POST' });
707
- const data = await resp.json();
708
- document.getElementById('key-display').textContent = data.key;
709
- genKeyBtn.textContent = '✅ Key Generated!';
710
- setTimeout(() => {
711
- genKeyBtn.textContent = '🔑 Generate New API Key';
712
- genKeyBtn.disabled = false;
713
- }, 2000);
714
- } catch(e) {
715
- genKeyBtn.textContent = '❌ Error — retry';
716
- genKeyBtn.disabled = false;
717
- }
718
- });
719
- }
720
-
721
- attachSidebarEvents();
722
- }
723
- """
724
-
725
-
726
- with gr.Blocks(title=APP_NAME, js=SIDEBAR_JS) as demo:
727
-
728
- gr.HTML(SIDEBAR_HTML)
729
 
730
  gr.Markdown(
731
  """
732
  # ⚡ Tasting AI Studio
733
- ### Image Generation + Real-Time AI Coding + OpenAI-Compatible API
 
 
734
  Public open-source models.
735
  """,
736
  elem_id="heading",
@@ -738,8 +448,12 @@ with gr.Blocks(title=APP_NAME, js=SIDEBAR_JS) as demo:
738
 
739
  with gr.Tabs():
740
 
741
- # ---- IMAGE TAB ----
 
 
 
742
  with gr.Tab("🎨 Image Generation"):
 
743
  gr.Markdown("## AI Image Generator")
744
 
745
  image_model = gr.Dropdown(
@@ -747,36 +461,105 @@ with gr.Blocks(title=APP_NAME, js=SIDEBAR_JS) as demo:
747
  value="SDXL Turbo",
748
  label="Choose Image Model",
749
  )
750
- image_prompt = gr.Textbox(label="Image Prompt", placeholder="Describe your image...", lines=4)
751
- negative_prompt = gr.Textbox(label="Negative Prompt", lines=2)
 
 
 
 
 
 
 
 
 
752
 
753
  with gr.Row():
754
- width = gr.Slider(256, 768, value=512, step=32, label="Width")
755
- height = gr.Slider(256, 768, value=512, step=32, label="Height")
756
 
757
- steps = gr.Slider(1, 30, value=4, step=1, label="Inference Steps")
758
- seed = gr.Number(value=0, precision=0, label="Seed")
759
- random_seed = gr.Checkbox(value=True, label="Random Seed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760
 
761
- generate_button = gr.Button("✨ Generate Image", variant="primary")
762
- image_output = gr.Image(label="Generated Image", type="pil")
763
- seed_output = gr.Number(label="Used Seed", precision=0)
 
764
 
765
  generate_button.click(
766
  fn=generate_image,
767
- inputs=[image_prompt, negative_prompt, image_model, width, height, steps, seed, random_seed],
768
- outputs=[image_output, seed_output],
 
 
 
 
 
 
 
 
 
 
 
 
769
  )
770
 
771
- # ---- CODING TAB ----
 
 
 
772
  with gr.Tab("💻 AI Coding"):
773
- gr.Markdown("## Real-Time Coding Assistant\nWatch your code being generated live.")
 
 
 
 
 
 
 
774
 
775
  code_model = gr.Dropdown(
776
  choices=list(CODE_MODELS.keys()),
777
  value="Qwen Coder 0.5B",
778
  label="Choose Coding Model",
779
  )
 
780
  code_prompt = gr.Textbox(
781
  label="Your Coding Request",
782
  placeholder="Create a complete Python application...",
@@ -784,110 +567,71 @@ with gr.Blocks(title=APP_NAME, js=SIDEBAR_JS) as demo:
784
  )
785
 
786
  with gr.Row():
787
- max_tokens = gr.Slider(128, 1024, value=512, step=128, label="Maximum Output Tokens")
788
- temperature = gr.Slider(0.1, 1.0, value=0.3, step=0.1, label="Temperature")
 
 
 
 
 
 
 
 
 
 
 
 
789
 
790
  with gr.Row():
791
- generate_code = gr.Button("⚡ Generate Code", variant="primary")
792
- stop_button = gr.Button("⏹ Stop Generation", variant="stop")
793
 
794
- coding_output = gr.Markdown(label="Live AI Response")
 
 
 
 
 
 
 
 
 
 
 
 
795
 
796
  generate_code.click(
797
  fn=coding_assistant,
798
- inputs=[code_prompt, code_model, max_tokens, temperature, gr.State([])],
 
 
 
 
 
 
799
  outputs=coding_output,
800
  )
801
- stop_button.click(fn=stop_generation, outputs=coding_output)
802
-
803
- # ---- API KEYS TAB ----
804
- with gr.Tab("🔑 API Keys"):
805
- gr.Markdown(
806
- """
807
- ## API Key Management
808
-
809
- Generate unlimited API keys to access the **OpenAI-compatible REST API**.
810
-
811
- ### How to use:
812
- ```
813
- Base URL : http://your-server:7860
814
- Endpoint : GET /v1/models
815
- POST /v1/chat/completions
816
-
817
- Header : Authorization: Bearer tai-xxxxxxxxxx
818
- ```
819
-
820
- ### Example curl:
821
- ```bash
822
- curl http://localhost:7860/v1/chat/completions \\
823
- -H "Authorization: Bearer tai-your-key-here" \\
824
- -H "Content-Type: application/json" \\
825
- -d '{
826
- "model": "Qwen Coder 0.5B",
827
- "messages": [{"role": "user", "content": "Write a hello world in Python"}],
828
- "max_tokens": 256
829
- }'
830
- ```
831
- """
832
- )
833
-
834
- with gr.Row():
835
- gen_key_btn = gr.Button("🔑 Generate New API Key", variant="primary", scale=1)
836
-
837
- key_output = gr.Textbox(label="Generated Key", interactive=False)
838
- key_status = gr.Markdown()
839
 
840
- gen_key_btn.click(
841
- fn=handle_generate_key,
842
- outputs=[key_output, key_status],
843
  )
844
 
845
- gr.Markdown("---")
846
- list_keys_btn = gr.Button("📋 Show All Generated Keys")
847
- keys_list = gr.Markdown()
848
-
849
- list_keys_btn.click(fn=handle_list_keys, outputs=keys_list)
850
-
851
  gr.Markdown(
852
  """
853
  ---
854
- **Tasting AI Studio** · Local inference · Live code streaming · OpenAI-compatible API · Public models
 
855
  """
856
  )
857
 
858
 
859
- # ==========================================
860
- # /generate_key REST endpoint (for sidebar JS)
861
- # ==========================================
862
-
863
- @api_app.post("/generate_key")
864
- async def rest_generate_key():
865
- key = generate_api_key()
866
- return {"key": key}
867
-
868
-
869
- # ==========================================
870
- # MOUNT GRADIO INSIDE FASTAPI
871
- # ==========================================
872
-
873
- from gradio.routes import mount_gradio_app
874
-
875
- # In Gradio 6, theme and css belong in launch(); when mounting into FastAPI
876
- # we pass them here via app_kwargs workaround — or set on the Blocks object directly.
877
- demo.theme = gr.themes.Soft()
878
- demo.css = CSS
879
-
880
- app = mount_gradio_app(api_app, demo, path="/")
881
-
882
-
883
  # ==========================================
884
  # START SERVER
885
  # ==========================================
886
 
887
  if __name__ == "__main__":
888
- uvicorn.run(
889
- app,
890
- host="0.0.0.0",
891
- port=7860,
892
- log_level="info",
893
  )
 
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"
 
16
  AutoTokenizer,
17
  AutoModelForCausalLM,
18
  TextIteratorStreamer,
 
 
19
  )
20
 
21
+ from threading import Thread, Event
 
 
 
 
 
22
 
23
 
24
  # ==========================================
 
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
 
40
+ "Qwen Coder 1.5B":
41
+ "Qwen/Qwen2.5-Coder-1.5B-Instruct",
 
 
 
 
 
 
 
 
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 = {
53
+ "name": None,
54
+ "tokenizer": None,
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
 
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
  # ==========================================
 
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
 
 
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.
 
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
 
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
 
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():
 
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)
 
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 = """
 
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",
 
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(
 
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(
521
+ label="Used Seed",
522
+ precision=0,
523
+ )
524
 
525
  generate_button.click(
526
  fn=generate_image,
527
+ inputs=[
528
+ image_prompt,
529
+ negative_prompt,
530
+ image_model,
531
+ width,
532
+ height,
533
+ steps,
534
+ seed,
535
+ random_seed,
536
+ ],
537
+ outputs=[
538
+ image_output,
539
+ seed_output,
540
+ ],
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...",
 
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(
588
+ "⚡ Generate Code",
589
+ variant="primary",
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(
602
  fn=coding_assistant,
603
+ inputs=[
604
+ code_prompt,
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
 
626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  # ==========================================
628
  # START SERVER
629
  # ==========================================
630
 
631
  if __name__ == "__main__":
632
+
633
+ demo.queue(
634
+ default_concurrency_limit=1,
635
+ ).launch(
636
+ show_error=True,
637
  )