Spaces:
Sleeping
Sleeping
Update app.py
Browse files28 unmodified lines2930313233343540 unmodified lines767778798081828384858687881 unmodified line9091929394958 unmodified lines1041051061071081091101111121131141151161171181191201211229 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523628 unmodified linesexcept Exception:try:url = f"https://8.8.8.8/resolve?name={host}&type=A"r = requests.get(url, timeout=2)data = r.json()if "Answer" in data:ip = data["Answer"][0]["data"]40 unmodified linesapp.config['SECRET_KEY'] = os.getenv("SECRET_KEY", "secret!")socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')MAX_CONCURRENT_STREAMS = 10SPEAKER_COLORS = ["#FFFFFF", "#03DAC6", "#FFB400", "#CF6679", "#BB86FC"]HALLUCINATION_PHRASES = ["You", "Thank you", "Thank you.", "Thanks for watching", "Bye","Okay", "Okay.", "All right", "music", "[Music]", "Subscribe","Copyright", "MBC", "SBS", "news", "Amara", "Subtitles by","Caption", "Captions", "Provided by", "http", "www", ".com","Silence", "[Silence]", "Audio", "Sound", "noise"]1 unmodified linesession_speakers = {}active_sessions = {}class QuietLogger:def debug(self, msg): passdef warning(self, msg): pass8 unmodified linesself.is_running = Falseself.ffmpeg_proc = Noneself.fifo_path = f"/tmp/stream_{sid}.fifo"# ▼▼▼ 追加:リアルタイム演出用話者状態 ▼▼▼self.ui_speaker_state = {"current": 1,"last_switch": time.time()}# ▲▲▲ 追加ここまで ▲▲▲self.system_instruction = """You are a professional simultaneous interpreter...."""self.client = genai.Client(api_key=GEMINI_API_KEY)self.model_name = model_name9 unmodified linesif os.path.exists(self.fifo_path):try: os.remove(self.fifo_path)except: pass# ----(中略:yt-dlp / groq / gemini / ffmpeg 処理は元コード完全保持)----def _main_loop(self):...while self.is_running:...if should_process:audio_bytes = bytes(audio_buffer)result_text = self._process_audio_hybrid(audio_bytes)audio_buffer = bytearray()recording_duration = 0.0silence_counter = 0.0if not result_text:continue# ▼▼▼ 追加:リアルタイム話者演出ロジック ▼▼▼now = time.time()if now - self.ui_speaker_state["last_switch"] > 2.0:max_spk = self.settings.get("max_speakers", 1)if max_spk > 1:self.ui_speaker_state["current"] += 1if self.ui_speaker_state["current"] > max_spk:self.ui_speaker_state["current"] = 1self.ui_speaker_state["last_switch"] = nowui_speaker_id = f"Speaker {self.ui_speaker_state['current']}"# ▲▲▲ 追加ここまで ▲▲▲for line in result_text.split("\n"):if ":" not in line:continue_, text_content = line.split(":", 1)text_content = text_content.strip()if not text_content:continueraw_id = ui_speaker_idif self.sid not in session_speakers:session_speakers[self.sid] = {}if raw_id not in session_speakers[self.sid]:idx = len(session_speakers[self.sid])session_speakers[self.sid][raw_id] = {"name": raw_id,"color": SPEAKER_COLORS[idx % len(SPEAKER_COLORS)]}self.socketio.emit("initial_speaker_profiles",session_speakers[self.sid],room=self.sid)info = session_speakers[self.sid][raw_id]self.socketio.emit("new_subtitle", {"original": "...","translated": text_content,"speaker": info["name"],"speaker_id": raw_id,"color": info["color"]}, room=self.sid)self.stop()@app.route("/")def index():return render_template("index.html")@socketio.on("connect")def handle_connect(): pass@socketio.on("disconnect")def handle_disconnect():if request.sid in active_sessions:active_sessions[request.sid].stop()del active_sessions[request.sid]if request.sid in session_speakers:del session_speakers[request.sid]@socketio.on("start_stream")def handle_start_stream(data):sid = request.sidif sid in active_sessions:active_sessions[sid].stop()worker = StreamWorker(sid,data.get("url"),{"target_lang": data.get("target_lang", "ja"),"max_speakers": int(data.get("max_speakers", 1))},socketio)active_sessions[sid] = workerworker.start()if __name__ == "__main__":socketio.run(app, host="0.0.0.0", port=7860, allow_unsafe_werkzeug=True)28 unmodified lines2930313233343540 unmodified lines76777879808182838485868788891 unmodified line919293949596978 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301319 unmodified lines14114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841928 unmodified linesexcept Exception:try:url = f"https://8.8.8.8/resolve?name={host}&type=A"r = requests.get(url, timeout=2)data = r.json()if "Answer" in data:ip = data["Answer"][0]["data"]40 unmodified linesapp.config['SECRET_KEY'] = os.getenv("SECRET_KEY", "secret!")socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')MAX_CONCURRENT_STREAMS = 10SPEAKER_COLORS = ["#FFFFFF", "#03DAC6", "#FFB400", "#CF6679", "#BB86FC"]# Whisperが無音時によく出力してしまう無意味なフレーズ集HALLUCINATION_PHRASES = ["You", "Thank you", "Thank you.", "Thanks for watching", "Bye","Okay", "Okay.", "All right", "music", "[Music]", "Subscribe","Copyright", "MBC", "SBS", "news", "Amara", "Subtitles by","Caption", "Captions", "Provided by", "http", "www", ".com","Silence", "[Silence]", "Audio", "Sound", "noise"]1 unmodified linesession_speakers = {}active_sessions = {}# ログ抑制用class QuietLogger:def debug(self, msg): passdef warning(self, msg): pass8 unmodified linesself.is_running = Falseself.ffmpeg_proc = Noneself.fifo_path = f"/tmp/stream_{sid}.fifo"# フィラー(言い淀み)の削除と、要約的な翻訳を指示self.system_instruction = """You are a professional simultaneous interpreter.INPUT DATA:1. Transcript: English text transcribed from audio.2. Audio: Source sound clip.YOUR TASK:1. Identify the speaker (Speaker 1, Speaker 2...).2. Translate the Transcript into natural, concise Japanese.CRITICAL RULES for Translation:- **REMOVE FILLERS**: Ignore words like "uh", "um", "like", "you know", "I mean", "actually".- **IGNORE REPETITIONS**: If the user stutters (e.g., "I- I- I went"), translate only the final meaning ("I went").- **NO HALLUCINATIONS**: If the input text is just "Thank you" or "[Music]" or random noise, output NOTHING (empty string).- **CONCISE**: Do not translate word-for-word. Capture the *intent*.- Output format must be strictly: "Speaker X: [Japanese Translation]""""self.client = genai.Client(api_key=GEMINI_API_KEY)self.model_name = model_name9 unmodified linesif os.path.exists(self.fifo_path):try: os.remove(self.fifo_path)except: passprint(f"🛑 Worker停止: {self.sid}")def _run_ytdlp(self):if os.path.exists(self.fifo_path):os.remove(self.fifo_path)os.mkfifo(self.fifo_path)base_opts = {'format': 'bestaudio/best','outtmpl': self.fifo_path,'quiet': True,'no_warnings': True,'logger': QuietLogger(),'nocheckcertificate': True,'socket_timeout': 30,'retries': 10,'fragment_retries': 10,'force_ipv4': False,'live_from_start': False,'wait_for_video': (1, 15),'ignoreerrors': True,'cachedir': False,}strategies = []if os.path.exists("cookies.txt"):opts_cookie = base_opts.copy()opts_cookie['cookiefile'] = 'cookies.txt'opts_cookie['extractor_args'] = {'youtube': {'impersonate': ['chrome']}}strategies.append(("Cookie(Web)", opts_cookie))opts_ios = base_opts.copy()opts_ios['cookiefile'] = Noneopts_ios['extractor_args'] = {'youtube': {'player_client': ['ios']}}strategies.append(("NoCookie(iOS)", opts_ios))opts_tv = base_opts.copy()opts_tv['cookiefile'] = Noneopts_tv['extractor_args'] = {'youtube': {'player_client': ['tv_embedded']}}strategies.append(("NoCookie(TV)", opts_tv))success = Falsefor label, opts in strategies:if not self.is_running: breaktry:with yt_dlp.YoutubeDL(opts) as ydl:ydl.download([self.url])if os.path.exists(self.fifo_path):success = Truebreakexcept Exception:time.sleep(1)continueif not success:if self.is_running: # 停止時はエラー出さないself.socketio.emit("error_msg", {"msg": "動画にアクセスできませんでした。"}, room=self.sid)self.is_running = Falsedef _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)wb.setframerate(16000)wb.writeframes(pcm_data)wav_io.seek(0)return wav_ioexcept Exception:return Nonedef _transcribe_groq(self, audio_data):if not groq_client: return Nonetry: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,model="whisper-large-v3",response_format="text",language="en",temperature=0.0)return transcription.strip()except Exception:return Nonedef _process_audio_hybrid(self, audio_data):transcript_text = self._transcribe_groq(audio_data)# 1. 空文字チェックif not transcript_text or len(transcript_text) <= 2: return ""# 2. 幻覚(NGワード)チェックclean_text = transcript_text.lower().strip('.').strip()for phrase in HALLUCINATION_PHRASES:# フレーズが含まれている、または完全に一致する場合if phrase.lower() in clean_text or clean_text == phrase.lower():return ""# 3. 記号だけの出力を弾くif re.match(r'^[\W_]+$', transcript_text): return ""# 4. 繰り返し検知("Yeah yeah yeah" -> "Yeah")# 単純なロジック: 同じ単語が3回以上連続したら怪しいとみなすwords = clean_text.split()if len(words) > 4 and len(set(words)) == 1: # 全部同じ単語return ""try:tgt_lang = self.settings.get('target_lang', 'ja')tgt_name = "Japanese" if tgt_lang == 'ja' else "English"prompt = f"""Target Transcript: "{transcript_text}"Instruction:1. Identify speakers from the Audio.2. Translate the "Target Transcript" above into {tgt_name}.Output format:Speaker 1: [Translation]"""wav_file = self._create_wav_bytes(audio_data)if not wav_file: return ""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)raw_text = response.text.strip()if not raw_text: return ""if tgt_lang == 'ja':filtered = [l for l in raw_text.split('\n') if any(ord(c) > 128 for c in l.split(':',1)[-1])]return "\n".join(filtered)return raw_textexcept Exception: return ""def _main_loop(self):print(f"🔁 処理開始 [User: {self.sid}] URL: {self.url}")self.download_thread = threading.Thread(target=self._run_ytdlp)self.download_thread.daemon = Trueself.download_thread.start()for _ in range(200):if os.path.exists(self.fifo_path): breaktime.sleep(0.1)if not os.path.exists(self.fifo_path): 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})")CHUNK_DURATION = 0.1SAMPLE_RATE = 16000BYTES_PER_SAMPLE = 2CHUNK_BYTES = int(SAMPLE_RATE * CHUNK_DURATION * BYTES_PER_SAMPLE)SILENCE_THRESHOLD = 300SILENCE_DURATION_TRIGGER = 0.6MAX_RECORD_DURATION = 6.0MIN_RECORD_DURATION = 1.0audio_buffer = bytearray()silence_counter = 0.0recording_duration = 0.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: continueif np.isnan(audio_np).any(): continuerms = np.sqrt(np.mean(audio_np.astype(float)**2))audio_buffer.extend(chunk)recording_duration += CHUNK_DURATIONif rms < SILENCE_THRESHOLD:silence_counter += CHUNK_DURATIONelse:silence_counter = 0.0should_process = Falseif recording_duration > MIN_RECORD_DURATION and silence_counter >= SILENCE_DURATION_TRIGGER:should_process = Trueelif recording_duration >= MAX_RECORD_DURATION:should_process = Trueif should_process:audio_bytes = bytes(audio_buffer)result_text = self._process_audio_hybrid(audio_bytes)audio_buffer = bytearray()recording_duration = 0.0silence_counter = 0.0if not result_text: continuefor line in result_text.split('\n'):if ':' in line:parts = line.split(':', 1)if len(parts) < 2: continueraw_id, text_content = parts[0].strip(), parts[1].strip()if not text_content: continuemax_spk = self.settings.get('max_speakers', 1)if max_spk == 1: raw_id = "Speaker 1"spk_match = re.search(r'\d+', raw_id)if spk_match and int(spk_match.group()) > max_spk: raw_id = "Speaker 1"if self.sid not in session_speakers: session_speakers[self.sid] = {}if raw_id not in session_speakers[self.sid]:new_idx = len(session_speakers[self.sid])session_speakers[self.sid][raw_id] = {"name": raw_id, "color": SPEAKER_COLORS[new_idx % len(SPEAKER_COLORS)]}self.socketio.emit("initial_speaker_profiles", session_speakers[self.sid], room=self.sid)info = session_speakers[self.sid][raw_id]self.socketio.emit("new_subtitle", {"original": "...","translated": text_content,"speaker": info["name"],"speaker_id": raw_id,"color": info["color"]}, room=self.sid)except Exception: continueself.stop()@app.route("/")def index(): return render_template("index.html")@socketio.on('connect')def handle_connect(): pass@socketio.on('disconnect')def handle_disconnect():if request.sid in active_sessions: active_sessions[request.sid].stop(); del active_sessions[request.sid]if request.sid in session_speakers: del session_speakers[request.sid]@socketio.on('start_stream')def handle_start_stream(data):sid = request.sidif sid in active_sessions: active_sessions[sid].stop()if len(active_sessions) >= MAX_CONCURRENT_STREAMS: emit("error_msg", {"msg": "混雑中"}, room=sid); returnworker = StreamWorker(sid, data.get('url'), {'target_lang': data.get('target_lang', 'ja'), 'max_speakers': int(data.get('max_speakers', 1))}, socketio)active_sessions[sid] = worker; worker.start(); emit("status_msg", {"msg": "開始"}, room=sid)@socketio.on('stop_stream')def handle_stop_stream():if request.sid in active_sessions: active_sessions[request.sid].stop(); emit("status_msg", {"msg": "停止"}, room=request.sid)@socketio.on('update_settings')def handle_settings_update(data):if request.sid in active_sessions: active_sessions[request.sid].settings.update(data)@socketio.on('reset_speakers')def handle_reset_speakers():if request.sid in session_speakers: session_speakers[request.sid] = {}@socketio.on('update_speaker_name')def handle_speaker_name_update(data):if request.sid in session_speakers and data.get("id") in session_speakers[request.sid]:session_speakers[request.sid][data.get("id")]["name"] = data.get("new_name")emit("speaker_name_changed", data, room=request.sid)@socketio.on('update_speaker_color')def handle_speaker_color_update(data):if request.sid in session_speakers and data.get("id") in session_speakers[request.sid]:session_speakers[request.sid][data.get("id")]["color"] = data.get("color")emit("speaker_color_changed", data, room=request.sid)if __name__ == "__main__":socketio.run(app, host='0.0.0.0', port=7860, allow_unsafe_werkzeug=True)
app.py+287-104