Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import os, shutil, base64, uuid, mimetypes
|
| 2 |
from pydub import AudioSegment
|
| 3 |
from openai import OpenAI
|
| 4 |
import gradio as gr
|
|
@@ -11,7 +11,7 @@ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
|
| 11 |
print("===== 🚀 啟動中 =====")
|
| 12 |
print(f"APP_PASSWORD: {'✅ 已載入' if PASSWORD else '❌ 未載入'}")
|
| 13 |
|
| 14 |
-
# ======
|
| 15 |
MIME_EXT = {
|
| 16 |
"audio/mp4": "m4a",
|
| 17 |
"audio/m4a": "m4a",
|
|
@@ -30,7 +30,7 @@ def _dataurl_to_file(data_url: str, orig_name: str | None = None) -> str:
|
|
| 30 |
try:
|
| 31 |
header, b64 = data_url.split(",", 1)
|
| 32 |
except ValueError:
|
| 33 |
-
raise ValueError("data URL
|
| 34 |
# 取 MIME
|
| 35 |
mime = header.split(";")[0].split(":", 1)[-1].strip()
|
| 36 |
ext = MIME_EXT.get(mime) or (mimetypes.guess_extension(mime) or "m4a").lstrip(".")
|
|
@@ -38,48 +38,75 @@ def _dataurl_to_file(data_url: str, orig_name: str | None = None) -> str:
|
|
| 38 |
fname = orig_name if (orig_name and "." in orig_name) else f"upload_{uuid.uuid4().hex}.{ext}"
|
| 39 |
with open(fname, "wb") as f:
|
| 40 |
f.write(base64.b64decode(b64))
|
|
|
|
| 41 |
return fname
|
| 42 |
|
| 43 |
def _extract_effective_path(file_obj) -> str:
|
| 44 |
"""
|
| 45 |
-
從 Gradio 的 File
|
| 46 |
-
|
| 47 |
"""
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
if isinstance(file_obj, str):
|
| 50 |
s = file_obj.strip().strip('"')
|
|
|
|
| 51 |
if s.startswith("data:"):
|
|
|
|
| 52 |
return _dataurl_to_file(s, None)
|
| 53 |
if os.path.isfile(s):
|
|
|
|
| 54 |
return s
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 57 |
if isinstance(file_obj, dict):
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
p = str(file_obj.get("path") or "").strip().strip('"')
|
| 60 |
if p and os.path.isfile(p):
|
|
|
|
| 61 |
return p
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
if isinstance(data, str) and data.startswith("data:"):
|
| 65 |
-
return _dataurl_to_file(data, file_obj.get("orig_name"))
|
| 66 |
-
# 有些版本可能把真路徑放在 url
|
| 67 |
u = str(file_obj.get("url") or "").strip().strip('"')
|
| 68 |
if u and os.path.isfile(u):
|
|
|
|
| 69 |
return u
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
for attr in ("name", "path"):
|
| 72 |
p = getattr(file_obj, attr, None)
|
| 73 |
if isinstance(p, str):
|
| 74 |
s = p.strip().strip('"')
|
| 75 |
if os.path.isfile(s):
|
|
|
|
| 76 |
return s
|
| 77 |
-
|
|
|
|
| 78 |
data = getattr(file_obj, "data", None)
|
| 79 |
if isinstance(data, str) and data.startswith("data:"):
|
|
|
|
| 80 |
return _dataurl_to_file(data, getattr(file_obj, "orig_name", None))
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
|
| 84 |
# ====== 分段處理 ======
|
| 85 |
def split_audio(path):
|
|
@@ -98,7 +125,7 @@ def split_audio(path):
|
|
| 98 |
|
| 99 |
# ====== 轉錄核心 ======
|
| 100 |
def transcribe_core(path, model="whisper-1"):
|
| 101 |
-
# iPhone LINE
|
| 102 |
if path.lower().endswith(".mp4"):
|
| 103 |
fixed = path[:-4] + ".m4a"
|
| 104 |
try:
|
|
@@ -119,56 +146,77 @@ def transcribe_core(path, model="whisper-1"):
|
|
| 119 |
raw.append(txt)
|
| 120 |
raw_txt = "\n".join(raw)
|
| 121 |
|
| 122 |
-
#
|
| 123 |
conv = client.chat.completions.create(
|
| 124 |
model="gpt-4o-mini",
|
| 125 |
messages=[
|
| 126 |
{"role":"system","content":"你是嚴格的繁體中文轉換器"},
|
| 127 |
-
{"role":"user","content":f"
|
| 128 |
],
|
| 129 |
temperature=0.0
|
| 130 |
)
|
| 131 |
trad = conv.choices[0].message.content.strip()
|
| 132 |
|
| 133 |
-
#
|
| 134 |
summ = client.chat.completions.create(
|
| 135 |
model="gpt-4o-mini",
|
| 136 |
messages=[
|
| 137 |
{"role":"system","content":"你是繁體摘要助手"},
|
| 138 |
-
{"role":"user","content":f"
|
| 139 |
],
|
| 140 |
temperature=0.2
|
| 141 |
)
|
| 142 |
return trad, summ.choices[0].message.content.strip()
|
| 143 |
|
| 144 |
-
# ======
|
| 145 |
def transcribe(password, file):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
if password.strip() != PASSWORD:
|
| 147 |
-
|
|
|
|
|
|
|
| 148 |
if not file:
|
| 149 |
-
|
|
|
|
| 150 |
|
| 151 |
try:
|
| 152 |
path = _extract_effective_path(file)
|
|
|
|
|
|
|
| 153 |
except Exception as e:
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
# ====== Gradio UI ======
|
| 160 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 161 |
-
gr.Markdown("## 🎧 LINE
|
| 162 |
-
pw = gr.Textbox(label="
|
| 163 |
-
f = gr.File(label="
|
| 164 |
-
run = gr.Button("
|
| 165 |
-
s = gr.Textbox(label="
|
| 166 |
-
t = gr.Textbox(label="
|
| 167 |
-
su = gr.Textbox(label="AI
|
| 168 |
-
#
|
| 169 |
run.click(transcribe, [pw, f], [s, t, su], queue=False)
|
| 170 |
|
| 171 |
app = demo
|
| 172 |
|
| 173 |
if __name__ == "__main__":
|
| 174 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
import os, shutil, base64, uuid, mimetypes, json
|
| 2 |
from pydub import AudioSegment
|
| 3 |
from openai import OpenAI
|
| 4 |
import gradio as gr
|
|
|
|
| 11 |
print("===== 🚀 啟動中 =====")
|
| 12 |
print(f"APP_PASSWORD: {'✅ 已載入' if PASSWORD else '❌ 未載入'}")
|
| 13 |
|
| 14 |
+
# ====== 工具:把 data:URL 轉成臨時檔 ======
|
| 15 |
MIME_EXT = {
|
| 16 |
"audio/mp4": "m4a",
|
| 17 |
"audio/m4a": "m4a",
|
|
|
|
| 30 |
try:
|
| 31 |
header, b64 = data_url.split(",", 1)
|
| 32 |
except ValueError:
|
| 33 |
+
raise ValueError("data URL 格式錯誤(缺少逗號)。")
|
| 34 |
# 取 MIME
|
| 35 |
mime = header.split(";")[0].split(":", 1)[-1].strip()
|
| 36 |
ext = MIME_EXT.get(mime) or (mimetypes.guess_extension(mime) or "m4a").lstrip(".")
|
|
|
|
| 38 |
fname = orig_name if (orig_name and "." in orig_name) else f"upload_{uuid.uuid4().hex}.{ext}"
|
| 39 |
with open(fname, "wb") as f:
|
| 40 |
f.write(base64.b64decode(b64))
|
| 41 |
+
print(f"✅ 已從 data URL 生成檔案:{fname}, 大小:{os.path.getsize(fname)} bytes")
|
| 42 |
return fname
|
| 43 |
|
| 44 |
def _extract_effective_path(file_obj) -> str:
|
| 45 |
"""
|
| 46 |
+
從 Gradio 的 File 輸入中,得到真正存在的檔案路徑。
|
| 47 |
+
🔴 加強版:詳細記錄所有嘗試過程
|
| 48 |
"""
|
| 49 |
+
print(f"\n🔍 開始解析檔案...")
|
| 50 |
+
print(f"📦 收到的類型: {type(file_obj)}")
|
| 51 |
+
print(f"📦 收到的內容: {file_obj}")
|
| 52 |
+
|
| 53 |
+
# 情況 A:字串(可能是路徑或 data:URL)
|
| 54 |
if isinstance(file_obj, str):
|
| 55 |
s = file_obj.strip().strip('"')
|
| 56 |
+
print(f" → 情況A:字串模式")
|
| 57 |
if s.startswith("data:"):
|
| 58 |
+
print(f" → 偵測到 data URL,長度:{len(s)}")
|
| 59 |
return _dataurl_to_file(s, None)
|
| 60 |
if os.path.isfile(s):
|
| 61 |
+
print(f" → 找到有效路徑:{s}")
|
| 62 |
return s
|
| 63 |
+
print(f" → 字串無效,繼續嘗試...")
|
| 64 |
+
|
| 65 |
+
# 情況 B:dict
|
| 66 |
if isinstance(file_obj, dict):
|
| 67 |
+
print(f" → 情況B:字典模式")
|
| 68 |
+
print(f" → 字典的 keys: {list(file_obj.keys())}")
|
| 69 |
+
|
| 70 |
+
# 🔴 優先檢查 data(Base64 模式)
|
| 71 |
+
data = file_obj.get("data")
|
| 72 |
+
if isinstance(data, str) and data.startswith("data:"):
|
| 73 |
+
print(f" → ✅ 找到 data URL! 長度:{len(data)}")
|
| 74 |
+
orig_name = file_obj.get("orig_name")
|
| 75 |
+
print(f" → 檔名:{orig_name}")
|
| 76 |
+
return _dataurl_to_file(data, orig_name)
|
| 77 |
+
|
| 78 |
+
# 再檢查 path
|
| 79 |
p = str(file_obj.get("path") or "").strip().strip('"')
|
| 80 |
if p and os.path.isfile(p):
|
| 81 |
+
print(f" → 找到 path:{p}")
|
| 82 |
return p
|
| 83 |
+
|
| 84 |
+
# 檢查 url
|
|
|
|
|
|
|
|
|
|
| 85 |
u = str(file_obj.get("url") or "").strip().strip('"')
|
| 86 |
if u and os.path.isfile(u):
|
| 87 |
+
print(f" → 找到 url:{u}")
|
| 88 |
return u
|
| 89 |
+
|
| 90 |
+
print(f" → ❌ 字典內沒有有效的 data/path/url")
|
| 91 |
+
|
| 92 |
+
# 情況 C:物件
|
| 93 |
+
print(f" → 情況C:物件模式")
|
| 94 |
for attr in ("name", "path"):
|
| 95 |
p = getattr(file_obj, attr, None)
|
| 96 |
if isinstance(p, str):
|
| 97 |
s = p.strip().strip('"')
|
| 98 |
if os.path.isfile(s):
|
| 99 |
+
print(f" → 找到物件屬性 {attr}:{s}")
|
| 100 |
return s
|
| 101 |
+
|
| 102 |
+
# 物件上的 data:URL
|
| 103 |
data = getattr(file_obj, "data", None)
|
| 104 |
if isinstance(data, str) and data.startswith("data:"):
|
| 105 |
+
print(f" → 找到物件的 data URL")
|
| 106 |
return _dataurl_to_file(data, getattr(file_obj, "orig_name", None))
|
| 107 |
+
|
| 108 |
+
print(f" → ❌ 所有方法都失敗!")
|
| 109 |
+
raise FileNotFoundError(f"無法解析上傳檔案。收到的類型:{type(file_obj)}, 內容:{str(file_obj)[:200]}")
|
| 110 |
|
| 111 |
# ====== 分段處理 ======
|
| 112 |
def split_audio(path):
|
|
|
|
| 125 |
|
| 126 |
# ====== 轉錄核心 ======
|
| 127 |
def transcribe_core(path, model="whisper-1"):
|
| 128 |
+
# iPhone LINE 常��:mp4(其實是音訊容器)
|
| 129 |
if path.lower().endswith(".mp4"):
|
| 130 |
fixed = path[:-4] + ".m4a"
|
| 131 |
try:
|
|
|
|
| 146 |
raw.append(txt)
|
| 147 |
raw_txt = "\n".join(raw)
|
| 148 |
|
| 149 |
+
# 簡轉繁(不意譯)
|
| 150 |
conv = client.chat.completions.create(
|
| 151 |
model="gpt-4o-mini",
|
| 152 |
messages=[
|
| 153 |
{"role":"system","content":"你是嚴格的繁體中文轉換器"},
|
| 154 |
+
{"role":"user","content":f"將以下內容轉為台灣繁體,不意譯:\n{raw_txt}"}
|
| 155 |
],
|
| 156 |
temperature=0.0
|
| 157 |
)
|
| 158 |
trad = conv.choices[0].message.content.strip()
|
| 159 |
|
| 160 |
+
# 摘要(內容多→條列;內容少→一句話)
|
| 161 |
summ = client.chat.completions.create(
|
| 162 |
model="gpt-4o-mini",
|
| 163 |
messages=[
|
| 164 |
{"role":"system","content":"你是繁體摘要助手"},
|
| 165 |
+
{"role":"user","content":f"請用台灣繁體中文摘要;內容多則條列重點,內容短則一句話:\n{trad}"}
|
| 166 |
],
|
| 167 |
temperature=0.2
|
| 168 |
)
|
| 169 |
return trad, summ.choices[0].message.content.strip()
|
| 170 |
|
| 171 |
+
# ====== 對外函式(UI / API 共用) ======
|
| 172 |
def transcribe(password, file):
|
| 173 |
+
print("\n" + "="*50)
|
| 174 |
+
print("🎯 新的轉錄請求")
|
| 175 |
+
print(f"🔑 密碼: {password[:2]}*** (長度:{len(password)})")
|
| 176 |
+
print(f"📁 檔案: {type(file)}")
|
| 177 |
+
print("="*50)
|
| 178 |
+
|
| 179 |
if password.strip() != PASSWORD:
|
| 180 |
+
print("❌ 密碼驗證失敗")
|
| 181 |
+
return "❌ Password incorrect", "", ""
|
| 182 |
+
|
| 183 |
if not file:
|
| 184 |
+
print("❌ 未收到檔案")
|
| 185 |
+
return "⚠️ No file uploaded", "", ""
|
| 186 |
|
| 187 |
try:
|
| 188 |
path = _extract_effective_path(file)
|
| 189 |
+
print(f"✅ 成功解析檔案:{path}")
|
| 190 |
+
print(f"📊 檔案大小:{os.path.getsize(path)} bytes")
|
| 191 |
except Exception as e:
|
| 192 |
+
import traceback
|
| 193 |
+
error_msg = traceback.format_exc()
|
| 194 |
+
print(f"❌ 檔案解析失敗:\n{error_msg}")
|
| 195 |
+
return f"❌ File parsing failed: {e}", "", ""
|
| 196 |
|
| 197 |
+
try:
|
| 198 |
+
text, summary = transcribe_core(path)
|
| 199 |
+
print("✅ 轉錄完成")
|
| 200 |
+
return "✅ Transcription completed", text, summary
|
| 201 |
+
except Exception as e:
|
| 202 |
+
import traceback
|
| 203 |
+
error_msg = traceback.format_exc()
|
| 204 |
+
print(f"❌ 轉錄失敗:\n{error_msg}")
|
| 205 |
+
return f"❌ Transcription failed: {e}", "", ""
|
| 206 |
|
| 207 |
# ====== Gradio UI ======
|
| 208 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 209 |
+
gr.Markdown("## 🎧 LINE Audio Transcription & Summary (Enhanced Debug)")
|
| 210 |
+
pw = gr.Textbox(label="Password", type="password")
|
| 211 |
+
f = gr.File(label="Upload Audio File")
|
| 212 |
+
run = gr.Button("Start Transcription 🚀")
|
| 213 |
+
s = gr.Textbox(label="Status", interactive=False)
|
| 214 |
+
t = gr.Textbox(label="Transcription Result", lines=10)
|
| 215 |
+
su = gr.Textbox(label="AI Summary", lines=8)
|
| 216 |
+
# 關鍵:queue=False 讓 API 直接回應
|
| 217 |
run.click(transcribe, [pw, f], [s, t, su], queue=False)
|
| 218 |
|
| 219 |
app = demo
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
| 222 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|