MichaelChou0806 commited on
Commit
0b13a9c
·
verified ·
1 Parent(s): c313f52

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -14
app.py CHANGED
@@ -4,19 +4,24 @@ import shutil
4
  from pydub import AudioSegment
5
  from openai import OpenAI
6
  import gradio as gr
7
- from fastapi import FastAPI, File, UploadFile
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
 
16
- print(PASSWORD)
 
17
 
18
  # FastAPI App for捷徑 API
19
- app = FastAPI()
20
 
21
  # ========================
22
  # 🎧 音訊轉錄核心
@@ -35,6 +40,7 @@ def split_audio_if_needed(path: str):
35
  parts.append(fn)
36
  return parts
37
 
 
38
  def transcribe_core(path: str, model: str = "whisper-1"):
39
  if path.lower().endswith(".mp4"):
40
  fixed = path[:-4] + ".m4a"
@@ -55,34 +61,40 @@ def transcribe_core(path: str, model: str = "whisper-1"):
55
  txts.append(t)
56
  full = "\n".join(txts)
57
  summ = client.chat.completions.create(
58
-
59
-
60
-
61
-
62
  model="gpt-4o-mini",
63
  messages=[{"role": "user", "content": f"請用繁體中文摘要以下內容:\n{full}"}],
64
  temperature=0.4,
65
  ).choices[0].message.content.strip()
66
  return full, summ
67
 
 
68
  # ========================
69
  # 🌐 FastAPI 端點(捷徑用)
70
  # ========================
71
  @app.post("/api/transcribe")
72
- async def api_transcribe(file: UploadFile = File(...)):
 
 
 
73
  """供 iPhone 捷徑上傳音訊並取得 JSON"""
 
 
 
74
  temp = file.filename
75
  with open(temp, "wb") as f:
76
  f.write(await file.read())
 
77
  text, summary = transcribe_core(temp)
78
  os.remove(temp)
79
  return {"text": text, "summary": summary}
80
 
 
81
  @app.get("/health")
82
  def health():
83
  """捷徑可先 ping 這個確認服務運作中"""
84
  return {"status": "ok", "time": int(time.time())}
85
 
 
86
  # ========================
87
  # 💬 Gradio 介面
88
  # ========================
@@ -94,6 +106,7 @@ def transcribe_with_pw(password, file):
94
  text, summary = transcribe_core(file.name)
95
  return "✅ 完成", text, summary
96
 
 
97
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
98
  gr.Markdown("## 🎧 LINE 語音轉錄與摘要工具(支援 .m4a / .mp4)")
99
  pw = gr.Textbox(label="輸入密碼", type="password")
@@ -102,16 +115,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
102
  s = gr.Textbox(label="狀態", interactive=False)
103
  t = gr.Textbox(label="逐字稿", lines=10)
104
  su = gr.Textbox(label="摘要", lines=8)
105
-
106
  run.click(transcribe_with_pw, [pw, f], [s, t, su])
107
 
108
  # ========================
109
  # 🚀 啟動(單一埠)
110
  # ========================
111
- # 讓 Gradio 介面掛載到 FastAPI
112
  gr.mount_gradio_app(app, demo, path="/")
113
 
114
- # Hugging Face 自動綁定 port=7860,不用手動設定
115
  if __name__ == "__main__":
116
  import uvicorn
117
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
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
 
9
  # ========================
10
  # 🔐 基本設定
11
  # ========================
12
  PASSWORD = os.getenv("APP_PASSWORD", "defaultpass")
13
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
14
+
15
+ print("===== 🚀 啟動中 =====")
16
+ print(f"OPENAI_API_KEY: {'✅ 已載入' if OPENAI_API_KEY else '❌ 未載入'}")
17
+ print(f"APP_PASSWORD: {'✅ 已載入' if PASSWORD else '❌ 未載入'}")
18
+ print(f"目前密碼內容:{PASSWORD}")
19
 
20
+ MAX_SIZE = 25 * 1024 * 1024
21
+ client = OpenAI(api_key=OPENAI_API_KEY)
22
 
23
  # FastAPI App for捷徑 API
24
+ app = FastAPI(title="LINE Audio Transcriber")
25
 
26
  # ========================
27
  # 🎧 音訊轉錄核心
 
40
  parts.append(fn)
41
  return parts
42
 
43
+
44
  def transcribe_core(path: str, model: str = "whisper-1"):
45
  if path.lower().endswith(".mp4"):
46
  fixed = path[:-4] + ".m4a"
 
61
  txts.append(t)
62
  full = "\n".join(txts)
63
  summ = client.chat.completions.create(
 
 
 
 
64
  model="gpt-4o-mini",
65
  messages=[{"role": "user", "content": f"請用繁體中文摘要以下內容:\n{full}"}],
66
  temperature=0.4,
67
  ).choices[0].message.content.strip()
68
  return full, summ
69
 
70
+
71
  # ========================
72
  # 🌐 FastAPI 端點(捷徑用)
73
  # ========================
74
  @app.post("/api/transcribe")
75
+ async def api_transcribe(
76
+ file: UploadFile = File(...),
77
+ token: str = Form(default=None)
78
+ ):
79
  """供 iPhone 捷徑上傳音訊並取得 JSON"""
80
+ if token != PASSWORD:
81
+ raise HTTPException(status_code=403, detail="Invalid token")
82
+
83
  temp = file.filename
84
  with open(temp, "wb") as f:
85
  f.write(await file.read())
86
+
87
  text, summary = transcribe_core(temp)
88
  os.remove(temp)
89
  return {"text": text, "summary": summary}
90
 
91
+
92
  @app.get("/health")
93
  def health():
94
  """捷徑可先 ping 這個確認服務運作中"""
95
  return {"status": "ok", "time": int(time.time())}
96
 
97
+
98
  # ========================
99
  # 💬 Gradio 介面
100
  # ========================
 
106
  text, summary = transcribe_core(file.name)
107
  return "✅ 完成", text, summary
108
 
109
+
110
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
111
  gr.Markdown("## 🎧 LINE 語音轉錄與摘要工具(支援 .m4a / .mp4)")
112
  pw = gr.Textbox(label="輸入密碼", type="password")
 
115
  s = gr.Textbox(label="狀態", interactive=False)
116
  t = gr.Textbox(label="逐字稿", lines=10)
117
  su = gr.Textbox(label="摘要", lines=8)
 
118
  run.click(transcribe_with_pw, [pw, f], [s, t, su])
119
 
120
  # ========================
121
  # 🚀 啟動(單一埠)
122
  # ========================
 
123
  gr.mount_gradio_app(app, demo, path="/")
124
 
 
125
  if __name__ == "__main__":
126
  import uvicorn
127
+ uvicorn.run(app, host="0.0.0.0", port=7860)