import os
import logging
from aiogram import Router, F, Bot
from aiogram.types import Message
from config import ADMIN_USER_ID
from services.voice_service import VoiceService
from pathlib import Path
logger = logging.getLogger(__name__)
router = Router()
_voice_service = None
def get_voice_service():
global _voice_service
if _voice_service is None:
DB_PATH = "/home/matrixhasyou/domovoy_bot/database/domovoy.db"
_voice_service = VoiceService(db_path=DB_PATH, model_size="small")
return _voice_service
@router.message(F.voice | F.video_note)
async def handle_voice_message(message: Message, bot: Bot):
if int(message.from_user.id) != int(ADMIN_USER_ID):
return
status_msg = await message.reply("⏳ Расшифровываю...", parse_mode="HTML")
await bot.send_chat_action(message.chat.id, "typing")
# Абсолютный путь к временной папке
temp_dir = Path("/home/matrixhasyou/domovoy_bot/temp_voice")
temp_dir.mkdir(parents=True, exist_ok=True)
try:
if message.voice:
file_id = message.voice.file_id
ext = "oga"
msg_type = "VOICE"
else:
file_id = message.video_note.file_id
ext = "mp4"
msg_type = "VIDEO_NOTE"
file = await bot.get_file(file_id)
file_path = temp_dir / f"{file_id}.{ext}"
# Скачиваем
await bot.download_file(file.file_path, str(file_path))
# Ждем секунду, чтобы ФС успела "переварить" файл
import asyncio
await asyncio.sleep(1)
if not file_path.exists():
raise FileNotFoundError(f"Файл {file_path} не был скачан!")
service = get_voice_service()
text = service.transcribe(str(file_path), message.from_user.id, message.from_user.username or "Owner", msg_type)
if file_path.exists(): file_path.unlink()
if text:
await status_msg.edit_text(f"📝 РАСШИФРОВКА:\n\n{text}", parse_mode="HTML")
else:
await status_msg.edit_text("🔇 Не удалось распознать текст.")
except Exception as e:
logger.error(f"❌ Voice Error: {e}")
await status_msg.edit_text(f"❌ Ошибка: {e}")
voice_router = router