Hashim-dotcom commited on
Commit
df9a08e
·
verified ·
1 Parent(s): 41f8ccf

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +2 -35
bot.py CHANGED
@@ -7,34 +7,26 @@ import logging
7
  from huggingface_hub import hf_hub_download
8
  import asyncio
9
 
10
- # إضافة مسار المشروع إلى مسارات بايثون
11
  sys.path.append(os.getcwd())
12
-
13
  from infer.modules.vc.pipeline import Pipeline
14
  from configs.config import Config
15
 
16
- # إعداد السجلات
17
  logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
18
  logger = logging.getLogger(__name__)
19
 
20
- # --- إعدادات أساسية ---
21
  config = Config()
22
  config.device = "cpu"
23
  config.is_half = False
24
 
25
- # --- تحميل النموذج ---
26
  HUB_REPO_ID = "Hashim-dotcom/Hashim.ai.rvc"
27
  MODEL_FILE = "model.pth"
28
  WEIGHTS_DIR = "assets/weights"
29
-
30
  pipeline = None
31
  try:
32
  logger.info("تجهيز مجلد النماذج...")
33
  os.makedirs(WEIGHTS_DIR, exist_ok=True)
34
-
35
  logger.info(f"جاري تحميل نموذجك الخاص '{MODEL_FILE}'...")
36
  model_path_on_disk = hf_hub_download(repo_id=HUB_REPO_ID, filename=MODEL_FILE, cache_dir="/tmp/.cache/huggingface")
37
-
38
  final_model_path = os.path.join(WEIGHTS_DIR, MODEL_FILE)
39
  os.rename(model_path_on_disk, final_model_path)
40
  logger.info("تم تحميل النموذج بنجاح!")
@@ -46,7 +38,6 @@ try:
46
  except Exception as e:
47
  logger.error(f"حدث خطأ فادح أثناء تحميل النموذج: {e}")
48
 
49
- # --- دوال البوت ---
50
  async def start(update, context):
51
  await update.message.reply_text("مرحباً! أنا بوت تحويل الصوت. أرسل لي رسالة صوتية أو ملفاً صوتياً.")
52
 
@@ -54,36 +45,27 @@ async def handle_audio(update, context):
54
  if pipeline is None:
55
  await update.message.reply_text("عذراً، البوت يواجه مشكلة تقنية (فشل تحميل النموذج).")
56
  return
57
-
58
  await update.message.reply_text("تم استلام صوتك، جاري المعالجة...")
59
-
60
  try:
61
  if update.message.voice:
62
  file_id = update.message.voice.file_id
63
  elif update.message.audio:
64
  file_id = update.message.audio.file_id
65
  else: return
66
-
67
  audio_file = await context.bot.get_file(file_id)
68
  input_path = f"{file_id}_input"
69
  await audio_file.download_to_drive(input_path)
70
 
71
- output_audio = pipeline.infer(
72
- model_name=MODEL_FILE,
73
- input_audio_path=input_path,
74
- f0_up_key=0
75
- )
76
  output_path = f"{file_id}_output.wav"
77
  import soundfile as sf
78
  sf.write(output_path, output_audio[1], output_audio[0], format='WAV')
79
 
80
  await update.message.reply_audio(audio=open(output_path, 'rb'), title="صوت محول")
81
-
82
  except Exception as e:
83
  logger.error(f"حدث خطأ أثناء المعالجة: {e}")
84
  await update.message.reply_text(f"عذراً، حدث خطأ: {str(e)}")
85
  finally:
86
- # تنظيف الملفات
87
  if 'input_path' in locals() and os.path.exists(input_path): os.remove(input_path)
88
  if 'output_path' in locals() and os.path.exists(output_path): os.remove(output_path)
89
 
@@ -92,28 +74,13 @@ async def main():
92
  if not TOKEN:
93
  logger.critical("خطأ: لم يتم العثور على TELEGRAM_TOKEN.")
94
  return
95
-
96
- from telegram.ext import AIORateLimiter
97
- from telegram.request import HTTPXRequest
98
-
99
- request = HTTPXRequest(http_version="1.1")
100
-
101
- application = (
102
- Application.builder()
103
- .token(TOKEN)
104
- .request(request)
105
- .rate_limiter(AIORateLimiter())
106
- .build()
107
- )
108
-
109
  application.add_handler(CommandHandler("start", start))
