Spaces:
Sleeping
Sleeping
Update app.py
Browse files18 unmodified lines1920212223242513 unmodified lines394041424344458 unmodified lines54555657585960619 unmodified lines717273747576777853 unmodified lines13213313413513613713813914014114214314430 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002014 unmodified lines2062072082092102112122132142152162172182192202212222232242252262272282292302315 unmodified lines23723823924024124224313 unmodified lines2572582592602612622632642652662672682692702712722732742752762772782792 unmodified lines2822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163174 unmodified lines3223233243253263273283293303314 unmodified lines33633733833934034134234334434534634734834924 unmodified lines37437537637737837938038138238338438538638718 unmodified linesfrom google.genai import typesfrom groq import Groq# ▼▼▼ [DNS解決パッチ] ▼▼▼_original_getaddrinfo = socket.getaddrinfodef patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):13 unmodified linesreturn _original_getaddrinfo(host, port, family, type, proto, flags)socket.getaddrinfo = patched_getaddrinfo# ▲▲▲ パッチここまで ▲▲▲load_dotenv()8 unmodified lineswith open("cookies.txt", "w") as f:f.write(cookie_content)print("DEBUG: cookies.txt を生成しました")except Exception as e:print(f"DEBUG: Cookie生成エラー: {e}")GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")GROQ_API_KEY = os.getenv("GROQ_API_KEY")9 unmodified linesprint("✅ Groq Client Initialized")except Exception as e:print(f"❌ Groq Init Error: {e}")else:print("⚠️ GROQ_API_KEYがありません。暫定文字起こし機能は動きません。")sys.stdout.reconfigure(line_buffering=True)53 unmodified linesos.remove(self.fifo_path)os.mkfifo(self.fifo_path)# ▼▼▼ DEBUG: ログをフル出力設定に変更 ▼▼▼base_opts = {'format': 'bestaudio/best','outtmpl': self.fifo_path,'quiet': False, # ログを出す'verbose': True, # 詳細ログを出す'no_warnings': False, # 警告も出す'nocheckcertificate': True,'socket_timeout': 30,'retries': 10,30 unmodified lineswith yt_dlp.YoutubeDL(opts) as ydl:ydl.download([self.url])# ファイルが生成されたかチェックif os.path.exists(self.fifo_path):print(f"✅ ダウンロード成功 [{label}]")success = Truebreakelse:print(f"⚠️ ダウンロード完了したがファイルがない [{label}]")except Exception as e:print(f"❌ yt-dlpエラー [{label}]: {e}")time.sleep(1)continueif not success:print("❌ 全ての接続方法で失敗")self.socketio.emit("error_msg", {"msg": "動画にアクセスできませんでした。(ログを確認してください)"}, room=self.sid)self.is_running = Falsedef _transcribe_interim(self, audio_data):if not groq_client: return Nonetry:audio_file = io.BytesIO(audio_data)audio_file.name = "audio.wav"transcription = groq_client.audio.transcriptions.create(file=audio_file,4 unmodified lines)return transcription.strip()except Exception as e:print(f"DEBUG: Groq Error: {e}")return Nonedef _process_audio_final(self, audio_data):print("DEBUG: Final処理開始 (Groq -> Gemini)")transcript_text = self._transcribe_interim(audio_data)if not transcript_text or len(transcript_text) <= 2:print("DEBUG: Groq結果が空、または短すぎます")return ""print(f"DEBUG: Transcript: {transcript_text[:30]}...")clean_text = transcript_text.lower().strip('.').strip()for phrase in HALLUCINATION_PHRASES:if clean_text == phrase.lower():print("DEBUG: 幻覚フィルター検���")return ""if transcript_text.startswith('[') and transcript_text.endswith(']'):return ""try:tgt_lang = self.settings.get('target_lang', 'ja')tgt_name = "Japanese" if tgt_lang == 'ja' else "English"5 unmodified linesOutput format:Speaker 1: [Translation]"""contents = [prompt, types.Part.from_bytes(data=audio_data, mime_type="audio/wav")]config = types.GenerateContentConfig(temperature=0.0, system_instruction=self.system_instruction)response = self.client.models.generate_content(model=self.model_name, contents=contents, config=config)13 unmodified linesself.download_thread.daemon = Trueself.download_thread.start()# パイプができるまで待機for i in range(200):if os.path.exists(self.fifo_path):print("DEBUG: FIFOパイプを確認しました")breaktime.sleep(0.1)if i % 50 == 0: print("DEBUG: パイプ生成待ち...")if not os.path.exists(self.fifo_path):print("ERROR: パイプが生成されませんでした (yt-dlp失敗)")self.stop(); returnffmpeg_cmd = ["ffmpeg", "-y", "-i", self.fifo_path, "-f", "s16le", "-acodec", "pcm_s16le", "-ac", "1", "-ar", "16000", "-bufsize", "0", "pipe:1"]try: self.ffmpeg_proc = subprocess.Popen(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=None)except Exception as e:print(f"ERROR: FFmpeg起動失敗: {e}")self.stop(); returnprint(f"👂 音声待機中... ({self.sid})")2 unmodified linesBYTES_PER_SAMPLE = 2CHUNK_BYTES = int(SAMPLE_RATE * CHUNK_DURATION * BYTES_PER_SAMPLE)# ▼▼▼ 設定値: 反応が悪い場合はここを調整 ▼▼▼SILENCE_THRESHOLD = 300 # 音量の閾値 (下げました: 500 -> 300)SILENCE_DURATION_TRIGGER = 0.8 # 区切りとみなす無音秒数MAX_RECORD_DURATION = 12.0 # 強制区切り秒数MIN_RECORD_DURATION = 1.0 # 最短秒数PREVIEW_INTERVAL = 1.0 # プレビュー更新間隔last_preview_time = time.time()audio_buffer = bytearray()silence_counter = 0.0recording_duration = 0.0debug_log_counter = 0while self.is_running:try:chunk = self.ffmpeg_proc.stdout.read(CHUNK_BYTES)if not chunk:print("DEBUG: FFmpegストリーム終了")breakaudio_np = np.frombuffer(chunk, dtype=np.int16)if len(audio_np) == 0: continuerms = np.sqrt(np.mean(audio_np**2))# ▼▼▼ DEBUG: 音量(RMS)を表示 (5回に1回表示してログ流れすぎを防ぐ) ▼▼▼debug_log_counter += 1if debug_log_counter % 5 == 0:print(f"DEBUG: RMS={rms:.1f} | Dur={recording_duration:.1f}s | Silence={silence_counter:.1f}s")audio_buffer.extend(chunk)recording_duration += CHUNK_DURATION4 unmodified lines# 1. 暫定送信current_time = time.time()if recording_duration > 0.5 and (current_time - last_preview_time) > PREVIEW_INTERVAL:print("DEBUG: Interim送信試行...")interim_text = self._transcribe_interim(bytes(audio_buffer))if interim_text:print(f"DEBUG: Interim結果: {interim_text}")self.socketio.emit("new_subtitle", {"translated": interim_text,"is_final": False,4 unmodified lines# 2. 確定条件should_process = Falseif recording_duration > MIN_RECORD_DURATION and silence_counter >= SILENCE_DURATION_TRIGGER:print("DEBUG: 無音検知による区切り")should_process = Trueelif recording_duration >= MAX_RECORD_DURATION:print("DEBUG: 最大時間到達による強制区切り")should_process = True# 3. 確定処理if should_process:audio_bytes = bytes(audio_buffer)result_text = self._process_audio_final(audio_bytes)24 unmodified linesinfo = session_speakers[self.sid][raw_id]print(f"DEBUG: Final送信: {text_content}")self.socketio.emit("new_subtitle", {"translated": text_content,"is_final": True,"speaker": info["name"], "speaker_id": raw_id, "color": info["color"]}, room=self.sid)except Exception as e:print(f"ERROR: Main loop exception: {e}")continueself.stop()18 unmodified lines1920212223242513 unmodified lines3940414243448 unmodified lines53545556575859609 unmodified lines70717273747553 unmodified lines12913013113213313413513613713813914030 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122134 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402415 unmodified lines24724824925025125225325425525625725825926026113 unmodified lines2752762772782792802812822832842852862872882892902912 unmodified lines2942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293304 unmodified lines3353363373383393403413423433444 unmodified lines34935035135235335435535635735835936036124 unmodified lines38638738838939039139239339439539639739818 unmodified linesfrom google.genai import typesfrom groq import Groq# DNSパッチ_original_getaddrinfo = socket.getaddrinfodef patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):13 unmodified linesreturn _original_getaddrinfo(host, port, family, type, proto, flags)socket.getaddrinfo = patched_getaddrinfoload_dotenv()8 unmodified lineswith open("cookies.txt", "w") as f:f.write(cookie_content)print("DEBUG: cookies.txt を生成しました")except Exception:passGEMINI_API_KEY = os.getenv("GEMINI_API_KEY")GROQ_API_KEY = os.getenv("GROQ_API_KEY")9 unmodified linesprint("✅ Groq Client Initialized")except Exception as e:print(f"❌ Groq Init Error: {e}")sys.stdout.reconfigure(line_buffering=True)53 unmodified linesos.remove(self.fifo_path)os.mkfifo(self.fifo_path)base_opts = {'format': 'bestaudio/best','outtmpl': self.fifo_path,'quiet': False,'verbose': True,'no_warnings': False,'nocheckcertificate': True,'socket_timeout': 30,'retries': 10,30 unmodified lineswith yt_dlp.YoutubeDL(opts) as ydl:ydl.download([self.url])if os.path.exists(self.fifo_path):print(f"✅ ダウンロード成功 [{label}]")success = Truebreakelse:print(f"⚠️ ファイル未生成 [{label}]")except Exception as e:print(f"❌ yt-dlpエラー [{label}]: {e}")time.sleep(1)continueif not success:self.socketio.emit("error_msg", {"msg": "動画にアクセスできませんでした。"}, room=self.sid)self.is_running = False# ▼▼▼ 重要: 生データをWAVファイル形式に変換する関数 ▼▼▼def _create_wav_bytes(self, pcm_data):wav_io = io.BytesIO()try:with wave.open(wav_io, 'wb') as wb:wb.setnchannels(1) # モノラルwb.setsampwidth(2) # 16bit (2byte)wb.setframerate(16000) # 16kHzwb.writeframes(pcm_data)wav_io.seek(0) # 先頭に戻すreturn wav_ioexcept Exception as e:print(f"ERROR: WAV変換失敗: {e}")return Nonedef _transcribe_interim(self, audio_data):if not groq_client: return Nonetry:# ここで生データではなく、正規のWAVファイルを生成して渡すaudio_file = self._create_wav_bytes(audio_data)if not audio_file: return Noneaudio_file.name = "audio.wav"transcription = groq_client.audio.transcriptions.create(file=audio_file,4 unmodified lines)return transcription.strip()except Exception as e:# 400エラーの原因がこれだったので、詳細を出力print(f"DEBUG: Groq Error: {e}")return Nonedef _process_audio_final(self, audio_data):# 1. Groqで確定文字起こしtranscript_text = self._transcribe_interim(audio_data)if not transcript_text or len(transcript_text) <= 2:return ""clean_text = transcript_text.lower().strip('.').strip()for phrase in HALLUCINATION_PHRASES:if clean_text == phrase.lower(): return ""if transcript_text.startswith('[') and transcript_text.endswith(']'): return ""print(f"DEBUG: Final Transcript: {transcript_text[:30]}...")# 2. Geminiで翻訳try:tgt_lang = self.settings.get('target_lang', 'ja')tgt_name = "Japanese" if tgt_lang == 'ja' else "English"5 unmodified linesOutput format:Speaker 1: [Translation]"""# Geminiにも生データではなくWAVコンテナに入れたものを渡す方が安全wav_file = self._create_wav_bytes(audio_data)if not wav_file: return ""# BytesIOからバイト列を取り出して渡すwav_bytes = wav_file.getvalue()contents = [prompt, types.Part.from_bytes(data=wav_bytes, mime_type="audio/wav")]config = types.GenerateContentConfig(temperature=0.0, system_instruction=self.system_instruction)response = self.client.models.generate_content(model=self.model_name, contents=contents, config=config)13 unmodified linesself.download_thread.daemon = Trueself.download_thread.start()for i in range(200):if os.path.exists(self.fifo_path): breaktime.sleep(0.1)if not os.path.exists(self.fifo_path):print("ERROR: パイプ生成失敗")self.stop(); returnffmpeg_cmd = ["ffmpeg", "-y", "-i", self.fifo_path, "-f", "s16le", "-acodec", "pcm_s16le", "-ac", "1", "-ar", "16000", "-bufsize", "0", "pipe:1"]try: self.ffmpeg_proc = subprocess.Popen(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=None)except Exception: self.stop(); returnprint(f"👂 音声待機中... ({self.sid})")2 unmodified linesBYTES_PER_SAMPLE = 2CHUNK_BYTES = int(SAMPLE_RATE * CHUNK_DURATION * BYTES_PER_SAMPLE)SILENCE_THRESHOLD = 300SILENCE_DURATION_TRIGGER = 0.8MAX_RECORD_DURATION = 12.0MIN_RECORD_DURATION = 1.0PREVIEW_INTERVAL = 1.0last_preview_time = time.time()audio_buffer = bytearray()silence_counter = 0.0recording_duration = 0.0debug_cnt = 0while self.is_running:try:chunk = self.ffmpeg_proc.stdout.read(CHUNK_BYTES)if not chunk: breakaudio_np = np.frombuffer(chunk, dtype=np.int16)if len(audio_np) == 0: continue# ▼▼▼ nan対策: 数値が正常かチェック ▼▼▼if np.isnan(audio_np).any():print("DEBUG: NaN detected in audio chunk")continuerms = np.sqrt(np.mean(audio_np.astype(float)**2)) # float変換でオーバーフロー防止debug_cnt += 1if debug_cnt % 10 == 0:print(f"DEBUG: RMS={rms:.1f}")audio_buffer.extend(chunk)recording_duration += CHUNK_DURATION4 unmodified lines# 1. 暫定送信current_time = time.time()if recording_duration > 0.5 and (current_time - last_preview_time) > PREVIEW_INTERVAL:# print("DEBUG: Interim送信...")interim_text = self._transcribe_interim(bytes(audio_buffer))if interim_text:# print(f"DEBUG: Interim={interim_text}")self.socketio.emit("new_subtitle", {"translated": interim_text,"is_final": False,4 unmodified lines# 2. 確定条件should_process = Falseif recording_duration > MIN_RECORD_DURATION and silence_counter >= SILENCE_DURATION_TRIGGER:should_process = Trueelif recording_duration >= MAX_RECORD_DURATION:should_process = True# 3. 確定処理if should_process:print("DEBUG: Final処理実行")audio_bytes = bytes(audio_buffer)result_text = self._process_audio_final(audio_bytes)24 unmodified linesinfo = session_speakers[self.sid][raw_id]self.socketio.emit("new_subtitle", {"translated": text_content,"is_final": True,"speaker": info["name"], "speaker_id": raw_id, "color": info["color"]}, room=self.sid)except Exception as e:print(f"ERROR Loop: {e}")continueself.stop()
app.py+66-55