File size: 3,632 Bytes
8ea04ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import os
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
import gradio as gr
from transformers import pipeline

DATA_FILE = "stress_data.csv"

if not os.path.exists(DATA_FILE):
    df = pd.DataFrame(columns=["date","score"])
    df.to_csv(DATA_FILE,index=False)

emotion_model = pipeline(
    "sentiment-analysis",
    model="IDEA-CCNL/Erlangshen-Roberta-110M-Sentiment"
)

stress_keywords = [
"焦慮","壓力","煩","崩潰","絕望","害怕","痛苦",
"失眠","難過","憂鬱","無助","失落","疲倦"
]

crisis_keywords = [
"不想活","活不下去","想死","絕望","沒有意義"
]

violence_keywords = [
"放火","殺人","報復","傷害"
]

def stress_level(score):

    if score < 30:
        return "低壓力"
    elif score < 60:
        return "中等壓力"
    elif score < 80:
        return "高壓力"
    else:
        return "非常高壓力"

def detect_source(text):

    if any(w in text for w in ["考試","成績","作業","報告"]):
        return "學業壓力"

    if any(w in text for w in ["朋友","同學","關係"]):
        return "人際壓力"

    if any(w in text for w in ["未來","人生","迷茫"]):
        return "未來焦慮"

    if any(w in text for w in ["失眠","睡不著"]):
        return "睡眠壓力"

    return "一般壓力"

advice = {

"學業壓力":{
"relief":"使用番茄鐘學習法,每40分鐘休息10分鐘",
"food":"增加B群食物:雞蛋、全穀類",
"life":"建立讀書計畫"
},

"人際壓力":{
"relief":"與信任的人聊聊",
"food":"Omega-3食物:魚類、堅果",
"life":"安排放鬆時間"
},

"未來焦慮":{
"relief":"寫下短期目標",
"food":"富含鎂食物:香蕉、菠菜",
"life":"每天運動30分鐘"
},

"睡眠壓力":{
"relief":"睡前冥想或深呼吸",
"food":"避免咖啡因",
"life":"睡前一小時不要滑手機"
},

"一般壓力":{
"relief":"散步或慢跑",
"food":"均衡飲食",
"life":"保持規律作息"
}
}

def analyze(text):

    result = emotion_model(text)[0]

    if result["label"] == "negative":
        ai_score = result["score"] * 100
    else:
        ai_score = (1-result["score"]) * 40

    kw_score = 0

    for w in stress_keywords:
        if w in text:
            kw_score += 8

    for w in crisis_keywords:
        if w in text:
            kw_score += 40

    for w in violence_keywords:
        if w in text:
            kw_score += 30

    total_score = min(ai_score*0.7 + kw_score*0.3 ,100)

    level = stress_level(total_score)

    source = detect_source(text)

    adv = advice[source]

    df = pd.read_csv(DATA_FILE)

    new = pd.DataFrame({
        "date":[datetime.now().strftime("%Y-%m-%d %H:%M")],
        "score":[total_score]
    })

    df = pd.concat([df,new],ignore_index=True)

    df.to_csv(DATA_FILE,index=False)

    fig, ax = plt.subplots()

    df["date"] = pd.to_datetime(df["date"])

    ax.plot(df["date"],df["score"],marker="o")

    ax.set_title("Stress Trend")

    fig.autofmt_xdate()

    avg = df["score"].mean()

    dashboard = f"""
目前壓力:{total_score:.1f}
平均壓力:{avg:.1f}
"""

    result_text = f"""
壓力分數:{total_score:.1f}

壓力等級:{level}

壓力來源:{source}

減壓方式:{adv['relief']}

飲食建議:{adv['food']}

生活建議:{adv['life']}
"""

    return result_text,dashboard,fig

interface = gr.Interface(

fn=analyze,

inputs=gr.Textbox(lines=4,label="輸入你的心情"),

outputs=[
gr.Textbox(label="分析結果"),
gr.Textbox(label="壓力儀表板"),
gr.Plot(label="壓力趨勢")
],

title="AI心理壓力分析系統"

)

interface.launch()