MichaelChou0806 commited on
Commit
4eafb07
·
verified ·
1 Parent(s): bcd946f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -29
app.py CHANGED
@@ -1,18 +1,17 @@
1
  import os
2
  import time
3
  import shutil
 
 
4
  import gradio as gr
5
  from fastapi import FastAPI, File, UploadFile, Form, HTTPException
6
- from openai import OpenAI
7
- from pydub import AudioSegment
8
  from fastapi.responses import JSONResponse
9
 
10
- # ========================
11
- # 🔐 環境變數 / Secret 修
12
- # ========================
13
- # Hugging Face 有時不會正確傳入 Secret,所以做雙重保險:
14
- OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") or os.getenv("OPENAI_API_KEY")
15
- APP_PASSWORD = os.environ.get("APP_PASSWORD") or os.getenv("APP_PASSWORD")
16
 
17
  print("===== 🚀 啟動中 =====")
18
  print(f"OPENAI_API_KEY: {'✅ 已載入' if OPENAI_API_KEY else '❌ 未載入'}")
@@ -20,11 +19,10 @@ print(f"APP_PASSWORD: {'✅ 已載入' if APP_PASSWORD else '❌ 未載入'}")
20
 
21
  client = OpenAI(api_key=OPENAI_API_KEY)
22
  MAX_SIZE = 25 * 1024 * 1024
23
- app = FastAPI(title="LINE Audio Transcriber")
24
 
25
- # ========================
26
- # 🎧 核心轉錄函式
27
- # ========================
28
  def split_audio_if_needed(path: str):
29
  size = os.path.getsize(path)
30
  if size <= MAX_SIZE:
@@ -39,6 +37,7 @@ def split_audio_if_needed(path: str):
39
  parts.append(fn)
40
  return parts
41
 
 
42
  def transcribe_core(path: str, model: str = "whisper-1"):
43
  chunks = split_audio_if_needed(path)
44
  txts = []
@@ -54,15 +53,22 @@ def transcribe_core(path: str, model: str = "whisper-1"):
54
  ).choices[0].message.content.strip()
55
  return full, summ
56
 
57
- # ========================
58
- # 🌐 API 路由 (for 捷徑)
59
- # ========================
 
 
 
 
 
 
 
60
  @app.post("/api/transcribe")
61
  async def api_transcribe(
62
  file: UploadFile = File(...),
63
  token: str = Form(default=None)
64
  ):
65
- """捷徑可 POST 來呼叫語轉錄"""
66
  if APP_PASSWORD and token != APP_PASSWORD:
67
  raise HTTPException(status_code=403, detail="Forbidden: invalid token")
68
 
