lastwarning commited on
Commit
2da6147
·
verified ·
1 Parent(s): 8ee8b3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +506 -538
app.py CHANGED
@@ -1,669 +1,637 @@
 
1
  import os
2
  import gc
3
- import io
4
- import json
5
- import time
6
- import uuid
7
- import sqlite3
8
- import hashlib
9
- import secrets
10
  import threading
11
- from datetime import datetime, timezone
12
- from typing import Optional, Iterator
13
 
14
- os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
15
- os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
16
 
17
  import gradio as gr
18
  import torch
19
  import spaces
20
- from PIL import Image
21
  from diffusers import DiffusionPipeline
22
  from transformers import (
23
  AutoTokenizer,
24
  AutoModelForCausalLM,
25
  TextIteratorStreamer,
26
- StoppingCriteria,
27
- StoppingCriteriaList,
28
  )
 
29
  from threading import Thread, Event
30
- from fastapi import FastAPI, Header, HTTPException
31
- from fastapi.middleware.cors import CORSMiddleware
32
- from fastapi.responses import StreamingResponse
33
- from pydantic import BaseModel, Field
34
 
35
 
36
- # ---------------------------------------------------------------------
37
- # Configuration
38
- # ---------------------------------------------------------------------
39
 
40
  APP_NAME = "Tasting AI Studio"
41
- DB_PATH = os.getenv("TASTING_DB_PATH", "tasting_api_keys.sqlite3")
42
- DEFAULT_MAX_NEW_TOKENS = 1024
43
- MAX_PROMPT_CHARS = 20000
44
- MAX_IMAGE_STEPS = 4
45
 
46
  IMAGE_MODELS = {
47
  "SDXL Turbo": "stabilityai/sdxl-turbo",
48
- "Stable Diffusion 1.5": "stable-diffusion-v1-5/stable-diffusion-v1-5",
 
49
  }
50
 
51
  CODE_MODELS = {
52
- "Qwen Coder 0.5B": "Qwen/Qwen2.5-Coder-0.5B-Instruct",
53
- "Qwen Coder 1.5B": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
54
- "DeepSeek Coder 1.3B": "deepseek-ai/deepseek-coder-1.3b-instruct",
 
 
 
 
 
55
  }
56
 
57
- ALL_MODELS = {
58
- **{model_id: {"id": model_id, "name": name, "type": "image", "capabilities": ["image_generation"]}
59
- for name, model_id in IMAGE_MODELS.items()},
60
- **{model_id: {"id": model_id, "name": name, "type": "coding", "capabilities": ["chat", "code", "streaming"]}
61
- for name, model_id in CODE_MODELS.items()},
62
  }
63
 
64
- SYSTEM_PROMPT = """You are Tasting AI Studio, a helpful coding assistant.
65
- Write accurate, complete code. Explain errors clearly. When asked to fix code,
66
- provide the corrected code and preserve existing functionality. Do not claim
67
- that code was executed or tested unless it actually was. Use Markdown code blocks.
68
- """
69
 
 
 
70
 
71
- # ---------------------------------------------------------------------
72
- # SQLite API key storage
73
- # Note: keys are stored so the dashboard can show/copy older keys again.
74
- # Protect persistent storage and do not expose the database publicly.
75
- # ---------------------------------------------------------------------
76
 
77
- def db_connect():
78
- conn = sqlite3.connect(DB_PATH, timeout=20)
79
- conn.row_factory = sqlite3.Row
80
- return conn
81
 
 
 
 
82
 
83
- def init_db():
84
- with db_connect() as conn:
85
- conn.execute("""
86
- CREATE TABLE IF NOT EXISTS api_keys (
87
- id TEXT PRIMARY KEY,
88
- api_key TEXT NOT NULL UNIQUE,
89
- created_at TEXT NOT NULL,
90
- active INTEGER NOT NULL DEFAULT 1
91
- )
92
- """)
93
- conn.commit()
94
-
95
-
96
- def create_api_key():
97
- key = "tasting_" + secrets.token_urlsafe(32)
98
- key_id = uuid.uuid4().hex[:12]
99
- created = datetime.now(timezone.utc).isoformat()
100
- with db_connect() as conn:
101
- conn.execute(
102
- "INSERT INTO api_keys (id, api_key, created_at, active) VALUES (?, ?, ?, 1)",
103
- (key_id, key, created),
104
- )
105
- conn.commit()
106
- return key_id, key
107
 
 
 
