Update main.py
Browse files
main.py
CHANGED
|
@@ -18,7 +18,7 @@ app = Flask(__name__)
|
|
| 18 |
|
| 19 |
@app.route('/')
|
| 20 |
def home():
|
| 21 |
-
return "ربات یکپارچه آلفا (نسخه پرو + دانلود فایل ۱۰۰٪ تضمینی + چت چندرسانهای) روشن است! 🚀"
|
| 22 |
|
| 23 |
def run_flask():
|
| 24 |
app.run(host="0.0.0.0", port=7860)
|
|
@@ -245,7 +245,7 @@ SPEAKERS = {
|
|
| 245 |
user_states = {}
|
| 246 |
|
| 247 |
|
| 248 |
-
# --- ۱. پردازش چت متنی و چندرسانهای
|
| 249 |
async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=None):
|
| 250 |
if not GEMINI_KEYS:
|
| 251 |
await send_with_keyboard(client, chat_id, "❌ کلیدهای API جیمینای تنظیم نشدهاند.", False)
|
|
@@ -255,7 +255,6 @@ async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=Non
|
|
| 255 |
|
| 256 |
history = user_states[chat_id].get("history",[])
|
| 257 |
|
| 258 |
-
# آمادهسازی بخشهای پیام کاربر (متن + فایل در صورت وجود)
|
| 259 |
new_parts =[]
|
| 260 |
|
| 261 |
if prompt:
|
|
@@ -283,14 +282,11 @@ async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=Non
|
|
| 283 |
}
|
| 284 |
})
|
| 285 |
|
| 286 |
-
# افزودن پیام جدید به سابقه
|
| 287 |
if history and history[-1]["role"] == "user":
|
| 288 |
-
# اگر پیام قبلی هم از کاربر بود، پیام جدید (فایل یا متن) را به آن اضافه کن
|
| 289 |
history[-1]["parts"].extend(new_parts)
|
| 290 |
else:
|
| 291 |
history.append({"role": "user", "parts": new_parts})
|
| 292 |
|
| 293 |
-
# تغییر تاریخچه به ۴۰ مورد برای ذخیره کردن ۲۰ سوال و جواب (۲۰ پیام رفت و برگشت)
|
| 294 |
if len(history) > 40:
|
| 295 |
history = history[-40:]
|
| 296 |
if history[0]["role"] == "model":
|
|
@@ -361,14 +357,57 @@ async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=Non
|
|
| 361 |
await send_with_keyboard(client, chat_id, "❌ خطایی در ارسال پیام رخ داد.", False)
|
| 362 |
|
| 363 |
|
| 364 |
-
# --- ۲. پردازش ساخت عکس ---
|
| 365 |
async def process_image(client, chat_id, prompt):
|
| 366 |
if not HF_TOKENS:
|
| 367 |
await send_with_keyboard(client, chat_id, "❌ توکنهای هاگینگ فیس تنظیم نشدهاند.", False)
|
| 368 |
return
|
| 369 |
|
| 370 |
-
proc_msg = await send_with_keyboard(client, chat_id, "
|
| 371 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
keys_to_try = HF_TOKENS.copy()
|
| 373 |
random.shuffle(keys_to_try)
|
| 374 |
generated_image = None
|
|
@@ -377,7 +416,8 @@ async def process_image(client, chat_id, prompt):
|
|
| 377 |
for token in keys_to_try:
|
| 378 |
try:
|
| 379 |
hf_client = AsyncInferenceClient(provider="fal-ai", api_key=token)
|
| 380 |
-
|
|
|
|
| 381 |
break
|
| 382 |
except Exception as e:
|
| 383 |
last_error_log = str(e)
|
|
@@ -402,7 +442,7 @@ async def process_image(client, chat_id, prompt):
|
|
| 402 |
rgb_im.save(file_name, format="JPEG", quality=100)
|
| 403 |
|
| 404 |
await asyncio.sleep(1)
|
| 405 |
-
caption_text = "🎨 تصویر شما آماده شد!\n(مدل: Z-Image-Turbo)"
|
| 406 |
|
| 407 |
upload_result = await helper_upload_file(client, chat_id, file_name, "Image", caption_text)
|
| 408 |
|
|
@@ -637,7 +677,7 @@ else:
|
|
| 637 |
|
| 638 |
if user_text_str in["/image", "🎨 عکس", "ساخت تصاویر با هوش مصنوعی🎨"]:
|
| 639 |
user_states[chat_id] = {"mode": "image_waiting_for_text", "text": "", "history":[]}
|
| 640 |
-
await send_with_keyboard(client, chat_id, "🎨 شما وارد بخش **ساخت عکس** شدید.\n\n
|
| 641 |
return
|
| 642 |
|
| 643 |
if user_text_str in["/tts", "🎙️ صدا", "تبدیل متن به صدا با هوش مصنوعی🎙️"]:
|
|
@@ -662,13 +702,12 @@ else:
|
|
| 662 |
elif user_text_str: await send_with_keyboard(client, chat_id, "⚠️ لطفاً ابتدا از کیبورد پایین، بخش مورد نظرتان را انتخاب کنید:", True)
|
| 663 |
return
|
| 664 |
|
| 665 |
-
# --- مسیریابی
|
| 666 |
elif current_mode == "chat":
|
| 667 |
if is_file:
|
| 668 |
await send_with_keyboard(client, chat_id, "📥 در حال دانلود فایل برای چت هوشمند...", False)
|
| 669 |
try:
|
| 670 |
file_bytes = await helper_download_file(client, msg_obj)
|
| 671 |
-
# اگر کاربر همراه عکس کپشن نوشته باشد ارسال میشود، در غیر اینصورت ربات متوجه میشود فایل فرستاده
|
| 672 |
asyncio.create_task(process_gemini(client, chat_id, user_text_str, file_bytes=file_bytes, file_name=file_name))
|
| 673 |
except Exception as dl_err:
|
| 674 |
err_trace = traceback.format_exc()
|
|
@@ -731,7 +770,6 @@ else:
|
|
| 731 |
await send_with_keyboard(client, chat_id, f"❌ خطا در دانلود فایل!\n\n🔴 لاگ برنامهنویس:\n`{err_trace[-300:]}`\n{str(dl_err)}", False)
|
| 732 |
return
|
| 733 |
|
| 734 |
-
# --- بخش تحلیل فایل اختصاصی ---
|
| 735 |
elif current_mode == "file_waiting_for_file":
|
| 736 |
if not is_file:
|
| 737 |
await send_with_keyboard(client, chat_id, "⚠️ لطفاً ابتدا یک فایل (تصویر، ویدیو، PDF و...) ارسال کنید.", False)
|
|
|
|
| 18 |
|
| 19 |
@app.route('/')
|
| 20 |
def home():
|
| 21 |
+
return "ربات یکپارچه آلفا (نسخه پرو + دانلود فایل ۱۰۰٪ تضمینی + چت چندرسانهای + پرامپتنویس هوشمند) روشن است! 🚀"
|
| 22 |
|
| 23 |
def run_flask():
|
| 24 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 245 |
user_states = {}
|
| 246 |
|
| 247 |
|
| 248 |
+
# --- ۱. پردازش چت متنی و چندرسانهای ---
|
| 249 |
async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=None):
|
| 250 |
if not GEMINI_KEYS:
|
| 251 |
await send_with_keyboard(client, chat_id, "❌ کلیدهای API جیمینای تنظیم نشدهاند.", False)
|
|
|
|
| 255 |
|
| 256 |
history = user_states[chat_id].get("history",[])
|
| 257 |
|
|
|
|
| 258 |
new_parts =[]
|
| 259 |
|
| 260 |
if prompt:
|
|
|
|
| 282 |
}
|
| 283 |
})
|
| 284 |
|
|
|
|
| 285 |
if history and history[-1]["role"] == "user":
|
|
|
|
| 286 |
history[-1]["parts"].extend(new_parts)
|
| 287 |
else:
|
| 288 |
history.append({"role": "user", "parts": new_parts})
|
| 289 |
|
|
|
|
| 290 |
if len(history) > 40:
|
| 291 |
history = history[-40:]
|
| 292 |
if history[0]["role"] == "model":
|
|
|
|
| 357 |
await send_with_keyboard(client, chat_id, "❌ خطایی در ارسال پیام رخ داد.", False)
|
| 358 |
|
| 359 |
|
| 360 |
+
# --- ۲. پردازش ساخت عکس (ارتقا یافته با پرامپتنویس هوشمند) ---
|
| 361 |
async def process_image(client, chat_id, prompt):
|
| 362 |
if not HF_TOKENS:
|
| 363 |
await send_with_keyboard(client, chat_id, "❌ توکنهای هاگینگ فیس تنظیم نشدهاند.", False)
|
| 364 |
return
|
| 365 |
|
| 366 |
+
proc_msg = await send_with_keyboard(client, chat_id, "✨ در حال ترجمه و بهینهسازی پرامپت شما توسط جیمینای...\n(تبدیل به پرامپت حرفهای)", False)
|
| 367 |
|
| 368 |
+
# مرحله اول: ارسال پرامپت به جیمینای برای ترجمه و بهینهسازی
|
| 369 |
+
enhanced_prompt = prompt # مقدار پیشفرض اگر جیمینای خطا داد
|
| 370 |
+
if GEMINI_KEYS:
|
| 371 |
+
keys_to_try_gemini = GEMINI_KEYS.copy()
|
| 372 |
+
random.shuffle(keys_to_try_gemini)
|
| 373 |
+
|
| 374 |
+
# پرامپت سیستم برای جیمینای
|
| 375 |
+
gemini_sys_prompt = (
|
| 376 |
+
"You are an expert AI image generation prompt engineer. "
|
| 377 |
+
"Translate the following user input to English, and enhance it with high-quality, "
|
| 378 |
+
"highly detailed, 4k resolution, cinematic lighting, and visually striking descriptive keywords "
|
| 379 |
+
"suitable for Midjourney or Stable Diffusion. "
|
| 380 |
+
"Return ONLY the final English prompt string, with absolutely no extra text or explanations. "
|
| 381 |
+
f"User input: {prompt}"
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
async with aiohttp.ClientSession() as session:
|
| 385 |
+
for key in keys_to_try_gemini:
|
| 386 |
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key}"
|
| 387 |
+
payload = {"contents": [{"parts":[{"text": gemini_sys_prompt}]}], "generationConfig": {"temperature": 0.7}}
|
| 388 |
+
try:
|
| 389 |
+
async with session.post(url, json=payload, timeout=20) as response:
|
| 390 |
+
if response.status == 200:
|
| 391 |
+
data = await response.json()
|
| 392 |
+
enhanced_prompt = data["candidates"][0]["content"]["parts"][0]["text"].strip()
|
| 393 |
+
break
|
| 394 |
+
except Exception:
|
| 395 |
+
continue
|
| 396 |
+
|
| 397 |
+
# پاک کردن پیام قبلی و اطلاع به کاربر درباره شروع طراحی
|
| 398 |
+
try:
|
| 399 |
+
if proc_msg:
|
| 400 |
+
msg_id = getattr(proc_msg, 'message_id', None)
|
| 401 |
+
if isinstance(proc_msg, dict):
|
| 402 |
+
msg_id = proc_msg.get('message_update', {}).get('message_id') or proc_msg.get('message_id')
|
| 403 |
+
if msg_id:
|
| 404 |
+
await client.delete_messages(chat_id,[msg_id])
|
| 405 |
+
except Exception: pass
|
| 406 |
+
|
| 407 |
+
short_preview = enhanced_prompt[:150] + "..." if len(enhanced_prompt) > 150 else enhanced_prompt
|
| 408 |
+
proc_msg = await send_with_keyboard(client, chat_id, f"🎨 در حال طراحی عکس...\n\n📝 پرامپت حرفهای ساخته شده:\n`{short_preview}`\n\n(ممکن است چند ثانیه زمان ببرد)", False)
|
| 409 |
+
|
| 410 |
+
# مرحله دوم: ساخت عکس با پرامپت بهینهشده
|
| 411 |
keys_to_try = HF_TOKENS.copy()
|
| 412 |
random.shuffle(keys_to_try)
|
| 413 |
generated_image = None
|
|
|
|
| 416 |
for token in keys_to_try:
|
| 417 |
try:
|
| 418 |
hf_client = AsyncInferenceClient(provider="fal-ai", api_key=token)
|
| 419 |
+
# اینجا پرامپت بهینهشده ارسال میشود
|
| 420 |
+
generated_image = await hf_client.text_to_image(enhanced_prompt, model="Tongyi-MAI/Z-Image-Turbo")
|
| 421 |
break
|
| 422 |
except Exception as e:
|
| 423 |
last_error_log = str(e)
|
|
|
|
| 442 |
rgb_im.save(file_name, format="JPEG", quality=100)
|
| 443 |
|
| 444 |
await asyncio.sleep(1)
|
| 445 |
+
caption_text = f"🎨 تصویر شما با پرامپت هوشمند آماده شد!\n\n✨ ایده اولیه شما: {prompt}\n(مدل: Z-Image-Turbo)"
|
| 446 |
|
| 447 |
upload_result = await helper_upload_file(client, chat_id, file_name, "Image", caption_text)
|
| 448 |
|
|
|
|
| 677 |
|
| 678 |
if user_text_str in["/image", "🎨 عکس", "ساخت تصاویر با هوش مصنوعی🎨"]:
|
| 679 |
user_states[chat_id] = {"mode": "image_waiting_for_text", "text": "", "history":[]}
|
| 680 |
+
await send_with_keyboard(client, chat_id, "🎨 شما وارد بخش **ساخت عکس پیشرفته** شدید.\n\n💡 نکته: کافیست تصویر مورد نظرتان را به سادگی توصیف کنید، من خودم آن را به یک پرامپت انگلیسی و حرفهای تبدیل میکنم و میسازم!\n\nمتن خود را ارسال کنید:\n\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
|
| 681 |
return
|
| 682 |
|
| 683 |
if user_text_str in["/tts", "🎙️ صدا", "تبدیل متن به صدا با هوش مصنوعی🎙️"]:
|
|
|
|
| 702 |
elif user_text_str: await send_with_keyboard(client, chat_id, "⚠️ لطفاً ابتدا از کیبورد پایین، بخش مورد نظرتان را انتخاب کنید:", True)
|
| 703 |
return
|
| 704 |
|
| 705 |
+
# --- مسیریابی ---
|
| 706 |
elif current_mode == "chat":
|
| 707 |
if is_file:
|
| 708 |
await send_with_keyboard(client, chat_id, "📥 در حال دانلود فایل برای چت هوشمند...", False)
|
| 709 |
try:
|
| 710 |
file_bytes = await helper_download_file(client, msg_obj)
|
|
|
|
| 711 |
asyncio.create_task(process_gemini(client, chat_id, user_text_str, file_bytes=file_bytes, file_name=file_name))
|
| 712 |
except Exception as dl_err:
|
| 713 |
err_trace = traceback.format_exc()
|
|
|
|
| 770 |
await send_with_keyboard(client, chat_id, f"❌ خطا در دانلود فایل!\n\n🔴 لاگ برنامهنویس:\n`{err_trace[-300:]}`\n{str(dl_err)}", False)
|
| 771 |
return
|
| 772 |
|
|
|
|
| 773 |
elif current_mode == "file_waiting_for_file":
|
| 774 |
if not is_file:
|
| 775 |
await send_with_keyboard(client, chat_id, "⚠️ لطفاً ابتدا یک فایل (تصویر، ویدیو، PDF و...) ارسال کنید.", False)
|