Opera8 commited on
Commit
981f66b
·
verified ·
1 Parent(s): c6e931b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +79 -100
main.py CHANGED
@@ -88,9 +88,9 @@ async def send_with_keyboard(client, chat_id, text, use_keyboard=True):
88
  return msg
89
 
90
 
91
- # --- 🚨 تابع هوشمند دانلود فایل (آپدیت و رفع باگ مسیر ذخیره) 🚨 ---
92
  async def helper_download_file(client, msg_obj):
93
- errors = []
94
 
95
  file_id = None
96
  file_obj = None
@@ -102,22 +102,17 @@ async def helper_download_file(client, msg_obj):
102
  elif isinstance(val, dict) and 'file_id' in val: file_id = val['file_id']
103
  if file_id: break
104
 
105
- # ساخت یک نام رندوم تا کتابخانه rubpy ارور NoneType برای نام فایل ندهد
106
  temp_name = f"temp_dl_{random.randint(1000, 999999)}.tmp"
107
 
108
  if hasattr(client, "download_file"):
109
-
110
- # تلاش ۱: ارسال مستقیم آبجکت پیام و نام فایل
111
  try:
112
  await client.download_file(msg_obj, temp_name)
113
  if os.path.exists(temp_name):
114
  with open(temp_name, 'rb') as f: data = f.read()
115
  os.remove(temp_name)
116
  return data
117
- except Exception as e:
118
- errors.append(f"تلاش ۱ (msg_obj): {e}")
119
 
120
- # تلاش ۲: ارسال آبجکت فایل اختصاصی
121
  if file_obj:
122
  try:
123
  await client.download_file(file_obj, temp_name)
@@ -125,10 +120,8 @@ async def helper_download_file(client, msg_obj):
125
  with open(temp_name, 'rb') as f: data = f.read()
126
  os.remove(temp_name)
127
  return data
128
- except Exception as e:
129
- errors.append(f"تلاش ۲ (file_obj): {e}")
130
 
131
- # تلاش ۳: ارسال آیدی با آرگومان file_name
132
  if file_id:
133
  try:
134
  await client.download_file(file_id, file_name=temp_name)
@@ -136,24 +129,70 @@ async def helper_download_file(client, msg_obj):
136
  with open(temp_name, 'rb') as f: data = f.read()
137
  os.remove(temp_name)
138
  return data
139
- except Exception as e:
140
- errors.append(f"تلاش ۳ (file_id, file_name): {e}")
141
 
142
- # تلاش ۴: ارسال آیدی با آرگومان save_as
143
- if file_id:
144
  try:
145
  await client.download_file(file_id, save_as=temp_name)
146
  if os.path.exists(temp_name):
147
  with open(temp_name, 'rb') as f: data = f.read()
148
  os.remove(temp_name)
149
  return data
150
- except Exception as e:
151
- errors.append(f"تلاش ۴ (file_id, save_as): {e}")
152
 
153
- # در صورت شکست تمام حالت‌ها
154
  raise Exception("دانلود ناموفق. لاگ:\n" + "\n".join(errors))
155
 
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  # --- لیست تمام سرورهای تولید صدای شما ---
158
  WORKER_URLS =[
159
  "https://hamed744-ttspro.hf.space/generate",
@@ -245,7 +284,7 @@ async def process_gemini(client, chat_id, prompt):
245
  await send_with_keyboard(client, chat_id, "❌ متأسفانه پاسخی دریافت نشد. لطفاً دوباره تلاش کنید.", False)
246
  return
247
 
248
- history.append({"role": "model", "parts": [{"text": final_answer}]})
249
  user_states[chat_id]["history"] = history
250
 
251
  try:
@@ -275,7 +314,7 @@ async def process_gemini(client, chat_id, prompt):
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)
@@ -303,7 +342,7 @@ async def process_image(client, chat_id, prompt):
303
  if isinstance(proc_msg, dict):
304
  msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
305
  if msg_id:
306
- await client.delete_messages(chat_id, [msg_id])
307
  except Exception: pass
308
 
309
  if not generated_image:
@@ -318,50 +357,22 @@ async def process_image(client, chat_id, prompt):
318
  await asyncio.sleep(1)
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)
@@ -405,48 +416,16 @@ async def process_tts(client, chat_id, user_text, speaker_id, speaker_name):
405
  file_name = f"audio_{random.randint(1000, 999999)}.wav"
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:
@@ -482,7 +461,7 @@ async def process_stt(client, chat_id, audio_bytes):
482
  if proc_msg:
483
  msg_id = getattr(proc_msg, 'message_id', None)
484
  if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
485
- if msg_id: await client.delete_messages(chat_id, [msg_id])
486
  except Exception: pass
