Nafiul Huda commited on
Commit
3fa3c1c
·
verified ·
1 Parent(s): fb58181

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -88
app.py CHANGED
@@ -15,43 +15,37 @@ model = AutoModelForCausalLM.from_pretrained(
15
  )
16
 
17
 
18
- def to_str(content):
19
- if content is None:
20
  return ""
21
- if isinstance(content, str):
22
- return content
23
- if isinstance(content, (list, tuple)):
24
- parts = []
25
- for c in content:
26
- if isinstance(c, dict):
27
- parts.append(str(c.get("text", c.get("value", ""))))
28
- else:
29
- parts.append(str(c))
30
- return " ".join(parts)
31
- return str(content)
32
 
33
 
34
  def user_submit(message, history):
35
  if not message or not message.strip():
36
  return "", history
37
- return "", history + [{"role": "user", "content": message.strip()}]
 
 
38
 
39
 
40
  @torch.no_grad()
41
  def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking):
42
- if not history:
 
43
  yield history
44
  return
45
 
46
- last = history[-1] if isinstance(history[-1], dict) else {}
47
- if last.get("role") != "user":
48
- yield history
49
- return
50
 
51
  messages = []
52
- if system_prompt and str(system_prompt).strip():
53
- messages.append({"role": "system", "content": str(system_prompt).strip()})
54
-
55
  for turn in history:
56
  if not isinstance(turn, dict):
57
  continue
@@ -59,17 +53,18 @@ def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, e
59
  continue
60
  role = str(turn.get("role", ""))
61
  content = to_str(turn.get("content", ""))
62
- if role in ("user", "assistant", "system") and content:
63
  messages.append({"role": role, "content": content})
64
 
65
  try:
66
  text = tokenizer.apply_chat_template(
67
  messages, tokenize=False, add_generation_prompt=True,
68
- enable_thinking=bool(enable_thinking)
69
  )
70
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
71
  except Exception as e:
72
- yield history + [{"role": "assistant", "content": str(e)}]
 
73
  return
74
 
75
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
@@ -87,7 +82,14 @@ def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, e
87
 
88
  try:
89
  for chunk in streamer:
90
- raw = raw + str(chunk)
 
 
 
 
 
 
 
91
  has_o = "<think>" in raw
92
  has_c = "</think>" in raw
93
 
@@ -98,30 +100,26 @@ def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, e
98
  t_elapsed = time.time() - t0
99
 
100
  if not has_o:
101
- yield history + [
102
- {"role": "assistant", "content": raw.strip()}
103
- ]
104
  elif not has_c:
105
  sec = time.time() - t0
106
  thought = raw[raw.find("<think>") + 7:].strip()
107
  yield history + [
108
  {"role": "assistant", "content": thought,
109
- "metadata": {"title": "💭 Thinking (" + f"{sec:.1f}" + "s)..."}}
110
  ]
111
  else:
112
  m = re.search(r"<think>(.*?)</think>", raw, flags=re.DOTALL)
113
  thought = m.group(1).strip() if m else ""
114
  answer = raw[raw.find("</think>") + 8:].strip()
115
- new_msgs = []
116
- new_msgs.append(
117
- {"role": "assistant", "content": thought,
118
- "metadata": {"title": "💭 Thinking (" + f"{t_elapsed:.1f}" + "s)"}}
119
- )
120
  if answer:
121
- new_msgs.append({"role": "assistant", "content": answer})
122
- yield history + new_msgs
123
  except Exception as e:
124
- yield history + [{"role": "assistant", "content": str(e)}]
125
  finally:
126
  thread.join()
127
  del inputs
@@ -129,20 +127,30 @@ def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, e
129
 
130
  @torch.no_grad()
131
  def api_generate(message, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking):
 
 
 
 
 
 
 
 
 
 
132
  messages = []
133
- if system_prompt and str(system_prompt).strip():
134
- messages.append({"role": "system", "content": str(system_prompt).strip()})
135
- messages.append({"role": "user", "content": str(message)})
136
 
137
  text = tokenizer.apply_chat_template(
138
  messages, tokenize=False, add_generation_prompt=True,
139
- enable_thinking=bool(enable_thinking)
140
  )
141
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
142
  out = model.generate(
143
- **inputs, max_new_tokens=int(max_tokens),
144
- temperature=float(temperature), top_p=float(top_p),
145
- top_k=int(top_k), do_sample=True
146
  )
