Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
| 12 |
-
from typing import Optional, Iterator
|
| 13 |
|
| 14 |
-
os.environ
|
| 15 |
-
os.environ
|
| 16 |
|
| 17 |
import gradio as gr
|
| 18 |
import torch
|
| 19 |
import spaces
|
| 20 |
-
|
| 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 |
-
#
|
| 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":
|
|
|
|
| 49 |
}
|
| 50 |
|
| 51 |
CODE_MODELS = {
|
| 52 |
-
"Qwen Coder 0.5B":
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
}
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 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 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 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 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 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 |
-
|
| 110 |
-
|
| 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 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
return dict(row) if row else None
|
| 124 |
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
|
|
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
# ---------------------------------------------------------------------
|
| 142 |
|
| 143 |
-
|
| 144 |
-
image_pipeline_id = None
|
| 145 |
-
image_lock = threading.Lock()
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
|
|
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
tokenizer = AutoTokenizer.from_pretrained(
|
| 160 |
model_id,
|
| 161 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
return tokenizer, model
|
| 173 |
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 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 |
-
|
|
|
|
| 197 |
|
| 198 |
-
|
| 199 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 200 |
-
{"role": "user", "content": prompt.strip()},
|
| 201 |
-
]
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
try:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
-
thread.start()
|
| 252 |
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 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 |
-
|
| 267 |
-
while True:
|
| 268 |
-
try:
|
| 269 |
-
piece = next(streamer)
|
| 270 |
-
if piece:
|
| 271 |
-
yield piece
|
| 272 |
-
except Exception:
|
| 273 |
-
break
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
raise RuntimeError(errors[0])
|
| 278 |
|
|
|
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
global image_pipeline, image_pipeline_id
|
| 287 |
|
| 288 |
-
|
| 289 |
-
|
| 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 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
gc.collect()
|
| 304 |
-
torch.cuda.empty_cache()
|
| 305 |
|
| 306 |
-
|
| 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 |
-
|
| 330 |
-
# ---------------------------------------------------------------------
|
| 331 |
|
| 332 |
-
|
| 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 |
-
|
| 349 |
-
|
| 350 |
-
|
|
|
|
|
|
|
| 351 |
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
raise HTTPException(status_code=401, detail="Invalid or revoked API key.")
|
| 356 |
-
return record
|
| 357 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
| 363 |
|
|
|
|
|
|
|
|
|
|
| 364 |
|
| 365 |
-
|
| 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 |
-
|
| 373 |
-
def health():
|
| 374 |
-
return {"status": "ok", "service": APP_NAME, "version": "1.0.0"}
|
| 375 |
|
|
|
|
|
|
|
|
|
|
| 376 |
|
| 377 |
-
|
| 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 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
}
|
| 391 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
"data": [v for v in ALL_MODELS.values() if v["type"] == "coding"],
|
| 398 |
-
}
|
| 399 |
|
|
|
|
| 400 |
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
raise HTTPException(status_code=400, detail="Selected model is not an available coding model.")
|
| 408 |
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 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 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 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 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 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 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
return
|
| 513 |
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
output += piece
|
| 519 |
-
yield output
|
| 520 |
-
except Exception as exc:
|
| 521 |
-
yield output + f"\n\n**Error:** {exc}"
|
| 522 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 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 |
-
|
| 534 |
-
# -
|
| 535 |
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
"Image Generation + AI Coding + Developer API"
|
| 540 |
-
)
|
| 541 |
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 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 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 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 |
-
|
| 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 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
|
| 654 |
-
|
| 655 |
-
|
|
|
|
| 656 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 657 |
|
| 658 |
if __name__ == "__main__":
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 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 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|