108
 
109
- def list_api_keys():
110
- with db_connect() as conn:
111
- rows = conn.execute(
112
- "SELECT id, api_key, created_at, active FROM api_keys ORDER BY created_at DESC"
113
- ).fetchall()
114
- return [dict(row) for row in rows]
115
 
 
116
 
117
- def get_api_key_record(key):
118
- with db_connect() as conn:
119
- row = conn.execute(
120
- "SELECT id, api_key, active FROM api_keys WHERE api_key = ?",
121
- (key,),
122
- ).fetchone()
123
- return dict(row) if row else None
124
 
 
 
125
 
126
- def revoke_api_key(key_id):
127
- with db_connect() as conn:
128
- cur = conn.execute(
129
- "UPDATE api_keys SET active = 0 WHERE id = ?",
130
- (key_id,),
131
- )
132
- conn.commit()
133
- return cur.rowcount > 0
134
 
 
 
135
 
136
- init_db()
 
 
 
 
137
 
 
138
 
139
- # ---------------------------------------------------------------------
140
- # Model caches
141
- # ---------------------------------------------------------------------
142
 
143
- image_pipeline = None
144
- image_pipeline_id = None
145
- image_lock = threading.Lock()
146
 
147
- code_models_cache = {}
148
- code_model_lock = threading.Lock()
 
149
 
 
 
 
 
 
 
150
 
151
- def load_code_model(model_id: str):
152
- if model_id not in ALL_MODELS or ALL_MODELS[model_id]["type"] != "coding":
153
- raise ValueError("Unknown coding model ID.")
 
 
 
 
 
 
154
 
155
- with code_model_lock:
156
- if model_id in code_models_cache:
157
- return code_models_cache[model_id]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
  tokenizer = AutoTokenizer.from_pretrained(
160
  model_id,
161
- trust_remote_code=True,
162
  )
 
163
  model = AutoModelForCausalLM.from_pretrained(
164
  model_id,
 
165
  torch_dtype=torch.float32,
166
  low_cpu_mem_usage=True,
167
- trust_remote_code=True,
168
- device_map="cpu",
169
  )
 
 
170
  model.eval()
171
- code_models_cache[model_id] = (tokenizer, model)
 
 
 
 
172
  return tokenizer, model
173
 
174
 
175
- class StopOnEvent(StoppingCriteria):
176
- def __init__(self, stop_event):
177
- self.stop_event = stop_event
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- def __call__(self, input_ids, scores, **kwargs):
180
- return self.stop_event.is_set()
 
 
 
 
 
181
 
 
 
 
182
 
183
- def generate_code_stream(
184
- model_id: str,
185
- prompt: str,
186
- max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
187
- stop_event: Optional[Event] = None,
188
- ) -> Iterator[str]:
189
- if not prompt or not prompt.strip():
190
- raise ValueError("Prompt cannot be empty.")
191
- if len(prompt) > MAX_PROMPT_CHARS:
192
- raise ValueError(f"Prompt is too long. Maximum is {MAX_PROMPT_CHARS} characters.")
193
- if stop_event is None:
194
- stop_event = Event()
195
 
196
- tokenizer, model = load_code_model(model_id)
 
197
 
198
- messages = [
199
- {"role": "system", "content": SYSTEM_PROMPT},
200
- {"role": "user", "content": prompt.strip()},
201
- ]
202
 
203
- if hasattr(tokenizer, "apply_chat_template"):
204
- input_text = tokenizer.apply_chat_template(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  messages,
206
  tokenize=False,
207
  add_generation_prompt=True,
208
  )
209
- else:
210
- input_text = SYSTEM_PROMPT + "\n\nUser:\n" + prompt + "\n\nAssistant:\n"
211
-
212
- inputs = tokenizer(
213
- input_text,
214
- return_tensors="pt",
215
- truncation=True,
216
- max_length=4096,
217
- )
218
 
219
- streamer = TextIteratorStreamer(
220
- tokenizer,
221
- skip_prompt=True,
222
- skip_special_tokens=True,
223
- timeout=1.0,
224
- )
225
 
