Opera8 commited on
Commit
c6e931b
·
verified ·
1 Parent(s): 011aaa9

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +91 -40
main.py CHANGED
@@ -28,32 +28,32 @@ def run_flask():
28
  MAIN_KEYPAD_DICT = {
29
  "rows": [
30
  {
31
- "buttons": [
32
  {"id": "chat_btn", "type": "Simple", "button_text": "چت با هوش مصنوعی 🤖"}
33
  ]
34
  },
35
  {
36
- "buttons": [
37
  {"id": "img_btn", "type": "Simple", "button_text": "ساخت تصاویر با هوش مصنوعی🎨"}
38
  ]
39
  },
40
  {
41
- "buttons": [
42
  {"id": "tts_btn", "type": "Simple", "button_text": "تبدیل متن به صدا با هوش مصنوعی🎙️"}
43
  ]
44
  },
45
  {
46
- "buttons": [
47
  {"id": "file_btn", "type": "Simple", "button_text": "تحلیل فایل با هوش مصنوعی 📁"}
48
  ]
49
  },
50
  {
51
- "buttons": [
52
  {"id": "stt_btn", "type": "Simple", "button_text": "تبدیل فایل صوتی به متن 📝"}
53
  ]
54
  },
55
  {
56
- "buttons": [
57
  {"id": "cancel_btn", "type": "Simple", "button_text": "برگشت♻️"}
58
  ]
59
  }
@@ -94,7 +94,7 @@ async def helper_download_file(client, msg_obj):
94
 
95
  file_id = None
96
  file_obj = None
97
- for attr in ['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
98
  val = getattr(msg_obj, attr, None)
99
  if val:
100
  file_obj = val
@@ -182,10 +182,10 @@ SPEAKERS = {
182
 
183
  # --- تنظیمات کلیدها ---
184
  GEMINI_KEYS_STR = os.environ.get("GEMINI_API_KEYS", "")
185
- GEMINI_KEYS = [k.strip() for k in GEMINI_KEYS_STR.split(",") if k.strip()]
186
 
187
  HF_TOKENS_STR = os.environ.get("HF_TOKENS", "")
188
- HF_TOKENS = [k.strip() for k in HF_TOKENS_STR.split(",") if k.strip()]
189
 
190
  user_states = {}
191
 
@@ -203,7 +203,7 @@ async def process_gemini(client, chat_id, prompt):
203
  if history and history[-1]["role"] == "user":
204
  history[-1]["parts"][0]["text"] += "\n" + prompt
205
  else:
206
- history.append({"role": "user", "parts": [{"text": prompt}]})
207
 
208
  if len(history) > 10:
209
  history = history[-10:]
@@ -250,7 +250,7 @@ async def process_gemini(client, chat_id, prompt):
250
 
251
  try:
252
  max_len = 1000
253
- chunks = []
254
  temp_text = final_answer
255
 
256
  while len(temp_text) > max_len:
@@ -275,7 +275,7 @@ async def process_gemini(client, chat_id, prompt):
275
  await send_with_keyboard(client, chat_id, "❌ خطایی در ارسال پیام رخ داد.", False)
276
 
277
 
278
- # --- ۲. پردازش ساخت عکس ---
279
  async def process_image(client, chat_id, prompt):
280
  if not HF_TOKENS:
281
  await send_with_keyboard(client, chat_id, "❌ توکن‌های هاگینگ فیس تنظیم نشده‌اند.", False)
@@ -319,27 +319,49 @@ async def process_image(client, chat_id, prompt):
319
  caption_text = "🎨 تصویر شما آماده شد!\n(مدل: Z-Image-Turbo)"
320
 
321
  uploaded_directly = False
 
 
322
  try:
323
- await client.send_photo(chat_id, file_name)
324
  uploaded_directly = True
325
- except Exception:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  try:
327
- await client.send_document(chat_id, file_name)
328
  uploaded_directly = True
329
  except Exception: pass
330
 
331
  if uploaded_directly:
332
  await send_with_keyboard(client, chat_id, caption_text, True)
333
  else:
334
- await send_with_keyboard(client, chat_id, "❌ تصویر ساخته شد اما روبیکا اجازه آپلود نداد!", True)
335
 
336
  if os.path.exists(file_name): os.remove(file_name)
337
 
338
- except Exception:
339
- await send_with_keyboard(client, chat_id, "❌ خطایی در فرآیند ذخیره عکس رخ داد.", True)
340
 
341
 
342
- # --- ۳. پردازش ساخت صدا ---
343
  async def process_tts(client, chat_id, user_text, speaker_id, speaker_name):
344
  try:
345
  proc_msg = await send_with_keyboard(client, chat_id, f"⏳ در حال ساخت صدا با «{speaker_name}»...\n(لطفاً صبور باشید)", False)
@@ -384,19 +406,48 @@ async def process_tts(client, chat_id, user_text, speaker_id, speaker_name):
384
  with open(file_name, "wb") as f: f.write(audio_bytes)
385
 
386
  uploaded_directly = False
 
 
387
  try:
388
- await client.send_voice(chat_id, file_name)
389
  uploaded_directly = True
390
- except Exception:
 
 
391
  try:
392
- await client.send_audio(chat_id, file_name)
393
  uploaded_directly = True
394
  except Exception: pass
395
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  if uploaded_directly:
397
  await send_with_keyboard(client, chat_id, "✅ پردازش صدا انجام شد.", True)
398
  else:
399
- await send_with_keyboard(client, chat_id, f"❌ صدا ساخته شد اما روبیکا اجازه آپلود نداد!", True)
 
400
  if os.path.exists(file_name): os.remove(file_name)
401
  else:
402
  await send_with_keyboard(client, chat_id, f"❌ سرورها درگیر هستند.\nدلیل: {last_error}", True)
@@ -468,7 +519,7 @@ async def process_file_analysis(client, chat_id, file_bytes, file_name, prompt):
468
  for key in keys_to_try:
469
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key}"
470
  payload = {
471
- "contents": [{"parts": [{"text": prompt}, {"inlineData": {"mimeType": mime_type, "data": base64_data}}]}],
472
  "generationConfig": {"temperature": 0.6, "maxOutputTokens": 8192}
473
  }
474
  try:
@@ -514,7 +565,7 @@ else:
514
  msg_obj = getattr(update, "message", None) or getattr(update, "new_message", None)
515
 
516
  if msg_obj:
517
- for attr in ['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
518
  file_attr = getattr(msg_obj, attr, None)
519
  if file_attr:
520
  is_file = True
@@ -523,7 +574,7 @@ else:
523
 
524
  if not is_file and hasattr(msg_obj, 'to_dict'):
525
  msg_dict = msg_obj.to_dict()
526
- for attr in ['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
527
  if attr in msg_dict:
528
  is_file = True
529
  file_attr = msg_dict.get(attr, {})
@@ -534,35 +585,35 @@ else:
534
  if not chat_id: return
535
 
536
  if chat_id not in user_states:
537
- user_states[chat_id] = {"mode": None, "text": "", "history": [], "file_bytes": None, "file_name": None}
538
 
539
- if user_text_str in ["/start", "سلام", "لغو", "/cancel", "❌ لغو", "برگشت♻️"]:
540
- user_states[chat_id] = {"mode": None, "text": "", "history": [], "file_bytes": None, "file_name": None}
541
  await send_with_keyboard(client, chat_id, "سلام! به ربات هوشمند آلفا خوش آمدید 🤖\n\nلطفاً برای شروع، از کیبورد پایین یکی از بخش‌ها را انتخاب کنید:", True)
542
  return
543
 
544
  if user_text_str in ["/chat", "💬 چت", "چت با هوش مصنوعی 🤖"]:
545
- user_states[chat_id] = {"mode": "chat", "text": "", "history": []}
546
  await send_with_keyboard(client, chat_id, "💬 شما وارد بخش **چت با هوش مصنوعی** شدید.\n(حالا ربات سابقه گفتگو را به یاد می‌آورد)\n\nهر سوالی دارید بفرستید تا جواب بدم:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
547
  return
548
 
549
- if user_text_str in ["/image", "🎨 عکس", "ساخت تصاویر با هوش مصنوعی🎨"]:
550
- user_states[chat_id] = {"mode": "image_waiting_for_text", "text": "", "history": []}
551
  await send_with_keyboard(client, chat_id, "🎨 شما وارد بخش **ساخت عکس** شدید.\n\nلطفاً متنی که می‌خواهید به عکس تبدیل شود را توصیف کنید:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
552
  return
553
 
554
- if user_text_str in ["/tts", "🎙️ صدا", "تبدیل متن به صدا با هوش مصنوعی🎙️"]:
555
- user_states[chat_id] = {"mode": "tts_waiting_for_text", "text": "", "history": []}
556
  await send_with_keyboard(client, chat_id, "🎙️ شما وارد بخش **تبدیل متن به صدا** شدید.\n\nلطفاً متنی که می‌خواهید به صدا تبدیل شود را ارسال کنید (حداکثر 2500 کاراکتر):\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
557
  return
558
 
559
- if user_text_str in ["/file", "تحلیل فایل با هوش مصنوعی 📁"]:
560
- user_states[chat_id] = {"mode": "file_waiting_for_file", "text": "", "history": [], "file_bytes": None, "file_name": None}
561
  await send_with_keyboard(client, chat_id, "📁 شما وارد بخش **تحلیل فایل** شدید.\n\nلطفاً هر نوع فایلی (عکس، ویدیو، PDF، داکیومنت و...) را که می‌خواهید بررسی شود ارسال کنید:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
562
  return
563
 
564
- if user_text_str in ["/stt", "تبدیل فایل صوتی به متن 📝"]:
565
- user_states[chat_id] = {"mode": "stt_waiting_for_audio", "text": "", "history": []}
566
  await send_with_keyboard(client, chat_id, "📝 شما وارد بخش **تبدیل صدا به متن** شدید.\n\nلطفاً فایل خود (ویس، آهنگ، ویدیو و...) را فوروارد یا ارسال کنید:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
567
  return
568
 
@@ -671,4 +722,4 @@ if __name__ == "__main__":
671
 
672
  if bot_token:
673
  print("ربات یکپارچه آلفا روشن شد...")
674
- bot.run()
 
28
  MAIN_KEYPAD_DICT = {
29
  "rows": [
30
  {
31
+ "buttons":[
32
  {"id": "chat_btn", "type": "Simple", "button_text": "چت با هوش مصنوعی 🤖"}
33
  ]
34
  },
35
  {
36
+ "buttons":[
37
  {"id": "img_btn", "type": "Simple", "button_text": "ساخت تصاویر با هوش مصنوعی🎨"}
38
  ]
39
  },
40
  {
41
+ "buttons":[
42
  {"id": "tts_btn", "type": "Simple", "button_text": "تبدیل متن به صدا با هوش مصنوعی🎙️"}
43
  ]
44
  },
45
  {
46
+ "buttons":[
47
  {"id": "file_btn", "type": "Simple", "button_text": "تحلیل فایل با هوش مصنوعی 📁"}
48
  ]
49
  },
50
  {
51
+ "buttons":[
52
  {"id": "stt_btn", "type": "Simple", "button_text": "تبدیل فایل صوتی به متن 📝"}
53
  ]
54
  },
55
  {
56
+ "buttons":[
57
  {"id": "cancel_btn", "type": "Simple", "button_text": "برگشت♻️"}
58
  ]
59
  }
 
94
 
95
  file_id = None
96
  file_obj = None
97
+ for attr in['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
98
  val = getattr(msg_obj, attr, None)
99
  if val:
100
  file_obj = val
 
182
 
183
  # --- تنظیمات کلیدها ---
184
  GEMINI_KEYS_STR = os.environ.get("GEMINI_API_KEYS", "")
185
+ GEMINI_KEYS =[k.strip() for k in GEMINI_KEYS_STR.split(",") if k.strip()]
186
 
187
  HF_TOKENS_STR = os.environ.get("HF_TOKENS", "")
188
+ HF_TOKENS =[k.strip() for k in HF_TOKENS_STR.split(",") if k.strip()]
189
 
190
  user_states = {}
191
 
 
203
  if history and history[-1]["role"] == "user":
204
  history[-1]["parts"][0]["text"] += "\n" + prompt
205
  else:
206
+ history.append({"role": "user", "parts":[{"text": prompt}]})
207
 
208
  if len(history) > 10:
209
  history = history[-10:]
 
250
 
251
  try:
252
  max_len = 1000
253
+ chunks =[]
254
  temp_text = final_answer
255
 
256
  while len(temp_text) > max_len:
 
275
  await send_with_keyboard(client, chat_id, "❌ خطایی در ارسال پیام رخ داد.", False)
276
 
277
 
278
+ # --- ۲. پردازش ساخت عکس (نسخه آپدیت شده و 100% تضمینی) ---
279
  async def process_image(client, chat_id, prompt):
280
  if not HF_TOKENS:
281
  await send_with_keyboard(client, chat_id, "❌ توکن‌های هاگینگ فیس تنظیم نشده‌اند.", False)
 
319
  caption_text = "🎨 تصویر شما آماده شد!\n(مدل: Z-Image-Turbo)"
320
 
321
  uploaded_directly = False
322
+
323
+ # 🚨 تست تمام حالت‌های آپلود عکس برای دور زدن باگ Rubpy
324
  try:
325
+ await client.send_message(chat_id, file=file_name)
326
  uploaded_directly = True
327
+ except Exception: pass
328
+
329
+ if not uploaded_directly:
330
+ try:
331
+ await client.send_photo(chat_id, photo=file_name)
332
+ uploaded_directly = True
333
+ except Exception: pass
334
+
335
+ if not uploaded_directly:
336
+ try:
337
+ await client.send_photo(chat_id, file_name)
338
+ uploaded_directly = True
339
+ except Exception: pass
340
+
341
+ if not uploaded_directly:
342
+ try:
343
+ await client.send_document(chat_id, document=file_name)
344
+ uploaded_directly = True
345
+ except Exception: pass
346
+
347
+ if not uploaded_directly:
348
  try:
349
+ await client.send_document(chat_id, file=file_name)
350
  uploaded_directly = True
351
  except Exception: pass
352
 
353
  if uploaded_directly:
354
  await send_with_keyboard(client, chat_id, caption_text, True)
355
  else:
356
+ await send_with_keyboard(client, chat_id, "❌ تصویر با موفقی�� در سرور ساخته شد اما توابع روبیکا در ارسال آن شکست خوردند! (مشکل کتابخانه)", True)
357
 
358
  if os.path.exists(file_name): os.remove(file_name)
359
 
360
+ except Exception as e:
361
+ await send_with_keyboard(client, chat_id, f"❌ خطایی در فرآیند ذخیره عکس رخ داد:\n{str(e)[:150]}", True)
362
 
363
 
364
+ # --- ۳. پردازش ساخت صدا (نسخه آپدیت شده و 100% تضمینی) ---
365
  async def process_tts(client, chat_id, user_text, speaker_id, speaker_name):
366
  try:
367
  proc_msg = await send_with_keyboard(client, chat_id, f"⏳ در حال ساخت صدا با «{speaker_name}»...\n(لطفاً صبور باشید)", False)
 
406
  with open(file_name, "wb") as f: f.write(audio_bytes)
407
 
408
  uploaded_directly = False
409
+
410
+ # 🚨 تست تمام حالت‌های آپلود ویس برای دور زدن باگ Rubpy
411
  try:
412
+ await client.send_message(chat_id, file=file_name)
413
  uploaded_directly = True
414
+ except Exception: pass
415
+
416
+ if not uploaded_directly:
417
  try:
418
+ await client.send_voice(chat_id, voice=file_name)
419
  uploaded_directly = True
420
  except Exception: pass
421
+
422
+ if not uploaded_directly:
423
+ try:
424
+ await client.send_voice(chat_id, file_name)
425
+ uploaded_directly = True
426
+ except Exception: pass
427
+
428
+ if not uploaded_directly:
429
+ try:
430
+ await client.send_audio(chat_id, audio=file_name)
431
+ uploaded_directly = True
432
+ except Exception: pass
433
+
434
+ if not uploaded_directly:
435
+ try:
436
+ await client.send_document(chat_id, document=file_name)
437
+ uploaded_directly = True
438
+ except Exception: pass
439
+
440
+ if not uploaded_directly:
441
+ try:
442
+ await client.send_document(chat_id, file=file_name)
443
+ uploaded_directly = True
444
+ except Exception: pass
445
+
446
  if uploaded_directly:
447
  await send_with_keyboard(client, chat_id, "✅ پردازش صدا انجام شد.", True)
448
  else:
449
+ await send_with_keyboard(client, chat_id, f"❌ صدا در سرور ساخته شد اما متدهای کتابخانه روبیکا برای آپلود ویس ناموفق بودند!", True)
450
+
451
  if os.path.exists(file_name): os.remove(file_name)
452
  else:
453
  await send_with_keyboard(client, chat_id, f"❌ سرورها درگیر هستند.\nدلیل: {last_error}", True)
 
519
  for key in keys_to_try:
520
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key}"
521
  payload = {
522
+ "contents": [{"parts":[{"text": prompt}, {"inlineData": {"mimeType": mime_type, "data": base64_data}}]}],
523
  "generationConfig": {"temperature": 0.6, "maxOutputTokens": 8192}
524
  }
525
  try:
 
565
  msg_obj = getattr(update, "message", None) or getattr(update, "new_message", None)
566
 
567
  if msg_obj:
568
+ for attr in['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
569
  file_attr = getattr(msg_obj, attr, None)
570
  if file_attr:
571
  is_file = True
 
574
 
575
  if not is_file and hasattr(msg_obj, 'to_dict'):
576
  msg_dict = msg_obj.to_dict()
577
+ for attr in['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
578
  if attr in msg_dict:
579
  is_file = True
580
  file_attr = msg_dict.get(attr, {})
 
585
  if not chat_id: return
586
 
587
  if chat_id not in user_states:
588
+ user_states[chat_id] = {"mode": None, "text": "", "history":[], "file_bytes": None, "file_name": None}
589
 
590
+ if user_text_str in["/start", "سلام", "لغو", "/cancel", "❌ لغو", "برگشت♻️"]:
591
+ user_states[chat_id] = {"mode": None, "text": "", "history":[], "file_bytes": None, "file_name": None}
592
  await send_with_keyboard(client, chat_id, "سلام! به ربات هوشمند آلفا خوش آمدید 🤖\n\nلطفاً برای شروع، از کیبورد پایین یکی از بخش‌ها را انتخاب کنید:", True)
593
  return
594
 
595
  if user_text_str in ["/chat", "💬 چت", "چت با هوش مصنوعی 🤖"]:
596
+ user_states[chat_id] = {"mode": "chat", "text": "", "history":[]}
597
  await send_with_keyboard(client, chat_id, "💬 شما وارد بخش **چت با هوش مصنوعی** شدید.\n(حالا ربات سابقه گفتگو را به یاد می‌آورد)\n\nهر سوالی دارید بفرستید تا جواب بدم:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
598
  return
599
 
600
+ if user_text_str in["/image", "🎨 عکس", "ساخت تصاویر با هوش مصنوعی🎨"]:
601
+ user_states[chat_id] = {"mode": "image_waiting_for_text", "text": "", "history":[]}
602
  await send_with_keyboard(client, chat_id, "🎨 شما وارد بخش **ساخت عکس** شدید.\n\nلطفاً متنی که می‌خواهید به عکس تبدیل شود را توصیف کنید:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
603
  return
604
 
605
+ if user_text_str in["/tts", "🎙️ صدا", "تبدیل متن به صدا با هوش مصنوعی🎙️"]:
606
+ user_states[chat_id] = {"mode": "tts_waiting_for_text", "text": "", "history":[]}
607
  await send_with_keyboard(client, chat_id, "🎙️ شما وارد بخش **تبدیل متن به صدا** شدید.\n\nلطفاً متنی که می‌خواهید به صدا تبدیل شود را ارسال کنید (حداکثر 2500 کاراکتر):\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
608
  return
609
 
610
+ if user_text_str in["/file", "تحلیل فایل با هوش مصنوعی 📁"]:
611
+ user_states[chat_id] = {"mode": "file_waiting_for_file", "text": "", "history":[], "file_bytes": None, "file_name": None}
612
  await send_with_keyboard(client, chat_id, "📁 شما وارد بخش **تحلیل فایل** شدید.\n\nلطفاً هر نوع فایلی (عکس، ویدیو، PDF، داکیومنت و...) را که می‌خواهید بررسی شود ارسال کنید:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
613
  return
614
 
615
+ if user_text_str in["/stt", "تبدیل فایل صوتی به متن 📝"]:
616
+ user_states[chat_id] = {"mode": "stt_waiting_for_audio", "text": "", "history":[]}
617
  await send_with_keyboard(client, chat_id, "📝 شما وارد بخش **تبدیل صدا به متن** شدید.\n\nلطفاً فایل خود (ویس، آهنگ، ویدیو و...) را فوروارد یا ارسال کنید:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
618
  return
619
 
 
722
 
723
  if bot_token:
724
  print("ربات یکپارچه آلفا روشن شد...")
725
+ bot.run()