Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,50 @@
|
|
1 |
import gradio as gr
|
2 |
-
from
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
"""
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
):
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
demo = gr.ChatInterface(
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
)
|
61 |
|
62 |
-
|
63 |
-
if __name__ == "__main__":
|
64 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
3 |
+
|
4 |
+
# 初始化模型
|
5 |
+
emotion_analyzer = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
|
6 |
+
safety_checker = pipeline("text-classification", model="meta-llama/Meta-Llama-Guard-2-8B")
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
8 |
+
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
|
9 |
+
|
10 |
+
# 预定义安全回复模板
|
11 |
+
SAFE_RESPONSES = {
|
12 |
+
"crisis": "我注意到您可能需要专业帮助,建议立即联系心理咨询师或拨打心理援助热线。",
|
13 |
+
"sadness": "听起来您最近压力很大,要不要试试深呼吸或听舒缓音乐?",
|
14 |
+
"anger": "情绪波动很正常,我们可以一起分析问题的根源。"
|
15 |
+
}
|
16 |
+
|
17 |
+
def generate_response(user_input, history):
|
18 |
+
# 安全检查
|
19 |
+
safety_result = safety_checker(user_input)[0]
|
20 |
+
if safety_result["label"] == "UNSAFE":
|
21 |
+
return SAFE_RESPONSES["crisis"]
|
22 |
+
|
23 |
+
# 情绪分析
|
24 |
+
emotion = emotion_analyzer(user_input)[0]["label"]
|
25 |
+
|
26 |
+
# 根据情绪选择生成策略
|
27 |
+
if emotion in ["sadness", "fear"]:
|
28 |
+
return SAFE_RESPONSES.get(emotion, "我理解您的感受,可以多聊聊吗?")
|
29 |
+
|
30 |
+
# 生成对话
|
31 |
+
inputs = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors="pt")
|
32 |
+
reply_ids = model.generate(
|
33 |
+
inputs,
|
34 |
+
max_length=1000,
|
35 |
+
pad_token_id=tokenizer.eos_token_id,
|
36 |
+
no_repeat_ngram_size=3 # 避免重复
|
37 |
+
)
|
38 |
+
response = tokenizer.decode(reply_ids[:, inputs.shape[-1]:][0], skip_special_tokens=True)
|
39 |
+
|
40 |
+
return response
|
41 |
+
|
42 |
+
# 创建Gradio界面
|
|
|
|
|
|
|
43 |
demo = gr.ChatInterface(
|
44 |
+
fn=generate_response,
|
45 |
+
examples=["最近总是失眠", "感觉没有人理解我", "考试成绩让我很焦虑"],
|
46 |
+
title="青少年心理健康助手",
|
47 |
+
description="请随时倾诉您的感受,我会尽力帮助您调整情绪。"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
)
|
49 |
|
50 |
+
demo.launch()
|
|
|
|