CoolFace
Apppublic

xuanwsx/ErlangshenModel

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
app.py183 linesDownload Raw Back to root
1import os2from datetime import datetime3import pandas as pd4import matplotlib.pyplot as plt5import gradio as gr6from transformers import pipeline7 8DATA_FILE = "stress_data.csv"9 10if not os.path.exists(DATA_FILE):11    df = pd.DataFrame(columns=["date","score"])12    df.to_csv(DATA_FILE,index=False)13 14emotion_model = pipeline(15    "sentiment-analysis",16    model="IDEA-CCNL/Erlangshen-Roberta-110M-Sentiment"17)18 19stress_keywords = [20"焦慮","壓力","煩","崩潰","絕望","害怕","痛苦",21"失眠","難過","憂鬱","無助","失落","疲倦"22]23 24crisis_keywords = [25"不想活","活不下去","想死","絕望","沒有意義"26]27 28violence_keywords = [29"放火","殺人","報復","傷害"30]31 32def stress_level(score):33 34    if score < 30:35        return "低壓力"36    elif score < 60:37        return "中等壓力"38    elif score < 80:39        return "高壓力"40    else:41        return "非常高壓力"42 43def detect_source(text):44 45    if any(w in text for w in ["考試","成績","作業","報告"]):46        return "學業壓力"47 48    if any(w in text for w in ["朋友","同學","關係"]):49        return "人際壓力"50 51    if any(w in text for w in ["未來","人生","迷茫"]):52        return "未來焦慮"53 54    if any(w in text for w in ["失眠","睡不著"]):55        return "睡眠壓力"56 57    return "一般壓力"58 59advice = {60 61"學業壓力":{62"relief":"使用番茄鐘學習法,每40分鐘休息10分鐘",63"food":"增加B群食物:雞蛋、全穀類",64"life":"建立讀書計畫"65},66 67"人際壓力":{68"relief":"與信任的人聊聊",69"food":"Omega-3食物:魚類、堅果",70"life":"安排放鬆時間"71},72 73"未來焦慮":{74"relief":"寫下短期目標",75"food":"富含鎂食物:香蕉、菠菜",76"life":"每天運動30分鐘"77},78 79"睡眠壓力":{80"relief":"睡前冥想或深呼吸",81"food":"避免咖啡因",82"life":"睡前一小時不要滑手機"83},84 85"一般壓力":{86"relief":"散步或慢跑",87"food":"均衡飲食",88"life":"保持規律作息"89}90}91 92def analyze(text):93 94    result = emotion_model(text)[0]95 96    if result["label"] == "negative":97        ai_score = result["score"] * 10098    else:99        ai_score = (1-result["score"]) * 40100 101    kw_score = 0102 103    for w in stress_keywords:104        if w in text:105            kw_score += 8106 107    for w in crisis_keywords:108        if w in text:109            kw_score += 40110 111    for w in violence_keywords:112        if w in text:113            kw_score += 30114 115    total_score = min(ai_score*0.7 + kw_score*0.3 ,100)116 117    level = stress_level(total_score)118 119    source = detect_source(text)120 121    adv = advice[source]122 123    df = pd.read_csv(DATA_FILE)124 125    new = pd.DataFrame({126        "date":[datetime.now().strftime("%Y-%m-%d %H:%M")],127        "score":[total_score]128    })129 130    df = pd.concat([df,new],ignore_index=True)131 132    df.to_csv(DATA_FILE,index=False)133 134    fig, ax = plt.subplots()135 136    df["date"] = pd.to_datetime(df["date"])137 138    ax.plot(df["date"],df["score"],marker="o")139 140    ax.set_title("Stress Trend")141 142    fig.autofmt_xdate()143 144    avg = df["score"].mean()145 146    dashboard = f"""147目前壓力:{total_score:.1f}148平均壓力:{avg:.1f}149"""150 151    result_text = f"""152壓力分數:{total_score:.1f}153 154壓力等級:{level}155 156壓力來源:{source}157 158減壓方式:{adv['relief']}159 160飲食建議:{adv['food']}161 162生活建議:{adv['life']}163"""164 165    return result_text,dashboard,fig166 167interface = gr.Interface(168 169fn=analyze,170 171inputs=gr.Textbox(lines=4,label="輸入你的心情"),172 173outputs=[174gr.Textbox(label="分析結果"),175gr.Textbox(label="壓力儀表板"),176gr.Plot(label="壓力趨勢")177],178 179title="AI心理壓力分析系統"180 181)182 183interface.launch()