MichaelChou0806 commited on
Commit
70cf2d7
·
verified ·
1 Parent(s): 34eab1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -49
app.py CHANGED
@@ -1,103 +1,174 @@
1
- import os, shutil, base64
2
  from pydub import AudioSegment
3
  from openai import OpenAI
4
  import gradio as gr
5
 
6
- # === 解鎖 Gradio 檔案限制 ===
7
- import gradio.processing_utils as pu
8
- def _dummy_check_allowed(*a, **kw): return True
9
- pu._check_allowed = _dummy_check_allowed
10
- print("🔓 已解除 Gradio 上傳路徑限制")
11
-
12
- # === 設定 ===
13
  PASSWORD = os.getenv("APP_PASSWORD", "chou")
14
  MAX_SIZE = 25 * 1024 * 1024
15
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
16
  print("===== 🚀 啟動中 =====")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- # === 分段 ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def split_audio(path):
20
  size = os.path.getsize(path)
21
- if size <= MAX_SIZE: return [path]
 
22
  audio = AudioSegment.from_file(path)
23
  n = int(size / MAX_SIZE) + 1
24
  chunk_ms = len(audio) / n
25
- files = []
26
  for i in range(n):
27
  fn = f"chunk_{i+1}.wav"
28
  audio[int(i*chunk_ms):int((i+1)*chunk_ms)].export(fn, format="wav")
29
- files.append(fn)
30
- return files
31
 
32
- # === 核心轉錄 ===
33
  def transcribe_core(path, model="whisper-1"):
 
34
  if path.lower().endswith(".mp4"):
35
  fixed = path[:-4] + ".m4a"
36
- try: shutil.copy(path, fixed); path = fixed
37
- except Exception as e: print(f"⚠️ mp4→m4a 失敗: {e}")
 
 
 
38
 
39
  chunks = split_audio(path)
40
- text_list = []
41
- for f in chunks:
42
- with open(f, "rb") as af:
43
- txt = client.audio.transcriptions.create(model=model, file=af, response_format="text")
44
- text_list.append(txt)
45
- full_txt = "\n".join(text_list)
46
-
47
- trad = client.chat.completions.create(
 
 
 
 
 
48
  model="gpt-4o-mini",
49
  messages=[
50
  {"role":"system","content":"你是嚴格的繁體中文轉換器"},
51
- {"role":"user","content":f"將以下內容轉為台灣繁體,不意譯:\n{full_txt}"}
52
- ], temperature=0.0).choices[0].message.content.strip()
 
 
 
53
 
 
54
  summ = client.chat.completions.create(
55
  model="gpt-4o-mini",
56
  messages=[
57
  {"role":"system","content":"你是繁體摘要助手"},
58
- {"role":"user","content":f"用條列或一句話摘要:\n{trad}"}
59
- ], temperature=0.2).choices[0].message.content.strip()
60
- return trad, summ
 
 
61
 
62
- # === 外層驗證 ===
63
  def transcribe(password, file):
64
  if password.strip() != PASSWORD:
65
  return "❌ 密碼錯誤", "", ""
66
  if not file:
67
  return "⚠️ 未選擇檔案", "", ""
68
 
69
- # 🔒 防呆處理 base64 與錯誤 path
70
- temp_path = "uploaded_audio.m4a"
71
  try:
72
- if hasattr(file, "data") and isinstance(file.data, str) and file.data.startswith("data:audio"):
73
- base64_str = file.data.split(",")[1]
74
- with open(temp_path, "wb") as f:
75
- f.write(base64.b64decode(base64_str))
76
- file.name = temp_path
77
- elif os.path.isdir(getattr(file, "name", "")):
78
- print("⚠️ path 是資料夾,改用 base64")
79
- base64_str = getattr(file, "data", "").split(",")[1]
80
- with open(temp_path, "wb") as f:
81
- f.write(base64.b64decode(base64_str))
82
- file.name = temp_path
83
  except Exception as e:
84
- print(f"⚠️ base64 寫入失敗: {e}")
85
- return f"❌ 上傳格式錯誤: {e}", "", ""
86
 
87
- text, summary = transcribe_core(file.name)
88
  return "✅ 完成", text, summary
89
 
90
- # === Gradio UI ===
91
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
92
- gr.Markdown("## 🎧 LINE 語音轉錄與摘要(Base64 安全版)")
93
  pw = gr.Textbox(label="密碼", type="password")
94
  f = gr.File(label="上傳音訊檔")
95
  run = gr.Button("開始轉錄 🚀")
96
  s = gr.Textbox(label="狀態", interactive=False)
97
  t = gr.Textbox(label="轉錄結果", lines=10)
98
  su = gr.Textbox(label="AI 摘要", lines=8)
99
- run.click(transcribe, [pw, f], [s, t, su])
 
100
 
101
  app = demo
 
