MichaelChou0806 commited on
Commit
e7827e3
·
verified ·
1 Parent(s): 651f96b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -180
app.py CHANGED
@@ -1,196 +1,52 @@
1
  import os
2
- import time
3
  import smtplib
4
  from email.mime.text import MIMEText
5
- from pydub import AudioSegment
6
- from openai import OpenAI
7
  import gradio as gr
 
8
 
9
- # ========================
10
- # 🔐 設定區
11
- # ========================
12
- PASSWORD = os.getenv("APP_PASSWORD", "defaultpass")
13
- MAX_SIZE = 25 * 1024 * 1024
14
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
15
- ALERT_EMAIL = os.getenv("ALERT_EMAIL")
16
- ALERT_PASS = os.getenv("ALERT_PASS")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- # ========================
19
- # 📧 寄信通知
20
- # ========================
21
- def send_alert_email(session_id, reason):
22
- """當使用者嘗試過多或被鎖定時寄出警報郵件"""
23
- if not ALERT_EMAIL or not ALERT_PASS:
24
- return
25
- msg = MIMEText(
26
- f"Session {session_id} 已被鎖定。\n原因:{reason}\n時間:{time.ctime()}",
27
- "plain",
28
- "utf-8"
29
- )
30
- msg["Subject"] = "⚠️ 語音轉錄系統警報"
31
- msg["From"] = ALERT_EMAIL
32
- msg["To"] = ALERT_EMAIL
33
  try:
34
  with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
35
- server.login(ALERT_EMAIL, ALERT_PASS)
36
- server.sendmail(ALERT_EMAIL, ALERT_EMAIL, msg.as_string())
37
- print(f"✅ 已寄出警報郵件至 {ALERT_EMAIL}")
38
  except Exception as e:
39
- print(f"❌ 寄信失敗:{e}")
40
-
41
- # ========================
42
- # ⚔️ 防暴力破解
43
- # ========================
44
- MAX_FAILED_IN_WINDOW = 10
45
- WINDOW_SECONDS = 24 * 3600
46
- LOCK_DURATION_SECONDS = 24 * 3600
47
- SHORT_BURST_LIMIT = 5
48
- SHORT_BURST_SECONDS = 60
49
-
50
- attempts = {}
51
- locked = {}
52
-
53
- def _now(): return int(time.time())
54
-
55
- def prune_old_attempts(sid):
56
- cutoff = _now() - WINDOW_SECONDS
57
- if sid in attempts:
58
- attempts[sid] = [t for t in attempts[sid] if t >= cutoff]
59
- if not attempts[sid]:
60
- del attempts[sid]
61
-
62
- def check_lock(sid):
63
- if sid in locked:
64
- if _now() < locked[sid]:
65
- remain = locked[sid] - _now()
66
- return True, f"🔒 已被鎖定,請 {remain // 60} 分鐘後再試。"
67
- else:
68
- locked.pop(sid, None)
69
- attempts.pop(sid, None)
70
- prune_old_attempts(sid)
71
- cnt = len(attempts.get(sid, []))
72
- if cnt >= MAX_FAILED_IN_WINDOW:
73
- locked[sid] = _now() + LOCK_DURATION_SECONDS
74
- send_alert_email(sid, f"密碼錯誤 {cnt} 次,鎖定24小時")
75
- return True, f"🔒 嘗試過多,已鎖定 24 小時。"
76
- return False, ""
77
-
78
- def record_failed_attempt(sid):
79
- now = _now()
80
- attempts.setdefault(sid, []).append(now)
81
- prune_old_attempts(sid)
82
- recent_cutoff = now - SHORT_BURST_SECONDS
83
- recent = [t for t in attempts[sid] if t >= recent_cutoff]
84
- if len(recent) >= SHORT_BURST_LIMIT:
85
- locked[sid] = now + 300
86
- send_alert_email(sid, "短時間內多次錯誤,鎖定5分鐘")
87
- return len(attempts[sid]), "⚠️ 多次快速嘗試,暫時鎖定5分鐘。"
88
- return len(attempts[sid]), ""
89
-
90
- def clear_attempts(sid):
91
- attempts.pop(sid, None)
92
- locked.pop(sid, None)
93
-
94
- # ========================
95
- # 🎧 音訊轉錄
96
- # ========================
97
- def split_audio_if_needed(path):
98
- size = os.path.getsize(path)
99
- if size <= MAX_SIZE:
100
- return [path]
101
- audio = AudioSegment.from_file(path)
102
- num = int(size / MAX_SIZE) + 1
103
- chunk_ms = len(audio) / num
104
- files = []
105
- for i in range(num):
106
- start, end = int(i * chunk_ms), int((i + 1) * chunk_ms)
107
- chunk = audio[start:end]
108
- fn = f"chunk_{i+1}.wav"
109
- chunk.export(fn, format="wav")
110
- files.append(fn)
111
- return files
112
-
113
- def transcribe_core(path, model):
114
- chunks = split_audio_if_needed(path)
115
- txts = []
116
- for f in chunks:
117
- with open(f, "rb") as af:
118
- res = client.audio.transcriptions.create(model=model, file=af, response_format="text")
119
- txts.append(res)
120
- full = "\n".join(txts)
121
- res = client.chat.completions.create(
122
- model="gpt-4o-mini",
123
- messages=[{"role": "user", "content": f"請用繁體中文摘要以下內容:\n{full}"}],
124
- temperature=0.4,
125
- )
126
- summ = res.choices[0].message.content.strip()
127
- return full, summ
128
-
129
- # ========================
130
- # 💬 主流程
131
- # ========================
132
- def transcribe_with_password(session_id, password, file, model_choice):
133
- locked_flag, msg = check_lock(session_id)
134
- if locked_flag:
135
- return msg, "", "", None, None
136
- if password != PASSWORD:
137
- cnt, msg2 = record_failed_attempt(session_id)
138
- return msg2 or f"密碼錯誤(第 {cnt} 次)", "", "", None, None
139
- if not file:
140
- return "請上傳音訊檔。", "", "", None, None
141
- clear_attempts(session_id)
142
- full, summ = transcribe_core(file, model_choice)
143
- open("transcript_full.txt", "w", encoding="utf-8").write(full)
144
- open("transcript_summary.txt", "w", encoding="utf-8").write(summ)
145
- return "✅ 轉錄完成", full, summ, "transcript_full.txt", "transcript_summary.txt"
146
-
147
- def ask_about_transcript(full_text, q):
148
- if not full_text.strip():
149
- return "⚠️ 尚未有轉錄內容"
150
- if not q.strip():
151
- return "請輸入問題"
152
- prompt = f"以下是轉錄內容:\n{full_text}\n\n問題:{q}\n請用繁體中文回答。"
153
- res = client.chat.completions.create(
154
- model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], temperature=0.6)
155
- return res.choices[0].message.content.strip()
156
-
157
- # ========================
158
- # 🌐 Gradio 介面
159
- # ========================
160
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
161
- gr.Markdown("## 🎧 語音轉錄與摘要工具(防暴力破解+郵件警報)")
162
-
163
- session_state = gr.State(value=None)
164
-
165
- with gr.Row():
166
- password_input = gr.Textbox(label="輸入密碼", type="password")
167
- model_choice = gr.Dropdown(["whisper-1", "gpt-4o-mini-transcribe"], value="whisper-1", label="選擇模型")
168
 
