Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import gradio as grimport pandas as pdimport matplotlib.pyplot as pltfrom datetime import datetimeimport os# CSV 檔案位置(HF Spaces 用 /tmp 保留 session 期間)DATA_FILE = "/tmp/stress_data.csv"# 模擬分析函數def analyze(text):# 假設這裡是你的 BERT 或 transformers 分析import randomstress_score = random.randint(0, 100) # 模擬壓力值result_text = f"文字分析結果:壓力指數 {stress_score}"# 儲存資料save_data(text, stress_score)# 生成趨勢圖fig = plot_trend()return result_text, fig# 儲存資料到 CSVdef save_data(text, score):now = datetime.now()df = pd.DataFrame([[now, text, score]], columns=["timestamp", "text", "stress"])if os.path.exists(DATA_FILE):df.to_csv(DATA_FILE, mode="a", header=False, index=False)else:df.to_csv(DATA_FILE, index=False)# 畫心理壓力趨勢圖def plot_trend():fig, ax = plt.subplots(figsize=(6,3))if not os.path.exists(DATA_FILE):ax.text(0.5, 0.5, "暫無資料", ha='center', va='center')ax.set_axis_off()return figdf = pd.read_csv(DATA_FILE)df['timestamp'] = pd.to_datetime(df['timestamp'])ax.plot(df['timestamp'], df['stress'], marker='o', linestyle='-')ax.set_title("心理壓力趨勢")ax.set_xlabel("時間")ax.set_ylabel("壓力指數")ax.grid(True)plt.xticks(rotation=30)return fig# 清除資料功能def reset_data():if os.path.exists(DATA_FILE):os.remove(DATA_FILE)fig, ax = plt.subplots()ax.text(0.5, 0.5, "資料已重置", ha='center', va='center')ax.set_axis_off()return "資料已重置", fig# Gradio 介面with gr.Blocks() as demo:gr.Markdown("# 中文心理壓力分析器")gr.Markdown("BERT + 關鍵詞分析總壓力值。輸入你的心情,查看文字分析與心理壓力趨勢。")with gr.Row():text_input = gr.Textbox(label="和我聊聊吧",placeholder="說說今天的心情或煩惱...",lines=5)with gr.Row():submit_btn = gr.Button("分析")reset_btn = gr.Button("重置資料")result_text = gr.Textbox(label="分析結果")trend_plot = gr.Plot(label="心理壓力趨勢")# 按鈕觸發事件submit_btn.click(analyze, inputs=text_input, outputs=[result_text, trend_plot])reset_btn.click(reset_data, inputs=None, outputs=[result_text, trend_plot])demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import gradio as grimport pandas as pdimport matplotlib.pyplot as pltfrom datetime import datetimeimport osfrom transformers import pipeline# CSV 檔案位置DATA_FILE = "/tmp/stress_data.csv"# 初始化 transformers 分析 pipeline# 這裡使用假設的中文情緒分析模型# 如果你有心理壓力專用模型,替換 model="你的模型名稱"classifier = pipeline("text-classification",model="uer/roberta-base-finetuned-chinanews-chinese", # 中文分類範例device=-1 # CPU;若有 GPU,可設成 0)# 分析函數def analyze(text):# 用模型預測pred = classifier(text)[0] # 回傳 dict: {'label': 'POSITIVE', 'score': 0.95}label = pred['label']score = pred['score']# 假設我們把正面 -> 壓力低,負面 -> 壓力高if label in ["POSITIVE", "positive"]:stress_score = int((1 - score) * 100) # 正面越高,壓力越低else:stress_score = int(score * 100) # 負面越高,壓力越高result_text = f"文字分析結果:情緒標籤 {label},壓力指數 {stress_score}"# 儲存資料save_data(text, stress_score)# 生成趨勢圖fig = plot_trend()return result_text, fig# 以下函數維持不變def save_data(text, score):now = datetime.now()df = pd.DataFrame([[now, text, score]], columns=["timestamp", "text", "stress"])if os.path.exists(DATA_FILE):df.to_csv(DATA_FILE, mode="a", header=False, index=False)else:df.to_csv(DATA_FILE, index=False)def plot_trend():fig, ax = plt.subplots(figsize=(6,3))if not os.path.exists(DATA_FILE):ax.text(0.5, 0.5, "暫無資料", ha='center', va='center')ax.set_axis_off()return figdf = pd.read_csv(DATA_FILE)df['timestamp'] = pd.to_datetime(df['timestamp'])ax.plot(df['timestamp'], df['stress'], marker='o', linestyle='-')ax.set_title("心理壓力趨勢")ax.set_xlabel("時間")ax.set_ylabel("壓力指數")ax.grid(True)plt.xticks(rotation=30)return figdef reset_data():if os.path.exists(DATA_FILE):os.remove(DATA_FILE)fig, ax = plt.subplots()ax.text(0.5, 0.5, "資料已重置", ha='center', va='center')ax.set_axis_off()return "資料���重置", fig# Gradio 介面維持不變with gr.Blocks() as demo:gr.Markdown("# 中文心理壓力分析器")gr.Markdown("""這是一款結合 BERT 深度學習模型與關鍵詞分析的心理壓力評估工具。輸入中文文字,它就能分析文字隱含的心理壓力,並生成壓力分數與趨勢圖。""")with gr.Row():text_input = gr.Textbox(label="和我聊聊吧",placeholder="說說今天的心情或煩惱...",lines=5)with gr.Row():submit_btn = gr.Button("分析")reset_btn = gr.Button("重置資料")result_text = gr.Textbox(label="分析結果")trend_plot = gr.Plot(label="心理壓力趨勢")submit_btn.click(analyze, inputs=text_input, outputs=[result_text, trend_plot])reset_btn.click(reset_data, inputs=None, outputs=[result_text, trend_plot])demo.launch()
app.py+99-82