Update app.py
Browse files
app.py
CHANGED
|
@@ -1,111 +1,82 @@
|
|
| 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,
|
|
|
|
| 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 |
-
#
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
if size <= MAX_SIZE:
|
| 25 |
-
return [path]
|
| 26 |
-
audio = AudioSegment.from_file(path)
|
| 27 |
-
n = int(size / MAX_SIZE) + 1
|
| 28 |
-
chunk_ms = len(audio) / n
|
| 29 |
-
parts = []
|
| 30 |
-
for i in range(n):
|
| 31 |
-
fn = f"chunk_{i+1}.wav"
|
| 32 |
-
audio[int(i * chunk_ms):int((i + 1) * chunk_ms)].export(fn, format="wav")
|
| 33 |
-
parts.append(fn)
|
| 34 |
-
return parts
|
| 35 |
-
|
| 36 |
-
def transcribe_core(path: str, model: str = "whisper-1"):
|
| 37 |
-
if path.lower().endswith(".mp4"):
|
| 38 |
-
fixed = path[:-4] + ".m4a"
|
| 39 |
-
try:
|
| 40 |
-
shutil.copy(path, fixed)
|
| 41 |
-
path = fixed
|
| 42 |
-
print("🔧 已自動修正 mp4 → m4a")
|
| 43 |
-
except Exception as e:
|
| 44 |
-
print(f"⚠️ mp4→m4a 轉檔失敗:{e}")
|
| 45 |
-
|
| 46 |
-
chunks = split_audio_if_needed(path)
|
| 47 |
-
txts = []
|
| 48 |
-
for f in chunks:
|
| 49 |
-
with open(f, "rb") as af:
|
| 50 |
-
t = client.audio.transcriptions.create(
|
| 51 |
-
model=model, file=af, response_format="text"
|
| 52 |
-
)
|
| 53 |
-
txts.append(t)
|
| 54 |
-
full = "\n".join(txts)
|
| 55 |
-
summ = client.chat.completions.create(
|
| 56 |
model="gpt-4o-mini",
|
| 57 |
-
messages=[{"role": "user", "content":
|
| 58 |
-
temperature=0.4,
|
| 59 |
).choices[0].message.content.strip()
|
| 60 |
-
return full, summ
|
| 61 |
|
| 62 |
-
# ========================
|
| 63 |
-
# 🌐 FastAPI 端點(捷徑用)
|
| 64 |
-
# ========================
|
| 65 |
-
@app.post("/api/transcribe")
|
| 66 |
-
async def api_transcribe(file: UploadFile = File(...)):
|
| 67 |
-
"""供 iPhone 捷徑上傳音訊並取得 JSON"""
|
| 68 |
-
temp = file.filename
|
| 69 |
-
with open(temp, "wb") as f:
|
| 70 |
-
f.write(await file.read())
|
| 71 |
-
text, summary = transcribe_core(temp)
|
| 72 |
-
os.remove(temp)
|
| 73 |
return {"text": text, "summary": summary}
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
| 109 |
if __name__ == "__main__":
|
| 110 |
-
|
| 111 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
+
from fastapi import FastAPI, UploadFile, Form, HTTPException
|
| 4 |
+
from openai import OpenAI
|
| 5 |
|
| 6 |
+
# 初始化 FastAPI + Gradio
|
| 7 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
| 8 |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 9 |
|
| 10 |
+
# 載入安全金鑰(請在 Hugging Face → Settings → Secrets 裡設 APP_PASSWORD)
|
| 11 |
+
APP_PASSWORD = os.getenv("APP_PASSWORD", None)
|
| 12 |
+
|
| 13 |
+
# === API endpoint ===
|
| 14 |
+
@app.post("/api/transcribe")
|
| 15 |
+
async def transcribe_api(file: UploadFile, token: str = Form(...)):
|
| 16 |
+
# 驗證 token
|
| 17 |
+
if not APP_PASSWORD:
|
| 18 |
+
raise HTTPException(status_code=500, detail="Server misconfiguration: APP_PASSWORD not set.")
|
| 19 |
+
if token != APP_PASSWORD:
|
| 20 |
+
raise HTTPException(status_code=403, detail="Forbidden: invalid token.")
|
| 21 |
+
|
| 22 |
+
# 儲存臨時音訊檔
|
| 23 |
+
contents = await file.read()
|
| 24 |
+
temp_path = f"/tmp/{file.filename}"
|
| 25 |
+
with open(temp_path, "wb") as f:
|
| 26 |
+
f.write(contents)
|
| 27 |
+
|
| 28 |
+
# 語音轉文字
|
| 29 |
+
with open(temp_path, "rb") as audio_file:
|
| 30 |
+
transcript = client.audio.transcriptions.create(
|
| 31 |
+
model="whisper-1",
|
| 32 |
+
file=audio_file
|
| 33 |
+
)
|
| 34 |
|
| 35 |
+
text = transcript.text.strip()
|
| 36 |
+
|
| 37 |
+
# 簡短摘要
|
| 38 |
+
summary_prompt = f"請幫我用中文摘要以下內容:\n\n{text}"
|
| 39 |
+
summary = client.chat.completions.create(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
model="gpt-4o-mini",
|
| 41 |
+
messages=[{"role": "user", "content": summary_prompt}]
|
|
|
|
| 42 |
).choices[0].message.content.strip()
|
|
|
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
return {"text": text, "summary": summary}
|
| 45 |
|
| 46 |
+
|
| 47 |
+
# === Gradio 前端 ===
|
| 48 |
+
def transcribe_ui(audio):
|
| 49 |
+
if audio is None:
|
| 50 |
+
return "請上傳音訊檔案", ""
|
| 51 |
+
with open(audio, "rb") as f:
|
| 52 |
+
transcript = client.audio.transcriptions.create(
|
| 53 |
+
model="whisper-1",
|
| 54 |
+
file=f
|
| 55 |
+
)
|
| 56 |
+
text = transcript.text.strip()
|
| 57 |
+
|
| 58 |
+
summary_prompt = f"請幫我用中文摘要以下內容:\n\n{text}"
|
| 59 |
+
summary = client.chat.completions.create(
|
| 60 |
+
model="gpt-4o-mini",
|
| 61 |
+
messages=[{"role": "user", "content": summary_prompt}]
|
| 62 |
+
).choices[0].message.content.strip()
|
| 63 |
+
|
| 64 |
+
return text, summary
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
demo = gr.Interface(
|
| 68 |
+
fn=transcribe_ui,
|
| 69 |
+
inputs=gr.Audio(type="filepath", label="上傳音訊"),
|
| 70 |
+
outputs=[
|
| 71 |
+
gr.Textbox(label="轉錄結果"),
|
| 72 |
+
gr.Textbox(label="AI 摘要")
|
| 73 |
+
],
|
| 74 |
+
title="LINE 語音轉錄與摘要 (安全版)",
|
| 75 |
+
description="上傳 LINE 語音或其他音訊,進行自動轉錄與摘要"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# 掛載 Gradio 到 FastAPI
|
| 79 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
| 80 |
+
|
| 81 |
if __name__ == "__main__":
|
| 82 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|