domovoy_bot/handlers/voice.py

106 lines
4.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import logging
import aiohttp
import json
import sqlite3
from datetime import datetime
from aiogram import Router, F, Bot
from aiogram.types import Message
from config import ADMIN_USER_ID, DATABASE_PATH
from pathlib import Path
logger = logging.getLogger(__name__)
router = Router()
WHISPER_API_URL = "http://192.168.10.168:9001/transcribe"
def log_voice_to_db(user_id, username, msg_type, duration, text):
"""Фиксация статистики в основную базу Домового"""
try:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS voice_recognition_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
message_type TEXT,
duration INTEGER,
text TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
INSERT INTO voice_recognition_logs (user_id, username, message_type, duration, text)
VALUES (?, ?, ?, ?, ?)
''', (user_id, username, msg_type, duration, text))
conn.commit()
conn.close()
except Exception as e:
logger.error(f"❌ DB Log error: {e}")
@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("⏳ <i>Распознаю голос (Whisper AI)...</i>", parse_mode="HTML")
await bot.send_chat_action(message.chat.id, "typing")
try:
if message.voice:
file_id = message.voice.file_id
filename = f"{file_id}.oga"
msg_type = "VOICE"
else:
file_id = message.video_note.file_id
filename = f"{file_id}.mp4"
msg_type = "VIDEO_NOTE"
file = await bot.get_file(file_id)
# Используем aiohttp для отправки файла в микросервис
async with aiohttp.ClientSession() as session:
# Скачиваем файл во временный буфер
file_url = f"https://api.telegram.org/file/bot{bot.token}/{file.file_path}"
# Прокси если нужно (подтянется из конфига если настроено, но тут идем напрямую)
async with session.get(file_url) as file_resp:
if file_resp.status != 200:
raise Exception(f"Не удалось скачать файл из TG: {file_resp.status}")
file_content = await file_resp.read()
# Отправляем в наш Whisper-Service
data = aiohttp.FormData()
data.add_field('file', file_content, filename=filename)
async with session.post(WHISPER_API_URL, data=data) as whisper_resp:
if whisper_resp.status != 200:
err_text = await whisper_resp.text()
raise Exception(f"Ошибка Whisper API: {err_text}")
result = await whisper_resp.json()
text = result.get("text", "")
duration = result.get("duration", 0)
if text:
# Логируем в базу
log_voice_to_db(message.from_user.id, message.from_user.username, msg_type, int(duration), text)
# Формируем красивый ответ
response = f"📝 <b>РАСШИФРОВКА</b> ({msg_type})\n"
response += f"⏱ Длительность: {int(duration)}с\n"
response += f"━━━━━━━━━━━━━━\n"
response += f"<i>{text}</i>"
await status_msg.edit_text(response, parse_mode="HTML")
else:
await status_msg.edit_text("🔇 Голос обнаружен, но слов не разобрал.")
except Exception as e:
logger.error(f"❌ Voice Integration Error: {e}")
await status_msg.edit_text(f"❌ Ошибка модуля Whisper: {e}")
voice_router = router