Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,74 +8,67 @@ import os
|
|
| 8 |
from telegram import Update
|
| 9 |
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters
|
| 10 |
|
| 11 |
-
# 1. Загрузка модели
|
| 12 |
model_name = "facebook/mms-tts-che"
|
| 13 |
model = VitsModel.from_pretrained(model_name)
|
| 14 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 15 |
|
| 16 |
def tts_chechen_logic(text):
|
| 17 |
-
# Очистка
|
| 18 |
-
|
| 19 |
-
inputs = tokenizer(clean_text, return_tensors="pt")
|
| 20 |
-
|
| 21 |
with torch.no_grad():
|
| 22 |
output = model(**inputs).waveform
|
| 23 |
|
| 24 |
sampling_rate = model.config.sampling_rate
|
| 25 |
audio_data = output.squeeze().numpy()
|
| 26 |
-
file_path = "
|
| 27 |
scipy.io.wavfile.write(file_path, rate=sampling_rate, data=audio_data)
|
| 28 |
return sampling_rate, audio_data, file_path
|
| 29 |
|
| 30 |
-
# --- БЛОК
|
| 31 |
-
# Твой
|
| 32 |
TG_TOKEN = "8287698372:AAEwoOWgQWHbeyDmJdN0B-OpKpy7-TARHMg"
|
| 33 |
|
| 34 |
async def handle_tg_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 35 |
if not update.message or not update.message.text:
|
| 36 |
return
|
| 37 |
|
| 38 |
-
print(f"📩
|
| 39 |
try:
|
| 40 |
-
# Генерируем голос
|
| 41 |
_, _, file_path = tts_chechen_logic(update.message.text)
|
| 42 |
-
# Отправляем аудио файл
|
| 43 |
with open(file_path, 'rb') as audio:
|
| 44 |
await context.bot.send_voice(chat_id=update.effective_chat.id, voice=audio)
|
| 45 |
-
print("✅ Голосовое сообщение отправлено!")
|
| 46 |
except Exception as e:
|
| 47 |
-
print(f"❌
|
| 48 |
|
| 49 |
-
def
|
| 50 |
try:
|
| 51 |
-
# Настройка
|
| 52 |
loop = asyncio.new_event_loop()
|
| 53 |
asyncio.set_event_loop(loop)
|
| 54 |
|
| 55 |
app = ApplicationBuilder().token(TG_TOKEN).build()
|
| 56 |
app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_tg_message))
|
| 57 |
|
| 58 |
-
print("🚀 Бот запущен
|
| 59 |
app.run_polling(drop_pending_updates=True, close_loop=False)
|
| 60 |
except Exception as e:
|
| 61 |
-
print(f"🔥
|
| 62 |
|
| 63 |
-
# Запуск бота в отдельном потоке
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
# ---------------------------------
|
| 67 |
|
| 68 |
-
# Интерфейс
|
| 69 |
def gradio_interface(text):
|
| 70 |
sr, audio, _ = tts_chechen_logic(text)
|
| 71 |
return (sr, audio)
|
| 72 |
|
| 73 |
demo = gr.Interface(
|
| 74 |
fn=gradio_interface,
|
| 75 |
-
inputs=gr.Textbox(label="
|
| 76 |
-
outputs=gr.Audio(label="
|
| 77 |
-
title="NoxchiynAz
|
| 78 |
-
description="Ваш персональный бот для озвучки чеченского текста."
|
| 79 |
)
|
| 80 |
|
| 81 |
if __name__ == "__main__":
|
|
|
|
| 8 |
from telegram import Update
|
| 9 |
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters
|
| 10 |
|
| 11 |
+
# 1. Загрузка модели для чеченского языка
|
| 12 |
model_name = "facebook/mms-tts-che"
|
| 13 |
model = VitsModel.from_pretrained(model_name)
|
| 14 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 15 |
|
| 16 |
def tts_chechen_logic(text):
|
| 17 |
+
# Очистка и синтез
|
| 18 |
+
inputs = tokenizer(text.strip().lower(), return_tensors="pt")
|
|
|
|
|
|
|
| 19 |
with torch.no_grad():
|
| 20 |
output = model(**inputs).waveform
|
| 21 |
|
| 22 |
sampling_rate = model.config.sampling_rate
|
| 23 |
audio_data = output.squeeze().numpy()
|
| 24 |
+
file_path = "voice.wav"
|
| 25 |
scipy.io.wavfile.write(file_path, rate=sampling_rate, data=audio_data)
|
| 26 |
return sampling_rate, audio_data, file_path
|
| 27 |
|
| 28 |
+
# --- БЛОК TELEGRAM БОТА ---
|
| 29 |
+
# Твой новый токен
|
| 30 |
TG_TOKEN = "8287698372:AAEwoOWgQWHbeyDmJdN0B-OpKpy7-TARHMg"
|
| 31 |
|
| 32 |
async def handle_tg_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 33 |
if not update.message or not update.message.text:
|
| 34 |
return
|
| 35 |
|
| 36 |
+
print(f"📩 Текст для бота: {update.message.text}")
|
| 37 |
try:
|
|
|
|
| 38 |
_, _, file_path = tts_chechen_logic(update.message.text)
|
|
|
|
| 39 |
with open(file_path, 'rb') as audio:
|
| 40 |
await context.bot.send_voice(chat_id=update.effective_chat.id, voice=audio)
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
+
print(f"❌ Ошибка: {e}")
|
| 43 |
|
| 44 |
+
def run_bot_in_background():
|
| 45 |
try:
|
| 46 |
+
# Настройка асинхронности для контейнера
|
| 47 |
loop = asyncio.new_event_loop()
|
| 48 |
asyncio.set_event_loop(loop)
|
| 49 |
|
| 50 |
app = ApplicationBuilder().token(TG_TOKEN).build()
|
| 51 |
app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_tg_message))
|
| 52 |
|
| 53 |
+
print("🚀 Бот запущен и слушает Telegram!")
|
| 54 |
app.run_polling(drop_pending_updates=True, close_loop=False)
|
| 55 |
except Exception as e:
|
| 56 |
+
print(f"🔥 Критическая ошибка: {e}")
|
| 57 |
|
| 58 |
+
# Запуск бота в отдельном потоке
|
| 59 |
+
threading.Thread(target=run_bot_in_background, daemon=True).start()
|
| 60 |
+
# --------------------------
|
|
|
|
| 61 |
|
| 62 |
+
# Интерфейс Gradio (сайт)
|
| 63 |
def gradio_interface(text):
|
| 64 |
sr, audio, _ = tts_chechen_logic(text)
|
| 65 |
return (sr, audio)
|
| 66 |
|
| 67 |
demo = gr.Interface(
|
| 68 |
fn=gradio_interface,
|
| 69 |
+
inputs=gr.Textbox(label="Чеченский текст"),
|
| 70 |
+
outputs=gr.Audio(label="Голос"),
|
| 71 |
+
title="NoxchiynAz"
|
|
|
|
| 72 |
)
|
| 73 |
|
| 74 |
if __name__ == "__main__":
|