lauren-cw commited on
Commit
c309296
·
verified ·
1 Parent(s): 6484003

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +424 -0
app.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """DASS心理模型(Q12).ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/19ATyW5Lb692QV2Gk2I0rlsbeSQNwEDnQ
8
+
9
+ 建立環境
10
+ """
11
+
12
+ import pandas as pd
13
+ import matplotlib.pyplot as plt
14
+ import numpy as np
15
+ import gradio as gr
16
+ import sklearn
17
+ import pickle
18
+ import joblib
19
+ import time
20
+ import os
21
+ import json
22
+ import gspread
23
+
24
+
25
+ from sklearn.model_selection import train_test_split, RandomizedSearchCV
26
+ from sklearn.compose import ColumnTransformer
27
+ from sklearn.preprocessing import OneHotEncoder, StandardScaler
28
+ from sklearn.pipeline import Pipeline
29
+ from sklearn.linear_model import LogisticRegression
30
+ from sklearn.metrics import classification_report, confusion_matrix, f1_score, accuracy_score, precision_score, balanced_accuracy_score
31
+ from sklearn.ensemble import RandomForestClassifier
32
+ from lightgbm import LGBMClassifier
33
+ from AutoPreprocess import AutoPreprocess
34
+ from google.oauth2.service_account import Credentials
35
+ from datetime import datetime, timezone, timedelta
36
+
37
+ """Gradio 使用者介面"""
38
+
39
+ # 載入模型
40
+ import pickle
41
+ model_path = os.path.abspath("DASS_model.bin")
42
+
43
+ with open(model_path, "rb") as f:
44
+ model = pickle.load(f)
45
+ model
46
+
47
+ """定義歷史紀錄功能"""
48
+
49
+ def update_history(current_result_1, current_result_2, history_list):
50
+ """
51
+ current_result_1 & 2: 來自 predict_risk 的兩個回傳值 (HTML 字串)
52
+ history_list: 來自 gr.State 的現有紀錄列表
53
+ """
54
+
55
+ # 獲取當前時間,格式為:2023-10-27 14:30:05
56
+ now = datetime.now(tw_timezone).strftime("%Y-%m-%d %H:%M:%S")
57
+
58
+ # 組合這次的結果 (假設你想存這兩個 outputs 的組合)
59
+ new_entry = f"""
60
+ <div style="border-bottom: 2px solid #eee; padding-bottom: 20px; margin-bottom: 20px;">
61
+ <div style="font-size: 18px; color: #666; margin-bottom: 10px; font-weight: bold;">
62
+ 🕒 測驗時間:{now}
63
+ </div>
64
+
65
+ <div style="
66
+ display: flex;
67
+ flex-direction: row;
68
+ justify-content: space-between;
69
+ align-items: flex-start;
70
+ gap: 20px;
71
+ border-bottom: 1px dashed #ccc;
72
+ padding-bottom: 15px;
73
+ margin-bottom: 15px;
74
+ width: 100%;">
75
+
76
+ <div style="flex: 1;">{current_result_1}</div>
77
+ <div style="flex: 1;">{current_result_2}</div>
78
+
79
+ </div>
80
+ </div>
81
+ """
82
+
83
+ # 將新紀錄放在最前面 (置頂)
84
+ history_list.insert(0, new_entry)
85
+
86
+ # 組合所有歷史紀錄,並整體縮小 80%
87
+ # 使用 zoom: 0.8 或 transform 達到字體與版面同時縮小的效果
88
+ combined_html = f"""
89
+ <div style="zoom: 0.8; -moz-transform: scale(0.8); -moz-transform-origin: 0 0;">
90
+ {"".join(history_list)}
91
+ </div>
92
+ """
93
+
94
+ return combined_html, history_list
95
+
96
+ """定義儲存測試資料的功能
97
+
98
+ Google Sheet 連線
99
+ """
100
+
101
+ import os
102
+ import json
103
+ from datetime import datetime, timezone, timedelta
104
+ import gspread
105
+ from google.oauth2.service_account import Credentials
106
+
107
+ # 1. 設定 Google Sheets 存取權限
108
+ scope = ['https://www.googleapis.com/auth/spreadsheets',
109
+ 'https://www.googleapis.com/auth/drive']
110
+ google_json = os.environ.get("DASS_JSON")
111
+
112
+ # 全域變數預設為 None
113
+ sheet = None
114
+
115
+ if google_json:
116
+ try:
117
+ info = json.loads(google_json)
118
+ creds = Credentials.from_service_account_info(info, scopes=scope)
119
+ client = gspread.authorize(creds)
120
+ sheet = client.open("DASS使用者測試資料").sheet1 # 存於檔案的第一張工作表
121
+ print("✅ Google Sheets 連線成功")
122
+ except Exception as e:
123
+ print(f"❌ Google Sheets 初始化失敗: {e}")
124
+ else:
125
+ print("⚠️ 找不到 DASS_JSON 環境變數")
126
+
127
+ def save_to_google_sheets(inputs, a_score, d_score, s_score, t_score, score):
128
+
129
+ if sheet is None:
130
+ print("⚠️ 試算表未連線,跳過儲存步驟")
131
+ return
132
+
133
+ try:
134
+
135
+ # 設定台灣時區
136
+ tw_timezone = timezone(timedelta(hours=8))
137
+ # 1. 拆分資料:前 3 個是基本資料,後面剩下的 (*rest) 是 12 題答案
138
+ user_info = inputs[:3] # 取得前三個:姓名, 年齡, 性別
139
+ q_answers = inputs[3:] # 取得剩下的 12 題
140
+ now = datetime.now(tw_timezone).strftime("%Y-%m-%d %H:%M:%S")
141
+
142
+ # 2. 準備要儲存的資料字典
143
+ row_to_add = [
144
+ now, # 欄位 A: 測試時間
145
+ user_info[0], # 欄位 B: 性別
146
+ user_info[1], # 欄位 C: 年齡
147
+ user_info[2], # 欄位 D: 家庭人數
148
+ a_score, # 欄位 E: 焦慮分數
149
+ d_score, # 欄位 F: 憂鬱分數
150
+ s_score, # 欄位 G: 壓力分數
151
+ t_score, # 欄位 H: 總體分數
152
+ score # 欄位 I: 整體程度 (標籤)
153
+ ]
154
+
155
+ row_to_add.extend(q_answers) # 加入 Q1-Q12 (J欄以後)
156
+
157
+ # 4. 追加到試算表最後一行
158
+ sheet.append_row(row_to_add)
159
+ print(f"✨ 資料已成功存入試算表: {now}")
160
+
161
+ except Exception as e:
162
+ print(f"❌ 寫入資料時發生錯誤: {e}")
163
+
164
+ """定義重新測驗功能"""
165
+
166
+ # 清空函數:回傳與輸入組件數量相同的 None (15個:gen, age, family + 12個問題)
167
+ def clear_all():
168
+ # 15個輸入(gen, age, family, q1~q12) + 2個即時結果
169
+ return [None] * 15 + ["", ""]
170
+
171
+ """定義主要測試功能"""
172
+
173
+ def predict_risk(gen, age, family, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12):
174
+ inputs = [gen, age, family, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12]
175
+
176
+ # 檢查是否有任何一個選項是 None (未按)
177
+ if any(v is None or v == "" for v in inputs):
178
+ return "<div style=\"color: red; font-weight: bold;\">⚠️測驗載入有誤:請確保每一題都已填答或查看填答格式是否正確。</div>", ""
179
+
180
+
181
+ # 1. 跑進度條 (需確保函式參數有 progress=gr.Progress())
182
+ progress = gr.Progress()
183
+ progress(0, desc="模型計算中...")
184
+
185
+ try:
186
+ # 2. 將 12 個輸入整理成模型認得的 DataFrame
187
+ # 欄位名稱必須與訓練時完全相同
188
+ cols = ["gender", "age", "familysize", "Q2A", "Q4A", "Q19A", "Q20A", "Q28A", "Q21A", "Q26A", "Q37A", "Q42A", "Q11A", "Q12A", "Q27A"]
189
+ input_df = pd.DataFrame([[gen, age, family, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12]], columns=cols)
190
+
191
+ progress(0.5, desc="正在分析數據...")
192
+ time.sleep(0.5) # 模擬運算時間
193
+
194
+ # 3. 使用模型 model 進行預測
195
+ score = model.predict(input_df)[0]
196
+ progress(1.0, desc="計算完成!")
197
+
198
+
199
+ # 4. 定義風險標籤
200
+ if score == 0:
201
+ label = "低度風險"
202
+ color = "#91cd92" # 綠色
203
+ elif score == 1:
204
+ label = "中度風險"
205
+ color = "#f59e0b" # 橘色
206
+ elif score == 2:
207
+ label = "高度風險"
208
+ color = "#ef4444" # 紅色
209
+ else:
210
+ label = "計算結果有誤,請重新測試。"
211
+
212
+ # 定義類別分數條
213
+ a_score = (q1 + q2 + q3 + q4 + q5)
214
+ d_score = (q6 + q7 + q8 + q9)
215
+ s_score = (q10 + q11 + q12)
216
+ t_score = a_score + d_score + s_score
217
+ max_val = 36
218
+
219
+ def make_bar(label, score, max_val, color):
220
+ percent = (score / max_val) * 100
221
+ return f"""
222
+ <div style="margin-bottom: 10px;">
223
+ <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
224
+ <span style="font-weight: bold;">{label}</span>
225
+ </div>
226
+ <div style="background-color: #e0e0e0; border-radius: 10px; height: 12px; width: 100%;">
227
+ <div style="background-color: {color}; width: {percent}%; height: 100%; border-radius: 10px;"></div>
228
+ </div>
229
+ </div>
230
+ """
231
+
232
+ # 5. 準備回傳內容
233
+ # 總分與風險標籤
234
+ result_score = f"""
235
+ <div style="text-align: center; font-family: sans-serif;">
236
+ <h2 style="color: #313230;">您的預測結果為</h2>
237
+ <h1 style="font-size: 60px; color: {color}; margin: 0;">
238
+ {label}
239
+ </h1>
240
+ <h1 style="font-size: 20px; color: #bbbbc2; margin: 0;">
241
+ {t_score}/36
242
+ </h1>
243
+ </div>
244
+ """
245
+
246
+ # 類別分數條
247
+ label_html = f"""
248
+ <div style="padding: 20px; background: white; border-radius: 10px; border: 1px solid #ddd;">
249
+ <h2 style="color: #313230;margin-top: 0; margin-bottom: 15px;">各面向之比重</h2>
250
+ {make_bar("焦慮 (Anxiety)", a_score, max_val, "#fccb42")}
251
+ {make_bar("憂鬱 (Depression)", d_score, max_val, "#6dc8fe")}
252
+ {make_bar("壓力 (Stress)", s_score, max_val, "#fb6d6d")}
253
+ </div>
254
+ """
255
+
256
+ # 儲存測試資料
257
+ try:
258
+ save_to_google_sheets(inputs, a_score, d_score, s_score, t_score, score)
259
+ except Exception as sheet_err:
260
+ print(f"Sheet Error: {sheet_err}")
261
+
262
+
263
+ progress(1.0, desc="完成")
264
+
265
+ return result_score, label_html, error_message
266
+
267
+ except Exception as e:
268
+ return f"<div style='color: red;'>系統錯誤: {str(e)}</div>", "Error"
269
+
270
+ # 設定主題色
271
+
272
+ theme = gr.themes.Default(
273
+ primary_hue="amber",
274
+ secondary_hue="amber",
275
+ ).set(
276
+ body_background_fill="#fffbeb"
277
+ )
278
+
279
+ # 線上主題調色器
280
+ # gr.themes.builder()
281
+
282
+ # 介面編排
283
+
284
+ #按鈕及面板格式設定
285
+ custom_css = """
286
+ #my_green_btn {
287
+ background-color: #91cd92 !important;
288
+ color: white !important;
289
+ border: none;
290
+ }
291
+ #my_green_btn:hover {
292
+ background-color: #72a473 !important; /* 滑鼠懸停時變深 */
293
+ }
294
+
295
+ #my_white_btn {
296
+ background-color: #ffffff !important;
297
+ color: black !important;
298
+ border: 1px solid #e4e4e7;
299
+ }
300
+
301
+ #my_white_btn:hover {
302
+ background-color: #e4e4e7 !important;
303
+ color: black !important; /* 滑鼠懸停時變深 */
304
+ }
305
+
306
+
307
+ .my-custom-panel {
308
+ background-color: #fffef8 !important;
309
+ border: 2px solid #e4e4e7 !important;
310
+ padding: 20px;
311
+ border-radius: 15px;
312
+ }
313
+
314
+ #history_panel .label-wrap span {
315
+ font-weight: bold !important;
316
+ }
317
+ """
318
+
319
+ with gr.Blocks(theme=theme, css=custom_css) as demo:
320
+
321
+ # 建立 Session 狀態 (開啟瀏覽器時初始化為空列表)
322
+ history_state = gr.State([])
323
+
324
+ # 標題及說明
325
+ gr.Markdown("")
326
+ gr.HTML(f"""
327
+ <div style="text-align: center; font-family: sans-serif;">
328
+ <h2 style="font-size: 32px; color: #313230; margin: 0;">🌿心理健康風險程度測試📝</h2>
329
+ </div>
330
+ """)
331
+ gr.HTML(f"""
332
+ <div style="text-align: center; font-family: sans-serif;">
333
+ <h2 style="font-size: 18px; color: #313230; margin: 0;">歡迎來到心理健康風險程度測試環境!<br>
334
+ 本測驗將透過12題問答,替您在5分鐘內簡單計算出潛在的心理健康風險程度。<br>
335
+ 請輕鬆填答,無須思慮過度,測驗愉快!</h2>
336
+ </div>
337
+ """)
338
+
339
+ with gr.Column(variant="panel", elem_classes="my-custom-panel"):
340
+
341
+ # 輸入區塊1(人口靜態欄位)
342
+ gr.Markdown("## Step 1. 請輸入基本資訊")
343
+ with gr.Row():
344
+ with gr.Column():
345
+ name = gr.Textbox(label="暱稱")
346
+ gen = gr.Dropdown(choices=["男", "女", "其他"],
347
+ label="性別",
348
+ value=[])
349
+ with gr.Column():
350
+ age = gr.Number(label="年齡 (僅限填寫數字)", value ="")
351
+ family = gr.Number(label="家庭人數 (僅限填寫數字)", value ="")
352
+
353
+
354
+ # 輸入區塊2(測驗題)
355
+ gr.Markdown("")
356
+ gr.Markdown("## Step 2. 請依自身狀態選擇符合的答案")
357
+ q1 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
358
+ label="Q1.我感覺到口乾舌燥。")
359
+ q2 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
360
+ label="Q2.我感到呼吸困難(例如:在沒有體力勞動的情況下,呼吸過度急促或喘不過氣)。")
361
+ q3 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
362
+ label="Q3.在氣溫不高或沒有體力勞動的情況下,我明顯地流汗(例如:手汗)。")
363
+ q4 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
364
+ label="Q4.我無緣無故地感到害怕。")
365
+ q5 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
366
+ label="Q5.我覺得自己接近恐慌發作的邊緣。")
367
+ q6 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
368
+ label="Q6.我覺得生命沒什麼意義/價值。")
369
+ q7 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
370
+ label="Q7.我感到垂頭喪氣、情緒低落。")
371
+ q8 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
372
+ label="Q8.我覺得未來毫無希望。")
373
+ q9 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
374
+ label="Q9.我發現自己很難打起精神主動去做事。")
375
+ q10 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
376
+ label="Q10.我發現自己很容易變得心煩意亂。")
377
+ q11 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
378
+ label="Q11.我覺得自己消耗了大量的神經能量(處於高度緊繃狀態)。")
379
+ q12 = gr.Radio([("從不", 0), ("偶爾", 1), ("經常", 2), ("總是", 3)],
380
+ label="Q12.我發現自己非常易怒(容易焦躁)。")
381
+
382
+
383
+ # 確認送出按鈕
384
+ sub_button = gr.Button("確認送出", elem_id="my_green_btn")
385
+ # 重新測驗按鈕
386
+ with gr.Row():
387
+ btn_reset = gr.Button("重新測驗", elem_id="my_white_btn")
388
+
389
+ # 輸出測試結果
390
+ with gr.Row():
391
+ out_html = gr.HTML()
392
+ out_label = gr.HTML()
393
+
394
+
395
+ # --- 新增:歷史紀錄呈現區域 ---
396
+ with gr.Accordion("查看歷史紀錄", open=False, elem_id="history_panel"):
397
+ history_display = gr.HTML(value="目前尚無測驗紀錄")
398
+
399
+
400
+ # 按鈕設定
401
+ # 1. 確認送出
402
+ sub_button.click(fn=predict_risk,
403
+ inputs= [gen, age, family, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12],
404
+ outputs= [out_html, out_label]
405
+ ).then(
406
+ fn=update_history,
407
+ inputs=[out_html, out_label, history_state],
408
+ outputs=[history_display, history_state])
409
+
410
+ # 2. 重新測驗 (清空所有輸入與輸出)
411
+ # 注意:outputs 必須包含所有輸入的組件
412
+ btn_reset.click(
413
+ fn=lambda: [None]*15 + ["", ""],
414
+ inputs=None,
415
+ outputs=[gen, age, family, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, out_html , out_label]
416
+ )
417
+
418
+ gr.Markdown("## 免責聲明")
419
+ gr.Markdown("""本測驗結果僅供參考,非屬正規醫療檢驗範疇。
420
+ 若對於自身狀況有任何疑慮,敬請尋求正規專業醫療協助!♡第四組關心您♡""")
421
+
422
+ demo.launch(share=True)
423
+
424
+ # 如需免費永久托管,需在終端機模式執行「gradio deploy」部署到 Hugging Face Spaces。