From 4b6cc5410e85fd70462d565f9fa1f4404376863f Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 30 Mar 2026 17:36:14 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BB=D0=BE=D0=BA=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9=20Whisper=20(faster-whisper=20large-v3)=20?= =?UTF-8?q?=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20OpenAI=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Не зависит от OpenAI API/прокси. Модель large-v3 int8 на CPU. Лучшее качество распознавания русского языка. Co-Authored-By: Claude Opus 4.6 (1M context) --- src/smeta_railway/ai/telegram_bot.py | 42 +++++++++++++++++----------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/src/smeta_railway/ai/telegram_bot.py b/src/smeta_railway/ai/telegram_bot.py index 0cd3500..d9648c2 100644 --- a/src/smeta_railway/ai/telegram_bot.py +++ b/src/smeta_railway/ai/telegram_bot.py @@ -298,25 +298,35 @@ async def text_message(update: Update, context: ContextTypes.DEFAULT_TYPE): # ── Voice message handling ──────────────────────────────────────────────── +_whisper_model = None + + +def _get_whisper(): + """Lazy-load faster-whisper model (large-v3, CPU).""" + global _whisper_model + if _whisper_model is None: + from faster_whisper import WhisperModel + model_size = os.environ.get("WHISPER_MODEL", "large-v3") + logger.info(f"Loading Whisper model: {model_size} ...") + _whisper_model = WhisperModel( + model_size, device="cpu", compute_type="int8", + ) + logger.info("Whisper model loaded.") + return _whisper_model + + async def transcribe_voice(file_path: str) -> str: - """Transcribe voice message using OpenAI Whisper API.""" - import httpx + """Transcribe voice message using local faster-whisper.""" + loop = asyncio.get_event_loop() + return await loop.run_in_executor(None, _transcribe_sync, file_path) - api_key = os.environ.get("OPENAI_API_KEY", "") - if not api_key: - return "" - proxy = os.environ.get("OPENAI_PROXY") or os.environ.get("HTTPS_PROXY") - async with httpx.AsyncClient(timeout=30, proxy=proxy) as client: - with open(file_path, "rb") as f: - resp = await client.post( - "https://api.openai.com/v1/audio/transcriptions", - headers={"Authorization": f"Bearer {api_key}"}, - files={"file": ("voice.ogg", f, "audio/ogg")}, - data={"model": "whisper-1", "language": "ru"}, - ) - resp.raise_for_status() - return resp.json().get("text", "") +def _transcribe_sync(file_path: str) -> str: + model = _get_whisper() + segments, info = model.transcribe( + file_path, language="ru", beam_size=5, vad_filter=True, + ) + return " ".join(seg.text.strip() for seg in segments) async def voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE):