import gradio as gr import httpx import json import base64 # آدرس سرور رانفلر شما URL = "https://appalpha.ir/api/chat_proxy" def convert_to_b64(path): """تبدیل تصویر به فرمت Base64 خام بدون هدر آغازین""" if not path: return None try: with open(path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8') except Exception as e: print(f"Error encoding image: {e}") return None def respond(message, history): """دریافت ورودی مالتی‌مودال از گرادیو و ارسال به API رانفلر""" text_content = message.get("text", "") files = message.get("files", []) # بررسی وجود تصویر در پیام image_path = None if files: image_path = files[0]["path"] if isinstance(files[0], dict) else files[0] img_b64 = convert_to_b64(image_path) if image_path else None # ساخت لود درخواستی دقیقا مطابق مستندات شما payload = { "type": "text", "content": text_content, "model": "gpt5", "text_history": "", "image_base64": img_b64, "session_id": "hf_space_test_session" } headers = {"Content-Type": "application/json"} full_text = "" try: # برقراری ارتباط استریم با سرور رانفلر with httpx.stream("POST", URL, json=payload, headers=headers, timeout=120.0) as r: if r.status_code != 200: yield f"❌ خطای سرور رانفلر: کد وضعیت {r.status_code}\nاحتمالاً سرور مقصد درخواست‌های خارج از کشور را مسدود کرده است." return for line in r.iter_lines(): if line.strip(): try: data = json.loads(line) if data.get("status") == "streaming" and "text" in data: full_text += data["text"] yield full_text except json.JSONDecodeError: pass except httpx.ConnectError: yield "❌ خطای اتصال (ConnectError): سرور Runflare از این موقعیت جغرافیایی (آمریکا/اروپا) در دسترس نیست." except httpx.TimeoutException: yield "⏳ خطای زمان پاسخ‌دهی (Timeout): سرور مقصد پاسخگو نبود." except Exception as e: yield f"❌ خطای غیرمنتظره: {e}" # در Gradio 6 پارامتر theme از ساختار Blocks حذف شده است with gr.Blocks() as demo: gr.ChatInterface( fn=respond, title="Alpha AI Test Space 🤖", description="تست اتصال متنی و تصویری به هوش مصنوعی آلفا از سرورهای خارج از کشور (Hugging Face / USA)", multimodal=True, textbox=gr.MultimodalTextbox( placeholder="پیام خود را بنویسید یا تصویر آپلود کنید...", file_types=["image"] ), examples=[ {"text": "درباره اهمیت هوش مصنوعی در زندگی روزمره توضیح بده.", "files": []}, {"text": "سه کتاب معروف در زمینه خودشناسی معرفی کن.", "files": []} ] ) # تم به متد launch منتقل شد تا هشداری نمایش داده نشود if __name__ == "__main__": demo.launch(theme="soft")