58 lines
2.2 KiB
Python
58 lines
2.2 KiB
Python
import os
|
|
import logging
|
|
from aiogram import Router, F, Bot
|
|
from aiogram.types import Message, ContentType
|
|
from config import ADMIN_USER_ID
|
|
from services.voice_service import VoiceService
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = Router()
|
|
|
|
# Initialize VoiceService
|
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
db_path = os.path.join(BASE_DIR, "database", "domovoy.db")
|
|
voice_service = VoiceService(db_path=db_path, model_size="small")
|
|
|
|
@router.message(F.content_type.in_({ContentType.VOICE, ContentType.VIDEO_NOTE}))
|
|
async def handle_voice_message(message: Message, bot: Bot):
|
|
# Только для владельца
|
|
if message.from_user.id != ADMIN_USER_ID:
|
|
return
|
|
|
|
msg_type = "VOICE" if message.voice else "VIDEO_NOTE"
|
|
file_id = message.voice.file_id if message.voice else message.video_note.file_id
|
|
|
|
# Отправляем статус "печатает"
|
|
await bot.send_chat_action(message.chat.id, "typing")
|
|
|
|
# Создаем папку для временных файлов если её нет
|
|
temp_dir = os.path.join(BASE_DIR, "temp_voice")
|
|
os.makedirs(temp_dir, exist_ok=True)
|
|
|
|
try:
|
|
file = await bot.get_file(file_id)
|
|
file_path = os.path.join(temp_dir, f"{file_id}.oga" if message.voice else f"{file_id}.mp4")
|
|
await bot.download_file(file.file_path, file_path)
|
|
|
|
# Распознавание
|
|
text = voice_service.transcribe(
|
|
file_path=file_path,
|
|
user_id=message.from_user.id,
|
|
username=message.from_user.username or "Unknown",
|
|
msg_type=msg_type
|
|
)
|
|
|
|
# Удаляем временный файл
|
|
if os.path.exists(file_path): os.remove(file_path)
|
|
|
|
if text:
|
|
await message.reply(f"📝 <b>Распознанный текст:</b>\n\n{text}", parse_mode="HTML")
|
|
else:
|
|
await message.reply("🔇 Аудио сообщение пустое или не распознано.")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Voice handler error: {e}")
|
|
await message.reply(f"❌ Ошибка обработки: {e}")
|
|
|
|
# Export router
|
|
voice_router = router
|