102
  if __name__ == "__main__":
103
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ import os, shutil, base64, uuid, mimetypes
2
  from pydub import AudioSegment
3
  from openai import OpenAI
4
  import gradio as gr
5
 
6
+ # ====== 基本設定 ======
 
 
 
 
 
 
7
  PASSWORD = os.getenv("APP_PASSWORD", "chou")
8
  MAX_SIZE = 25 * 1024 * 1024
9
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
10
+
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",
18
+ "audio/aac": "aac",
19
+ "audio/mpeg": "mp3",
20
+ "audio/wav": "wav",
21
+ "audio/x-wav": "wav",
22
+ "audio/ogg": "ogg",
23
+ "audio/webm": "webm",
24
+ "audio/opus": "opus",
25
+ "video/mp4": "mp4",
26
+ }
27
+
28
+ def _dataurl_to_file(data_url: str, orig_name: str | None = None) -> str:
29
+ # data_url: "data:audio/mp4;base64,AAAA..."
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(".")
37
+ # 臨時檔名
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 輸入(可能是 str / dict / 物件)中,得到真正存在的檔案路徑。
46
+ 若沒有實檔,就從 data:URL 產生一個臨時檔。
47
+ """
48
+ # 情況 A:字串(可能是路徑或 data:URL)
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
+ # 情況 B:dict(/gradio_api/call 會送這型)
57
+ if isinstance(file_obj, dict):
58
+ # 優先用 path
59
+ p = str(file_obj.get("path") or "").strip().strip('"')
60
+ if p and os.path.isfile(p):
61
+ return p
62
+ # 不行就用 data
63
+ data = file_obj.get("data")
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
+ # 情況 C:物件(本機 UI 上傳常見)
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
+ # 物件上有 data:URL?
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
+ raise FileNotFoundError("無法解析上傳檔案:沒有有效路徑,也沒有 data:URL。")
83
+
84
+ # ====== 分段處理 ======
85
  def split_audio(path):
86
  size = os.path.getsize(path)
87
+ if size <= MAX_SIZE:
88
+ return [path]
89
  audio = AudioSegment.from_file(path)
90
  n = int(size / MAX_SIZE) + 1
91
  chunk_ms = len(audio) / n
92
+ parts = []
93
  for i in range(n):
94
  fn = f"chunk_{i+1}.wav"
95
  audio[int(i*chunk_ms):int((i+1)*chunk_ms)].export(fn, format="wav")
96
+ parts.append(fn)
97
+ return parts
98
 
99
+ # ====== 轉錄核心 ======
100
  def transcribe_core(path, model="whisper-1"):
101
+ # iPhone LINE 常見:mp4(其實是音訊容器)
102
  if path.lower().endswith(".mp4"):
103
  fixed = path[:-4] + ".m4a"
104
+ try:
105
+ shutil.copy(path, fixed)
106
+ path = fixed
107
+ except Exception as e:
108
+ print(f"⚠️ mp4→m4a 失敗: {e}")
109
 
110
  chunks = split_audio(path)
111
+ raw = []
112
+ for c in chunks:
113
+ with open(c, "rb") as af:
114
+ txt = client.audio.transcriptions.create(
115
+ model=model,
116
+ file=af,
117
+ response_format="text"
118
+ )
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"將以下內容轉為台灣繁體,不意譯:\n{raw_txt}"}
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"請用台灣繁體中文摘要;內容多則條列重點,內容短則一句話:\n{trad}"}
139
+ ],
140
+ temperature=0.2
141
+ )
142
+ return trad, summ.choices[0].message.content.strip()
143
 
144
+ # ====== 對外函式(UI / API 共用) ======
145
  def transcribe(password, file):
146
  if password.strip() != PASSWORD:
147
  return "❌ 密碼錯誤", "", ""
148
  if not file:
149
  return "⚠️ 未選擇檔案", "", ""
150
 
 
 
151
  try:
152
+ path = _extract_effective_path(file)
 
 
 
 
 
 
 
 
 
 
153
  except Exception as e:
154
+ return f" 檔案解析失敗:{e}", "", ""
 
155
 
156
+ text, summary = transcribe_core(path)
157
  return "✅ 完成", text, summary
158
 
159
+ # ====== Gradio UI ======
160
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
161
+ gr.Markdown("## 🎧 LINE 語音轉錄與摘要(Hugging Face 版)")
162
  pw = gr.Textbox(label="密碼", type="password")
163
  f = gr.File(label="上傳音訊檔")
164
  run = gr.Button("開始轉錄 🚀")
165
  s = gr.Textbox(label="狀態", interactive=False)
166
  t = gr.Textbox(label="轉錄結果", lines=10)
167
  su = gr.Textbox(label="AI 摘要", lines=8)
168
+ # 🔴 關鍵:這個事件關閉 queue /gradio_api/call/transcribe 直接回結果
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)