147
  decoded = tokenizer.decode(out[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
148
  del inputs
@@ -153,56 +161,58 @@ def api_generate(message, system_prompt, max_tokens, temperature, top_p, top_k,
153
  if m:
154
  thinking = m.group(1).strip()
155
  response = decoded[decoded.find("</think>") + 8:].strip()
 
 
156
 
157
  return {"thinking": thinking, "response": response}
158
 
159
 
160
  with gr.Blocks(title="Qwen3-0.6B") as demo:
161
- gr.Markdown("# Qwen3-0.6B")
162
 
163
- chatbot = gr.Chatbot(height=500)
164
-
165
- with gr.Row():
166
- msg = gr.Textbox(placeholder="Type a message...", scale=4,
167
- container=False, show_label=False)
168
- send = gr.Button("Send", variant="primary", scale=1)
169
-
170
- with gr.Accordion("Settings", open=False):
171
- system_prompt = gr.Textbox(label="System Prompt",
172
- placeholder="You are a helpful assistant.", lines=2)
173
- enable_thinking = gr.Checkbox(label="Enable Thinking", value=True)
174
  with gr.Row():
175
- max_tokens = gr.Slider(64, 4096, value=2048, step=64, label="Max Tokens")
176
- temperature = gr.Slider(0.05, 2.0, value=0.6, step=0.05, label="Temperature")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  with gr.Row():
178
- top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-P")
179
- top_k = gr.Slider(1, 100, value=20, step=1, label="Top-K")
180
-
181
- clear = gr.ClearButton([msg, chatbot], value="Clear")
182
-
183
- params = [chatbot, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking]
184
-
185
- msg.submit(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then(
186
- bot_respond, params, chatbot
187
- )
188
- send.click(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then(
189
- bot_respond, params, chatbot
190
- )
191
-
192
- api_btn = gr.Button(visible=False)
193
- api_msg = gr.Textbox(visible=False)
194
- api_sys = gr.Textbox(visible=False)
195
- api_max = gr.Number(visible=False, value=2048)
196
- api_temp = gr.Number(visible=False, value=0.6)
197
- api_topp = gr.Number(visible=False, value=0.95)
198
- api_topk = gr.Number(visible=False, value=20)
199
- api_think = gr.Checkbox(visible=False, value=True)
200
- api_out = gr.JSON(visible=False)
201
- api_btn.click(
202
- api_generate,
203
- inputs=[api_msg, api_sys, api_max, api_temp, api_topp, api_topk, api_think],
204
- outputs=api_out,
205
- api_name="generate"
206
- )
207
 
208
  demo.launch(ssr_mode=False)
 
15
  )
16
 
17
 
18
+ def to_str(val):
19
+ if val is None:
20
  return ""
21
+ if isinstance(val, str):
22
+ return val
23
+ if isinstance(val, (list, tuple)):
24
+ return " ".join(str(v.get("text", "")) if isinstance(v, dict) else str(v) for v in val)
25
+ return str(val)
 
 
 
 
 
 
26
 
27
 
28
  def user_submit(message, history):
29
  if not message or not message.strip():
30
  return "", history
31
+ history = list(history) if history else []
32
+ history.append({"role": "user", "content": message.strip()})
33
+ return "", history
34
 
35
 
36
  @torch.no_grad()
37
  def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking):
38
+ history = list(history) if history else []
39
+ if not history or history[-1].get("role") != "user":
40
  yield history
41
  return
42
 
43
+ thinking_on = bool(enable_thinking)
 
 
 
44
 
45
  messages = []
46
+ sp = to_str(system_prompt).strip()
47
+ if sp:
48
+ messages.append({"role": "system", "content": sp})
49
  for turn in history:
50
  if not isinstance(turn, dict):
51
  continue
 
53
  continue
54
  role = str(turn.get("role", ""))
55
  content = to_str(turn.get("content", ""))
56
+ if role in ("user", "assistant") and content:
57
  messages.append({"role": role, "content": content})
58
 
59
  try:
60
  text = tokenizer.apply_chat_template(
61
  messages, tokenize=False, add_generation_prompt=True,
62
+ enable_thinking=thinking_on
63
  )
64
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
65
  except Exception as e:
66
+ history.append({"role": "assistant", "content": "Error: " + str(e)})
67
+ yield history
68
  return
69
 
70
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
 
82
 
83
  try:
84
  for chunk in streamer:
85
+ raw += str(chunk)
86
+
87
+ if not thinking_on:
88
+ clean = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL)
89
+ clean = re.sub(r"<think>.*$", "", clean, flags=re.DOTALL)
90
+ yield history + [{"role": "assistant", "content": clean.strip()}]
91
+ continue
92
+
93
  has_o = "<think>" in raw
94
  has_c = "</think>" in raw
95
 
 
100
  t_elapsed = time.time() - t0
101
 
102
  if not has_o:
103
+ yield history + [{"role": "assistant", "content": raw.strip()}]
 
 
104
  elif not has_c:
105
  sec = time.time() - t0
106
  thought = raw[raw.find("<think>") + 7:].strip()
107
  yield history + [
108
  {"role": "assistant", "content": thought,
109
+ "metadata": {"title": "💭 Thinking (" + str(round(sec, 1)) + "s)..."}}
110
  ]
111
  else:
112
  m = re.search(r"<think>(.*?)</think>", raw, flags=re.DOTALL)
113
  thought = m.group(1).strip() if m else ""
114
  answer = raw[raw.find("</think>") + 8:].strip()
115
+ out = []
116
+ out.append({"role": "assistant", "content": thought,
117
+ "metadata": {"title": "💭 Thinking (" + str(round(t_elapsed, 1)) + "s)"}})
 
 
118
  if answer:
119
+ out.append({"role": "assistant", "content": answer})
120
+ yield history + out
121
  except Exception as e:
122
+ yield history + [{"role": "assistant", "content": "Error: " + str(e)}]
123
  finally:
124
  thread.join()
125
  del inputs
 
127
 
128
  @torch.no_grad()
129
  def api_generate(message, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking):
130
+ message = str(message) if message else ""
131
+ system_prompt = str(system_prompt).strip() if system_prompt else ""
132
+ max_tokens = int(float(max_tokens)) if max_tokens else 2048
133
+ temperature = float(temperature) if temperature else 0.6
134
+ top_p = float(top_p) if top_p else 0.95
135
+ top_k = int(float(top_k)) if top_k else 20
136
+ if isinstance(enable_thinking, str):
137
+ enable_thinking = enable_thinking.lower() in ("true", "1", "yes")
138
+ thinking_on = bool(enable_thinking)
139
+
140
  messages = []
141
+ if system_prompt:
142
+ messages.append({"role": "system", "content": system_prompt})
143
+ messages.append({"role": "user", "content": message})
144
 
145
  text = tokenizer.apply_chat_template(
146
  messages, tokenize=False, add_generation_prompt=True,
147
+ enable_thinking=thinking_on
148
  )
149
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
150
  out = model.generate(
151
+ **inputs, max_new_tokens=max_tokens,
152
+ temperature=temperature, top_p=top_p,
153
+ top_k=top_k, do_sample=True
154
  )
155
  decoded = tokenizer.decode(out[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
156
  del inputs
 
161
  if m:
162
  thinking = m.group(1).strip()
163
  response = decoded[decoded.find("</think>") + 8:].strip()
164
+ else:
165
+ response = re.sub(r"<think>.*?</think>", "", decoded, flags=re.DOTALL).strip()
166
 
167
  return {"thinking": thinking, "response": response}
168
 
169
 
170
  with gr.Blocks(title="Qwen3-0.6B") as demo:
 
171
 
172
+ with gr.Tab("💬 Chat"):
173
+ gr.Markdown("# Qwen3-0.6B")
174
+ chatbot = gr.Chatbot(height=500)
 
 
 
 
 
 
 
 
175
  with gr.Row():
176
+ msg = gr.Textbox(placeholder="Type a message...", scale=4,
177
+ container=False, show_label=False)
178
+ send_btn = gr.Button("Send", variant="primary", scale=1)
179
+ with gr.Accordion("Settings", open=False):
180
+ system_prompt = gr.Textbox(label="System Prompt",
181
+ placeholder="You are a helpful assistant.", lines=2)
182
+ enable_thinking = gr.Checkbox(label="Enable Thinking", value=True)
183
+ with gr.Row():
184
+ max_tokens = gr.Slider(64, 4096, value=2048, step=64, label="Max Tokens")
185
+ temperature = gr.Slider(0.05, 2.0, value=0.6, step=0.05, label="Temperature")
186
+ with gr.Row():
187
+ top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-P")
188
+ top_k = gr.Slider(1, 100, value=20, step=1, label="Top-K")
189
+ gr.ClearButton([msg, chatbot], value="Clear")
190
+
191
+ params = [chatbot, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking]
192
+ msg.submit(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then(
193
+ bot_respond, params, chatbot)
194
+ send_btn.click(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then(
195
+ bot_respond, params, chatbot)
196
+
197
+ with gr.Tab("🔌 API"):
198
+ gr.Markdown("# API Endpoint\nTest here or call via `gradio_client`")
199
+ api_msg = gr.Textbox(label="Message")
200
+ api_sys = gr.Textbox(label="System Prompt", value="")
201
  with gr.Row():
202
+ api_max = gr.Slider(64, 4096, value=2048, step=64, label="Max Tokens")
203
+ api_temp = gr.Slider(0.05, 2.0, value=0.6, step=0.05, label="Temperature")
204
+ with gr.Row():
205
+ api_topp = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-P")
206
+ api_topk = gr.Slider(1, 100, value=20, step=1, label="Top-K")
207
+ api_think = gr.Checkbox(label="Enable Thinking", value=True)
208
+ api_btn = gr.Button("Generate", variant="primary")
209
+ api_out = gr.JSON(label="Response")
210
+
211
+ api_btn.click(
212
+ api_generate,
213
+ inputs=[api_msg, api_sys, api_max, api_temp, api_topp, api_topk, api_think],
214
+ outputs=api_out,
215
+ api_name="generate"
216
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
  demo.launch(ssr_mode=False)