QiLi520 commited on
Commit
cd6b68c
·
verified ·
1 Parent(s): 4841140

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -60
app.py CHANGED
@@ -1,64 +1,50 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
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
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
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()