169
- audio_input = gr.Audio(type="filepath", label="上傳音訊 (.m4a, .aac, .wav)")
170
- transcribe_btn = gr.Button("開始轉錄與摘要 🚀")
171
- status_box = gr.Textbox(label="狀態", interactive=False)
172
- transcript_box = gr.Textbox(label="完整轉錄文字", lines=10)
173
- summary_box = gr.Textbox(label="摘要結果", lines=10)
174
 
175
- with gr.Row():
176
- download_full = gr.File(label="下載完整轉錄文字 (.txt)")
177
- download_summary = gr.File(label="下載摘要結果 (.txt)")
178
 
179
- with gr.Accordion("💬 進一步問 AI", open=False):
180
- user_q = gr.Textbox(label="輸入問題", lines=2)
181
- ask_btn = gr.Button("詢問 AI 🤔")
182
- ai_reply = gr.Textbox(label="AI 回覆", lines=6)
183
 
184
- def init_session():
185
- import uuid
186
- return str(uuid.uuid4())
187
- demo.load(init_session, None, session_state)
188
 
189
- transcribe_btn.click(
190
- transcribe_with_password,
191
- [session_state, password_input, audio_input, model_choice],
192
- [status_box, transcript_box, summary_box, download_full, download_summary],
193
- )
194
- ask_btn.click(ask_about_transcript, [transcript_box, user_q], [ai_reply])
195
 
196
  demo.launch()
 
1
  import os
 
2
  import smtplib
3
  from email.mime.text import MIMEText
 
 
4
  import gradio as gr
5
+ import time
6
 
7
+ def check_env_and_email():
8
+ results = []
9
+ # 檢查環境變數
10
+ app_pw = os.getenv("APP_PASSWORD")
11
+ openai_key = os.getenv("OPENAI_API_KEY")
12
+ alert_email = os.getenv("ALERT_EMAIL")
13
+ alert_pass = os.getenv("ALERT_PASS")
14
+
15
+ results.append("===== 🔍 環境變數檢查 =====")
16
+ results.append(f"APP_PASSWORD = {app_pw}")
17
+ results.append(f"OPENAI_API_KEY = {'✅ 已設定' if openai_key else '❌ 未設定'}")
18
+ results.append(f"ALERT_EMAIL = {alert_email}")
19
+ results.append(f"ALERT_PASS = {'✅ 已設定' if alert_pass else '❌ 未設定'}")
20
+
21
+ # 測試寄信
22
+ if not alert_email or not alert_pass:
23
+ results.append("\n⚠️ 無法測試寄信,請先設定 ALERT_EMAIL 與 ALERT_PASS。")
24
+ return "\n".join(results)
25
+
26
+ results.append("\n===== 📧 開始測試寄信 =====")
27
+ msg = MIMEText(f"這是一封來自 Hugging Face Space 的測試信。\n時間:{time.ctime()}", "plain", "utf-8")
28
+ msg["Subject"] = "✅ 測試信件:Hugging Face SMTP 設定成功"
29
+ msg["From"] = alert_email
30
+ msg["To"] = alert_email
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  try:
33
  with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
34
+ server.login(alert_email, alert_pass)
35
+ server.sendmail(alert_email, alert_email, msg.as_string())
36
+ results.append(f"✅ 測試成功!郵件已寄出至 {alert_email}")
37
  except Exception as e:
38
+ results.append(f"❌ 寄信失敗:{e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ return "\n".join(results)
 
 
 
 
41
 
 
 
 
42
 
43
+ with gr.Blocks(title="環境與寄信測試工具") as demo:
44
+ gr.Markdown("## 🧪 Hugging Face Space 環境變數與 Gmail 寄信測試")
45
+ gr.Markdown("此頁面用來確認 Variables 是否正確設定,以及 Gmail SMTP 是否可用。")
 
46
 
47
+ test_button = gr.Button("🚀 開始測試")
48
+ output_box = gr.Textbox(label="結果輸出", lines=15)
 
 
49
 
50
+ test_button.click(fn=check_env_and_email, outputs=output_box)
 
 
 
 
 
51
 
52
  demo.launch()