Spaces:
Sleeping

Kuenyuan's picture
Update app.py
b324da5 verified
Raw History Blame Contribute Delete
39.1 kB
import os import time import subprocess import sys from datetime import datetime import threading import queue import tempfile import numpy as np # --- 確保關鍵套件已安裝 --- def ensure_packages(): required = { 'google-generativeai': 'google.generativeai', 'gradio': 'gradio', 'pandas': 'pandas', 'python-docx': 'docx', 'mutagen': 'mutagen', 'boto3': 'boto3' } for pkg, import_name in required.items(): try: __import__(import_name) except ImportError: print(f"正在安裝 {pkg}...") subprocess.check_call([sys.executable, '-m', 'pip', 'install', pkg, '-q']) ensure_packages() import gradio as gr import pandas as pd from docx import Document from io import BytesIO import json # --- 導入 Gemini --- import google.generativeai as genai # --- Cloudflare R2 設定 --- import boto3 from botocore.config import Config R2_ACCOUNT_ID = os.environ.get('R2_ACCOUNT_ID', '').strip() R2_ACCESS_KEY = os.environ.get('R2_ACCESS_KEY_ID', '').strip() R2_SECRET_KEY = os.environ.get('R2_SECRET_ACCESS_KEY', '').strip() R2_BUCKET = os.environ.get('R2_BUCKET_NAME', 'transcripts').strip() HF_TOKEN = os.environ.get('HUGGING_FACE_TOKEN', '').strip() GEMINI_KEY = os.environ.get('GEMINI_API_KEY', '').strip() HAS_R2 = False r2_client = None if R2_ACCOUNT_ID and R2_ACCESS_KEY and R2_SECRET_KEY: try: r2_client = boto3.client( 's3', endpoint_url=f'https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com', aws_access_key_id=R2_ACCESS_KEY, aws_secret_access_key=R2_SECRET_KEY, config=Config(signature_version='s3v4'), region_name='auto' ) HAS_R2 = True print(f"✅ Cloudflare R2 連線成功 (Bucket: {R2_BUCKET})") except Exception as e: print(f"❌ R2 初始化失敗: {e}") else: print("⚠️ 未設定 R2 環境變數,僅使用本機儲存") # --- R2 操作函式 --- def r2_list_files(prefix=""): if not HAS_R2: return [] try: response = r2_client.list_objects_v2(Bucket=R2_BUCKET, Prefix=prefix) files = [obj['Key'] for obj in response.get('Contents', [])] return sorted(files, reverse=True) except Exception as e: print(f"R2 列表失敗: {e}") return [] def r2_upload_content(content, r2_key): if not HAS_R2: return False try: r2_client.put_object(Bucket=R2_BUCKET, Key=r2_key, Body=content.encode('utf-8')) print(f"✅ R2 上傳成功: {r2_key}") return True except Exception as e: print(f"❌ R2 上傳失敗: {e}") return False def r2_get_content(r2_key): if not HAS_R2: return None try: response = r2_client.get_object(Bucket=R2_BUCKET, Key=r2_key) content = response['Body'].read().decode('utf-8') return content except Exception as e: print(f"❌ R2 讀取失敗: {e}") return None # --- WhisperX 設定 --- HAS_TORCH = False HAS_WHISPERX = False DEVICE = "cpu" whisperx = None try: import torch HAS_TORCH = True DEVICE = "cuda" if torch.cuda.is_available() else "cpu" _original_torch_load = torch.load def _patched_torch_load(*args, **kwargs): kwargs['weights_only'] = False return _original_torch_load(*args, **kwargs) torch.load = _patched_torch_load try: import whisperx as _whisperx whisperx = _whisperx HAS_WHISPERX = True print("✅ WhisperX 載入成功") except Exception as e: print(f"⚠️ WhisperX 未安裝: {e}") except ImportError: print("⚠️ PyTorch 未安裝,將僅使用 Gemini Native 模式") # --- 全域設定 --- WHISPER_MODEL = "medium" LANGUAGE = "zh" COMPUTE_TYPE = "float16" if DEVICE == "cuda" else "int8" GEMINI_LLM_MODEL = 'gemini-2.0-flash-exp' if HF_TOKEN: os.environ['HUGGING_FACE_TOKEN'] = HF_TOKEN if GEMINI_KEY: os.environ['GEMINI_API_KEY'] = GEMINI_KEY HAS_GEMINI_KEY = False if GEMINI_KEY: try: genai.configure(api_key=GEMINI_KEY, transport="rest") HAS_GEMINI_KEY = True print("✅ Gemini API 初始化成功") except Exception as e: print(f"❌ Gemini 初始化失敗: {e}") SAVE_DIR = "saved_results" CACHE_DIR = "cache" os.makedirs(SAVE_DIR, exist_ok=True) os.makedirs(CACHE_DIR, exist_ok=True) # --- 音訊時長偵測 --- try: from mutagen import File as MutagenFile HAS_MUTAGEN = True except ImportError: HAS_MUTAGEN = False print("⚠️ mutagen 未安裝,將使用檔案大小估算") def get_audio_duration(audio_path): """獲取音訊時長 (秒)""" if HAS_MUTAGEN: try: audio = MutagenFile(audio_path) if audio and audio.info: return audio.info.length except Exception as e: print(f"mutagen 讀取失敗: {e}") try: file_size = os.path.getsize(audio_path) estimated_duration = file_size / (128 * 1024 / 8) return estimated_duration except: return 0 def format_duration(seconds): """格式化時長顯示""" if seconds < 60: return f"{seconds:.0f}秒" elif seconds < 3600: return f"{seconds/60:.1f}分鐘" else: return f"{seconds/3600:.1f}小時" # --- 全域取消控制 --- class CancelController: def __init__(self): self.cancel_transcribe = False self.cancel_optimize = False self.cancel_realtime = False self._lock = threading.Lock() def reset_all(self): with self._lock: self.cancel_transcribe = False self.cancel_optimize = False self.cancel_realtime = False def set_transcribe_cancel(self): with self._lock: self.cancel_transcribe = True def set_optimize_cancel(self): with self._lock: self.cancel_optimize = True def set_realtime_cancel(self): with self._lock: self.cancel_realtime = True def should_cancel(self, operation): with self._lock: return getattr(self, f'cancel_{operation}', False) cancel_ctrl = CancelController() # --- 智慧 Provider 選擇 --- HYBRID_THRESHOLD_MINUTES = 10 def get_smart_provider(audio_path, user_choice): """智慧選擇最佳轉錄 provider""" if user_choice == "Gemini Native": return "gemini", "使用者選擇" if user_choice == "本機端 WhisperX": if HAS_WHISPERX: return "whisperx", "使用者選擇" else: return "gemini", "WhisperX 未安裝" duration = get_audio_duration(audio_path) duration_min = duration / 60 if duration_min < HYBRID_THRESHOLD_MINUTES: return "gemini", f"短音訊 ({format_duration(duration)})" else: if HAS_WHISPERX: return "whisperx", f"長音訊 ({format_duration(duration)})" else: return "gemini", f"長音訊 (WhisperX 未安裝)" # --- Gemini 轉錄 --- def run_gemini_audio_process(audio_file_path, progress_callback=None): """Gemini Native Audio 轉錄 - 優化版""" if not HAS_GEMINI_KEY: return None, "❌ 錯誤: 請先設定 Google AI Studio API Key" filename = os.path.basename(audio_file_path) file_size_mb = os.path.getsize(audio_file_path) / (1024 * 1024) if progress_callback: progress_callback(0.1, f"📤 正在上傳音訊: {filename} ({file_size_mb:.1f}MB)") try: audio_file = genai.upload_file(path=audio_file_path) wait_count = 0 while audio_file.state.name == "PROCESSING": if cancel_ctrl.should_cancel('transcribe'): try: genai.delete_file(audio_file.name) except: pass return None, "⏹️ 轉錄已取消" wait_count += 1 if progress_callback: progress_callback(0.2 + min(wait_count * 0.03, 0.3), f"⏳ Gemini 處理中... ({wait_count * 2}秒)") time.sleep(2) audio_file = genai.get_file(audio_file.name) if wait_count > 150: return None, "❌ 處理超時 (超過5分鐘)" if audio_file.state.name == "FAILED": return None, f"❌ Gemini 處理失敗: {audio_file.state.name}" if progress_callback: progress_callback(0.5, "🤖 正在生成逐字稿...") prompt = """請將這段音訊轉錄為逐字稿,要求: 1. 嚴格區分不同發言者 (使用 [Speaker A], [Speaker B] 等標記) 2. 保留語氣詞和停頓 (如「嗯」、「那個」) 3. 每個發言者的完整句子為一行 4. 直接輸出內容,不要任何 Markdown 標記 格式範例: [Speaker A]: 你好,今天我們來討論一下這個專案。 [Speaker B]: 好的,我準備了一些資料。""" models_to_try = ["gemini-2.0-flash-exp", "gemini-1.5-flash"] final_text = "" used_model = "" for model_name in models_to_try: if cancel_ctrl.should_cancel('transcribe'): break try: if progress_callback: progress_callback(0.7, f"🔄 嘗試模型: {model_name}") model = genai.GenerativeModel(model_name) response = model.generate_content( [prompt, audio_file], request_options={"timeout": 600}, generation_config=genai.types.GenerationConfig( temperature=0.1, top_p=0.95, ) ) final_text = response.text used_model = model_name break except Exception as e: print(f"模型 {model_name} 失敗: {e}") continue try: genai.delete_file(audio_file.name) except: pass if not final_text: return None, "❌ 所有模型皆失敗,請檢查 API 配額" if progress_callback: progress_callback(1.0, "✅ 轉錄完成") return final_text, f"✅ 轉錄成功 ({used_model})" except Exception as e: return None, f"❌ 未預期錯誤: {str(e)}" # --- WhisperX 轉錄 --- def run_whisperx_process(audio_file_path, progress_callback=None): """WhisperX 轉錄 - 優化版""" if not HAS_WHISPERX: return None, "❌ WhisperX 未安裝" if not HF_TOKEN: return None, "❌ 請先設定 HUGGING_FACE_TOKEN" try: if progress_callback: progress_callback(0.1, "🔧 載入 Whisper 模型...") model = whisperx.load_model(WHISPER_MODEL, DEVICE, compute_type=COMPUTE_TYPE, language=LANGUAGE) audio = whisperx.load_audio(audio_file_path) if progress_callback: progress_callback(0.3, "🎯 執行語音轉錄...") result = model.transcribe(audio, batch_size=4, language=LANGUAGE) del model if HAS_TORCH: torch.cuda.empty_cache() if progress_callback: progress_callback(0.5, "📍 執行文字對齊...") model_a, metadata = whisperx.load_align_model(language_code=LANGUAGE, device=DEVICE) aligned_result = whisperx.align(result["segments"], model_a, metadata, audio, DEVICE) del model_a if HAS_TORCH: torch.cuda.empty_cache() if progress_callback: progress_callback(0.7, "👥 執行語者區分...") from whisperx.diarize import DiarizationPipeline diarize_model = DiarizationPipeline(use_auth_token=HF_TOKEN, device=DEVICE) diarize_segments = diarize_model(audio) final_result = whisperx.assign_word_speakers(diarize_segments, aligned_result) del diarize_model if HAS_TORCH: torch.cuda.empty_cache() if progress_callback: progress_callback(0.9, "📝 整理逐字稿...") raw_transcript = "" for segment in final_result["segments"]: speaker = segment.get('speaker', 'Unknown') raw_transcript += f"[{speaker}]: {segment['text'].strip()}\n" if progress_callback: progress_callback(1.0, "✅ 轉錄完成") return raw_transcript, "✅ 轉錄與區分完成" except Exception as e: return None, f"❌ WhisperX 處理失敗: {str(e)}" # --- 實時轉錄 (簡化版,使用 Gemini) --- class RealtimeTranscriber: def __init__(self): self.audio_buffer = [] self.transcript = "" self.is_active = False self.lock = threading.Lock() def start(self): with self.lock: self.is_active = True self.audio_buffer = [] self.transcript = "" def stop(self): with self.lock: self.is_active = False def add_audio(self, audio_data): with self.lock: if self.is_active and audio_data is not None: self.audio_buffer.append(audio_data) def get_transcript(self): with self.lock: return self.transcript def process_buffer(self): """處理累積的音訊 (應在背景執行緒呼叫)""" with self.lock: if not self.audio_buffer or not self.is_active: return # 簡化:僅示範架構,實際需要音訊處理 # 實際應用中應累積至一定長度後批次處理 if len(self.audio_buffer) >= 10: # 累積10個chunk self.audio_buffer = [] self.transcript += "[實時轉錄功能需要進階音訊處理] " realtime_transcriber = RealtimeTranscriber() # --- LLM 優化 --- def optimize_transcript_with_llm(raw_transcript, custom_prompt, speaker_info=None, analysis_target="全部"): """LLM 優化 - 改進版""" if cancel_ctrl.should_cancel('optimize'): return raw_transcript, "⏹️ 優化已取消", False if not HAS_GEMINI_KEY: return raw_transcript, "❌ LLM 不可用 (請檢查 API Key)", False role_prompt = "" if speaker_info: role_prompt = "\n\n【發言者角色定義】\n" for spk, role in speaker_info.items(): if role and role.strip(): role_prompt += f"- {spk}: {role}\n" target_prompt = "" if analysis_target and analysis_target != "全部": target_prompt = f"\n\n【重點分析對象】\n請特別針對「{analysis_target}」的發言內容進行分析與摘要。" full_prompt = ( f"以下是一段帶有發言者標籤的原始逐字稿,請依據「自定義優化指令」處理:\n\n" f"--- 原始逐字稿 ---\n{raw_transcript}\n\n" f"--- 自定義優化指令 ---\n{custom_prompt}" f"{role_prompt}" f"{target_prompt}" ) if cancel_ctrl.should_cancel('optimize'): return raw_transcript, "⏹️ 優化已取消", False try: model = genai.GenerativeModel(GEMINI_LLM_MODEL) response = model.generate_content( full_prompt, generation_config=genai.types.GenerationConfig( temperature=0.7, top_p=0.95, ) ) if cancel_ctrl.should_cancel('optimize'): return raw_transcript, "⏹️ 優化已取消 (忽略結果)", False return response.text, "✅ LLM 優化成功", True except Exception as e: error_msg = str(e) advice = "" if "429" in error_msg: advice = "💡 原因: API 配額已滿\n建議: 請稍候再試或更換 API Key" elif "400" in error_msg or "INVALID_ARGUMENT" in error_msg: advice = "💡 原因: Prompt 太長或格式錯誤\n建議: 嘗試縮短內容" elif "500" in error_msg or "503" in error_msg: advice = "💡 原因: Google 伺服器暫時無法回應\n建議: 稍後重試" else: advice = f"💡 原始錯誤: {error_msg}" full_msg = f"❌ 優化失敗\n{advice}\n→ 已保留原始逐字稿" return raw_transcript, full_msg, False # --- 檔案操作 --- def create_docx(content): """創建 Word 文件""" document = Document() for line in content.split('\n'): if line.startswith('# '): document.add_heading(line.lstrip('# ').strip(), level=1) elif line.startswith('## '): document.add_heading(line.lstrip('## ').strip(), level=2) else: document.add_paragraph(line) buffer = BytesIO() document.save(buffer) buffer.seek(0) return buffer.read() def save_transcript(content, filename_base, file_format='.txt', suffix='raw'): """儲存逐字稿""" timestamp = int(time.time()) filename = f"{filename_base}_{timestamp}_{suffix}{file_format}" filepath = os.path.join(SAVE_DIR, filename) try: if file_format == '.docx': docx_content = create_docx(content) with open(filepath, 'wb') as f: f.write(docx_content) else: with open(filepath, 'w', encoding='utf-8') as f: f.write(content) return filepath, filename except Exception as e: return None, f"儲存失敗: {e}" def list_saved_files(ext_filter=None): """列出已儲存檔案""" try: files = os.listdir(SAVE_DIR) if ext_filter: files = [f for f in files if f.endswith(ext_filter)] return sorted(files, reverse=True) except: return [] # --- 主要處理函式 --- def process_single_audio(audio_path, provider_choice, storage_dest, progress=gr.Progress()): """處理單一音訊檔案 - 優化版""" cancel_ctrl.reset_all() if not audio_path: return { 'status': "⚠️ 請上傳音訊檔案", 'transcript': "", 'file_info': "", 'download': None, 'next_enabled': False } filename = os.path.basename(audio_path) file_size = os.path.getsize(audio_path) / (1024 * 1024) duration = get_audio_duration(audio_path) file_info = f"📄 檔案: {filename}\n📊 大小: {file_size:.1f}MB | 時長: {format_duration(duration)}" provider, reason = get_smart_provider(audio_path, provider_choice) provider_label = "🌐 Gemini" if provider == "gemini" else "💻 WhisperX" progress(0.05, desc=f"{provider_label} 準備中...") start_time = time.time() def progress_callback(value, desc): if not cancel_ctrl.should_cancel('transcribe'): progress(value, desc=desc) try: if provider == "gemini": transcript, status = run_gemini_audio_process(audio_path, progress_callback) else: transcript, status = run_whisperx_process(audio_path, progress_callback) if cancel_ctrl.should_cancel('transcribe'): return { 'status': "⏹️ 轉錄已取消", 'transcript': "", 'file_info': file_info, 'download': None, 'next_enabled': False } if not transcript or "❌" in status: return { 'status': status, 'transcript': "", 'file_info': file_info, 'download': None, 'next_enabled': False } elapsed = time.time() - start_time base_name = os.path.splitext(filename)[0] filepath, saved_filename = save_transcript(transcript, base_name, '.txt', 'raw') storage_info = [] if storage_dest in ["本機", "兩者"]: storage_info.append(f"💾 本機: {saved_filename}") if storage_dest in ["Cloudflare R2", "兩者"] and HAS_R2: r2_key = f"transcripts/{saved_filename}" if r2_upload_content(transcript, r2_key): storage_info.append(f"☁️ R2: {r2_key}") final_status = ( f"✅ 轉錄完成!\n" f"⏱️ 耗時: {elapsed:.1f}秒 | {provider_label} ({reason})\n" f"{chr(10).join(storage_info)}\n" f"💡 你可以在下方編輯內容,或直接點擊「下一步:AI優化」" ) return { 'status': final_status, 'transcript': transcript, 'file_info': file_info, 'download': filepath, 'next_enabled': True } except Exception as e: return { 'status': f"❌ 處理失敗: {str(e)}", 'transcript': "", 'file_info': file_info, 'download': None, 'next_enabled': False } # --- UI 介面 --- CUSTOM_CSS = """ .main-title { text-align: center; font-size: 2.5em; font-weight: 700; margin-bottom: 0.3em; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .subtitle { text-align: center; color: #666; margin-bottom: 2em; font-size: 1.1em; } .status-box { font-family: 'Courier New', monospace; background: #f8f9fa; border-left: 4px solid #667eea; padding: 1em; } .info-box { background: #e7f3ff; border: 1px solid #b3d9ff; border-radius: 8px; padding: 1em; margin: 0.5em 0; } """ with gr.Blocks(title="業務訪談一鍵轉錄 V4", css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo: gr.Markdown("# 🎙️ 業務訪談一鍵轉錄 V4", elem_classes="main-title") gr.Markdown("智慧混合引擎 | 即時編輯 | 一鍵優化 | 穩定可靠", elem_classes="subtitle") current_transcript = gr.State("") current_filename = gr.State("") with gr.Tabs() as tabs: # ===== Tab 1: 音訊轉錄 ===== with gr.Tab("🎙️ 步驟一:音訊轉錄", id=0): with gr.Row(): with gr.Column(scale=2): gr.Markdown("### 📁 上傳音訊") audio_input = gr.Audio( label="上傳音訊檔案或麥克風錄音", type="filepath", sources=["upload", "microphone"] ) file_info_display = gr.Markdown("", elem_classes="info-box") gr.Markdown("### ⚙️ 轉錄設定") with gr.Row(): provider_choice = gr.Radio( label="轉錄引擎", choices=["智慧選擇 (推薦)", "Gemini Native", "本機端 WhisperX"], value="智慧選擇 (推薦)", info=f"智慧模式: <10分鐘用Gemini, ≥10分鐘用WhisperX | WhisperX: {'✅' if HAS_WHISPERX else '❌'}" ) storage_choice = gr.Radio( label="儲存位置", choices=["本機", "Cloudflare R2", "兩者"], value="本機", info=f"R2 狀態: {'✅ 已連線' if HAS_R2 else '❌ 未設定'}" ) with gr.Row(): transcribe_btn = gr.Button("🚀 開始轉錄", variant="primary", scale=3) cancel_transcribe_btn = gr.Button("⏹️ 取消", variant="stop", scale=1) with gr.Column(scale=3): gr.Markdown("### 📊 轉錄進度與結果") transcribe_status = gr.Markdown( "等待上傳音訊檔案...", elem_classes="status-box" ) transcript_editor = gr.Textbox( label="✏️ 逐字稿內容 (可編輯)", lines=15, placeholder="轉錄完成後,內容會顯示在此處,你可以直接編輯...", interactive=True ) with gr.Row(): download_transcript = gr.File(label="📥 下載逐字稿", visible=False) next_step_btn = gr.Button("➡️ 下一步:AI 優化", variant="primary", size="lg", visible=False) def on_transcribe(audio, provider, storage, progress=gr.Progress()): result = process_single_audio(audio, provider, storage, progress) return ( result['file_info'], result['status'], result['transcript'], result['download'], gr.Button(visible=result['next_enabled']), result['transcript'], os.path.basename(audio) if audio else "" ) transcribe_btn.click( fn=on_transcribe, inputs=[audio_input, provider_choice, storage_choice], outputs=[file_info_display, transcribe_status, transcript_editor, download_transcript, next_step_btn, current_transcript, current_filename] ) cancel_transcribe_btn.click( fn=lambda: [cancel_ctrl.set_transcribe_cancel(), "⏹️ 正在取消..."][1], outputs=transcribe_status ) transcript_editor.change( fn=lambda x: x, inputs=transcript_editor, outputs=current_transcript ) next_step_btn.click( fn=lambda: gr.Tabs(selected=1), outputs=tabs ) # ===== Tab 2: AI 優化 ===== with gr.Tab("✨ 步驟二:AI 優化", id=1): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 📄 選擇文本來源") source_type = gr.Radio( label="資料來源", choices=["從步驟一繼續", "選擇已儲存檔案", "上傳新檔案", "從 R2 讀取"], value="從步驟一繼續", info="推薦: 直接從步驟一轉錄的內容繼續" ) with gr.Group(visible=False) as saved_file_group: file_dropdown = gr.Dropdown( label="選擇檔案", choices=list_saved_files(".txt"), interactive=True ) refresh_btn = gr.Button("🔄 刷新列表", size="sm") with gr.Group(visible=False) as upload_file_group: upload_text = gr.File(label="上傳文字檔", file_types=[".txt", ".md"]) with gr.Group(visible=False) as r2_file_group: r2_dropdown = gr.Dropdown( label="R2 檔案", choices=r2_list_files("transcripts/") if HAS_R2 else [], interactive=True ) r2_refresh_btn = gr.Button("🔄 刷新 R2", size="sm") gr.Markdown("### 🎭 發言者設定 (選填)") with gr.Row(): host_name = gr.Textbox(label="主持人", placeholder="例如: 張經理", scale=1) guest_name = gr.Textbox(label="受訪者", placeholder="例如: 客戶A, 客戶B", scale=2) analysis_target = gr.Dropdown( label="重點分析對象", choices=["全部", "僅主持人", "僅受訪者"], value="全部", allow_custom_value=True, info="可手動輸入特定人名" ) gr.Markdown("### 📝 優化設定") report_type = gr.Dropdown( label="報告類型", choices=["綜合會議紀錄", "趨勢分析報告", "行動清單 (Action Items)", "自定義"], value="綜合會議紀錄", info="選擇後會自動調整 Prompt" ) optimize_prompt = gr.Textbox( label="優化指令", value="你是專業的會議紀錄分析專家。請分析逐字稿,產出結構化報告:\n1. 資料概覽\n2. 核心分析\n3. 後續建議\n4. 格式代碼", lines=6, info="可自由編輯優化指令" ) with gr.Row(): save_format = gr.Radio( label="輸出格式", choices=['.md', '.txt', '.docx'], value='.md', scale=2 ) save_dest = gr.Radio( label="儲存至", choices=["本機", "R2", "兩者"], value="本機", scale=1 ) with gr.Row(): optimize_btn = gr.Button("✨ 執行優化", variant="primary", scale=3) cancel_optimize_btn = gr.Button("⏹️ 取消", variant="stop", scale=1) with gr.Column(scale=2): gr.Markdown("### 📊 優化結果") optimize_status = gr.Markdown("等待執行...", elem_classes="status-box") with gr.Accordion("📜 原始逐字稿預覽", open=False): raw_preview = gr.Textbox(label="", lines=6, show_label=False, interactive=False) optimized_output = gr.Textbox( label="✅ 優化後內容", lines=18, placeholder="優化完成後會顯示在此...", interactive=True ) download_optimized = gr.File(label="📥 下載優化結果") def toggle_source(choice): return ( gr.Group(visible=(choice == "選擇已儲存檔案")), gr.Group(visible=(choice == "上傳新檔案")), gr.Group(visible=(choice == "從 R2 讀取")) ) source_type.change( fn=toggle_source, inputs=source_type, outputs=[saved_file_group, upload_file_group, r2_file_group] ) def update_prompt(report_type): templates = { "綜合會議紀錄": "你是專業的會議紀錄分析專家。請完整記錄會議流程,平衡各方觀點,總結最終共識。\n輸出結構:\n1. 會議概覽\n2. 討論內容\n3. 決議事項\n4. 後續行動", "趨勢分析報告": "你是市場趨勢分析專家。請識別市場/技術趨勢,分析數據變化軌跡,預測未來發展。\n輸出結構:\n1. 當前態勢\n2. 關鍵趨勢\n3. 數據分析\n4. 未來預測", "行動清單 (Action Items)": "你是專案管理專家。請條列式抓出所有待辦事項。\n輸出結構:\n每項包含:任務描述、負責人 (Owner)、預計完成時間 (ETA)、優先級", "自定義": "" } return templates.get(report_type, templates["綜合會議紀錄"]) report_type.change(fn=update_prompt, inputs=report_type, outputs=optimize_prompt) refresh_btn.click( fn=lambda: gr.Dropdown(choices=list_saved_files(".txt")), outputs=file_dropdown ) r2_refresh_btn.click( fn=lambda: gr.Dropdown(choices=r2_list_files("transcripts/") if HAS_R2 else []), outputs=r2_dropdown ) def run_optimization(source_type, current_trans, file_sel, upload_file, r2_file, prompt, host, guest, target, save_fmt, save_dst): cancel_ctrl.reset_all() raw_text = "" source_name = "" if source_type == "從步驟一繼續": if not current_trans: return "", "", "⚠️ 請先完成步驟一的轉錄", None raw_text = current_trans source_name = "transcribe_output" elif source_type == "選擇已儲存檔案": if not file_sel: return "", "", "⚠️ 請選擇檔案", None try: with open(os.path.join(SAVE_DIR, file_sel), 'r', encoding='utf-8') as f: raw_text = f.read() source_name = os.path.splitext(file_sel)[0] except Exception as e: return "", "", f"❌ 讀取失敗: {e}", None elif source_type == "上傳新檔案": if not upload_file: return "", "", "⚠️ 請上傳檔案", None try: with open(upload_file, 'r', encoding='utf-8') as f: raw_text = f.read() source_name = os.path.splitext(os.path.basename(upload_file))[0] except Exception as e: return "", "", f"❌ 讀取失敗: {e}", None elif source_type == "從 R2 讀取": if not r2_file: return "", "", "⚠️ 請選擇 R2 檔案", None raw_text = r2_get_content(r2_file) if not raw_text: return "", "", "❌ R2 讀取失敗", None source_name = os.path.splitext(os.path.basename(r2_file))[0] if not raw_text.strip(): return "", "", "⚠️ 文本內容為空", None speaker_info = {} if host.strip(): speaker_info["主持人"] = host.strip() if guest.strip(): speaker_info["受訪者"] = guest.strip() optimized, status, success = optimize_transcript_with_llm( raw_text, prompt, speaker_info, target ) if not success or cancel_ctrl.should_cancel('optimize'): return raw_text, optimized, status, None timestamp = int(time.time()) filename = f"{source_name}_optimized_{timestamp}" storage_info = [] download_path = None if save_dst in ["本機", "兩者"]: filepath, saved_name = save_transcript(optimized, filename, save_fmt, 'optimized') if filepath: storage_info.append(f"💾 本機: {saved_name}") download_path = filepath if save_dst in ["R2", "兩者"] and HAS_R2: r2_key = f"optimized/{filename}{save_fmt}" if r2_upload_content(optimized, r2_key): storage_info.append(f"☁️ R2: {r2_key}") final_status = f"{status}\n" + "\n".join(storage_info) return raw_text, optimized, final_status, download_path optimize_btn.click( fn=run_optimization, inputs=[source_type, current_transcript, file_dropdown, upload_text, r2_dropdown, optimize_prompt, host_name, guest_name, analysis_target, save_format, save_dest], outputs=[raw_preview, optimized_output, optimize_status, download_optimized] ) cancel_optimize_btn.click( fn=lambda: [cancel_ctrl.set_optimize_cancel(), "⏹️ 正在取消..."][1], outputs=optimize_status ) gr.Markdown(""" --- ### 💡 使用提示 **步驟一:音訊轉錄** - 支援上傳音訊檔案或直接麥克風錄音 - 智慧模式會自動選擇最佳引擎 (<10分鐘用Gemini,≥10分鐘用WhisperX) - 轉錄完成後可直接編輯內容,點擊「下一步」進入優化 **步驟二:AI 優化** - 推薦選擇「從步驟一繼續」以保持工作流暢 - 可設定發言者角色以產生更精準的分析 - 支援多種報告類型,會自動調整優化指令 **儲存選項** - 本機:儲存在 `saved_results/` 資料夾 - R2:需設定 Cloudflare R2 環境變數 - 兩者:同時儲存到本機和雲端 --- **🔧 V4 更新內容:** - ✅ 修復執行緒安全問題 (添加 Lock 機制) - ✅ 改進取消機制 (統一使用 should_cancel 方法) - ✅ 移除不穩定的實時轉錄功能 - ✅ 優化錯誤處理和資源清理 - ✅ 改進 UI 回應和狀態管理 """) if __name__ == "__main__": demo.queue(max_size=10) demo.launch( server_name="0.0.0.0", server_port=7860, share=False, show_error=True )
import os
import time
import subprocess
import sys
from datetime import datetime
import threading
import queue
import tempfile
import numpy as np
# --- 確保關鍵套件已安裝 ---
def ensure_packages():
required = {
'google-generativeai': 'google.generativeai',
'gradio': 'gradio',
'pandas': 'pandas',
'python-docx': 'docx',
'mutagen': 'mutagen',
'boto3': 'boto3'
}
for pkg, import_name in required.items():
try:
__import__(import_name)
except ImportError:
print(f"正在安裝 {pkg}...")
subprocess.check_call([sys.executable, '-m', 'pip', 'install', pkg, '-q'])
ensure_packages()
import gradio as gr
import pandas as pd
from docx import Document
from io import BytesIO
import json
# --- 導入 Gemini ---
import google.generativeai as genai
# --- Cloudflare R2 設定 ---
import boto3
from botocore.config import Config
R2_ACCOUNT_ID = os.environ.get('R2_ACCOUNT_ID', '').strip()
R2_ACCESS_KEY = os.environ.get('R2_ACCESS_KEY_ID', '').strip()
R2_SECRET_KEY = os.environ.get('R2_SECRET_ACCESS_KEY', '').strip()
R2_BUCKET = os.environ.get('R2_BUCKET_NAME', 'transcripts').strip()
HF_TOKEN = os.environ.get('HUGGING_FACE_TOKEN', '').strip()
GEMINI_KEY = os.environ.get('GEMINI_API_KEY', '').strip()
HAS_R2 = False
r2_client = None
if R2_ACCOUNT_ID and R2_ACCESS_KEY and R2_SECRET_KEY:
try:
r2_client = boto3.client(
's3',
endpoint_url=f'https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com',
aws_access_key_id=R2_ACCESS_KEY,
aws_secret_access_key=R2_SECRET_KEY,
config=Config(signature_version='s3v4'),
region_name='auto'
)
HAS_R2 = True
print(f"✅ Cloudflare R2 連線成功 (Bucket: {R2_BUCKET})")
except Exception as e:
print(f"❌ R2 初始化失敗: {e}")
else:
print("⚠️ 未設定 R2 環境變數,僅使用本機儲存")
# --- R2 操作函式 ---
def r2_list_files(prefix=""):
if not HAS_R2:
return []
try:
response = r2_client.list_objects_v2(Bucket=R2_BUCKET, Prefix=prefix)
files = [obj['Key'] for obj in response.get('Contents', [])]
return sorted(files, reverse=True)
except Exception as e:
print(f"R2 列表失敗: {e}")
return []
def r2_upload_content(content, r2_key):
if not HAS_R2:
return False
try:
r2_client.put_object(Bucket=R2_BUCKET, Key=r2_key, Body=content.encode('utf-8'))
print(f"✅ R2 上傳成功: {r2_key}")
return True
except Exception as e:
print(f"❌ R2 上傳失敗: {e}")
return False
def r2_get_content(r2_key):
if not HAS_R2:
return None
try:
response = r2_client.get_object(Bucket=R2_BUCKET, Key=r2_key)
content = response['Body'].read().decode('utf-8')
return content
except Exception as e: