File size: 3,636 Bytes
18a35d1
 
 
 
 
 
1b36612
18a35d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
032367f
 
b6424a6
 
 
 
 
 
 
 
 
 
 
 
 
 
18a35d1
032367f
18a35d1
032367f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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")