Hfzune commited on
Commit
eacc461
·
verified ·
1 Parent(s): b76a059

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -244
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # app.py
2
- # ⚠️ CRITICAL: Monkey-patch HfFolder BEFORE any other imports (Issue #1)
3
  import huggingface_hub
4
  if not hasattr(huggingface_hub, "HfFolder"):
5
  class _HfFolder:
@@ -14,15 +14,21 @@ if not hasattr(huggingface_hub, "HfFolder"):
14
  import spaces
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("SYSTEM_PROMPT", "You are a helpful, concise assistant.")
 
26
 
27
  # ── Load model ─────────────────────────────────────────────────────────────
28
  print(f"Loading model: {MODEL_ID}")
@@ -38,6 +44,9 @@ for special in ["<|im_end|>", "<|endoftext|>"]:
38
 
39
  print("Model loaded and ready.")
40
 
 
 
 
41
 
42
  # ═══════════════════════════════════════════════════════════════════════════
43
  # HELPERS
@@ -51,28 +60,13 @@ def _count_tokens(history: list, system_prompt: str) -> int:
51
  return 0
52
  try:
53
  ids = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt")
54
- # ✅ Transformers v5 returns BatchEncoding, not a raw tensor
55
  return int(ids["input_ids"].shape[-1]) if hasattr(ids, "input_ids") else int(ids.shape[-1])
56
  except Exception:
57
  return 0
58
 
59
 
60
- def _token_html(count: int) -> str:
61
- pct = min(count / MAX_CONTEXT_TOKENS * 100, 100) if MAX_CONTEXT_TOKENS else 0
62
- color = "#22c55e" if pct < 50 else "#f59e0b" if pct < 80 else "#ef4444"
63
- return f"""
64
- <div style="margin: 6px 0 10px 0;">
65
- <div style="display:flex;justify-content:space-between;font-size:12px;color:#6b7280;margin-bottom:4px;">
66
- <span>📊 Context window</span>
67
- <span>{count:,} / {MAX_CONTEXT_TOKENS:,} tokens ({pct:.0f}%)</span>
68
- </div>
69
- <div style="background:#e5e7eb;height:6px;border-radius:3px;overflow:hidden;">
70
- <div style="width:{pct:.1f}%;background:{color};height:100%;transition:width 0.3s ease;"></div>
71
- </div>
72
- </div>"""
73
-
74
-
75
  def _truncate_history(messages: list, max_tokens: int) -> list:
 
76
  while len(messages) > 1:
77
  try:
78
  ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
@@ -88,74 +82,55 @@ def _truncate_history(messages: list, max_tokens: int) -> list:
88
  return messages
89
 
90
 
91
- def _find_session(sessions: list, session_id: str):
92
- return next((s for s in (sessions or []) if s.get("id") == session_id), None)
93
-
94
-
95
- def _update_session(sessions: list, session_id: str, new_history: list, new_title=None):
96
- out = []
97
- for s in (sessions or []):
98
- if s.get("id") == session_id:
99
- updated = {**s, "history": new_history}
100
- if new_title:
101
- updated["title"] = new_title
102
- out.append(updated)
103
- else:
104
- out.append(s)
105
- return out
106
-
107
-
108
- def _new_session() -> dict:
109
- return {"id": str(uuid.uuid4()), "title": "New chat", "history": []}
110
-
111
-
112
- def _derive_title(prompt: str) -> str:
113
- p = prompt.strip().replace("\n", " ")
114
- return (p[:40] + "…") if len(p) > 40 else (p or "New chat")
115
-
116
-
117
  # ═══════════════════════════════════════════════════════════════════════════
118
- # STREAMING GENERATOR — yields ONLY the Chatbot view (no BrowserState writes)
119
  # ═══════════════════════════════════════════════════════════════════════════
 
120
  @spaces.GPU(duration=60)
121
- def generate_stream(
122
- prompt: str,
123
- sessions: list,
124
- active_id: str,
125
- system_prompt: str,
126
  max_new_tokens: int = 256,
127
  temperature: float = 0.7,
128
  top_p: float = 0.9,
129
- request: gr.Request = None,
130
- ):
131
- if request is not None and (not prompt or not prompt.strip()):
132
- url_prompt = request.query_params.get("prompt")
133
- if url_prompt:
134
- prompt = url_prompt
135
-
136
- if not prompt or not prompt.strip():
137
- yield []
 
 
 
