xuanwsx commited on
Commit
32f5fdd
·
verified ·
1 Parent(s): 8e6cde5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -82
app.py CHANGED
@@ -1,83 +1,100 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import matplotlib.pyplot as plt
4
- from datetime import datetime
5
- import os
6
-
7
- # CSV 檔案位置(HF Spaces 用 /tmp 保留 session 期間)
8
- DATA_FILE = "/tmp/stress_data.csv"
9
-
10
- # 模擬分析函數
11
- def analyze(text):
12
- # 假設這裡是你 BERT 或 transformers 分析
13
- import random
14
- stress_score = random.randint(0, 100) # 模擬壓力值
15
- result_text = f"文字分析結果:壓力指數 {stress_score}"
16
-
17
- # 儲存資料
18
- save_data(text, stress_score)
19
-
20
- # 生成趨勢圖
21
- fig = plot_trend()
22
-
23
- return result_text, fig
24
-
25
- # 儲存資料到 CSV
26
- def save_data(text, score):
27
- now = datetime.now()
28
- df = pd.DataFrame([[now, text, score]], columns=["timestamp", "text", "stress"])
29
- if os.path.exists(DATA_FILE):
30
- df.to_csv(DATA_FILE, mode="a", header=False, index=False)
31
- else:
32
- df.to_csv(DATA_FILE, index=False)
33
-
34
- # 畫心理壓力趨勢圖
35
- def plot_trend():
36
- fig, ax = plt.subplots(figsize=(6,3))
37
- if not os.path.exists(DATA_FILE):
38
- ax.text(0.5, 0.5, "暫無資料", ha='center', va='center')
39
- ax.set_axis_off()
40
- return fig
41
-
42
- df = pd.read_csv(DATA_FILE)
43
- df['timestamp'] = pd.to_datetime(df['timestamp'])
44
- ax.plot(df['timestamp'], df['stress'], marker='o', linestyle='-')
45
- ax.set_title("心理壓力趨勢")
46
- ax.set_xlabel("時間")
47
- ax.set_ylabel("壓力指數")
48
- ax.grid(True)
49
- plt.xticks(rotation=30)
50
- return fig
51
-
52
- # 清除資料功能
53
- def reset_data():
54
- if os.path.exists(DATA_FILE):
55
- os.remove(DATA_FILE)
56
- fig, ax = plt.subplots()
57
- ax.text(0.5, 0.5, "資料已重置", ha='center', va='center')
58
- ax.set_axis_off()
59
- return "資料已重置", fig
60
-
61
- # Gradio 介面
62
- with gr.Blocks() as demo:
63
- gr.Markdown("# 中文心理壓力分析器")
64
- gr.Markdown("BERT + 關鍵詞分析總壓力值。輸入你的心情,查看文字分析與心理壓力趨勢。")
65
-
66
- with gr.Row():
67
- text_input = gr.Textbox(
68
- label="和我聊聊吧",
69
- placeholder="說說今天的心情或煩惱...",
70
- lines=5
71
- )
72
- with gr.Row():
73
- submit_btn = gr.Button("分析")
74
- reset_btn = gr.Button("重置資料")
75
-
76
- result_text = gr.Textbox(label="分析結果")
77
- trend_plot = gr.Plot(label="心理壓力趨勢")
78
-
79
- # 按鈕觸發事件
80
- submit_btn.click(analyze, inputs=text_input, outputs=[result_text, trend_plot])
81
- reset_btn.click(reset_data, inputs=None, outputs=[result_text, trend_plot])
82
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  demo.launch()
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from datetime import datetime
5
+ import os
6
+ from transformers import pipeline
7
+
8
+ # CSV 檔案位置
9
+ DATA_FILE = "/tmp/stress_data.csv"
10
+
11
+ # 初始化 transformers 分析 pipeline
12
+ # 這裡使用假設中文情緒分析模型
13
+ # 如果你有心理壓力專用模型,替換 model="你的模型名稱"
14
+ classifier = pipeline(
15
+ "text-classification",
16
+ model="uer/roberta-base-finetuned-chinanews-chinese", # 中文分類範例
17
+ device=-1 # CPU;若有 GPU,可設成 0
18
+ )
19
+
20
+ # 分析函數
21
+ def analyze(text):
22
+ # 用模型預測
23
+ pred = classifier(text)[0] # 回傳 dict: {'label': 'POSITIVE', 'score': 0.95}
24
+
25
+ label = pred['label']
26
+ score = pred['score']
27
+
28
+ # 假設我們把正面 -> 壓力低,負面 -> 壓力高
29
+ if label in ["POSITIVE", "positive"]:
30
+ stress_score = int((1 - score) * 100) # 正面越高,壓力越低
31
+ else:
32
+ stress_score = int(score * 100) # 負面越高,壓力越高
33
+
34
+ result_text = f"文字分析結果:情緒標籤 {label},壓力指數 {stress_score}"
35
+
36
+ # 儲存資料
37
+ save_data(text, stress_score)
38
+
39
+ # 生成趨勢圖
40
+ fig = plot_trend()
41
+
42
+ return result_text, fig
43
+
44
+ # 以下函數維持不變
45
+ def save_data(text, score):
46
+ now = datetime.now()
47
+ df = pd.DataFrame([[now, text, score]], columns=["timestamp", "text", "stress"])
48
+ if os.path.exists(DATA_FILE):
49
+ df.to_csv(DATA_FILE, mode="a", header=False, index=False)
50
+ else:
51
+ df.to_csv(DATA_FILE, index=False)
52
+
53
+ def plot_trend():
54
+ fig, ax = plt.subplots(figsize=(6,3))
55
+ if not os.path.exists(DATA_FILE):
56
+ ax.text(0.5, 0.5, "暫無資料", ha='center', va='center')
57
+ ax.set_axis_off()
58
+ return fig
59
+
60
+ df = pd.read_csv(DATA_FILE)
61
+ df['timestamp'] = pd.to_datetime(df['timestamp'])
62
+ ax.plot(df['timestamp'], df['stress'], marker='o', linestyle='-')
63
+ ax.set_title("心理壓力趨勢")
64
+ ax.set_xlabel("時間")
65
+ ax.set_ylabel("壓力指數")
66
+ ax.grid(True)
67
+ plt.xticks(rotation=30)
68
+ return fig
69
+
70
+ def reset_data():
71
+ if os.path.exists(DATA_FILE):
72
+ os.remove(DATA_FILE)
73
+ fig, ax = plt.subplots()
74
+ ax.text(0.5, 0.5, "資料已重置", ha='center', va='center')
75
+ ax.set_axis_off()
76
+ return "資料���重置", fig
77
+
78
+ # Gradio 介面維持不變
79
+ with gr.Blocks() as demo:
80
+ gr.Markdown("# 中文心理壓力分析器")
81
+ gr.Markdown("""這是一款結合 BERT 深度學習模型與關鍵詞分析的心理壓力評估工具。
82
+ 輸入中文文字,它就能分析文字隱含的心理壓力,並生成壓力分數與趨勢圖。""")
83
+
84
+ with gr.Row():
85
+ text_input = gr.Textbox(
86
+ label="和我聊聊吧",
87
+ placeholder="說說今天的心情或煩惱...",
88
+ lines=5
89
+ )
90
+ with gr.Row():
91
+ submit_btn = gr.Button("分析")
92
+ reset_btn = gr.Button("重置資料")
93
+
94
+ result_text = gr.Textbox(label="分析結果")
95
+ trend_plot = gr.Plot(label="心理壓力趨勢")
96
+
97
+ submit_btn.click(analyze, inputs=text_input, outputs=[result_text, trend_plot])
98
+ reset_btn.click(reset_data, inputs=None, outputs=[result_text, trend_plot])
99
+
100
  demo.launch()