Rvc / bot.py
Hashim-dotcom's picture
Update bot.py
3ae27c8 verified
raw
history blame
4.15 kB
# Final version - 5 August
import os
import sys
import telegram
from telegram.ext import Application, CommandHandler, MessageHandler, filters, AIORateLimiter
from telegram.request import HTTPXRequest
import torch
import logging
from huggingface_hub import hf_hub_download
import asyncio
import soundfile as sf
# إضافة مسار المشروع إلى مسارات بايثون للوصول للمكتبات المحلية
sys.path.append(os.getcwd())
from infer.modules.vc.pipeline import Pipeline
from configs.config import Config
# إعداد السجلات
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# --- إعدادات أساسية ---
config = Config()
config.device = "cpu"
config.is_half = False
# --- تحميل النموذج ---
HUB_REPO_ID = "Hashim-dotcom/Hashim.ai.rvc"
MODEL_FILE = "model.pth"
WEIGHTS_DIR = "assets/weights"
pipeline = None
try:
logger.info("تجهيز مجلد النماذج...")
os.makedirs(WEIGHTS_DIR, exist_ok=True)
logger.info(f"جاري تحميل نموذجك الخاص '{MODEL_FILE}'...")
model_path_on_disk = hf_hub_download(repo_id=HUB_REPO_ID, filename=MODEL_FILE, cache_dir="/tmp/.cache/huggingface")
final_model_path = os.path.join(WEIGHTS_DIR, MODEL_FILE)
os.rename(model_path_on_disk, final_model_path)
logger.info("تم تحميل النموذج بنجاح!")
# هذا هو السطر الذي تم إصلاحه
pipeline = Pipeline(config)
except Exception as e:
logger.error(f"حدث خطأ فادح أثناء تحميل النموذج: {e}")
# --- دوال البوت ---
async def start(update, context):
await update.message.reply_text("مرحباً! أنا بوت تحويل الصوت. أرسل لي رسالة صوتية أو ملفاً صوتياً.")
async def handle_audio(update, context):
if pipeline is None:
await update.message.reply_text("عذراً، البوت يواجه مشكلة تقنية (فشل تحميل النموذج).")
return
await update.message.reply_text("تم استلام صوتك، جاري المعالجة...")
try:
if update.message.voice:
file_id = update.message.voice.file_id
elif update.message.audio:
file_id = update.message.audio.file_id
else:
return
audio_file = await context.bot.get_file(file_id)
input_path = f"{file_id}_input"
await audio_file.download_to_drive(input_path)
output_audio = pipeline.infer(model_name=MODEL_FILE, input_audio_path=input_path, f0_up_key=0)
output_path = f"{file_id}_output.wav"
sf.write(output_path, output_audio[1], output_audio[0], format='WAV')
await update.message.reply_audio(audio=open(output_path, 'rb'), title="صوت محول")
except Exception as e:
logger.error(f"حدث خطأ أثناء المعالجة: {e}")
await update.message.reply_text(f"عذراً، حدث خطأ: {str(e)}")
finally:
if 'input_path' in locals() and os.path.exists(input_path):
os.remove(input_path)
if 'output_path' in locals() and os.path.exists(output_path):
os.remove(output_path)
async def main():
TOKEN = os.getenv("TELEGRAM_TOKEN")
if not TOKEN:
logger.critical("خطأ: لم يتم العثور على TELEGRAM_TOKEN.")
return
request = HTTPXRequest(http_version="1.1")
application = (
Application.builder()
.token(TOKEN)
.request(request)
.rate_limiter(AIORateLimiter())
.build()
)
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, handle_audio))
logger.info("البوت قيد التشغيل...")
await application.initialize()
await application.updater.start_polling()
await application.start()
while True:
await asyncio.sleep(3600)
if __name__ == "__main__":
asyncio.run(main())