hsuwill000 commited on
Commit
6ae9b07
·
verified ·
1 Parent(s): cf81fc9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -42
app.py CHANGED
@@ -1,25 +1,26 @@
1
  #!/usr/bin/env python3
2
- # gradio_timer_streaming.py ── Gradio 4.x 相容,真正逐字即時顯示
 
3
  import gradio as gr
4
  import requests, json, re, sys, time
5
  from threading import Thread
6
- from queue import Queue
7
 
8
  URL = "http://localhost:8000/v1/chat/completions"
9
  HEADERS = {"Content-Type": "application/json"}
10
 
11
  def sanitize(text: str):
12
- return re.sub(r"[\ud800-\udfff]", "", text) # ✅ 修正:補上右括號
13
 
14
  history_openai = []
15
- output_queue = Queue()
16
  current_chatbot = []
 
17
 
18
- def stream_to_queue(user_input: str):
 
19
  user_input = sanitize(user_input)
20
  history_openai.append({"role": "user", "content": user_input})
21
  payload = {"messages": history_openai, "stream": True, "temperature": 0.7}
22
- assistant = ""
23
  try:
24
  with requests.post(URL, headers=HEADERS, json=payload, stream=True, timeout=60) as r:
25
  r.raise_for_status()
@@ -41,54 +42,36 @@ def stream_to_queue(user_input: str):
41
  except json.JSONDecodeError:
42
  byte_buf = line_bytes + b"\n" + byte_buf
43
  continue
44
- if tok is None:
45
- continue
46
- assistant += tok
47
- output_queue.put(assistant)
48
- time.sleep(0.02)
49
- history_openai.append({"role": "assistant", "content": sanitize(assistant)})
50
  except Exception as e:
51
- output_queue.put(f"请求失败: {e}")
52
 
53
  def user_submit(user_msg, chatbot):
54
- global current_chatbot
55
  current_chatbot = chatbot + [[user_msg, ""]]
56
- Thread(target=stream_to_queue, args=(user_msg,), daemon=True).start()
 
57
  return "", current_chatbot
58
 
59
- def poll_queue():
60
- global current_chatbot
61
- try:
62
- latest = output_queue.get_nowait()
63
- current_chatbot[-1][1] = latest
64
- except:
65
- pass
66
  return current_chatbot
67
 
68
  with gr.Blocks() as demo:
69
- gr.Markdown("## Chat8000 Lab2 - 真正即時逐字顯示(Gradio 4.x 相容)")
70
  chatbot = gr.Chatbot()
71
  msg = gr.Textbox(show_label=False, placeholder="輸入訊息後按 Enter")
72
  msg.submit(user_submit, [msg, chatbot], [msg, chatbot], queue=False)
73
 
74
- timer = gr.Timer(value=0.03, active=True)
75
- timer.tick(poll_queue, outputs=chatbot)
76
 
77
  if __name__ == "__main__":
78
- if len(sys.argv) > 1 and sys.argv[1] == "--cli":
79
- print("=== CLI 模式(支援 Streaming)===")
80
- while True:
81
- try:
82
- prompt = input(">>> ").strip()
83
- except (KeyboardInterrupt, EOFError):
84
- break
85
- if prompt.lower() in {"exit", "quit"}:
86
- break
87
- if not prompt:
88
- continue
89
- for token in stream_chat(prompt):
90
- print(token, end="", flush=True)
91
- print()
92
- print("\n再见!")
93
- else:
94
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  #!/usr/bin/env python3
2
+ # gradio_timer_buffer.py ── 定時刷新目前 buffer 的所有 token
3
+
4
  import gradio as gr
5
  import requests, json, re, sys, time
6
  from threading import Thread
 
7
 
8
  URL = "http://localhost:8000/v1/chat/completions"
9
  HEADERS = {"Content-Type": "application/json"}
10
 
11
  def sanitize(text: str):
12
+ return re.sub(r"[\ud800-\udfff]", "", text)
13
 
14
  history_openai = []
 
15
  current_chatbot = []
16
+ assistant_buffer = "" # 累積 token
17
 
18
+ def stream_to_buffer(user_input: str):
19
+ global assistant_buffer
20
  user_input = sanitize(user_input)
21
  history_openai.append({"role": "user", "content": user_input})
22
  payload = {"messages": history_openai, "stream": True, "temperature": 0.7}
23
+ assistant_buffer = ""
24
  try:
25
  with requests.post(URL, headers=HEADERS, json=payload, stream=True, timeout=60) as r:
26
  r.raise_for_status()
 
42
  except json.JSONDecodeError:
43
  byte_buf = line_bytes + b"\n" + byte_buf
44
  continue
45
+ if tok:
46
+ assistant_buffer += tok
47
+ # 完整回答放入 history
48
+ history_openai.append({"role": "assistant", "content": sanitize(assistant_buffer)})
 
 
49
  except Exception as e:
50
+ assistant_buffer = f"请求失败: {e}"
51
 
52
  def user_submit(user_msg, chatbot):
53
+ global current_chatbot, assistant_buffer
54
  current_chatbot = chatbot + [[user_msg, ""]]
55
+ assistant_buffer = ""
56
+ Thread(target=stream_to_buffer, args=(user_msg,), daemon=True).start()
57
  return "", current_chatbot
58
 
59
+ def flush_buffer():
60
+ """每 0.3 秒刷新 Chatbot,顯示目前 buffer 的所有 token"""
61
+ global current_chatbot, assistant_buffer
62
+ if not current_chatbot:
63
+ return current_chatbot
64
+ current_chatbot[-1][1] = assistant_buffer
 
65
  return current_chatbot
66
 
67
  with gr.Blocks() as demo:
68
+ gr.Markdown("## Chat8000 Lab2 - 0.3 秒刷新 buffer 顯示")
69
  chatbot = gr.Chatbot()
70
  msg = gr.Textbox(show_label=False, placeholder="輸入訊息後按 Enter")
71
  msg.submit(user_submit, [msg, chatbot], [msg, chatbot], queue=False)
72
 
73
+ timer = gr.Timer(value=0.3, active=True) # 每 0.3 秒刷新一次
74
+ timer.tick(flush_buffer, outputs=chatbot)
75
 
76
  if __name__ == "__main__":
77
+ demo.launch(server_name="0.0.0.0", server_port=7860)