226
- errors = []
 
 
 
 
 
227
 
228
- def worker():
229
- try:
230
- with torch.inference_mode():
231
- model.generate(
232
- **inputs,
233
- streamer=streamer,
234
- max_new_tokens=max(64, min(int(max_new_tokens), 4096)),
235
- do_sample=True,
236
- temperature=0.2,
237
- top_p=0.9,
238
- repetition_penalty=1.05,
239
- stopping_criteria=StoppingCriteriaList([StopOnEvent(stop_event)]),
240
- pad_token_id=tokenizer.eos_token_id,
241
- )
242
- except Exception as exc:
243
- errors.append(str(exc))
244
- # Ensure the consumer does not wait forever after a generation error.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  try:
246
- streamer.end()
247
- except Exception:
248
- pass
 
 
 
 
 
 
249
 
250
- thread = Thread(target=worker, daemon=True)
251
- thread.start()
252
 
253
- while thread.is_alive():
254
- try:
255
- piece = next(streamer)
256
- if piece:
257
- yield piece
258
- except StopIteration:
259
- break
260
- except Exception:
261
- # TextIteratorStreamer raises queue.Empty on its timeout.
262
- if not thread.is_alive():
263
  break
264
- continue
265
 
266
- # Drain any final queued text.
267
- while True:
268
- try:
269
- piece = next(streamer)
270
- if piece:
271
- yield piece
272
- except Exception:
273
- break
274
 
275
- thread.join(timeout=2)
276
- if errors:
277
- raise RuntimeError(errors[0])
278
 
 
279
 
280
- # ---------------------------------------------------------------------
281
- # Image generation (Hugging Face ZeroGPU Space)
282
- # ---------------------------------------------------------------------
 
 
 
283
 
284
- @spaces.GPU(duration=120)
285
- def generate_image(prompt: str, model_name: str, seed: int, steps: int):
286
- global image_pipeline, image_pipeline_id
287
 
288
- if not torch.cuda.is_available():
289
- raise RuntimeError(
290
- "CUDA GPU is not available. This image-generation function is configured "
291
- "for a Hugging Face ZeroGPU Space."
292
- )
293
- if not prompt or not prompt.strip():
294
- raise ValueError("Please enter an image prompt.")
295
 
296
- model_id = IMAGE_MODELS.get(model_name)
297
- if not model_id:
298
- raise ValueError("Unknown image model.")
299
 
300
- with image_lock:
301
- if image_pipeline is None or image_pipeline_id != model_id:
302
- image_pipeline = None
303
- gc.collect()
304
- torch.cuda.empty_cache()
305
 
306
- image_pipeline = DiffusionPipeline.from_pretrained(
307
- model_id,
308
- torch_dtype=torch.float16,
309
- use_safetensors=True,
310
- )
311
- image_pipeline.to("cuda")
312
- image_pipeline_id = model_id
313
-
314
- generator = torch.Generator(device="cuda").manual_seed(int(seed))
315
- is_turbo = "turbo" in model_id.lower()
316
- actual_steps = max(1, min(int(steps), MAX_IMAGE_STEPS if is_turbo else 30))
317
- guidance = 0.0 if is_turbo else 7.5
318
-
319
- result = image_pipeline(
320
- prompt=prompt.strip(),
321
- num_inference_steps=actual_steps,
322
- guidance_scale=guidance,
323
- generator=generator,
324
- )
325
- return result.images[0], int(seed)
326
 
 
327
 
328
- # ---------------------------------------------------------------------
329
- # FastAPI: API for external applications
330
- # ---------------------------------------------------------------------
331
 
332
- api = FastAPI(
333
- title="Tasting AI Studio API",
334
- version="1.0.0",
335
- description="Discover and use Tasting AI Studio image and coding models.",
336
- )
337
 
338
- # CORS allows browser-based clients to call the API. Keep API keys server-side.
339
- api.add_middleware(
340
- CORSMiddleware,
341
- allow_origins=["*"],
342
- allow_credentials=False,
343
- allow_methods=["GET", "POST", "OPTIONS"],
344
- allow_headers=["Authorization", "Content-Type"],
345
- )
346
 
 
 
 
347
 