138
  return
139
 
140
- session = _find_session(sessions, active_id)
141
- if session is None:
142
- yield []
143
  return
144
 
145
- history = list(session.get("history", []))
146
- history.append({"role": "user", "content": prompt})
 
147
 
 
148
  messages = []
149
  if system_prompt and system_prompt.strip():
150
  messages.append({"role": "system", "content": system_prompt})
151
  messages.extend(history)
152
  messages = _truncate_history(messages, MAX_CONTEXT_TOKENS)
153
 
 
154
  encoded = tokenizer.apply_chat_template(
155
  messages, add_generation_prompt=True, return_tensors="pt"
156
  ).to(model.device)
157
 
158
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10.0)
 
 
159
 
160
  gen_kwargs = dict(
161
  **encoded,
@@ -176,202 +151,58 @@ def generate_stream(
176
  thread = Thread(target=model.generate, kwargs=gen_kwargs)
177
  thread.start()
178
 
179
- # First yield: user message + empty assistant bubble
180
- yield history + [{"role": "assistant", "content": ""}]
181
-
182
  partial = ""
183
  for text in streamer:
184
  partial += text
185
- yield history + [{"role": "assistant", "content": partial}]
186
 
187
  thread.join()
188
- # Final yield guarantees the stored Chatbot value is the complete reply
189
- yield history + [{"role": "assistant", "content": partial}]
190
 
191
 
192
  # ═══════════════════════════════════════════════════════════════════════════
193
- # UI HANDLERS
194
  # ═══════════════════════════════════════════════════════════════════════════
195
- def _on_load(sessions, active_id, system_prompt):
196
- if not sessions:
197
- s = _new_session()
198
- sessions, active_id = [s], s["id"]
199
- if not active_id or not any(s["id"] == active_id for s in sessions):
200
- active_id = sessions[0]["id"]
201
- history = next((s["history"] for s in sessions if s["id"] == active_id), [])
202
- choices = [(s["title"], s["id"]) for s in sessions]
203
- return (sessions, active_id, history,
204
- gr.update(choices=choices, value=active_id),
205
- _token_html(_count_tokens(history, system_prompt)))
206
-
207
-
208
- def _new_chat(sessions, system_prompt):
209
- s = _new_session()
210
- sessions = list(sessions or []) + [s]
211
- choices = [(x["title"], x["id"]) for x in sessions]
212
- return (sessions, s["id"], [],
213
- gr.update(choices=choices, value=s["id"]),
214
- _token_html(_count_tokens([], system_prompt)), "")
215
-
216
-
217
- def _switch_session(selected_id, sessions, system_prompt):
218
- session = _find_session(sessions, selected_id)
219
- if session is None:
220
- return gr.update(), gr.update(), gr.update()
221
- return (selected_id, session["history"],
222
- _token_html(_count_tokens(session["history"], system_prompt)))
223
-
224
-
225
- def _delete_chat(sessions, active_id, system_prompt):
226
- remaining = [s for s in (sessions or []) if s["id"] != active_id]
227
- if not remaining:
228
- remaining = [_new_session()]
229
- active_id = remaining[0]["id"]
230
- history = next((s["history"] for s in remaining if s["id"] == active_id), [])
231
- choices = [(s["title"], s["id"]) for s in remaining]
232
- return (remaining, active_id, history,
233
- gr.update(choices=choices, value=active_id),
234
- _token_html(_count_tokens(history, system_prompt)), "")
235
-
236
-
237
- def _after_send(chatbot_history, sessions, active_id, system_prompt):
238
- """Persist the finished turn to BrowserState + refresh selector/meter."""
239
- chatbot_history = chatbot_history or []
240
- session = _find_session(sessions, active_id)
241
- title = (session or {}).get("title", "New chat")
242
- if title == "New chat" and chatbot_history:
243
- first_user = next((m["content"] for m in chatbot_history if m.get("role") == "user"), "")
244
- title = _derive_title(first_user)
245
- sessions = _update_session(sessions, active_id, chatbot_history, title)
246
- choices = [(s["title"], s["id"]) for s in sessions]
247
- return (sessions, gr.update(choices=choices, value=active_id),
248
- _token_html(_count_tokens(chatbot_history, system_prompt)), "")
249
-
250
-
251
- def _refresh_token(sessions, active_id, system_prompt):
252
- session = _find_session(sessions, active_id)
253
- return _token_html(_count_tokens(session["history"] if session else [], system_prompt))
254
 
255
 
256
  # ═══════════════════════════════════════════════════════════════════════════
257
- # UI LAYOUT
258
  # ═══════════════════════════════════════════════════════════════════════════
259
- CSS = """
260
- .gradio-container { max-width: 1400px !important; }
261
- #sidebar { background: linear-gradient(180deg, #fafafa 0%, #f0f0f0 100%);
262
- border-radius: 12px; padding: 16px; min-height: 640px;
263
- border: 1px solid #e5e7eb; }
264
- #sidebar button { width: 100% !important; margin-bottom: 6px; }
265
- #chat-main { padding: 0 8px; }
266
- #token-bar { margin-top: 4px; }
267
- /* Gradio 6 fill_height workaround (issue #12510) */
268
- div.sidebar-parent > div.contain > div.column { flex-grow: 1; }
269
- """
270
-
271
- DESCRIPTION = f"""
272
- # 🧠 Streaming Abliterated Chat
273
- **Model:** `{MODEL_ID}` · Multi-session · Context-aware
274
- """
275
-
276
- with gr.Blocks(title="Abliterated Chat", fill_height=True) as demo:
277
- sessions_state = gr.BrowserState([], storage_key="ablt_sessions")
278
- active_id_state = gr.BrowserState("", storage_key="ablt_active")
279
-
280
- gr.Markdown(DESCRIPTION)
281
-
282
- with gr.Row():
283
- with gr.Column(scale=1, elem_id="sidebar", min_width=220):
284
- new_chat_btn = gr.Button("➕ New chat", variant="primary")
285
- session_selector = gr.Radio(label="Your chats", choices=[], value=None, interactive=True)
286
- delete_btn = gr.Button("🗑️ Delete current", variant="secondary")
287
-
288
- with gr.Column(scale=4, elem_id="chat-main"):
289
- chatbot = gr.Chatbot(
290
- label="Conversation",
291
- height=520,
292
- buttons=["copy"], # ✅ Gradio 6 syntax
293
- show_label=False,
294
- )
295
-
296
- with gr.Row():
297
- prompt_input = gr.Textbox(
298
- placeholder="Type a message and press Enter…",
299
- show_label=False, lines=2, scale=5, autofocus=True,
300
- )
301
- send_btn = gr.Button("Send", variant="primary", scale=1)
302
-
303
- token_display = gr.HTML(value=_token_html(0), elem_id="token-bar")
304
 
305
- with gr.Accordion("⚙️ Settings", open=False):
306
- system_prompt = gr.Textbox(label="System prompt", value=DEFAULT_SYSTEM_PROMPT, lines=2)
307
- with gr.Row():
308
- max_tokens_slider = gr.Slider(16, 1024, value=256, step=16, label="Max new tokens")
309
- temperature_slider = gr.Slider(0.0, 2.0, value=0.7, step=0.1, label="Temperature")
310
- top_p_slider = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p")
311
 
312
- # Hidden ZeroGPU registration (inside Blocks context)
313
- _zerogpu_btn = gr.Button("init-gpu", visible=False)
314
- _zerogpu_btn.click(fn=lambda: "gpu-ready", inputs=None, outputs=None)
315
 
316
- # ── Wiring ──────────────────────────────────────────────────────────────
317
- demo.load(
318
- fn=_on_load,
319
- inputs=[sessions_state, active_id_state, system_prompt],
320
- outputs=[sessions_state, active_id_state, chatbot, session_selector, token_display],
321
- )
322
-
323
- send_inputs = [
324
- prompt_input, sessions_state, active_id_state, system_prompt,
325
- max_tokens_slider, temperature_slider, top_p_slider,
326
- ]
327
- after_inputs = [chatbot, sessions_state, active_id_state, system_prompt]
328
- after_outputs = [sessions_state, session_selector, token_display, prompt_input]
329
-
330
- send_btn.click(
331
- fn=generate_stream,
332
- inputs=send_inputs,
333
- outputs=[chatbot],
334
- api_name="stream_text",
335
- ).then(fn=_after_send, inputs=after_inputs, outputs=after_outputs)
336
-
337
- prompt_input.submit(
338
- fn=generate_stream,
339
- inputs=send_inputs,
340
- outputs=[chatbot],
341
- api_visibility="private", # ✅ Gradio 6 replacement for api_name=False
342
- ).then(fn=_after_send, inputs=after_inputs, outputs=after_outputs)
343
-
344
- new_chat_btn.click(
345
- fn=_new_chat,
346
- inputs=[sessions_state, system_prompt],
347
- outputs=[sessions_state, active_id_state, chatbot, session_selector, token_display, prompt_input],
348
- )
349
 
350
- # ✅ .input() not .change() — avoids programmatic-change loops
351
- session_selector.input(
352
- fn=_switch_session,
353
- inputs=[session_selector, sessions_state, system_prompt],
354
- outputs=[active_id_state, chatbot, token_display],
355
- )
356
-
357
- delete_btn.click(
358
- fn=_delete_chat,
359
- inputs=[sessions_state, active_id_state, system_prompt],
360
- outputs=[sessions_state, active_id_state, chatbot, session_selector, token_display, prompt_input],
361
- )
362
 
363
- system_prompt.input(
364
- fn=_refresh_token,
365
- inputs=[sessions_state, active_id_state, system_prompt],
366
- outputs=[token_display],
367
- )
368
 
369
- # ✅ css moved from Blocks() to launch()
370
- demo.launch(
371
- server_name="0.0.0.0",
372
- server_port=7860,
373
- share=False,
374
- ssr_mode=False,
375
- prevent_thread_lock=False,
376
- css=CSS,
377
- )
 
 
 
1
  # app.py
2
+ # ⚠️ CRITICAL: Monkey-patch HfFolder BEFORE any other imports
3
  import huggingface_hub
4
  if not hasattr(huggingface_hub, "HfFolder"):
5
  class _HfFolder:
 
14
  import spaces
15
  import torch
16
  import gradio as gr
17
+ from gradio import Server
18
  from threading import Thread
19
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
20
+ from fastapi.responses import HTMLResponse, FileResponse
21
+ from fastapi import Request
22
  import os
23
  import uuid
24
+ from pathlib import Path
25
+ from typing import Generator
26
 
27
  # ── Configuration ──────────────────────────────────────────────────────────
28
  MODEL_ID = os.getenv("MODEL_ID", "huihui-ai/Huihui-Qwen3.5-2B-abliterated")
29
  MAX_CONTEXT_TOKENS = int(os.getenv("MAX_CONTEXT_TOKENS", "6144"))
30
  DEFAULT_SYSTEM_PROMPT = os.getenv("SYSTEM_PROMPT", "You are a helpful, concise assistant.")
31
+ FRONTEND_DIR = Path(__file__).parent / "frontend"
32
 
33
  # ── Load model ─────────────────────────────────────────────────────────────
34
  print(f"Loading model: {MODEL_ID}")
 
44
 
45
  print("Model loaded and ready.")
46
 
47
+ # ── Server instance ────────────────────────────────────────────────────────
48
+ app = Server(title="Abliterated Chat Server")
49
+
50
 
51
  # ═══════════════════════════════════════════════════════════════════════════
52
  # HELPERS
 
60
  return 0
61
  try:
62
  ids = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt")
 
63
  return int(ids["input_ids"].shape[-1]) if hasattr(ids, "input_ids") else int(ids.shape[-1])
64
  except Exception:
65
  return 0
66
 
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  def _truncate_history(messages: list, max_tokens: int) -> list:
69
+ """Drop oldest non-system pairs until the templated conversation fits."""
70
  while len(messages) > 1:
71
  try:
72
  ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
 
82
  return messages
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  # ═══════════════════════════════════════════════════════════════════════════
86
+ # STREAMING API ENDPOINT — yields dicts, Gradio turns them into SSE
87
  # ═══════════════════════════════════════════════════════════════════════════
88
+ @app.api(name="chat_stream")
89
  @spaces.GPU(duration=60)
90
+ def chat_stream(
91
+ message: str,
92
+ history_json: str = "[]", # JSON-encoded message list
93
+ system_prompt: str = DEFAULT_SYSTEM_PROMPT,
 
94
  max_new_tokens: int = 256,
95
  temperature: float = 0.7,
96
  top_p: float = 0.9,
97
+ ) -> Generator[dict, None, None]:
98
+ """
99
+ Streams a chat completion. Yields:
100
+ - {"type": "token", "content": <partial reply so far>}
101
+ - {"type": "done", "content": <full reply>}
102
+ - {"type": "error", "content": <message>}
103
+ """
104
+ import json
105
+ try:
106
+ history = json.loads(history_json or "[]")
107
+ except Exception:
108
+ yield {"type": "error", "content": "Invalid history JSON"}
109
  return
110
 
111
+ if not message or not message.strip():
112
+ yield {"type": "error", "content": "Empty message"}
 
113
  return
114
 
115
+ # Append the new user turn
116
+ history = list(history)
117
+ history.append({"role": "user", "content": message})
118
 
119
+ # Build and truncate the full message list
120
  messages = []
121
  if system_prompt and system_prompt.strip():
122
  messages.append({"role": "system", "content": system_prompt})
123
  messages.extend(history)
124
  messages = _truncate_history(messages, MAX_CONTEXT_TOKENS)
125
 
126
+ # Apply chat template
127
  encoded = tokenizer.apply_chat_template(
128
  messages, add_generation_prompt=True, return_tensors="pt"
129
  ).to(model.device)
130
 
131
+ streamer = TextIteratorStreamer(
132
+ tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10.0
133
+ )
134
 
135
  gen_kwargs = dict(
136
  **encoded,
 
151
  thread = Thread(target=model.generate, kwargs=gen_kwargs)
152
  thread.start()
153
 
154
+ # Stream tokens
 
 
155
  partial = ""
156
  for text in streamer:
157
  partial += text
158
+ yield {"type": "token", "content": partial}
159
 
160
  thread.join()
161
+ yield {"type": "done", "content": partial}
 
162
 
163
 
164
  # ═══════════════════════════════════════════════════════════════════════════
165
+ # TOKEN COUNTING API (for the context meter in the UI)
166
  # ═══════════════════════════════════════════════════════════════════════════
167
+ @app.api(name="count_tokens")
168
+ def count_tokens(history_json: str = "[]", system_prompt: str = DEFAULT_SYSTEM_PROMPT) -> dict:
169
+ """Returns the current token usage of the given history."""
170
+ import json
171
+ try:
172
+ history = json.loads(history_json or "[]")
173
+ except Exception:
174
+ return {"tokens": 0, "max": MAX_CONTEXT_TOKENS}
175
+ n = _count_tokens(history, system_prompt)
176
+ return {"tokens": n, "max": MAX_CONTEXT_TOKENS}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
 
179
  # ═══════════════════════════════════════════════════════════════════════════
180
+ # STATIC FRONTEND ROUTES
181
  # ═══════════════════════════════════════════════════════════════════════════
182
+ @app.get("/", response_class=HTMLResponse)
183
+ async def homepage():
184
+ """Serve ui.html as the root page."""
185
+ return (FRONTEND_DIR / "ui.html").read_text(encoding="utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
 
 
 
 
 
 
187
 
188
+ @app.get("/ui.html")
189
+ async def ui_file():
190
+ return FileResponse(FRONTEND_DIR / "ui.html", media_type="text/html")
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
+ @app.get("/health")
194
+ async def health():
195
+ return {"status": "ok", "model": MODEL_ID}
 
 
 
 
 
 
 
 
 
196
 
 
 
 
 
 
197
 
198
+ # ═══════════════════════════════════════════════════════════════════════════
199
+ # LAUNCH
200
+ # ═══════════════════════════════════════════════════════════════════════════
201
+ if __name__ == "__main__":
202
+ app.launch(
203
+ server_name="0.0.0.0",
204
+ server_port=7860,
205
+ share=False,
206
+ ssr_mode=False,
207
+ prevent_thread_lock=False,
208
+ )