012ywu commited on
Commit
30fa119
·
1 Parent(s): 4cc3570

Initial commit

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import time
3
+ from typing import Iterator, List, Tuple, Any
4
+
5
+ # 模拟流式API响应
6
+ def simulate_stream_response(message: str) -> Iterator[str]:
7
+ """模拟API的流式响应"""
8
+ response = f"收到您的问题:'{message}'。这是一个模拟的AI助手回答,一个字一个字地流式输出。我正在尝试模仿Claude的回答风格,希望这个演示能够满足您的需求。"
9
+
10
+ for char in response:
11
+ yield char
12
+ time.sleep(0.05) # 模拟打字延迟
13
+
14
+ # 修复后的流式响应函数
15
+ def stream_response(message: str, history: List[Tuple[str, str]]) -> Iterator[List[Tuple[str, Any]]]:
16
+ """流式响应并格式化为Gradio Chatbot需要的格式"""
17
+ # 添加用户消息到历史
18
+ history = history + [(message, "")]
19
+
20
+ # 流式更新AI的回复
21
+ bot_message = ""
22
+ response_generator = simulate_stream_response(message)
23
+
24
+ for token in response_generator:
25
+ bot_message += token
26
+ # 更新最后一条消息的AI回复部分
27
+ updated_history = history.copy()
28
+ updated_history[-1] = (message, bot_message)
29
+ yield updated_history
30
+
31
+ # 创建自定义CSS样式
32
+ custom_css = """
33
+ .gradio-container {
34
+ font-family: 'Arial', sans-serif;
35
+ }
36
+ """
37
+
38
+ # 创建Gradio界面
39
+ def create_demo():
40
+ with gr.Blocks(css=custom_css) as demo:
41
+ gr.Markdown("# AI 问答助手")
42
+ gr.Markdown("这是一个类似Claude的问答系统,会逐字流式输出回答")
43
+
44
+ chatbot = gr.Chatbot(
45
+ show_label=False,
46
+ height=500,
47
+ )
48
+
49
+ with gr.Row():
50
+ msg = gr.Textbox(
51
+ show_label=False,
52
+ placeholder="在这里输入您的问题...",
53
+ scale=9
54
+ )
55
+ submit = gr.Button("发送", scale=1)
56
+
57
+ with gr.Accordion("示例问题", open=False):
58
+ examples = gr.Examples(
59
+ examples=[
60
+ ["材料管道中的数据预处理步骤有哪些?"],
61
+ ["如何优化材料管道的计算效率?"],
62
+ ["材料管道中常用的特征工程方法有哪些?"],
63
+ ["如何在材料管道中整合机器学习模型?"],
64
+ ["材料管道中的高通量筛选技术有什么优势?"]
65
+ ],
66
+ inputs=msg
67
+ )
68
+
69
+ # 设置提交操作
70
+ submit_event = submit.click(
71
+ fn=stream_response,
72
+ inputs=[msg, chatbot],
73
+ outputs=[chatbot],
74
+ queue=True
75
+ )
76
+
77
+ # 清空输入框
78
+ submit_event.then(
79
+ fn=lambda: "",
80
+ inputs=None,
81
+ outputs=[msg]
82
+ )
83
+
84
+ # 回车键提交
85
+ msg.submit(
86
+ fn=stream_response,
87
+ inputs=[msg, chatbot],
88
+ outputs=[chatbot],
89
+ queue=True
90
+ ).then(
91
+ fn=lambda: "",
92
+ inputs=None,
93
+ outputs=[msg]
94
+ )
95
+
96
+ return demo
97
+
98
+ # 创建演示
99
+ demo = create_demo()
100
+
101
+ # 主函数
102
+ if __name__ == "__main__":
103
+ demo.queue() # 启用队列处理
104
+ demo.launch() # 移除自定义参数,Hugging Face会自动处理
105
+ else:
106
+ # 用于Hugging Face Spaces部署
107
+ demo.queue()