Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,14 @@
|
|
| 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,9 +22,16 @@ from transformers import (
|
|
| 16 |
AutoTokenizer,
|
| 17 |
AutoModelForCausalLM,
|
| 18 |
TextIteratorStreamer,
|
|
|
|
|
|
|
| 19 |
)
|
| 20 |
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
# ==========================================
|
|
@@ -26,99 +39,89 @@ from threading import Thread, Event
|
|
| 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 |
-
|
| 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 |
-
|
| 48 |
-
"
|
| 49 |
-
"
|
| 50 |
}
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
image_lock = threading.Lock()
|
| 59 |
code_lock = threading.Lock()
|
| 60 |
-
|
| 61 |
stop_events = {}
|
| 62 |
|
| 63 |
|
| 64 |
# ==========================================
|
| 65 |
-
# IMAGE
|
| 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,16 +139,12 @@ def generate_image(
|
|
| 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,40 +152,23 @@ def generate_image(
|
|
| 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,30 +180,19 @@ def load_code_model(model_name):
|
|
| 198 |
|
| 199 |
|
| 200 |
# ==========================================
|
| 201 |
-
#
|
| 202 |
# ==========================================
|
| 203 |
|
| 204 |
SYSTEM_PROMPT = """
|
| 205 |
You are Tasting AI, an advanced software coding assistant.
|
| 206 |
|
| 207 |
You specialize in:
|
| 208 |
-
|
| 209 |
-
-
|
| 210 |
-
-
|
| 211 |
-
-
|
| 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,21 +207,13 @@ RULES:
|
|
| 236 |
|
| 237 |
|
| 238 |
# ==========================================
|
| 239 |
-
#
|
| 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,82 +222,34 @@ def coding_assistant(
|
|
| 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 |
-
|
| 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,9 +264,7 @@ def coding_assistant(
|
|
| 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,23 +274,14 @@ def coding_assistant(
|
|
| 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,27 +295,199 @@ def coding_assistant(
|
|
| 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 |
-
#
|
| 401 |
# ==========================================
|
| 402 |
|
| 403 |
-
|
| 404 |
|
| 405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
-
if event:
|
| 408 |
-
event.set()
|
| 409 |
|
| 410 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
|
| 413 |
# ==========================================
|
| 414 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
# ==========================================
|
| 416 |
|
| 417 |
CSS = """
|
|
@@ -420,27 +496,222 @@ CSS = """
|
|
| 420 |
margin: auto !important;
|
| 421 |
}
|
| 422 |
|
| 423 |
-
#heading {
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
}
|
| 426 |
|
| 427 |
-
.
|
| 428 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
"""
|
| 431 |
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,12 +719,8 @@ with gr.Blocks(
|
|
| 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,105 +728,36 @@ with gr.Blocks(
|
|
| 461 |
value="SDXL Turbo",
|
| 462 |
label="Choose Image Model",
|
| 463 |
)
|
| 464 |
-
|
| 465 |
-
|
| 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 |
-
|
| 479 |
-
|
| 480 |
-
|
| 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 |
-
|
| 506 |
-
|
| 507 |
-
|
| 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 |
-
|
| 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,71 +765,105 @@ with gr.Blocks(
|
|
| 567 |
)
|
| 568 |
|
| 569 |
with gr.Row():
|
| 570 |
-
|
| 571 |
-
|
| 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 |
-
|
| 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 |
-
|
| 614 |
-
|
| 615 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
)
|
|
|
|
|
|
|
| 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 |
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 |
# ==========================================
|
| 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 |
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 |
# ==========================================
|
| 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 |
|
| 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 |
|
| 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 |
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 |
"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 |
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 |
|
| 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 |
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 |
+
SIDEBAR_HTML = """
|
| 623 |
+
<button id="hamburger-btn" onclick="toggleSidebar()" title="API Settings">☰</button>
|
| 624 |
+
|
| 625 |
+
<div id="sidebar-overlay" onclick="closeSidebar()"></div>
|
| 626 |
+
|
| 627 |
+
<div id="sidebar-panel">
|
| 628 |
+
<button class="close-btn" onclick="closeSidebar()">✕</button>
|
| 629 |
+
<h2>⚙ API Access</h2>
|
| 630 |
+
|
| 631 |
+
<div class="sidebar-label">Base URL</div>
|
| 632 |
+
<div class="sidebar-row">
|
| 633 |
+
<span id="base-url-text" style="flex:1">Loading...</span>
|
| 634 |
+
<button class="copy-btn" onclick="copyText('base-url-text')">Copy</button>
|
| 635 |
+
</div>
|
| 636 |
+
|
| 637 |
+
<div class="sidebar-label">API Key</div>
|
| 638 |
+
<div id="key-display">No key generated yet.</div>
|
| 639 |
+
<button class="copy-btn" style="margin-top:8px; width:100%" onclick="copyText('key-display')">Copy Key</button>
|
| 640 |
+
|
| 641 |
+
<button class="gen-key-btn" onclick="generateKey()">🔑 Generate New API Key</button>
|
| 642 |
+
|
| 643 |
+
<div style="margin-top:24px; padding-top:16px; border-top:1px solid #45475a">
|
| 644 |
+
<div class="sidebar-label" style="margin-bottom:8px">Available Endpoints</div>
|
| 645 |
+
<div style="font-size:0.78rem; color:#89dceb; line-height:1.8">
|
| 646 |
+
GET <span style="color:#a6e3a1">/v1/models</span><br>
|
| 647 |
+
POST <span style="color:#a6e3a1">/v1/chat/completions</span>
|
| 648 |
+
</div>
|
| 649 |
+
<div style="margin-top:12px; font-size:0.75rem; color:#6c7086">
|
| 650 |
+
Use <code>Authorization: Bearer <key></code>
|
| 651 |
+
</div>
|
| 652 |
+
</div>
|
| 653 |
+
</div>
|
| 654 |
+
|
| 655 |
+
<script>
|
| 656 |
+
function toggleSidebar() {
|
| 657 |
+
const overlay = document.getElementById('sidebar-overlay');
|
| 658 |
+
const panel = document.getElementById('sidebar-panel');
|
| 659 |
+
const isOpen = panel.style.display === 'block';
|
| 660 |
+
overlay.style.display = isOpen ? 'none' : 'block';
|
| 661 |
+
panel.style.display = isOpen ? 'none' : 'block';
|
| 662 |
+
if (!isOpen) {
|
| 663 |
+
document.getElementById('base-url-text').textContent = window.location.origin;
|
| 664 |
+
}
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
function closeSidebar() {
|
| 668 |
+
document.getElementById('sidebar-overlay').style.display = 'none';
|
| 669 |
+
document.getElementById('sidebar-panel').style.display = 'none';
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
function copyText(elemId) {
|
| 673 |
+
const el = document.getElementById(elemId);
|
| 674 |
+
const text = el.textContent.trim();
|
| 675 |
+
navigator.clipboard.writeText(text).then(() => {
|
| 676 |
+
const btn = el.nextElementSibling || el.previousElementSibling;
|
| 677 |
+
if (btn && btn.classList.contains('copy-btn')) {
|
| 678 |
+
const orig = btn.textContent;
|
| 679 |
+
btn.textContent = '✓ Copied';
|
| 680 |
+
setTimeout(() => { btn.textContent = orig; }, 1500);
|
| 681 |
+
}
|
| 682 |
+
});
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
async function generateKey() {
|
| 686 |
+
const btn = document.querySelector('.gen-key-btn');
|
| 687 |
+
btn.textContent = '⏳ Generating...';
|
| 688 |
+
btn.disabled = true;
|
| 689 |
+
try {
|
| 690 |
+
const resp = await fetch('/generate_key', { method: 'POST' });
|
| 691 |
+
const data = await resp.json();
|
| 692 |
+
document.getElementById('key-display').textContent = data.key;
|
| 693 |
+
btn.textContent = '✅ Key Generated!';
|
| 694 |
+
setTimeout(() => {
|
| 695 |
+
btn.textContent = '🔑 Generate New API Key';
|
| 696 |
+
btn.disabled = false;
|
| 697 |
+
}, 2000);
|
| 698 |
+
} catch(e) {
|
| 699 |
+
btn.textContent = '❌ Error — retry';
|
| 700 |
+
btn.disabled = false;
|
| 701 |
+
}
|
| 702 |
+
}
|
| 703 |
+
</script>
|
| 704 |
+
"""
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=CSS, title=APP_NAME) as demo:
|
| 708 |
+
|
| 709 |
+
gr.HTML(SIDEBAR_HTML)
|
| 710 |
|
| 711 |
gr.Markdown(
|
| 712 |
"""
|
| 713 |
# ⚡ Tasting AI Studio
|
| 714 |
+
### Image Generation + Real-Time AI Coding + OpenAI-Compatible API
|
|
|
|
|
|
|
| 715 |
Public open-source models.
|
| 716 |
""",
|
| 717 |
elem_id="heading",
|
|
|
|
| 719 |
|
| 720 |
with gr.Tabs():
|
| 721 |
|
| 722 |
+
# ---- IMAGE TAB ----
|
|
|
|
|
|
|
|
|
|
| 723 |
with gr.Tab("🎨 Image Generation"):
|
|
|
|
| 724 |
gr.Markdown("## AI Image Generator")
|
| 725 |
|
| 726 |
image_model = gr.Dropdown(
|
|
|
|
| 728 |
value="SDXL Turbo",
|
| 729 |
label="Choose Image Model",
|
| 730 |
)
|
| 731 |
+
image_prompt = gr.Textbox(label="Image Prompt", placeholder="Describe your image...", lines=4)
|
| 732 |
+
negative_prompt = gr.Textbox(label="Negative Prompt", lines=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 733 |
|
| 734 |
with gr.Row():
|
| 735 |
+
width = gr.Slider(256, 768, value=512, step=32, label="Width")
|
| 736 |
+
height = gr.Slider(256, 768, value=512, step=32, label="Height")
|
| 737 |
|
| 738 |
+
steps = gr.Slider(1, 30, value=4, step=1, label="Inference Steps")
|
| 739 |
+
seed = gr.Number(value=0, precision=0, label="Seed")
|
| 740 |
+
random_seed = gr.Checkbox(value=True, label="Random Seed")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 741 |
|
| 742 |
+
generate_button = gr.Button("✨ Generate Image", variant="primary")
|
| 743 |
+
image_output = gr.Image(label="Generated Image", type="pil")
|
| 744 |
+
seed_output = gr.Number(label="Used Seed", precision=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 745 |
|
| 746 |
generate_button.click(
|
| 747 |
fn=generate_image,
|
| 748 |
+
inputs=[image_prompt, negative_prompt, image_model, width, height, steps, seed, random_seed],
|
| 749 |
+
outputs=[image_output, seed_output],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 750 |
)
|
| 751 |
|
| 752 |
+
# ---- CODING TAB ----
|
|
|
|
|
|
|
|
|
|
| 753 |
with gr.Tab("💻 AI Coding"):
|
| 754 |
+
gr.Markdown("## Real-Time Coding Assistant\nWatch your code being generated live.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 755 |
|
| 756 |
code_model = gr.Dropdown(
|
| 757 |
choices=list(CODE_MODELS.keys()),
|
| 758 |
value="Qwen Coder 0.5B",
|
| 759 |
label="Choose Coding Model",
|
| 760 |
)
|
|
|
|
| 761 |
code_prompt = gr.Textbox(
|
| 762 |
label="Your Coding Request",
|
| 763 |
placeholder="Create a complete Python application...",
|
|
|
|
| 765 |
)
|
| 766 |
|
| 767 |
with gr.Row():
|
| 768 |
+
max_tokens = gr.Slider(128, 1024, value=512, step=128, label="Maximum Output Tokens")
|
| 769 |
+
temperature = gr.Slider(0.1, 1.0, value=0.3, step=0.1, label="Temperature")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 770 |
|
| 771 |
with gr.Row():
|
| 772 |
+
generate_code = gr.Button("⚡ Generate Code", variant="primary")
|
| 773 |
+
stop_button = gr.Button("⏹ Stop Generation", variant="stop")
|
| 774 |
|
| 775 |
+
coding_output = gr.Markdown(label="Live AI Response")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 776 |
|
| 777 |
generate_code.click(
|
| 778 |
fn=coding_assistant,
|
| 779 |
+
inputs=[code_prompt, code_model, max_tokens, temperature, gr.State([])],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 780 |
outputs=coding_output,
|
| 781 |
)
|
| 782 |
+
stop_button.click(fn=stop_generation, outputs=coding_output)
|
| 783 |
|
| 784 |
+
# ---- API KEYS TAB ----
|
| 785 |
+
with gr.Tab("🔑 API Keys"):
|
| 786 |
+
gr.Markdown(
|
| 787 |
+
"""
|
| 788 |
+
## API Key Management
|
| 789 |
+
|
| 790 |
+
Generate unlimited API keys to access the **OpenAI-compatible REST API**.
|
| 791 |
+
|
| 792 |
+
### How to use:
|
| 793 |
+
```
|
| 794 |
+
Base URL : http://your-server:7860
|
| 795 |
+
Endpoint : GET /v1/models
|
| 796 |
+
POST /v1/chat/completions
|
| 797 |
+
|
| 798 |
+
Header : Authorization: Bearer tai-xxxxxxxxxx
|
| 799 |
+
```
|
| 800 |
+
|
| 801 |
+
### Example curl:
|
| 802 |
+
```bash
|
| 803 |
+
curl http://localhost:7860/v1/chat/completions \\
|
| 804 |
+
-H "Authorization: Bearer tai-your-key-here" \\
|
| 805 |
+
-H "Content-Type: application/json" \\
|
| 806 |
+
-d '{
|
| 807 |
+
"model": "Qwen Coder 0.5B",
|
| 808 |
+
"messages": [{"role": "user", "content": "Write a hello world in Python"}],
|
| 809 |
+
"max_tokens": 256
|
| 810 |
+
}'
|
| 811 |
+
```
|
| 812 |
+
"""
|
| 813 |
)
|
| 814 |
|
| 815 |
+
with gr.Row():
|
| 816 |
+
gen_key_btn = gr.Button("🔑 Generate New API Key", variant="primary", scale=1)
|
| 817 |
+
|
| 818 |
+
key_output = gr.Textbox(label="Generated Key", interactive=False, show_copy_button=True)
|
| 819 |
+
key_status = gr.Markdown()
|
| 820 |
+
|
| 821 |
+
gen_key_btn.click(
|
| 822 |
+
fn=handle_generate_key,
|
| 823 |
+
outputs=[key_output, key_status],
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
gr.Markdown("---")
|
| 827 |
+
list_keys_btn = gr.Button("📋 Show All Generated Keys")
|
| 828 |
+
keys_list = gr.Markdown()
|
| 829 |
+
|
| 830 |
+
list_keys_btn.click(fn=handle_list_keys, outputs=keys_list)
|
| 831 |
+
|
| 832 |
gr.Markdown(
|
| 833 |
"""
|
| 834 |
---
|
| 835 |
+
**Tasting AI Studio** · Local inference · Live code streaming · OpenAI-compatible API · Public models
|
|
|
|
| 836 |
"""
|
| 837 |
)
|
| 838 |
|
| 839 |
|
| 840 |
+
# ==========================================
|
| 841 |
+
# /generate_key REST endpoint (for sidebar JS)
|
| 842 |
+
# ==========================================
|
| 843 |
+
|
| 844 |
+
@api_app.post("/generate_key")
|
| 845 |
+
async def rest_generate_key():
|
| 846 |
+
key = generate_api_key()
|
| 847 |
+
return {"key": key}
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
# ==========================================
|
| 851 |
+
# MOUNT GRADIO INSIDE FASTAPI
|
| 852 |
+
# ==========================================
|
| 853 |
+
|
| 854 |
+
from gradio.routes import mount_gradio_app
|
| 855 |
+
|
| 856 |
+
app = mount_gradio_app(api_app, demo, path="/")
|
| 857 |
+
|
| 858 |
+
|
| 859 |
# ==========================================
|
| 860 |
# START SERVER
|
| 861 |
# ==========================================
|
| 862 |
|
| 863 |
if __name__ == "__main__":
|
| 864 |
+
uvicorn.run(
|
| 865 |
+
app,
|
| 866 |
+
host="0.0.0.0",
|
| 867 |
+
port=7860,
|
| 868 |
+
log_level="info",
|
| 869 |
)
|