348
- def require_api_key(authorization: Optional[str] = Header(default=None)):
349
- if not authorization or not authorization.lower().startswith("bearer "):
350
- raise HTTPException(status_code=401, detail="Missing Bearer API key.")
 
 
351
 
352
- key = authorization.split(" ", 1)[1].strip()
353
- record = get_api_key_record(key)
354
- if not record or not record["active"]:
355
- raise HTTPException(status_code=401, detail="Invalid or revoked API key.")
356
- return record
357
 
 
 
 
 
358
 
359
- class CodingRequest(BaseModel):
360
- model: str
361
- prompt: str = Field(min_length=1, max_length=MAX_PROMPT_CHARS)
362
- max_new_tokens: int = Field(default=DEFAULT_MAX_NEW_TOKENS, ge=64, le=4096)
 
363
 
 
 
 
364
 
365
- class ImageRequest(BaseModel):
366
- model: str
367
- prompt: str = Field(min_length=1, max_length=MAX_PROMPT_CHARS)
368
- seed: int = Field(default=42, ge=0, le=2147483647)
369
- steps: int = Field(default=4, ge=1, le=30)
370
 
 
 
 
 
371
 
372
- @api.get("/api/v1/health")
373
- def health():
374
- return {"status": "ok", "service": APP_NAME, "version": "1.0.0"}
375
 
 
 
 
376
 
377
- @api.get("/api/v1/models")
378
- def discover_models(_key=__import__("fastapi").Depends(require_api_key)):
379
- return {
380
- "object": "list",
381
- "data": list(ALL_MODELS.values()),
382
- }
383
 
 
384
 
385
- @api.get("/api/v1/models/image")
386
- def discover_image_models(_key=__import__("fastapi").Depends(require_api_key)):
387
- return {
388
- "object": "list",
389
- "data": [v for v in ALL_MODELS.values() if v["type"] == "image"],
390
- }
391
 
 
 
 
 
 
392
 
393
- @api.get("/api/v1/models/coding")
394
- def discover_coding_models(_key=__import__("fastapi").Depends(require_api_key)):
395
- return {
396
- "object": "list",
397
- "data": [v for v in ALL_MODELS.values() if v["type"] == "coding"],
398
- }
399
 
 
400
 
401
- @api.post("/api/v1/coding/chat")
402
- def coding_chat(
403
- body: CodingRequest,
404
- _key=__import__("fastapi").Depends(require_api_key),
405
- ):
406
- if body.model not in CODE_MODELS.values():
407
- raise HTTPException(status_code=400, detail="Selected model is not an available coding model.")
408
 
409
- def event_stream():
410
- stop_event = Event()
411
- try:
412
- for token in generate_code_stream(
413
- body.model,
414
- body.prompt,
415
- body.max_new_tokens,
416
- stop_event,
417
- ):
418
- yield "data: " + json.dumps({"token": token}, ensure_ascii=False) + "\n\n"
419
- yield "data: " + json.dumps({"done": True}) + "\n\n"
420
- except Exception as exc:
421
- yield "data: " + json.dumps({"error": str(exc)}, ensure_ascii=False) + "\n\n"
422
-
423
- return StreamingResponse(
424
- event_stream(),
425
- media_type="text/event-stream",
426
- headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
427
- )
428
 
 
 
 
 
 
 
429
 
430
- @api.post("/api/v1/image/generate")
431
- def image_generate(
432
- body: ImageRequest,
433
- _key=__import__("fastapi").Depends(require_api_key),
434
- ):
435
- model_name = next((name for name, mid in IMAGE_MODELS.items() if mid == body.model), None)
436
- if not model_name:
437
- raise HTTPException(status_code=400, detail="Selected model is not an available image model.")
438
 