@@ -74,14 +80,11 @@ async def api_transcribe(
74
  os.remove(temp)
75
  return JSONResponse({"text": text, "summary": summary})
76
 
77
- @app.get("/ping")
78
- def ping():
79
- return {"status": "ok", "key": bool(OPENAI_API_KEY), "pw": bool(APP_PASSWORD)}
80
 
81
- # ========================
82
- # 💬 Gradio 前端
83
- # ========================
84
- def gradio_ui(password, file):
85
  if APP_PASSWORD and password.strip() != APP_PASSWORD:
86
  return "❌ 密碼錯誤", "", ""
87
  if not file:
@@ -89,18 +92,20 @@ def gradio_ui(password, file):
89
  text, summary = transcribe_core(file.name)
90
  return "✅ 完成", text, summary
91
 
 
92
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
93
- gr.Markdown("## 🎧 LINE 語音轉錄與摘要工具")
94
  pw = gr.Textbox(label="輸入密碼", type="password")
95
  f = gr.File(label="上傳音訊檔 (.m4a/.mp3/.wav/.mp4)")
96
  run = gr.Button("開始轉錄 🚀")
97
  s = gr.Textbox(label="狀態", interactive=False)
98
  t = gr.Textbox(label="逐字稿", lines=10)
99
  su = gr.Textbox(label="摘要", lines=8)
100
- run.click(gradio_ui, [pw, f], [s, t, su])
101
 
102
- # 掛上 Gradio
103
- gr.mount_gradio_app(app, demo, path="/")
104
 
105
- # ✅ Hugging Face Spaces 需要這行來啟動 FastAPI app
106
- application = app
 
 
 
 
1
  import os
2
  import time
3
  import shutil
4
+ from pydub import AudioSegment
5
+ from openai import OpenAI
6
  import gradio as gr
7
  from fastapi import FastAPI, File, UploadFile, Form, HTTPException
 
 
8
  from fastapi.responses import JSONResponse
9
 
10
+ # ======================================================
11
+ # 🔐 基本設定:讀取環境變數(Secrets 也能確抓到)
12
+ # ======================================================
13
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
14
+ APP_PASSWORD = os.environ.get("APP_PASSWORD")
 
15
 
16
  print("===== 🚀 啟動中 =====")
17
  print(f"OPENAI_API_KEY: {'✅ 已載入' if OPENAI_API_KEY else '❌ 未載入'}")
 
19
 
20
  client = OpenAI(api_key=OPENAI_API_KEY)
21
  MAX_SIZE = 25 * 1024 * 1024
 
22
 
23
+ # ======================================================
24
+ # 🎧 音訊處理核心
25
+ # ======================================================
26
  def split_audio_if_needed(path: str):
27
  size = os.path.getsize(path)
28
  if size <= MAX_SIZE:
 
37
  parts.append(fn)
38
  return parts
39
 
40
+
41
  def transcribe_core(path: str, model: str = "whisper-1"):
42
  chunks = split_audio_if_needed(path)
43
  txts = []
 
53
  ).choices[0].message.content.strip()
54
  return full, summ
55
 
56
+
57
+ # ======================================================
58
+ # 🌐 FastAPI 主要端點
59
+ # ======================================================
60
+ app = FastAPI(title="LINE Audio Transcriber")
61
+
62
+ @app.get("/ping")
63
+ def ping():
64
+ return {"status": "ok", "key": bool(OPENAI_API_KEY), "pw": bool(APP_PASSWORD)}
65
+
66
  @app.post("/api/transcribe")
67
  async def api_transcribe(
68
  file: UploadFile = File(...),
69
  token: str = Form(default=None)
70
  ):
71
+ """iPhone 捷徑上傳"""
72
  if APP_PASSWORD and token != APP_PASSWORD:
73
  raise HTTPException(status_code=403, detail="Forbidden: invalid token")
74
 
 
80
  os.remove(temp)
81
  return JSONResponse({"text": text, "summary": summary})
82
 
 
 
 
83
 
84
+ # ======================================================
85
+ # 💬 Gradio 介面(共存 UI)
86
+ # ======================================================
87
+ def transcribe_with_pw(password, file):
88
  if APP_PASSWORD and password.strip() != APP_PASSWORD:
89
  return "❌ 密碼錯誤", "", ""
90
  if not file:
 
92
  text, summary = transcribe_core(file.name)
93
  return "✅ 完成", text, summary
94
 
95
+
96
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
97
+ gr.Markdown("## 🎧 LINE 語音轉錄與摘要工具(支援 .m4a / .mp4)")
98
  pw = gr.Textbox(label="輸入密碼", type="password")
99
  f = gr.File(label="上傳音訊檔 (.m4a/.mp3/.wav/.mp4)")
100
  run = gr.Button("開始轉錄 🚀")
101
  s = gr.Textbox(label="狀態", interactive=False)
102
  t = gr.Textbox(label="逐字稿", lines=10)
103
  su = gr.Textbox(label="摘要", lines=8)
104
+ run.click(transcribe_with_pw, [pw, f], [s, t, su])
105
 
 
 
106
 
107
+ # ======================================================
108
+ # 🚀 關鍵啟動(讓 HF 正確偵測)
109
+ # ======================================================
110
+ from gradio.routes import mount_gradio_app
111
+ application = mount_gradio_app(app, demo, path="/")