Kuenyuan commited on
Commit
80f9045
·
verified ·
1 Parent(s): 235e876

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -51
app.py CHANGED
@@ -41,61 +41,106 @@ if GEMINI_KEY:
41
  print(f"Gemini 客戶端初始化失敗: {e}")
42
 
43
  SAVE_DIR = "saved_results"
 
44
  os.makedirs(SAVE_DIR, exist_ok=True)
 
45
 
46
  # --- 2. 核心功能函式 ---
47
 
48
- # (A. run_whisperx_process 函式 - 轉錄與區分,預設中文)
49
- def run_whisperx_process(audio_file_path):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  if not HF_TOKEN:
51
  return "錯誤: 請先設定 HUGGING_FACE_TOKEN。", ""
52
 
53
  print(f"-> 開始處理檔案: {os.path.basename(audio_file_path)}")
54
 
55
- # 載入模型時指定語言
56
- model = whisperx.load_model(WHISPER_MODEL, DEVICE, compute_type=COMPUTE_TYPE, language=LANGUAGE)
57
-
58
- audio = whisperx.load_audio(audio_file_path)
59
- # 轉錄時也指定語言,避免自動偵測延遲
60
- result = model.transcribe(audio, batch_size=4, language=LANGUAGE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- model_a, metadata = whisperx.load_align_model(language_code=LANGUAGE, device=DEVICE)
63
- result = whisperx.align(result["segments"], model_a, metadata, audio, DEVICE)
64
-
65
- # 嘗試從 whisperx.diarize 獲取 DiarizationPipeline,如果直接存取失敗
66
- # 嘗試從 whisperx.diarize 獲取 DiarizationPipeline
67
- try:
68
- from whisperx.diarize import DiarizationPipeline
69
- diarize_model = DiarizationPipeline(use_auth_token=HF_TOKEN, device=DEVICE)
70
- except ImportError:
71
  try:
72
- diarize_model = whisperx.DiarizationPipeline(use_auth_token=HF_TOKEN, device=DEVICE)
 
73
  except Exception as e:
74
- return f"DiarizationPipeline 初始化失敗 (ImportError): {e}", ""
75
- except Exception as e:
76
- import traceback
77
- print(f"Diarization Init Error Traceback:\n{traceback.format_exc()}")
78
 
79
- # 捕捉 Pyannote 下載失敗 (通常是權限或條款未接受)
80
- error_msg = str(e)
81
- if "'NoneType' object has no attribute 'to'" in error_msg or "401" in error_msg or "403" in error_msg:
82
- return (
83
- "❌ **Pyannote 模型載入失敗**\n\n"
84
- "這通常是因為未接受模型使用條款或 Token 權限不足。\n"
85
- "請執行以下步驟:\n"
86
- "1. 前往 [Hugging Face Pyannote 3.1](https://hf.co/pyannote/speaker-diarization-3.1) 並點擊 **Agree and access repository**。\n"
87
- "2. 確保您的 Token 具有 **Read** 權限。\n"
88
- "3. 重新啟動 Space 或應用程式。"
89
- ), ""
90
- # 其他錯誤
91
- return f"Diarization 執行錯誤: {e}", ""
92
- diarize_segments = diarize_model(audio)
93
-
94
- result = whisperx.assign_word_speakers(diarize_segments, result)
95
-
96
  raw_transcript = ""
97
- for segment in result["segments"]:
98
- raw_transcript += f"[{segment['speaker']}]: {segment['text'].strip()}\n"
 
99
 
100
  return raw_transcript, "轉錄與區分完成。"
101
 
@@ -263,32 +308,43 @@ def auto_process_wrapper(audio_file, audio_save_dir, custom_prompt, save_format,
263
 
264
  # --- 3. Gradio 介面主邏輯 (更新輸出) ---
265
 
266
- def full_process(audio_file, audio_save_dir, custom_prompt, save_format):
267
  if not audio_file:
268
- return "請上傳音訊或現場錄音。", "", "", None, None, list_saved_files()
269
 
270
  audio_path = audio_file
 
271
 
272
- # 0. 如果有指定目錄,先備份音訊
 
 
 
 
 
 
 
 
 
 
 
273
  save_msg_prefix = ""
274
  if audio_save_dir and audio_save_dir.strip():
275
  _, msg = save_audio_file(audio_path, audio_save_dir)
276
  save_msg_prefix = f"[{msg}] "
277
 
278
- # 1. 轉錄與區分
279
  raw_transcript_text, status_whisper = run_whisperx_process(audio_path)
280
 
281
- # 2. LLM 優化
282
  optimized_text, status_llm, llm_success = optimize_transcript_with_llm(raw_transcript_text, custom_prompt)
283
 
284
- # 3. 儲存結果
285
- file_name = os.path.basename(audio_path)
286
- save_status, download_path = save_result(file_name, raw_transcript_text, optimized_text, save_format)
287
 
288
- #另外儲存原始逐字稿
289
  raw_download_path = export_raw_transcript(raw_transcript_text)
290
 
291
- # 返回所有結果 (狀態訊息加入音訊儲存結果)
292
  final_status = f"{save_msg_prefix}{status_whisper} | {status_llm} | {save_status}"
293
  return raw_transcript_text, optimized_text, final_status, download_path, raw_download_path, list_saved_files()
294
 
@@ -326,6 +382,7 @@ with gr.Blocks(title="零成本協作轉錄工具") as demo:
326
 
327
  with gr.Row():
328
  process_btn = gr.Button("🚀 執行轉錄、區分與優化", variant="primary")
 
329
  clear_btn = gr.Button("🧹 清空所有欄位")
330
 
331
  with gr.Column():
@@ -366,6 +423,13 @@ with gr.Blocks(title="零成本協作轉錄工具") as demo:
366
  inputs=[audio_input, audio_save_dir, optimization_prompt, save_format_input],
367
  outputs=[raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
368
  )
 
 
 
 
 
 
 
369
 
370
  # 綁定僅儲存按鈕
371
  save_only_btn.click(
 
41
  print(f"Gemini 客戶端初始化失敗: {e}")
42
 
43
  SAVE_DIR = "saved_results"
44
+ CACHE_DIR = "cache"
45
  os.makedirs(SAVE_DIR, exist_ok=True)
46
+ os.makedirs(CACHE_DIR, exist_ok=True)
47
 
48
  # --- 2. 核心功能函式 ---
49
 
50
+ def check_duplicate_file(audio_file_path):
51
+ """檢查是否有相同檔名的已處理結果"""
52
+ if not audio_file_path:
53
+ return None
54
+
55
+ filename = os.path.basename(audio_file_path)
56
+ # 搜尋 saved_results 下是否有檔名匹配的 CSV
57
+ # 格式通常是 filename_timestamp.csv
58
+ for f in os.listdir(SAVE_DIR):
59
+ if f.startswith(filename) and f.endswith(".csv"):
60
+ return f
61
+ return None
62
+
63
+ def get_cache_path(audio_file_path, stage):
64
+ """獲取各階段的暫存路徑"""
65
+ filename = os.path.basename(audio_file_path)
66
+ return os.path.join(CACHE_DIR, f"{filename}_{stage}.pt")
67
+
68
+ def save_to_cache(data, audio_file_path, stage):
69
+ """儲存中間結果到暫存"""
70
+ path = get_cache_path(audio_file_path, stage)
71
+ torch.save(data, path)
72
+ print(f"-> 已暫存階段 {stage}: {path}")
73
+
74
+ def load_from_cache(audio_file_path, stage):
75
+ """從暫存載入中間結果"""
76
+ path = get_cache_path(audio_file_path, stage)
77
+ if os.path.exists(path):
78
+ print(f"-> 載入暫存階段 {stage}: {path}")
79
+ return torch.load(path)
80
+ return None
81
+
82
+ # (A. run_whisperx_process 函式 - 轉錄與區分,支援暫存與恢復)
83
+ def run_whisperx_process(audio_file_path, progress=gr.Progress()):
84
  if not HF_TOKEN:
85
  return "錯誤: 請先設定 HUGGING_FACE_TOKEN。", ""
86
 
87
  print(f"-> 開始處理檔案: {os.path.basename(audio_file_path)}")
88
 
89
+ # --- 階段 1: 轉錄 ---
90
+ result = load_from_cache(audio_file_path, "transcribe")
91
+ if not result:
92
+ progress(0.1, desc="正在載入模型並開始轉錄...")
93
+ model = whisperx.load_model(WHISPER_MODEL, DEVICE, compute_type=COMPUTE_TYPE, language=LANGUAGE)
94
+ audio = whisperx.load_audio(audio_file_path)
95
+ progress(0.2, desc="正在轉錄語音...")
96
+ result = model.transcribe(audio, batch_size=4, language=LANGUAGE)
97
+ save_to_cache(result, audio_file_path, "transcribe")
98
+ # 釋放模型以節省記憶體,但也可能導致重新載入
99
+ del model
100
+ torch.cuda.empty_cache()
101
+ else:
102
+ progress(0.3, desc="已從暫存恢復轉錄結果...")
103
+
104
+ # --- 階段 2: 對齊 ---
105
+ aligned_result = load_from_cache(audio_file_path, "align")
106
+ if not aligned_result:
107
+ progress(0.4, desc="正在執行文字對齊...")
108
+ audio = whisperx.load_audio(audio_file_path)
109
+ model_a, metadata = whisperx.load_align_model(language_code=LANGUAGE, device=DEVICE)
110
+ aligned_result = whisperx.align(result["segments"], model_a, metadata, audio, DEVICE)
111
+ save_to_cache(aligned_result, audio_file_path, "align")
112
+ del model_a
113
+ torch.cuda.empty_cache()
114
+ else:
115
+ progress(0.5, desc="已從暫存恢復對齊結果...")
116
 
117
+ # --- 階段 3: 語者區分 ---
118
+ final_result = load_from_cache(audio_file_path, "diarize")
119
+ if not final_result:
120
+ progress(0.6, desc="正在初始化語者區分模型...")
 
 
 
 
 
121
  try:
122
+ from whisperx.diarize import DiarizationPipeline
123
+ diarize_model = DiarizationPipeline(use_auth_token=HF_TOKEN, device=DEVICE)
124
  except Exception as e:
125
+ # (省略部分重複的錯誤處理邏輯,保持簡潔)
126
+ return f"Diarization 初始化失敗: {e}", ""
 
 
127
 
128
+ progress(0.7, desc="正在分析語者...")
129
+ audio = whisperx.load_audio(audio_file_path)
130
+ diarize_segments = diarize_model(audio)
131
+ progress(0.8, desc="正在指派語者標籤...")
132
+ final_result = whisperx.assign_word_speakers(diarize_segments, aligned_result)
133
+ save_to_cache(final_result, audio_file_path, "diarize")
134
+ del diarize_model
135
+ torch.cuda.empty_cache()
136
+ else:
137
+ progress(0.9, desc="已從暫存恢復語者區分結果...")
138
+
139
+ progress(1.0, desc="整理逐字稿內容...")
 
 
 
 
 
140
  raw_transcript = ""
141
+ for segment in final_result["segments"]:
142
+ speaker = segment.get('speaker', 'Unknown')
143
+ raw_transcript += f"[{speaker}]: {segment['text'].strip()}\n"
144
 
145
  return raw_transcript, "轉錄與區分完成。"
146
 
 
308
 
309
  # --- 3. Gradio 介面主邏輯 (更新輸出) ---
310
 
311
+ def full_process(audio_file, audio_save_dir, custom_prompt, save_format, re_process=False):
312
  if not audio_file:
313
+ return "", "", "請上傳音訊或現場錄音。", None, None, list_saved_files()
314
 
315
  audio_path = audio_file
316
+ filename = os.path.basename(audio_path)
317
 
318
+ # 0. 檢查重複與自動載入 (如果是自動處裡且沒強制 re_process)
319
+ if not re_process:
320
+ duplicate_csv = check_duplicate_file(audio_path)
321
+ if duplicate_csv:
322
+ raw, opt, msg = load_file_content(duplicate_csv)
323
+ #另外儲存原始逐字稿供下載
324
+ raw_download_path = export_raw_transcript(raw)
325
+ # 儲存優化後的檔案供下載 (如果有的話)
326
+ _, download_path = save_result(filename, raw, opt, save_format) # 此處實際上是確保格式正確並生成路徑
327
+ return raw, opt, f"🔄 已自動載入先前處理過的檔案: {duplicate_csv}", download_path, raw_download_path, list_saved_files()
328
+
329
+ # 1. 如果有指定目錄,先備份音訊
330
  save_msg_prefix = ""
331
  if audio_save_dir and audio_save_dir.strip():
332
  _, msg = save_audio_file(audio_path, audio_save_dir)
333
  save_msg_prefix = f"[{msg}] "
334
 
335
+ # 2. 轉錄與區分 (支援暫存)
336
  raw_transcript_text, status_whisper = run_whisperx_process(audio_path)
337
 
338
+ # 3. LLM 優化
339
  optimized_text, status_llm, llm_success = optimize_transcript_with_llm(raw_transcript_text, custom_prompt)
340
 
341
+ # 4. 儲存結果
342
+ save_status, download_path = save_result(filename, raw_transcript_text, optimized_text, save_format)
 
343
 
344
+ # 5. 另外儲存原始逐字稿
345
  raw_download_path = export_raw_transcript(raw_transcript_text)
346
 
347
+ # 返回所有結果
348
  final_status = f"{save_msg_prefix}{status_whisper} | {status_llm} | {save_status}"
349
  return raw_transcript_text, optimized_text, final_status, download_path, raw_download_path, list_saved_files()
350
 
 
382
 
383
  with gr.Row():
384
  process_btn = gr.Button("🚀 執行轉錄、區分與優化", variant="primary")
385
+ re_process_btn = gr.Button("🔄 重新執行 (忽略已有結果)", variant="secondary")
386
  clear_btn = gr.Button("🧹 清空所有欄位")
387
 
388
  with gr.Column():
 
423
  inputs=[audio_input, audio_save_dir, optimization_prompt, save_format_input],
424
  outputs=[raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
425
  )
426
+
427
+ # 綁定重新執行按鈕
428
+ re_process_btn.click(
429
+ fn=lambda a, d, p, f: full_process(a, d, p, f, re_process=True),
430
+ inputs=[audio_input, audio_save_dir, optimization_prompt, save_format_input],
431
+ outputs=[raw_output, optimized_output, status_output, download_btn, raw_download_btn, saved_files_list]
432
+ )
433
 
434
  # 綁定僅儲存按鈕
435
  save_only_btn.click(