439
- try:
440
- image, used_seed = generate_image(body.prompt, model_name, body.seed, body.steps)
441
- buffer = io.BytesIO()
442
- image.save(buffer, format="PNG")
443
- import base64
444
- encoded = base64.b64encode(buffer.getvalue()).decode("ascii")
445
- return {
446
- "created": int(time.time()),
447
- "model": body.model,
448
- "seed": used_seed,
449
- "image_base64": encoded,
450
- "mime_type": "image/png",
451
- }
452
- except Exception as exc:
453
- raise HTTPException(status_code=500, detail=str(exc))
454
-
455
-
456
- # ---------------------------------------------------------------------
457
- # Gradio UI callbacks
458
- # ---------------------------------------------------------------------
459
-
460
- def get_base_url():
461
- host = os.getenv("SPACE_HOST")
462
- if host:
463
- return "https://" + host
464
- return os.getenv("PUBLIC_BASE_URL", "http://localhost:7860")
465
-
466
-
467
- def make_key_ui():
468
- key_id, key = create_api_key()
469
- choices = [
470
- f'{item["id"]} | {"Active" if item["active"] else "Revoked"} | {item["created_at"][:19]}'
471
- for item in list_api_keys()
472
- ]
473
- return key, gr.Dropdown(choices=choices, value=choices[0] if choices else None)
474
-
475
-
476
- def refresh_key_choices():
477
- rows = list_api_keys()
478
- choices = [
479
- f'{item["id"]} | {"Active" if item["active"] else "Revoked"} | {item["created_at"][:19]}'
480
- for item in rows
481
- ]
482
- return gr.Dropdown(choices=choices, value=choices[0] if choices else None)
483
-
484
-
485
- def show_selected_key(choice):
486
- if not choice:
487
- return ""
488
- key_id = choice.split(" | ", 1)[0]
489
- rows = list_api_keys()
490
- for item in rows:
491
- if item["id"] == key_id:
492
- return item["api_key"] if item["active"] else "This API key has been revoked."
493
- return "Key not found."
494
-
495
-
496
- def revoke_selected_key(choice):
497
- if not choice:
498
- return "Select an API key first.", refresh_key_choices(), ""
499
- key_id = choice.split(" | ", 1)[0]
500
- success = revoke_api_key(key_id)
501
- return (
502
- "API key revoked." if success else "Key not found.",
503
- refresh_key_choices(),
504
- "",
505
- )
506
 
 
 
 
 
507
 
508
- def coding_ui(prompt, model_name, max_tokens):
509
- model_id = CODE_MODELS.get(model_name)
510
- if not model_id:
511
- yield "Please select a coding model."
512
- return
513
 
514
- stop_event = Event()
515
- output = ""
516
- try:
517
- for piece in generate_code_stream(model_id, prompt, int(max_tokens), stop_event):
518
- output += piece
519
- yield output
520
- except Exception as exc:
521
- yield output + f"\n\n**Error:** {exc}"
522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
 
524
- def image_ui(prompt, model_name, seed, steps):
525
- try:
526
- image, used_seed = generate_image(prompt, model_name, int(seed), int(steps))
527
- return image, f"Image generated. Seed: {used_seed}"
528
- except Exception as exc:
529
- return None, f"Image generation error: {exc}"
530
 
 
531
 
532
- # ---------------------------------------------------------------------
533
- # Gradio interface
534
- # ---------------------------------------------------------------------
535
 
536
- with gr.Blocks(title=APP_NAME) as demo:
537
- gr.Markdown(
538
- "# ⚡ Tasting AI Studio\n"
539
- "Image Generation + AI Coding + Developer API"
540
- )
541
 
542
- with gr.Accordion("☰ API & Developer Settings", open=False):
543
- gr.Markdown("### Base URL")
544
- base_url_box = gr.Textbox(
545
- label="Your API Base URL",
546
- value=get_base_url(),
547
- interactive=False,
548
- buttons=["copy"],
549
- )
550
- gr.Markdown("### API Key Manager")
551
- gr.Markdown(
552
- "Generate keys without signing in. Keep your keys private. "
553
- "Revoked keys stop working immediately."
554
- )
555
- with gr.Row():
556
- generate_key_btn = gr.Button("🔑 Generate New API Key", variant="primary")
557
- refresh_keys_btn = gr.Button("Refresh Keys")
558
- new_key_box = gr.Textbox(
559
- label="New API Key — copy and save it",
560
- interactive=False,
561
- buttons=["copy"],
562
- )
563
- key_dropdown = gr.Dropdown(
564
- label="Previously Generated API Keys",
565
- choices=[],
566
- interactive=True,
567
- )
568
- old_key_box = gr.Textbox(
569
- label="Selected API Key — copy icon available",
570
- interactive=False,
571
- buttons=["copy"],
572
- )
573
- with gr.Row():
574
- show_key_btn = gr.Button("Show Selected Key")
575
- revoke_key_btn = gr.Button("Revoke Selected Key", variant="stop")
576
- key_status = gr.Markdown()
577
- gr.Markdown(
578
- "### External API Endpoints\n"
579
- "- `GET /api/v1/models`\n"
580
- "- `GET /api/v1/models/image`\n"
581
- "- `GET /api/v1/models/coding`\n"
582
- "- `POST /api/v1/image/generate`\n"
583
- "- `POST /api/v1/coding/chat` (Server-Sent Events streaming)\n\n"
584
- "Use the header `Authorization: Bearer YOUR_API_KEY`."
585
- )
586
 
