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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -52
app.py CHANGED
@@ -1,71 +1,58 @@
1
  import os
2
- import gradio as gr
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
 
 
57
 
58
- # === Gradio 部分 ===
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",
67
- file=f
68
- )
69
  text = transcript.text.strip()
70
 
71
  summary_prompt = f"請幫我用中文摘要以下內容:\n\n{text}"
@@ -73,24 +60,18 @@ def transcribe_ui(audio):
73
  model="gpt-4o-mini",
74
  messages=[{"role": "user", "content": summary_prompt}]
75
  ).choices[0].message.content.strip()
76
-
77
  return text, summary
78
 
79
-
80
  demo = gr.Interface(
81
- fn=transcribe_ui,
82
  inputs=gr.Audio(type="filepath", label="上傳音訊"),
83
- outputs=[gr.Textbox(label="轉錄結果"), gr.Textbox(label="AI 摘要")],
84
- title="LINE 語音轉錄與摘要 (安全版)",
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)
 
 
1
  import os
 
2
  from fastapi import FastAPI, UploadFile, Form, HTTPException
3
+ from fastapi.responses import JSONResponse
4
  from openai import OpenAI
5
+ import gradio as gr
6
+
7
+ print("===== 🚀 啟動中 =====")
8
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
9
+ APP_PASSWORD = os.getenv("APP_PASSWORD")
10
 
11
+ print(f"OPENAI_API_KEY: {OPENAI_API_KEY[:8]}********") # 前8碼檢查
12
+ print(f"APP_PASSWORD: {APP_PASSWORD}")
 
13
 
14
+ client = OpenAI(api_key=OPENAI_API_KEY)
 
15
 
16
+ # === 建立 FastAPI ===
17
+ app = FastAPI(title="Voice Transcribe API")
18
 
19
+ @app.get("/ping")
20
  async def ping():
21
+ return {"status": "ok", "APP_PASSWORD": APP_PASSWORD is not None}
22
 
23
+ @app.post("/api/transcribe")
24
  async def transcribe_api(file: UploadFile, token: str = Form(...)):
25
+ print(f"📥 收到 API 請求:{file.filename}, token={token}")
26
 
27
  if not APP_PASSWORD:
28
+ raise HTTPException(status_code=500, detail="APP_PASSWORD not set on server.")
 
29
  if token != APP_PASSWORD:
30
+ raise HTTPException(status_code=403, detail="Forbidden: invalid token")
 
31
 
 
 
32
  temp_path = f"/tmp/{file.filename}"
33
  with open(temp_path, "wb") as f:
34
+ f.write(await file.read())
 
35
 
 
36
  with open(temp_path, "rb") as audio_file:
37
+ transcript = client.audio.transcriptions.create(model="whisper-1", file=audio_file)
38
+
 
 
39
  text = transcript.text.strip()
40
+ print(f"🗣️ 轉錄文字:{text[:60]}...")
41
 
 
42
  summary_prompt = f"請幫我用中文摘要以下內容:\n\n{text}"
43
  summary = client.chat.completions.create(
44
  model="gpt-4o-mini",
45
  messages=[{"role": "user", "content": summary_prompt}]
46
  ).choices[0].message.content.strip()
 
 
 
47
 
48
+ return JSONResponse({"text": text, "summary": summary})
49
 
50
+ # === 建立 Gradio UI ===
51
+ def gradio_ui(audio):
52
  if audio is None:
53
  return "請上傳音訊檔案", ""
 
 
54
  with open(audio, "rb") as f:
55
+ transcript = client.audio.transcriptions.create(model="whisper-1", file=f)
 
 
 
56
  text = transcript.text.strip()
57
 
58
  summary_prompt = f"請幫我用中文摘要以下內容:\n\n{text}"
 
60
  model="gpt-4o-mini",
61
  messages=[{"role": "user", "content": summary_prompt}]
62
  ).choices[0].message.content.strip()
 
63
  return text, summary
64
 
 
65
  demo = gr.Interface(
66
+ fn=gradio_ui,
67
  inputs=gr.Audio(type="filepath", label="上傳音訊"),
68
+ outputs=[gr.Textbox(label="轉錄文字"), gr.Textbox(label="AI 摘要")],
69
+ title="LINE 語音轉錄與摘要 (整合 API 版)"
 
70
  )
71
 
72
+ # === Gradio 掛上 FastAPI ===
73
+ app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
74
 
75
+ print("✅ FastAPI 路由:")
76
+ for r in app.routes:
77
+ print("👉", r.path)