110
  application.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, handle_audio))
111
-
112
  logger.info("البوت قيد التشغيل...")
113
  await application.initialize()
114
  await application.updater.start_polling()
115
  await application.start()
116
  while True: await asyncio.sleep(3600)
117
-
118
  if __name__ == "__main__":
119
  asyncio.run(main())
 
7
  from huggingface_hub import hf_hub_download
8
  import asyncio
9
 
 
10
  sys.path.append(os.getcwd())
 
11
  from infer.modules.vc.pipeline import Pipeline
12
  from configs.config import Config
13
 
 
14
  logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
 
17
  config = Config()
18
  config.device = "cpu"
19
  config.is_half = False
20
 
 
21
  HUB_REPO_ID = "Hashim-dotcom/Hashim.ai.rvc"
22
  MODEL_FILE = "model.pth"
23
  WEIGHTS_DIR = "assets/weights"
 
24
  pipeline = None
25
  try:
26
  logger.info("تجهيز مجلد النماذج...")
27
  os.makedirs(WEIGHTS_DIR, exist_ok=True)
 
28
  logger.info(f"جاري تحميل نموذجك الخاص '{MODEL_FILE}'...")
29
  model_path_on_disk = hf_hub_download(repo_id=HUB_REPO_ID, filename=MODEL_FILE, cache_dir="/tmp/.cache/huggingface")
 
30
  final_model_path = os.path.join(WEIGHTS_DIR, MODEL_FILE)
31
  os.rename(model_path_on_disk, final_model_path)
32
  logger.info("تم تحميل النموذج بنجاح!")
 
38
  except Exception as e:
39
  logger.error(f"حدث خطأ فادح أثناء تحميل النموذج: {e}")
40
 
 
41
  async def start(update, context):
42
  await update.message.reply_text("مرحباً! أنا بوت تحويل الصوت. أرسل لي رسالة صوتية أو ملفاً صوتياً.")
43
 
 
45
  if pipeline is None:
46
  await update.message.reply_text("عذراً، البوت يواجه مشكلة تقنية (فشل تحميل النموذج).")
47
  return
 
48
  await update.message.reply_text("تم استلام صوتك، جاري المعالجة...")
 
49
  try:
50
  if update.message.voice:
51
  file_id = update.message.voice.file_id
52
  elif update.message.audio:
53
  file_id = update.message.audio.file_id
54
  else: return
 
55
  audio_file = await context.bot.get_file(file_id)
56
  input_path = f"{file_id}_input"
57
  await audio_file.download_to_drive(input_path)
58
 
59
+ output_audio = pipeline.infer(model_name=MODEL_FILE, input_audio_path=input_path, f0_up_key=0)
 
 
 
 
60
  output_path = f"{file_id}_output.wav"
61
  import soundfile as sf
62
  sf.write(output_path, output_audio[1], output_audio[0], format='WAV')
63
 
64
  await update.message.reply_audio(audio=open(output_path, 'rb'), title="صوت محول")
 
65
  except Exception as e:
66
  logger.error(f"حدث خطأ أثناء المعالجة: {e}")
67
  await update.message.reply_text(f"عذراً، حدث خطأ: {str(e)}")
68
  finally:
 
69
  if 'input_path' in locals() and os.path.exists(input_path): os.remove(input_path)
70
  if 'output_path' in locals() and os.path.exists(output_path): os.remove(output_path)
71
 
 
74
  if not TOKEN:
75
  logger.critical("خطأ: لم يتم العثور على TELEGRAM_TOKEN.")
76
  return
77
+ application = Application.builder().token(TOKEN).build()
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  application.add_handler(CommandHandler("start", start))
79
  application.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, handle_audio))
 
80
  logger.info("البوت قيد التشغيل...")
81
  await application.initialize()
82
  await application.updater.start_polling()
83
  await application.start()
84
  while True: await asyncio.sleep(3600)
 
85
  if __name__ == "__main__":
86
  asyncio.run(main())