587
- with gr.Tab("🎨 Image Generation"):
588
- image_prompt = gr.Textbox(
589
- label="Image Prompt",
590
- placeholder="Describe the image you want to create...",
591
- lines=3,
592
- )
593
- with gr.Row():
594
- image_model = gr.Dropdown(
595
- choices=list(IMAGE_MODELS.keys()),
596
- value="SDXL Turbo",
597
- label="Image Model",
598
  )
599
- image_seed = gr.Number(value=42, precision=0, label="Seed")
600
- image_steps = gr.Slider(1, 30, value=4, step=1, label="Steps")
601
- image_btn = gr.Button("Generate Image", variant="primary")
602
- image_output = gr.Image(label="Generated Image", type="pil")
603
- image_status = gr.Markdown()
604
- image_btn.click(
605
- image_ui,
606
- inputs=[image_prompt, image_model, image_seed, image_steps],
607
- outputs=[image_output, image_status],
608
- )
609
 
610
- with gr.Tab("💻 AI Coding"):
611
- coding_model = gr.Dropdown(
612
- choices=list(CODE_MODELS.keys()),
613
- value="Qwen Coder 0.5B",
614
- label="Coding Model",
615
- )
616
- coding_prompt = gr.Textbox(
617
- label="Your Coding Request",
618
- placeholder="Ask for code, debugging, explanation, or optimization...",
619
- lines=6,
620
- )
621
- max_tokens = gr.Slider(
622
- 64, 4096, value=1024, step=64, label="Maximum New Tokens"
623
- )
624
- coding_btn = gr.Button("Start Coding", variant="primary")
625
- coding_output = gr.Markdown()
626
- coding_btn.click(
627
- coding_ui,
628
- inputs=[coding_prompt, coding_model, max_tokens],
629
- outputs=coding_output,
630
- )
631
 
632
- generate_key_btn.click(
633
- make_key_ui,
634
- inputs=[],
635
- outputs=[new_key_box, key_dropdown],
636
- )
637
- refresh_keys_btn.click(
638
- refresh_key_choices,
639
- inputs=[],
640
- outputs=key_dropdown,
641
- )
642
- show_key_btn.click(
643
- show_selected_key,
644
- inputs=key_dropdown,
645
- outputs=old_key_box,
646
- )
647
- revoke_key_btn.click(
648
- revoke_selected_key,
649
- inputs=key_dropdown,
650
- outputs=[key_status, key_dropdown, old_key_box],
651
- )
652
 
 
 
 
 
653
 
654
- # FastAPI owns API routes; Gradio UI is mounted at the root path.
655
- app = gr.mount_gradio_app(api, demo, path="/")
 
656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
657
 
658
  if __name__ == "__main__":
659
- # Hugging Face Spaces' Gradio runtime manages the web server itself.
660
- # Starting Uvicorn here as well can cause Errno 98 (port 7860 in use).
661
- # Keep the direct Uvicorn entry point for local runs only.
662
- if not (os.getenv("SPACE_ID") or os.getenv("HF_SPACE_ID")):
663
- import uvicorn
664
- uvicorn.run(
665
- app,
666
- host="0.0.0.0",
667
- port=int(os.getenv("PORT", "7860")),
668
- log_level=os.getenv("LOG_LEVEL", "info"),
669
- )
 
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
+
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
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(
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...",
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(
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
+ )