File size: 5,632 Bytes
c269649
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import gradio as gr
from transformers import pipeline, set_seed
import torch  # لتحسين الأداء على GPU إذا متوفر

set_seed(42)

# 1️⃣ تهيئة النماذج مع معالجة الأخطاء
try:
    # نموذج الدردشة العربي (أخف وأسرع)
    chat_model = pipeline("text-generation", 
                         model="akhooli/distilgpt2-arabic",
                         device="cuda" if torch.cuda.is_available() else "cpu")

    # 2️⃣ نماذج الترجمة
    translator_en_ar = pipeline("translation_en_to_ar", model="Helsinki-NLP/opus-mt-en-ar")
    translator_ar_en = pipeline("translation_ar_to_en", model="Helsinki-NLP/opus-mt-ar-en")

    # 3️⃣ نموذج التلخيص
    summarizer = pipeline("summarization", model="facebook/bart-large-cnn")

    # 4️⃣ نموذج سؤال وجواب (QA) العربي
    qa_model = pipeline("question-answering", 
                       model="deepset/arabert-base-cased-qa",
                       device="cuda" if torch.cuda.is_available() else "cpu")

except Exception as e:
    raise gr.Error(f"خطأ في تحميل النماذج: {e}")

# ========== الدوال الأساسية ========== #
def chat(history, user_message):
    """وظيفة الدردشة مع الذكاء الاصطناعي"""
    try:
        if not user_message.strip():
            return history, "⚠️ الرجاء كتابة رسالة صحيحة!"

        # بناء تاريخ المحادثة
        prompt = "\n".join([f"👤: {user}\n🤖: {bot}" for user, bot in history])
        prompt += f"\n👤: {user_message}\n🤖:"

        # توليد الرد
        response = chat_model(
            prompt,
            max_length=150,
            num_return_sequences=1,
            do_sample=True,
            temperature=0.7,
            top_p=0.9
        )
        
        bot_reply = response[0]["generated_text"].split("🤖:")[-1].strip()
        history.append((user_message, bot_reply))
        return history, ""

    except Exception as e:
        error_msg = f"❌ حدث خطأ: {str(e)}"
        return history, error_msg

def translate_en_to_ar(text):
    """الترجمة: الإنجليزية → العربية"""
    try:
        return translator_en_ar(text)[0]['translation_text']
    except:
        return "⚠️ فشل في الترجمة!"

def translate_ar_to_en(text):
    """الترجمة: العربية → الإنجليزية"""
    try:
        return translator_ar_en(text)[0]['translation_text']
    except:
        return "⚠️ فشل في الترجمة!"

def summarize_text(text):
    """تلخيص النصوص الطويلة"""
    try:
        summary = summarizer(text, max_length=150, min_length=30)
        return summary[0]['summary_text']
    except:
        return "⚠️ لا يمكن تلخيص هذا النص!"

def ask_question(context, question):
    """الإجابة على الأسئلة من نص معين"""
    try:
        if not context.strip() or not question.strip():
            return "⚠️ الرجاء إدخال النص والسؤال!"
        
        answer = qa_model(question=question, context=context)
        return answer["answer"]
    except Exception as e:
        return f"⚠️ خطأ: {str(e)}"

# ========== واجهة Gradio ========== #
with gr.Blocks(theme=gr.themes.Soft(), title="المساعد العربي") as app:
    gr.Markdown("<h1 style='text-align: center;'>🤖 المساعد الذكي متعدد المهام</h1>")

    with gr.Tab("💬 دردشة عربية"):
        chatbot = gr.Chatbot(height=350)
        user_input = gr.Textbox(placeholder="اكتب رسالتك هنا...", label="المستخدم")
        send_btn = gr.Button("إرسال")
        clear_btn = gr.Button("مسح التاريخ")
        
        send_btn.click(chat, [chatbot, user_input], [chatbot, user_input])
        user_input.submit(chat, [chatbot, user_input], [chatbot, user_input])
        clear_btn.click(lambda: ([], ""), outputs=[chatbot, user_input])

    with gr.Tab("🌍 مترجم"):
        with gr.Row():
            with gr.Column():
                en_input = gr.Textbox(label="النص الإنجليزي")
                en_to_ar_btn = gr.Button("English → العربية")
            with gr.Column():
                ar_output = gr.Textbox(label="الترجمة")
        
        with gr.Row():
            with gr.Column():
                ar_input = gr.Textbox(label="النص العربي")
                ar_to_en_btn = gr.Button("العربية → English")
            with gr.Column():
                en_output = gr.Textbox(label="الترجمة")
        
        en_to_ar_btn.click(translate_en_to_ar, en_input, ar_output)
        ar_to_en_btn.click(translate_ar_to_en, ar_input, en_output)

    with gr.Tab("📝 ملخص النصوص"):
        text_input = gr.Textbox(label="النص الأصلي", lines=5)
        summarize_btn = gr.Button("توليد الملخص")
        summary_output = gr.Textbox(label="الملخص", lines=3)
        summarize_btn.click(summarize_text, text_input, summary_output)

    with gr.Tab("❓ سؤال وجواب"):
        context_box = gr.Textbox(label="النص المرجعي", lines=4)
        question_box = gr.Textbox(label="السؤال")
        answer_btn = gr.Button("البحث عن الإجابة")
        answer_box = gr.Textbox(label="الإجابة", interactive=False)
        answer_btn.click(ask_question, [context_box, question_box], answer_box)

# التشغيل
if __name__ == "__main__":
    app.launch(debug=True, share=False)