Kuenyuan commited on
Commit
0a371c9
·
verified ·
1 Parent(s): 2b152e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -131
app.py CHANGED
@@ -146,133 +146,68 @@ def run_whisperx_process(audio_file_path, progress=gr.Progress()):
146
 
147
  return raw_transcript, "轉錄與區分完成。"
148
 
149
- def run_remote_whisperx_process(audio_file_path, api_url, progress=gr.Progress()):
150
- """透過 Colab API 遠端執行轉錄"""
151
- if not api_url or not api_url.startswith("http"):
152
- return "錯誤: 請提供有效的 Colab API 網址。", ""
153
-
154
  filename = os.path.basename(audio_file_path)
155
- progress(0.1, desc="正在連線至 Colab 伺服器...")
156
 
157
  try:
158
- with open(audio_file_path, 'rb') as f:
159
- files = {'file': (filename, f, 'audio/wav')}
160
- progress(0.3, desc="正在傳送音訊檔案至 Colab (視檔案大小而定)...")
161
- response = requests.post(f"{api_url.rstrip('/')}/transcribe", files=files, timeout=600)
 
 
 
 
162
 
163
- if response.status_code == 200:
164
- result = response.json()
165
- raw_transcript = result.get('raw_transcript', '')
166
- return raw_transcript, "遠端轉錄完成 (Colab GPU)。"
167
- else:
168
- return f"遠端伺服器錯誤 ({response.status_code}): {response.text}", ""
169
 
170
- except Exception as e:
171
- return f"遠端連線失敗: {e}", ""
172
-
173
- COLAB_WORKER_CODE = """
174
- # 在 Google Colab 執行此程式碼以啟用 GPU 算力
175
-
176
- # [重要] 如果您之前執行過失敗,請務必先執行上方的 [執行階段] -> [中斷並刪除執行階段],以清除髒掉的環境!
177
-
178
- # 1. 解除安裝可能衝突的套件 (清理環境)
179
- !pip uninstall -y transformers torch torchvision torchaudio whisperx --quiet
180
-
181
- # 2. 安裝穩定版 WhisperX (PyPI 版本,雖較舊但穩定) 與基礎依賴
182
- !pip install whisperx --quiet
183
- !pip install "protobuf<5.0.0" --quiet
184
- !pip install fastapi uvicorn python-multipart pyngrok --quiet
185
-
186
- # 3. 確保 numpy 版本相容 (numba 需求)
187
- !pip install "numpy<2.0.0" --quiet
188
-
189
- import os
190
- import sys
191
-
192
- # 嘗試處理可能的 Import 錯誤 (通常發生在未重啟 Runtime 時)
193
- try:
194
- # 重要:先載入 torch 並套用 Patch,再載入 whisperx
195
- import torch
196
-
197
- # --- PyTorch 2.6 兼容性修復 ---
198
- _original_torch_load = torch.load
199
- def _patched_torch_load(*args, **kwargs):
200
- kwargs['weights_only'] = False
201
- return _original_torch_load(*args, **kwargs)
202
- torch.load = _patched_torch_load
203
- print("-> PyTorch 2.6 兼容性修復已套用 (weights_only=False)")
204
-
205
- import whisperx
206
- from fastapi import FastAPI, UploadFile, File
207
- import uvicorn
208
- from pyngrok import ngrok
209
-
210
- except ImportError as e:
211
- print(f"\\n❌ 偵測到 Import 錯誤: {e}")
212
- print("這通常是因為新安裝的套件需要重啟環境。")
213
- print("請點擊 Colab 選單:[Runtime] -> [Restart session],然後再次執行此儲存格即可!")
214
- # 如果是腳本模式,不直接退出,讓用戶能看到提示
215
- sys.exit(0)
216
-
217
- app = FastAPI()
218
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
219
- WHISPER_MODEL = "medium"
220
- HF_TOKEN = "YOUR_HUGGING_FACE_TOKEN" # 請貼上您的 Token
221
-
222
- # 自動選擇算力類型: GPU 使用 float16, CPU 使用 int8
223
- COMPUTE_TYPE = "float16" if DEVICE == "cuda" else "int8"
224
-
225
- # 預載入模型
226
- print(f"-> 正在載入 WhisperX 模型 ({WHISPER_MODEL}) 到 {DEVICE} (預計使用 {COMPUTE_TYPE})...")
227
- try:
228
- model = whisperx.load_model(WHISPER_MODEL, DEVICE, compute_type=COMPUTE_TYPE)
229
- except Exception as e:
230
- print(f"-> {COMPUTE_TYPE} 載入失敗,嘗試使用 int8 作為備援...")
231
- model = whisperx.load_model(WHISPER_MODEL, DEVICE, compute_type="int8")
232
-
233
- @app.post("/transcribe")
234
- async def transcribe(file: UploadFile = File(...)):
235
- temp_path = f"temp_{file.filename}"
236
- with open(temp_path, "wb") as buffer:
237
- buffer.write(await file.read())
238
-
239
- try:
240
- audio = whisperx.load_audio(temp_path)
241
- result = model.transcribe(audio, batch_size=4)
242
 
243
- # 對齊
244
- model_a, metadata = whisperx.load_align_model(language_code="zh", device=DEVICE)
245
- result = whisperx.align(result["segments"], model_a, metadata, audio, DEVICE)
246
 
247
- # 語者區分
248
- from whisperx.diarize import DiarizationPipeline
249
- diarize_model = DiarizationPipeline(use_auth_token=HF_TOKEN, device=DEVICE)
250
- diarize_segments = diarize_model(audio)
251
- result = whisperx.assign_word_speakers(diarize_segments, result)
252
 
253
- raw_transcript = ""
254
- for segment in result["segments"]:
255
- speaker = segment.get('speaker', 'Unknown')
256
- raw_transcript += f"[{speaker}]: {segment['text'].strip()}\\n"
257
 
258
- return {"raw_transcript": raw_transcript}
259
- except Exception as e:
260
- return {"error": str(e)}
261
- finally:
262
- if os.path.exists(temp_path):
263
- os.remove(temp_path)
264
-
265
- # 啟動 Ngrok 隧道
266
- print("\\n--- 設定連線 ---")
267
- # 如果您有 Ngrok Authtoken,請取消下方註釋並填入
268
- # ngrok.set_auth_token("YOUR_NGROK_AUTHTOKEN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
- public_url = ngrok.connect(8000).public_url
271
- print(f"✅ Colab API 網址: {public_url}")
272
- print("請將上方網址複製並貼回轉錄工具的「Colab API 網址」欄位。")
273
 
274
- uvicorn.run(app, host="0.0.0.0", port=8000)
275
- """
276
 
