-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot_app.py
87 lines (67 loc) · 2.53 KB
/
bot_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.types import File
# from recasepunc.recasepunc import WordpieceTokenizer
from pathlib import Path
from modules.translate import translate_vosk, translate_sr
from settings import TM_TOKEN
# Set FMS storage
storage = MemoryStorage()
# Set bot parameters
bot = Bot(token=TM_TOKEN, parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot, storage=storage)
# dp.middleware.setup(LoggingMiddleware())
async def handle_file(file: File, file_name: str) -> None:
"""
This handler download media files
:param file:
:param file_name:
:return:
"""
Path(f"cache").mkdir(parents=True, exist_ok=True)
await bot.download_file(file_path=file.file_path, destination=f"cache/{file_name}")
@dp.message_handler(commands=["start", "help"])
async def send_welcome(message: types.Message) -> None:
"""
This handler will be called when user sends `/start` or `/help` command
"""
await message.reply("Hi!\nI'm Perevodilka!\nI'm translate your voice massages.")
@dp.message_handler(content_types=["audio"])
async def echo(message: types.Message) -> None:
"""
This handler will be called when user sends audio file and starts the process of converting to text
:param message: Audio
:return: None
"""
print(message)
audio = await bot.get_file(message.audio.file_id) # Get file path
await handle_file(file=audio, file_name=f"{message.audio.file_name}")
google_text = translate_sr(message.audio.file_name)
await message.reply(f"Google: {google_text}")
vosk_text = translate_vosk(message.audio.file_name)
await message.reply(f"Vosk: {vosk_text}")
# Delete source file
Path(f"cache/{message.audio.file_name}").unlink()
# print(f"Google {text}")
# print(f"Vosk {text1}")
@dp.message_handler(content_types=["voice"])
async def echo(message: types.Message) -> None:
print(message)
voice = await message.voice.get_file()
await handle_file(file=voice, file_name=f"{voice.file_id}.ogg")
google_text = translate_sr(f"{voice.file_id}.ogg")
await message.reply(f"Google: {google_text}")
vosk_text = translate_vosk(f"{voice.file_id}.ogg")
await message.reply(f"Vosk: {vosk_text}")
print(message)
# Delete source file
Path(f"cache/{voice.file_id}.ogg").unlink()
def main() -> None:
"""
The main function
:return:
"""
executor.start_polling(dp, skip_updates=True)
# Start bot
if __name__ == "__main__":
main()