Update app.py
Browse files
app.py
CHANGED
|
@@ -11,18 +11,20 @@ if not hasattr(huggingface_hub, "HfFolder"):
|
|
| 11 |
def delete_token(): huggingface_hub.logout()
|
| 12 |
huggingface_hub.HfFolder = _HfFolder
|
| 13 |
|
| 14 |
-
# Now safe to import everything else
|
| 15 |
import spaces # Must come before torch (ZeroGPU rule)
|
| 16 |
import torch
|
| 17 |
import gradio as gr
|
| 18 |
from threading import Thread
|
| 19 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 20 |
import os
|
|
|
|
| 21 |
|
| 22 |
# ── Configuration ──────────────────────────────────────────────────────────
|
| 23 |
-
MODEL_ID = os.getenv(
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
# ── Load model & tokenizer at startup (required for ZeroGPU) ──────────────
|
|
@@ -44,42 +46,142 @@ for special in ["<|im_end|>", "<|endoftext|>"]:
|
|
| 44 |
print("Model loaded and ready.")
|
| 45 |
|
| 46 |
|
| 47 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
@spaces.GPU(duration=60)
|
| 49 |
def generate_stream(
|
| 50 |
prompt: str,
|
|
|
|
|
|
|
|
|
|
| 51 |
max_new_tokens: int = 256,
|
| 52 |
temperature: float = 0.7,
|
| 53 |
top_p: float = 0.9,
|
| 54 |
request: gr.Request = None,
|
| 55 |
):
|
| 56 |
-
|
|
|
|
| 57 |
url_prompt = request.query_params.get("prompt")
|
| 58 |
if url_prompt:
|
| 59 |
prompt = url_prompt
|
| 60 |
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 64 |
-
# ✅ FIX: transformers v5 returns a BatchEncoding, NOT a bare tensor.
|
| 65 |
-
# Passing it directly to generate() crashes on `.shape`.
|
| 66 |
-
# Unpack it with **inputs so input_ids and attention_mask are passed.
|
| 67 |
-
# ═══════════════════════════════════════════════════════════════════════
|
| 68 |
encoded = tokenizer.apply_chat_template(
|
| 69 |
-
messages,
|
| 70 |
-
add_generation_prompt=True,
|
| 71 |
-
return_tensors="pt",
|
| 72 |
).to(model.device)
|
| 73 |
|
| 74 |
streamer = TextIteratorStreamer(
|
| 75 |
-
tokenizer,
|
| 76 |
-
skip_prompt=True,
|
| 77 |
-
skip_special_tokens=True,
|
| 78 |
-
timeout=10.0,
|
| 79 |
)
|
| 80 |
|
| 81 |
-
|
| 82 |
-
**encoded,
|
| 83 |
max_new_tokens=int(max_new_tokens),
|
| 84 |
do_sample=True,
|
| 85 |
temperature=float(temperature),
|
|
@@ -89,82 +191,254 @@ def generate_stream(
|
|
| 89 |
pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id,
|
| 90 |
use_cache=True,
|
| 91 |
)
|
| 92 |
-
|
| 93 |
if float(temperature) <= 0:
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
|
| 98 |
-
thread = Thread(target=model.generate, kwargs=
|
| 99 |
thread.start()
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
partial = ""
|
| 102 |
for text in streamer:
|
| 103 |
partial += text
|
| 104 |
-
|
|
|
|
| 105 |
|
| 106 |
thread.join()
|
| 107 |
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
#
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
This Space streams responses token-by-token. You can also query it via URL:
|
| 115 |
-
`?prompt=Your+question+here`
|
| 116 |
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
"""
|
| 119 |
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
gr.Markdown(DESCRIPTION)
|
| 122 |
|
| 123 |
with gr.Row():
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
-
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
)
|
| 150 |
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
fn=generate_stream,
|
| 153 |
-
inputs=
|
| 154 |
-
outputs=
|
| 155 |
api_name="stream_text",
|
|
|
|
|
|
|
| 156 |
)
|
| 157 |
|
| 158 |
prompt_input.submit(
|
| 159 |
fn=generate_stream,
|
| 160 |
-
inputs=
|
| 161 |
-
outputs=
|
| 162 |
api_name=False,
|
|
|
|
|
|
|
| 163 |
)
|
| 164 |
|
| 165 |
-
#
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
# ── Launch at module level (required for HF Spaces runner) ─────────────────
|
| 170 |
demo.launch(
|
|
|
|
| 11 |
def delete_token(): huggingface_hub.logout()
|
| 12 |
huggingface_hub.HfFolder = _HfFolder
|
| 13 |
|
|
|
|
| 14 |
import spaces # Must come before torch (ZeroGPU rule)
|
| 15 |
import torch
|
| 16 |
import gradio as gr
|
| 17 |
from threading import Thread
|
| 18 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 19 |
import os
|
| 20 |
+
import uuid
|
| 21 |
|
| 22 |
# ── Configuration ──────────────────────────────────────────────────────────
|
| 23 |
+
MODEL_ID = os.getenv("MODEL_ID", "huihui-ai/Huihui-Qwen3.5-2B-abliterated")
|
| 24 |
+
MAX_CONTEXT_TOKENS = int(os.getenv("MAX_CONTEXT_TOKENS", "6144"))
|
| 25 |
+
DEFAULT_SYSTEM_PROMPT = os.getenv(
|
| 26 |
+
"SYSTEM_PROMPT",
|
| 27 |
+
"You are a helpful, concise assistant."
|
| 28 |
)
|
| 29 |
|
| 30 |
# ── Load model & tokenizer at startup (required for ZeroGPU) ──────────────
|
|
|
|
| 46 |
print("Model loaded and ready.")
|
| 47 |
|
| 48 |
|
| 49 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 50 |
+
# HELPERS
|
| 51 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 52 |
+
def _count_tokens(history: list, system_prompt: str) -> int:
|
| 53 |
+
"""Count tokens of the chat template that the model will actually receive."""
|
| 54 |
+
msgs = []
|
| 55 |
+
if system_prompt and system_prompt.strip():
|
| 56 |
+
msgs.append({"role": "system", "content": system_prompt})
|
| 57 |
+
msgs.extend(history or [])
|
| 58 |
+
if not msgs:
|
| 59 |
+
return 0
|
| 60 |
+
try:
|
| 61 |
+
ids = tokenizer.apply_chat_template(
|
| 62 |
+
msgs, add_generation_prompt=True, return_tensors="pt"
|
| 63 |
+
)
|
| 64 |
+
return int(ids.shape[-1])
|
| 65 |
+
except Exception:
|
| 66 |
+
return 0
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _token_html(count: int) -> str:
|
| 70 |
+
"""Render a colored progress bar for context usage."""
|
| 71 |
+
pct = min(count / MAX_CONTEXT_TOKENS * 100, 100) if MAX_CONTEXT_TOKENS else 0
|
| 72 |
+
color = "#22c55e" if pct < 50 else "#f59e0b" if pct < 80 else "#ef4444"
|
| 73 |
+
return f"""
|
| 74 |
+
<div style="margin: 6px 0 10px 0;">
|
| 75 |
+
<div style="display:flex;justify-content:space-between;font-size:12px;
|
| 76 |
+
color:#6b7280;margin-bottom:4px;">
|
| 77 |
+
<span>📊 Context window</span>
|
| 78 |
+
<span>{count:,} / {MAX_CONTEXT_TOKENS:,} tokens ({pct:.0f}%)</span>
|
| 79 |
+
</div>
|
| 80 |
+
<div style="background:#e5e7eb;height:6px;border-radius:3px;overflow:hidden;">
|
| 81 |
+
<div style="width:{pct:.1f}%;background:{color};height:100%;
|
| 82 |
+
transition:width 0.3s ease;"></div>
|
| 83 |
+
</div>
|
| 84 |
+
</div>"""
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _truncate_history(messages: list, max_tokens: int) -> list:
|
| 88 |
+
"""Drop oldest non-system pairs until the conversation fits the window."""
|
| 89 |
+
while len(messages) > 1:
|
| 90 |
+
try:
|
| 91 |
+
ids = tokenizer.apply_chat_template(
|
| 92 |
+
messages, add_generation_prompt=True, return_tensors="pt"
|
| 93 |
+
)
|
| 94 |
+
except Exception:
|
| 95 |
+
return messages
|
| 96 |
+
if ids.shape[-1] <= max_tokens:
|
| 97 |
+
return messages
|
| 98 |
+
if messages[0].get("role") == "system" and len(messages) >= 3:
|
| 99 |
+
messages = [messages[0]] + messages[3:]
|
| 100 |
+
else:
|
| 101 |
+
messages = messages[2:]
|
| 102 |
+
return messages
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _find_session(sessions: list, session_id: str):
|
| 106 |
+
return next((s for s in sessions if s.get("id") == session_id), None)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _update_session(sessions: list, session_id: str, new_history: list, new_title=None):
|
| 110 |
+
"""Return a new list with the given session's history/title replaced."""
|
| 111 |
+
out = []
|
| 112 |
+
for s in sessions:
|
| 113 |
+
if s.get("id") == session_id:
|
| 114 |
+
updated = {**s, "history": new_history}
|
| 115 |
+
if new_title:
|
| 116 |
+
updated["title"] = new_title
|
| 117 |
+
out.append(updated)
|
| 118 |
+
else:
|
| 119 |
+
out.append(s)
|
| 120 |
+
return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _new_session() -> dict:
|
| 124 |
+
return {"id": str(uuid.uuid4()), "title": "New chat", "history": []}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _derive_title(prompt: str) -> str:
|
| 128 |
+
p = prompt.strip().replace("\n", " ")
|
| 129 |
+
return (p[:40] + "…") if len(p) > 40 else (p or "New chat")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 133 |
+
# STREAMING GENERATOR (ZeroGPU) — history + system-prompt aware
|
| 134 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 135 |
@spaces.GPU(duration=60)
|
| 136 |
def generate_stream(
|
| 137 |
prompt: str,
|
| 138 |
+
sessions: list,
|
| 139 |
+
active_id: str,
|
| 140 |
+
system_prompt: str,
|
| 141 |
max_new_tokens: int = 256,
|
| 142 |
temperature: float = 0.7,
|
| 143 |
top_p: float = 0.9,
|
| 144 |
request: gr.Request = None,
|
| 145 |
):
|
| 146 |
+
# URL prompt override only when the textbox is empty
|
| 147 |
+
if request is not None and (not prompt or not prompt.strip()):
|
| 148 |
url_prompt = request.query_params.get("prompt")
|
| 149 |
if url_prompt:
|
| 150 |
prompt = url_prompt
|
| 151 |
|
| 152 |
+
if not prompt or not prompt.strip():
|
| 153 |
+
yield gr.update(), sessions
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
session = _find_session(sessions, active_id)
|
| 157 |
+
if session is None:
|
| 158 |
+
yield gr.update(), sessions
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
history = list(session.get("history", []))
|
| 162 |
+
history.append({"role": "user", "content": prompt})
|
| 163 |
+
|
| 164 |
+
new_title = session.get("title") or "New chat"
|
| 165 |
+
if new_title == "New chat":
|
| 166 |
+
new_title = _derive_title(prompt)
|
| 167 |
+
|
| 168 |
+
# Build messages: system prompt + history, then truncate
|
| 169 |
+
messages = []
|
| 170 |
+
if system_prompt and system_prompt.strip():
|
| 171 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 172 |
+
messages.extend(history)
|
| 173 |
+
messages = _truncate_history(messages, MAX_CONTEXT_TOKENS)
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
encoded = tokenizer.apply_chat_template(
|
| 176 |
+
messages, add_generation_prompt=True, return_tensors="pt"
|
|
|
|
|
|
|
| 177 |
).to(model.device)
|
| 178 |
|
| 179 |
streamer = TextIteratorStreamer(
|
| 180 |
+
tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10.0
|
|
|
|
|
|
|
|
|
|
| 181 |
)
|
| 182 |
|
| 183 |
+
gen_kwargs = dict(
|
| 184 |
+
**encoded,
|
| 185 |
max_new_tokens=int(max_new_tokens),
|
| 186 |
do_sample=True,
|
| 187 |
temperature=float(temperature),
|
|
|
|
| 191 |
pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id,
|
| 192 |
use_cache=True,
|
| 193 |
)
|
|
|
|
| 194 |
if float(temperature) <= 0:
|
| 195 |
+
gen_kwargs["do_sample"] = False
|
| 196 |
+
gen_kwargs.pop("temperature", None)
|
| 197 |
+
gen_kwargs.pop("top_p", None)
|
| 198 |
|
| 199 |
+
thread = Thread(target=model.generate, kwargs=gen_kwargs)
|
| 200 |
thread.start()
|
| 201 |
|
| 202 |
+
# First yield: user message + empty assistant bubble
|
| 203 |
+
base = history + [{"role": "assistant", "content": ""}]
|
| 204 |
+
yield base, _update_session(sessions, active_id, base, new_title)
|
| 205 |
+
|
| 206 |
+
# Stream tokens
|
| 207 |
partial = ""
|
| 208 |
for text in streamer:
|
| 209 |
partial += text
|
| 210 |
+
view = history + [{"role": "assistant", "content": partial}]
|
| 211 |
+
yield view, _update_session(sessions, active_id, view, new_title)
|
| 212 |
|
| 213 |
thread.join()
|
| 214 |
|
| 215 |
|
| 216 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 217 |
+
# UI EVENT HANDLERS
|
| 218 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 219 |
+
def _on_load(sessions, active_id, system_prompt):
|
| 220 |
+
"""Restore from browser storage; create a default session if empty."""
|
| 221 |
+
if not sessions:
|
| 222 |
+
s = _new_session()
|
| 223 |
+
sessions = [s]
|
| 224 |
+
active_id = s["id"]
|
| 225 |
+
if not active_id or not any(s["id"] == active_id for s in sessions):
|
| 226 |
+
active_id = sessions[0]["id"]
|
| 227 |
+
history = next((s["history"] for s in sessions if s["id"] == active_id), [])
|
| 228 |
+
choices = [(s["title"], s["id"]) for s in sessions]
|
| 229 |
+
count = _count_tokens(history, system_prompt)
|
| 230 |
+
return (
|
| 231 |
+
sessions,
|
| 232 |
+
active_id,
|
| 233 |
+
history,
|
| 234 |
+
gr.update(choices=choices, value=active_id),
|
| 235 |
+
_token_html(count),
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _new_chat(sessions, system_prompt):
|
| 240 |
+
s = _new_session()
|
| 241 |
+
sessions = list(sessions or []) + [s]
|
| 242 |
+
choices = [(x["title"], x["id"]) for x in sessions]
|
| 243 |
+
count = _count_tokens([], system_prompt)
|
| 244 |
+
return (
|
| 245 |
+
sessions,
|
| 246 |
+
s["id"],
|
| 247 |
+
[],
|
| 248 |
+
gr.update(choices=choices, value=s["id"]),
|
| 249 |
+
_token_html(count),
|
| 250 |
+
"",
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _switch_session(selected_id, sessions, system_prompt):
|
| 255 |
+
if not selected_id:
|
| 256 |
+
return gr.update(), gr.update(), gr.update()
|
| 257 |
+
session = _find_session(sessions, selected_id)
|
| 258 |
+
if session is None:
|
| 259 |
+
return gr.update(), gr.update(), gr.update()
|
| 260 |
+
count = _count_tokens(session["history"], system_prompt)
|
| 261 |
+
return selected_id, session["history"], _token_html(count)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _delete_chat(sessions, active_id, system_prompt):
|
| 265 |
+
remaining = [s for s in sessions if s["id"] != active_id]
|
| 266 |
+
if not remaining:
|
| 267 |
+
remaining = [_new_session()]
|
| 268 |
+
active_id = remaining[0]["id"]
|
| 269 |
+
history = next((s["history"] for s in remaining if s["id"] == active_id), [])
|
| 270 |
+
choices = [(s["title"], s["id"]) for s in remaining]
|
| 271 |
+
count = _count_tokens(history, system_prompt)
|
| 272 |
+
return (
|
| 273 |
+
remaining,
|
| 274 |
+
active_id,
|
| 275 |
+
history,
|
| 276 |
+
gr.update(choices=choices, value=active_id),
|
| 277 |
+
_token_html(count),
|
| 278 |
+
"",
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _after_send(sessions, active_id, system_prompt):
|
| 283 |
+
"""After streaming finishes: refresh selector labels, meter, clear prompt."""
|
| 284 |
+
session = _find_session(sessions, active_id)
|
| 285 |
+
count = _count_tokens(session["history"] if session else [], system_prompt)
|
| 286 |
+
choices = [(s["title"], s["id"]) for s in sessions]
|
| 287 |
+
return gr.update(choices=choices, value=active_id), _token_html(count), ""
|
| 288 |
|
|
|
|
|
|
|
| 289 |
|
| 290 |
+
def _refresh_token(sessions, active_id, system_prompt):
|
| 291 |
+
session = _find_session(sessions, active_id)
|
| 292 |
+
count = _count_tokens(session["history"] if session else [], system_prompt)
|
| 293 |
+
return _token_html(count)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 297 |
+
# UI LAYOUT
|
| 298 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 299 |
+
CSS = """
|
| 300 |
+
.gradio-container { max-width: 1400px !important; }
|
| 301 |
+
#sidebar { background: linear-gradient(180deg, #fafafa 0%, #f0f0f0 100%);
|
| 302 |
+
border-radius: 12px; padding: 16px; min-height: 640px;
|
| 303 |
+
border: 1px solid #e5e7eb; }
|
| 304 |
+
#sidebar button { width: 100% !important; margin-bottom: 6px; }
|
| 305 |
+
#chat-main { padding: 0 8px; }
|
| 306 |
+
#token-bar { margin-top: 4px; }
|
| 307 |
"""
|
| 308 |
|
| 309 |
+
DESCRIPTION = f"""
|
| 310 |
+
# 🧠 Streaming Abliterated Chat
|
| 311 |
+
**Model:** `{MODEL_ID}` · Multi-session · Context-aware
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
with gr.Blocks(title="Abliterated Chat", css=CSS, fill_height=True) as demo:
|
| 315 |
+
# ── State ──────────────────────────────────────────────────────────────
|
| 316 |
+
sessions_state = gr.BrowserState([], storage_key="ablt_sessions")
|
| 317 |
+
active_id_state = gr.BrowserState("", storage_key="ablt_active")
|
| 318 |
+
|
| 319 |
gr.Markdown(DESCRIPTION)
|
| 320 |
|
| 321 |
with gr.Row():
|
| 322 |
+
# ── Sidebar ────────────────────────────────────────────────────────
|
| 323 |
+
with gr.Column(scale=1, elem_id="sidebar", min_width=220):
|
| 324 |
+
new_chat_btn = gr.Button("➕ New chat", variant="primary")
|
| 325 |
+
session_selector = gr.Radio(
|
| 326 |
+
label="Your chats",
|
| 327 |
+
choices=[],
|
| 328 |
+
value=None,
|
| 329 |
+
interactive=True,
|
| 330 |
+
)
|
| 331 |
+
delete_btn = gr.Button("🗑️ Delete current", variant="secondary")
|
| 332 |
|
| 333 |
+
# ── Main chat ──────────────────────────────────────────────────────
|
| 334 |
+
with gr.Column(scale=4, elem_id="chat-main"):
|
| 335 |
+
chatbot = gr.Chatbot(
|
| 336 |
+
type="messages",
|
| 337 |
+
label="Conversation",
|
| 338 |
+
height=520,
|
| 339 |
+
buttons=["copy"],
|
| 340 |
+
show_label=False,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
with gr.Row():
|
| 344 |
+
prompt_input = gr.Textbox(
|
| 345 |
+
placeholder="Type a message and press Enter…",
|
| 346 |
+
show_label=False,
|
| 347 |
+
lines=2,
|
| 348 |
+
scale=5,
|
| 349 |
+
autofocus=True,
|
| 350 |
+
)
|
| 351 |
+
send_btn = gr.Button("Send", variant="primary", scale=1)
|
| 352 |
|
| 353 |
+
token_display = gr.HTML(value=_token_html(0), elem_id="token-bar")
|
| 354 |
|
| 355 |
+
with gr.Accordion("⚙️ Settings", open=False):
|
| 356 |
+
system_prompt = gr.Textbox(
|
| 357 |
+
label="System prompt",
|
| 358 |
+
value=DEFAULT_SYSTEM_PROMPT,
|
| 359 |
+
lines=2,
|
| 360 |
+
)
|
| 361 |
+
with gr.Row():
|
| 362 |
+
max_tokens_slider = gr.Slider(
|
| 363 |
+
16, 1024, value=256, step=16, label="Max new tokens"
|
| 364 |
+
)
|
| 365 |
+
temperature_slider = gr.Slider(
|
| 366 |
+
0.0, 2.0, value=0.7, step=0.1, label="Temperature"
|
| 367 |
+
)
|
| 368 |
+
top_p_slider = gr.Slider(
|
| 369 |
+
0.1, 1.0, value=0.9, step=0.05, label="Top-p"
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
# ── Hidden ZeroGPU registration (inside Blocks context) ───────────────
|
| 373 |
+
_zerogpu_btn = gr.Button("init-gpu", visible=False)
|
| 374 |
+
_zerogpu_btn.click(fn=lambda: "gpu-ready", inputs=None, outputs=None)
|
| 375 |
+
|
| 376 |
+
# ── Wire: page load ───────────────────────────────────────────────────
|
| 377 |
+
demo.load(
|
| 378 |
+
fn=_on_load,
|
| 379 |
+
inputs=[sessions_state, active_id_state, system_prompt],
|
| 380 |
+
outputs=[sessions_state, active_id_state, chatbot, session_selector, token_display],
|
| 381 |
)
|
| 382 |
|
| 383 |
+
# ── Wire: send (button + Enter key) ───────────────────────────────────
|
| 384 |
+
send_inputs = [
|
| 385 |
+
prompt_input, sessions_state, active_id_state, system_prompt,
|
| 386 |
+
max_tokens_slider, temperature_slider, top_p_slider,
|
| 387 |
+
]
|
| 388 |
+
send_after_inputs = [sessions_state, active_id_state, system_prompt]
|
| 389 |
+
send_after_outputs = [session_selector, token_display, prompt_input]
|
| 390 |
+
|
| 391 |
+
send_btn.click(
|
| 392 |
fn=generate_stream,
|
| 393 |
+
inputs=send_inputs,
|
| 394 |
+
outputs=[chatbot, sessions_state],
|
| 395 |
api_name="stream_text",
|
| 396 |
+
).then(
|
| 397 |
+
fn=_after_send, inputs=send_after_inputs, outputs=send_after_outputs,
|
| 398 |
)
|
| 399 |
|
| 400 |
prompt_input.submit(
|
| 401 |
fn=generate_stream,
|
| 402 |
+
inputs=send_inputs,
|
| 403 |
+
outputs=[chatbot, sessions_state],
|
| 404 |
api_name=False,
|
| 405 |
+
).then(
|
| 406 |
+
fn=_after_send, inputs=send_after_inputs, outputs=send_after_outputs,
|
| 407 |
)
|
| 408 |
|
| 409 |
+
# ── Wire: New Chat ────────────────────────────────────────────────────
|
| 410 |
+
new_chat_btn.click(
|
| 411 |
+
fn=_new_chat,
|
| 412 |
+
inputs=[sessions_state, system_prompt],
|
| 413 |
+
outputs=[
|
| 414 |
+
sessions_state, active_id_state, chatbot,
|
| 415 |
+
session_selector, token_display, prompt_input,
|
| 416 |
+
],
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# ── Wire: Switch session ──────────────────────────────────────────────
|
| 420 |
+
session_selector.change(
|
| 421 |
+
fn=_switch_session,
|
| 422 |
+
inputs=[session_selector, sessions_state, system_prompt],
|
| 423 |
+
outputs=[active_id_state, chatbot, token_display],
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
# ── Wire: Delete session ──────────────────────────────────────────────
|
| 427 |
+
delete_btn.click(
|
| 428 |
+
fn=_delete_chat,
|
| 429 |
+
inputs=[sessions_state, active_id_state, system_prompt],
|
| 430 |
+
outputs=[
|
| 431 |
+
sessions_state, active_id_state, chatbot,
|
| 432 |
+
session_selector, token_display, prompt_input,
|
| 433 |
+
],
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
# ── Wire: system prompt change → refresh meter ────────────────────────
|
| 437 |
+
system_prompt.change(
|
| 438 |
+
fn=_refresh_token,
|
| 439 |
+
inputs=[sessions_state, active_id_state, system_prompt],
|
| 440 |
+
outputs=[token_display],
|
| 441 |
+
)
|
| 442 |
|
| 443 |
# ── Launch at module level (required for HF Spaces runner) ─────────────────
|
| 444 |
demo.launch(
|