MichaelChou0806 commited on
Commit
e185c54
·
verified ·
1 Parent(s): 8702506

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -1
app.py CHANGED
@@ -3,36 +3,54 @@ import gradio as gr
3
  from fastapi import FastAPI, UploadFile, Form, HTTPException
4
  from openai import OpenAI
5
 
 
 
 
 
6
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
7
  APP_PASSWORD = os.getenv("APP_PASSWORD", None)
8
 
9
  # 初始化 FastAPI
10
  api = FastAPI()
11
 
 
 
 
 
12
  @api.post("/api/transcribe")
13
  async def transcribe_api(file: UploadFile, token: str = Form(...)):
 
 
14
  if not APP_PASSWORD:
 
15
  raise HTTPException(status_code=500, detail="Server misconfiguration: APP_PASSWORD not set.")
16
  if token != APP_PASSWORD:
 
17
  raise HTTPException(status_code=403, detail="Forbidden: invalid token.")
18
 
 
19
  contents = await file.read()
20
  temp_path = f"/tmp/{file.filename}"
21
  with open(temp_path, "wb") as f:
22
  f.write(contents)
 
23
 
 
24
  with open(temp_path, "rb") as audio_file:
25
  transcript = client.audio.transcriptions.create(
26
  model="whisper-1",
27
  file=audio_file
28
  )
29
  text = transcript.text.strip()
 
30
 
 
31
  summary_prompt = f"請幫我用中文摘要以下內容:\n\n{text}"
32
  summary = client.chat.completions.create(
33
  model="gpt-4o-mini",
34
  messages=[{"role": "user", "content": summary_prompt}]
35
  ).choices[0].message.content.strip()
 
36
 
37
  return {"text": text, "summary": summary}
38
 
@@ -41,6 +59,8 @@ async def transcribe_api(file: UploadFile, token: str = Form(...)):
41
  def transcribe_ui(audio):
42
  if audio is None:
43
  return "請上傳音訊檔案", ""
 
 
44
  with open(audio, "rb") as f:
45
  transcript = client.audio.transcriptions.create(
46
  model="whisper-1",
@@ -65,8 +85,12 @@ demo = gr.Interface(
65
  description="上傳 LINE 語音或其他音訊,進行自動轉錄與摘要"
66
  )
67
 
68
- # 用不同變數名防止覆蓋
69
  app = gr.mount_gradio_app(api, demo, path="/")
70
 
 
 
 
 
71
  if __name__ == "__main__":
72
  demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
 
3
  from fastapi import FastAPI, UploadFile, Form, HTTPException
4
  from openai import OpenAI
5
 
6
+ print("===== 🚀 啟動中,開始檢查環境變數 =====")
7
+ print("OPENAI_API_KEY:", "✅ 已設定" if os.getenv("OPENAI_API_KEY") else "❌ 未設定")
8
+ print("APP_PASSWORD:", "✅ 已設定" if os.getenv("APP_PASSWORD") else "❌ 未設定")
9
+
10
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
11
  APP_PASSWORD = os.getenv("APP_PASSWORD", None)
12
 
13
  # 初始化 FastAPI
14
  api = FastAPI()
15
 
16
+ @api.get("/ping")
17
+ async def ping():
18
+ return {"status": "ok", "APP_PASSWORD": bool(APP_PASSWORD)}
19
+
20
  @api.post("/api/transcribe")
21
  async def transcribe_api(file: UploadFile, token: str = Form(...)):
22
+ print(f"📥 收到請求:file={file.filename}, token={token}")
23
+
24
  if not APP_PASSWORD:
25
+ print("❌ APP_PASSWORD 未設定")
26
  raise HTTPException(status_code=500, detail="Server misconfiguration: APP_PASSWORD not set.")
27
  if token != APP_PASSWORD:
28
+ print("❌ token 驗證失敗")
29
  raise HTTPException(status_code=403, detail="Forbidden: invalid token.")
30
 
31
+ # 儲存臨時音訊檔
32
  contents = await file.read()
33
  temp_path = f"/tmp/{file.filename}"
34
  with open(temp_path, "wb") as f:
35
  f.write(contents)
36
+ print(f"✅ 音訊檔已儲存: {temp_path}")
37
 
38
+ # 語音轉文字
39
  with open(temp_path, "rb") as audio_file:
40
  transcript = client.audio.transcriptions.create(
41
  model="whisper-1",
42
  file=audio_file
43
  )
44
  text = transcript.text.strip()
45
+ print(f"🗣️ 轉錄結果: {text[:80]}...")
46
 
47
+ # 生成摘要
48
  summary_prompt = f"請幫我用中文摘要以下內容:\n\n{text}"
49
  summary = client.chat.completions.create(
50
  model="gpt-4o-mini",
51
  messages=[{"role": "user", "content": summary_prompt}]
52
  ).choices[0].message.content.strip()
53
+ print(f"🧠 AI 摘要完成。")
54
 
55
  return {"text": text, "summary": summary}
56
 
 
59
  def transcribe_ui(audio):
60
  if audio is None:
61
  return "請上傳音訊檔案", ""
62
+ print(f"🎧 Gradio 收到音訊: {audio}")
63
+
64
  with open(audio, "rb") as f:
65
  transcript = client.audio.transcriptions.create(
66
  model="whisper-1",
 
85
  description="上傳 LINE 語音或其他音訊,進行自動轉錄與摘要"
86
  )
87
 
88
+ # 掛載 Gradio 到 FastAPI
89
  app = gr.mount_gradio_app(api, demo, path="/")
90
 
91
+ print("===== ✅ FastAPI 路徑註冊完成 =====")
92
+ for route in app.routes:
93
+ print("👉", route.path)
94
+
95
  if __name__ == "__main__":
96
  demo.launch(server_name="0.0.0.0", server_port=7860, share=True)