487
 
488
  if transcribed_text:
@@ -519,7 +498,7 @@ async def process_file_analysis(client, chat_id, file_bytes, file_name, prompt):
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:
@@ -592,7 +571,7 @@ else:
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
 
88
  return msg
89
 
90
 
91
+ # --- 🚨 تابع هوشمند دانلود فایل 🚨 ---
92
  async def helper_download_file(client, msg_obj):
93
+ errors =[]
94
 
95
  file_id = None
96
  file_obj = None
 
102
  elif isinstance(val, dict) and 'file_id' in val: file_id = val['file_id']
103
  if file_id: break
104
 
 
105
  temp_name = f"temp_dl_{random.randint(1000, 999999)}.tmp"
106
 
107
  if hasattr(client, "download_file"):
 
 
108
  try:
109
  await client.download_file(msg_obj, temp_name)
110
  if os.path.exists(temp_name):
111
  with open(temp_name, 'rb') as f: data = f.read()
112
  os.remove(temp_name)
113
  return data
114
+ except Exception as e: errors.append(f"تلاش ۱: {e}")
 
115
 
 
116
  if file_obj:
117
  try:
118
  await client.download_file(file_obj, temp_name)
 
120
  with open(temp_name, 'rb') as f: data = f.read()
121
  os.remove(temp_name)
122
  return data
123
+ except Exception as e: errors.append(f"تلاش ۲: {e}")
 
124
 
 
125
  if file_id:
126
  try:
127
  await client.download_file(file_id, file_name=temp_name)
 
129
  with open(temp_name, 'rb') as f: data = f.read()
130
  os.remove(temp_name)
131
  return data
132
+ except Exception as e: errors.append(f"تلاش ۳: {e}")
 
133
 
 
 
134
  try:
135
  await client.download_file(file_id, save_as=temp_name)
136
  if os.path.exists(temp_name):
137
  with open(temp_name, 'rb') as f: data = f.read()
138
  os.remove(temp_name)
139
  return data
140
+ except Exception as e: errors.append(f"تلاش ۴: {e}")
 
141
 
 
142
  raise Exception("دانلود ناموفق. لاگ:\n" + "\n".join(errors))
143
 
144
 
145
+ # --- 🚨 تابع هوشمند آپلود فایل (نسخه فوق‌پیشرفته + دیباگر) 🚨 ---
146
+ async def helper_upload_file(client, chat_id, file_name, file_type="photo", caption=""):
147
+ abs_path = os.path.abspath(file_name) # پیدا کردن مسیر قطعی در سرور
148
+ error_logs =[]
149
+
150
+ # 1. تلاش اول: ارسال پیام با پارامتر فایل
151
+ try:
152
+ await client.send_message(chat_id, text=caption, file=abs_path)
153
+ return True
154
+ except Exception as e:
155
+ error_logs.append(f"MsgFile: {e}")
156
+
157
+ # 2. تلاش دوم: استفاده مستقیم بدون نام پارامتر
158
+ try:
159
+ if file_type == "photo":
160
+ await client.send_photo(chat_id, abs_path, caption=caption)
161
+ else:
162
+ await client.send_voice(chat_id, abs_path)
163
+ return True
164
+ except Exception as e:
165
+ error_logs.append(f"DirectArg: {e}")
166
+
167
+ # 3. تلاش سوم: استفاده با نام پارامتر
168
+ try:
169
+ if file_type == "photo":
170
+ await client.send_photo(chat_id, photo=abs_path, caption=caption)
171
+ else:
172
+ await client.send_voice(chat_id, voice=abs_path)
173
+ return True
174
+ except Exception as e:
175
+ error_logs.append(f"Kwarg: {e}")
176
+
177
+ # 4. تلاش چهارم: ارسال به عنوان سند (Document)
178
+ try:
179
+ await client.send_document(chat_id, document=abs_path, caption=caption)
180
+ return True
181
+ except Exception as e:
182
+ error_logs.append(f"Doc: {e}")
183
+
184
+ # 5. تلاش پنجم: تبدیل به بایت و ارسال مستقیم حافظه
185
+ try:
186
+ with open(abs_path, 'rb') as f:
187
+ await client.send_message(chat_id, text=caption, file=f)
188
+ return True
189
+ except Exception as e:
190
+ error_logs.append(f"ByteObj: {e}")
191
+
192
+ # در صورت شکست، لیست ارور��ا را خروجی می‌دهد
193
+ return "\n".join(error_logs)
194
+
195
+
196
  # --- لیست تمام سرورهای تولید صدای شما ---