277
 
278
  # --- B. LLM 優化 (模型已更新,含備援機制) ---
@@ -426,19 +361,19 @@ def save_only_wrapper(audio_file, target_dir):
426
  _, msg = save_audio_file(audio_file, target_dir)
427
  return msg, list_saved_files()
428
 
429
- def auto_process_wrapper(audio_file, audio_save_dir, custom_prompt, save_format, compute_provider, colab_url, auto_process):
430
  """自動處理包裝函數"""
431
  if not auto_process or not audio_file:
432
  # 如果沒勾選自動處理,或沒有音訊,什麼都不做 (返回原本的輸出狀態)
433
  return gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip()
434
 
435
  # 執行完整處理流程
436
- return full_process(audio_file, audio_save_dir, custom_prompt, save_format, compute_provider, colab_url)
437
 
438
 
439
  # --- 3. Gradio 介面主邏輯 (更新輸出) ---
440
 
441
- def full_process(audio_file, audio_save_dir, custom_prompt, save_format, compute_provider, colab_url, re_process=False):
442
  if not audio_file:
443
  return "", "", "請上傳音訊或現場錄音。", None, None, list_saved_files()
444
 
@@ -463,8 +398,10 @@ def full_process(audio_file, audio_save_dir, custom_prompt, save_format, compute
463
  save_msg_prefix = f"[{msg}] "
464
 
465
  # 2. 轉錄與區分
466
- if compute_provider == "Google Colab (GPU)":
467
- raw_transcript_text, status_whisper = run_remote_whisperx_process(audio_path, colab_url)
 
 
468
  else:
469
  # 本地端處理 (支援暫存)
470
  raw_transcript_text, status_whisper = run_whisperx_process(audio_path)
@@ -506,15 +443,12 @@ with gr.Blocks(title="零成本協作轉錄工具") as demo:
506
  with gr.Row():
507
  compute_provider = gr.Radio(
508
  label="���擇算力提供者",
509
- choices=["本機端 (CPU/GPU)", "Google Colab (GPU)"],
510
  value="本機端 (CPU/GPU)",
511
  scale=1
512
  )
513
- colab_url = gr.Textbox(label="Colab API 網址 (若選 Colab)", placeholder="https://xxxx.ngrok-free.app", scale=1)
514
-
515
- with gr.Accordion("🛠️ 如何使用 Google Colab 算力?", open=False):
516
- gr.Markdown("1. 開啟 [Google Colab](https://colab.research.google.com/) 並新增筆記本。\n2. 設定執行階段類型為 **T4 GPU**。\n3. 複製下方代碼並執行:")
517
- gr.Code(COLAB_WORKER_CODE, language="python")
518
 
519
  auto_process_chk = gr.Checkbox(label="錄音停止/上傳後立即轉錄", value=False)
520
 
@@ -571,14 +505,14 @@ with gr.Blocks(title="零成本協作轉錄工具") as demo:
571
  # 綁定主要按鈕 (新增 audio_save_dir 輸入)
572
  process_btn.click(
573
  fn=full_process,
574
- inputs=[audio_input, audio_save_dir, optimization_prompt, save_format_input, compute_provider, colab_url],
575
  outputs=[raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
576
  )
577
 
578
  # 綁定重新執行按鈕
579
  re_process_btn.click(
580
- fn=lambda a, d, p, f, c, u: full_process(a, d, p, f, c, u, re_process=True),
581
- inputs=[audio_input, audio_save_dir, optimization_prompt, save_format_input, compute_provider, colab_url],
582
  outputs=[raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
583
  )
584
 
@@ -590,7 +524,7 @@ with gr.Blocks(title="零成本協作轉錄工具") as demo:
590
  )
591
 
592
  # 綁定自動處理 (錄音停止或上傳完成)
593
- auto_trigger_inputs = [audio_input, audio_save_dir, optimization_prompt, save_format_input, compute_provider, colab_url, auto_process_chk]
594
  auto_trigger_outputs = [raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
595
 
596
  audio_input.stop_recording(fn=auto_process_wrapper, inputs=auto_trigger_inputs, outputs=auto_trigger_outputs)
 
146
 
147
  return raw_transcript, "轉錄與區分完成。"
148
 
149
+ def run_gemini_audio_process(audio_file_path, progress=gr.Progress()):
150
+ """透過 Gemini Native Audio 直接轉錄 (支援長音訊與語者區分)"""
151
+ if not LLM_CLIENT:
152
+ return "錯誤: 請先設定有效的 Google AI Studio API Key。", ""
153
+
154
  filename = os.path.basename(audio_file_path)
155
+ progress(0.1, desc=f"正在上傳音訊至 Gemini: {filename}...")
156
 
157
  try:
158
+ # 1. 上傳檔案
159
+ audio_file = LLM_CLIENT.upload_file(audio_file_path)
160
+
161
+ # 2. 等待檔案處理完成 (State Polling)
162
+ while audio_file.state.name == "PROCESSING":
163
+ progress(0.2, desc="Gemini 正在處理音訊檔案 (轉檔中)...")
164
+ time.sleep(2)
165
+ audio_file = LLM_CLIENT.get_file(audio_file.name)
166
 
167
+ if audio_file.state.name == "FAILED":
168
+ return f"Gemini 檔案處理失敗: {audio_file.state.name}", ""
 
 
 
 
169
 
170
+ progress(0.4, desc="正在請求 Gemini 進行轉錄與區分 (可能需要幾分鐘)...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ # 3. 定義提示詞 (要求語者區分)
173
+ prompt = "請將這段音訊轉錄為逐字稿。請務必區分不同的發言者 (例如 [Speaker A], [Speaker B])。請直接輸出內容,不要包含 Markdown 程式碼區塊。"
 
174
 
175
+ # 4. 模型嘗試順序 (2025/12 策略: 2.5 -> 2.0)
176
+ models_to_try = ["gemini-2.5-flash", "gemini-2.0-flash"]
 
 
 
177
 
178
+ final_text = ""
179
+ used_model = ""
 
 
180
 
181
+ for model_name in models_to_try:
182
+ try:
183
+ progress(0.5, desc=f"嘗試模型: {model_name}...")
184
+ model = LLM_CLIENT.GenerativeModel(model_name)
185
+ # 設定 generation_config 增加輸出 token 上限,避免長錄音截斷
186
+ response = model.generate_content(
187
+ [prompt, audio_file],
188
+ config=types.GenerateContentConfig(max_output_tokens=8192)
189
+ )
190
+ final_text = response.text
191
+ used_model = model_name
192
+ break # 成功則跳出迴圈
193
+ except Exception as e:
194
+ print(f"模型 {model_name} 失敗: {e}")
195
+ continue # 嘗試下一個模型
196
+
197
+ # 5. 清理雲端檔案 (重要!避免占用配額)
198
+ try:
199
+ LLM_CLIENT.delete_file(audio_file.name)
200
+ except:
201
+ pass
202
+
203
+ if not final_text:
204
+ return "錯誤: 所有 Gemini 模型皆嘗試失敗,請檢查 API 配額或改用本機端轉錄。", ""
205
+
206
+ return final_text, f"Gemini 轉錄完成 (使用模型: {used_model})。"
207
 
208
+ except Exception as e:
209
+ return f"Gemini 處理發生未預期錯誤: {e}", ""
 
210
 
 
 
211
 
212
 
213
  # --- B. LLM 優化 (模型已更新,含備援機制) ---
 
361
  _, msg = save_audio_file(audio_file, target_dir)
362
  return msg, list_saved_files()
363
 
364
+ def auto_process_wrapper(audio_file, audio_save_dir, custom_prompt, save_format, compute_provider, auto_process):
365
  """自動處理包裝函數"""
366
  if not auto_process or not audio_file:
367
  # 如果沒勾選自動處理,或沒有音訊,什麼都不做 (返回原本的輸出狀態)
368
  return gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip()
369
 
370
  # 執行完整處理流程
371
+ return full_process(audio_file, audio_save_dir, custom_prompt, save_format, compute_provider)
372
 
373
 
374
  # --- 3. Gradio 介面主邏輯 (更新輸出) ---
375
 
376
+ def full_process(audio_file, audio_save_dir, custom_prompt, save_format, compute_provider, re_process=False):
377
  if not audio_file:
378
  return "", "", "請上傳音訊或現場錄音。", None, None, list_saved_files()
379
 
 
398
  save_msg_prefix = f"[{msg}] "
399
 
400
  # 2. 轉錄與區分
401
+ # 2. 轉錄與區分
402
+ if compute_provider == "Gemini Native (Free/Fast)":
403
+ # 使用 Gemini 原生音訊處理 (2025/12 推薦)
404
+ raw_transcript_text, status_whisper = run_gemini_audio_process(audio_path)
405
  else:
406
  # 本地端處理 (支援暫存)
407
  raw_transcript_text, status_whisper = run_whisperx_process(audio_path)
 
443
  with gr.Row():
444
  compute_provider = gr.Radio(
445
  label="���擇算力提供者",
446
+ choices=["本機端 (CPU/GPU)", "Gemini Native (Free/Fast)"],
447
  value="本機端 (CPU/GPU)",
448
  scale=1
449
  )
450
+ with gr.Accordion("ℹ️ 關於 Gemini Native 算力", open=False):
451
+ gr.Markdown("使用 Google Gemini 2.5 Flash 模型直接處理音訊,無需 Colab 或本地顯卡。支援長達 9 小時的音訊。")
 
 
 
452
 
453
  auto_process_chk = gr.Checkbox(label="錄音停止/上傳後立即轉錄", value=False)
454
 
 
505
  # 綁定主要按鈕 (新增 audio_save_dir 輸入)
506
  process_btn.click(
507
  fn=full_process,
508
+ inputs=[audio_input, audio_save_dir, optimization_prompt, save_format_input, compute_provider],
509
  outputs=[raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
510
  )
511
 
512
  # 綁定重新執行按鈕
513
  re_process_btn.click(
514
+ fn=lambda a, d, p, f, c: full_process(a, d, p, f, c, re_process=True),
515
+ inputs=[audio_input, audio_save_dir, optimization_prompt, save_format_input, compute_provider],
516
  outputs=[raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
517
  )
518
 
 
524
  )
525
 
526
  # 綁定自動處理 (錄音停止或上傳完成)
527
+ auto_trigger_inputs = [audio_input, audio_save_dir, optimization_prompt, save_format_input, compute_provider, auto_process_chk]
528
  auto_trigger_outputs = [raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
529
 
530
  audio_input.stop_recording(fn=auto_process_wrapper, inputs=auto_trigger_inputs, outputs=auto_trigger_outputs)