197
  WORKER_URLS =[
198
  "https://hamed744-ttspro.hf.space/generate",
 
284
  await send_with_keyboard(client, chat_id, "❌ متأسفانه پاسخی دریافت نشد. لطفاً دوباره تلاش کنید.", False)
285
  return
286
 
287
+ history.append({"role": "model", "parts":[{"text": final_answer}]})
288
  user_states[chat_id]["history"] = history
289
 
290
  try:
 
314
  await send_with_keyboard(client, chat_id, "❌ خطایی در ارسال پیام رخ داد.", False)
315
 
316
 
317
+ # --- ۲. پردازش ساخت عکس ---
318
  async def process_image(client, chat_id, prompt):
319
  if not HF_TOKENS:
320
  await send_with_keyboard(client, chat_id, "❌ توکن‌های هاگینگ فیس تنظیم نشده‌اند.", False)
 
342
  if isinstance(proc_msg, dict):
343
  msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
344
  if msg_id:
345
+ await client.delete_messages(chat_id,[msg_id])
346
  except Exception: pass
347
 
348
  if not generated_image:
 
357
  await asyncio.sleep(1)
358
  caption_text = "🎨 تصویر شما آماده شد!\n(مدل: Z-Image-Turbo)"
359
 
360
+ # استفاده از تابع هوشمند برای آپلود
361
+ upload_result = await helper_upload_file(client, chat_id, file_name, "photo", caption_text)
362
 
363
+ if upload_result is True:
364
+ await send_with_keyboard(client, chat_id, "✅ تصویر با موفقیت ارسال شد.", True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  else:
366
+ err_msg = str(upload_result)[:800]
367
+ await send_with_keyboard(client, chat_id, f"❌ تصویر در سرور ساخته شد، اما روبیکا در آپلود آن ارور داد.\n\n🔴 لاگ ارور برنامه‌نویس:\n`{err_msg}`", True)
368
+
369
  if os.path.exists(file_name): os.remove(file_name)
370
 
371
  except Exception as e:
372
  await send_with_keyboard(client, chat_id, f"❌ خطایی در فرآیند ذخیره عکس رخ داد:\n{str(e)[:150]}", True)
373
 
374
 
375
+ # --- ۳. پردازش ساخت صدا ---
376
  async def process_tts(client, chat_id, user_text, speaker_id, speaker_name):
377
  try:
378
  proc_msg = await send_with_keyboard(client, chat_id, f"⏳ در حال ساخت صدا با «{speaker_name}»...\n(لطفاً صبور باشید)", False)
 
416
  file_name = f"audio_{random.randint(1000, 999999)}.wav"
417
  with open(file_name, "wb") as f: f.write(audio_bytes)
418
 
419
+ await asyncio.sleep(1)
420
 
421
+ # استفاده از تابع هوشمند برای آپلود
422
+ upload_result = await helper_upload_file(client, chat_id, file_name, "voice", "")
423
+
424
+ if upload_result is True:
425
+ await send_with_keyboard(client, chat_id, "✅ صدای شما با موفقیت ارسال شد.", True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  else:
427
+ err_msg = str(upload_result)[:800]
428
+ await send_with_keyboard(client, chat_id, f"❌ صدا ساخته شد، اما روبیکا در آپلود آن ارور داد.\n\n🔴 لاگ ارور برنامه‌نویس:\n`{err_msg}`", True)
429
 
430
  if os.path.exists(file_name): os.remove(file_name)
431
  else:
 
461
  if proc_msg:
462
  msg_id = getattr(proc_msg, 'message_id', None)
463
  if isinstance(proc_msg, dict): msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
464
+ if msg_id: await client.delete_messages(chat_id,[msg_id])
465
  except Exception: pass
466
 
467
  if transcribed_text:
 
498
  for key in keys_to_try:
499
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key}"
500
  payload = {
501
+ "contents":[{"parts":[{"text": prompt}, {"inlineData": {"mimeType": mime_type, "data": base64_data}}]}],
502
  "generationConfig": {"temperature": 0.6, "maxOutputTokens": 8192}
503
  }
504
  try:
 
571
  await send_with_keyboard(client, chat_id, "سلام! به ربات هوشمند آلفا خوش آمدید 🤖\n\nلطفاً برای شروع، از کیبورد پایین یکی از بخش‌ها را انتخاب کنید:", True)
572
  return
573
 
574
+ if user_text_str in["/chat", "💬 چت", "چت با هوش مصنوعی 🤖"]:
575
  user_states[chat_id] = {"mode": "chat", "text": "", "history":[]}
576
  await send_with_keyboard(client, chat_id, "💬 شما وارد بخش **چت با هوش مصنوعی** شدید.\n(حالا ربات سابقه گفتگو را به یاد می‌آورد)\n\nهر سوالی دارید بفرستید تا جواب بدم:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
577
  return