Spaces:
Runtime error

File size: 14,111 Bytes
424bd17
 
 
a5394d2
 
 
 
424bd17
a5394d2
 
 
424bd17
a5394d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424bd17
a5394d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b276f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5394d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424bd17
a5394d2
 
 
 
 
 
 
424bd17
a5394d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424bd17
a5394d2
 
 
 
 
 
424bd17
a5394d2
424bd17
a5394d2
 
424bd17
 
a5394d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424bd17
 
a5394d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424bd17
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import gradio as gr
import requests
import json
import logging
from datetime import datetime
import plotly.graph_objects as go
import plotly.express as px

# إعداد التسجيل
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# وظيفة تسجيل الدخول
def login(username, password):
    try:
        response = requests.post("http://localhost:8000/login", data={
            "username": username,
            "password": password
        })
        if response.status_code == 200:
            token = response.json()["access_token"]
            role = response.json().get("role", "viewer")
            return f"تم تسجيل الدخول بنجاح! الدور: {role}", token
        else:
            return "خطأ في تسجيل الدخول", None
    except Exception as e:
        logger.error(f"Login error: {str(e)}")
        return f"خطأ في الاتصال: {str(e)}", None

# وظيفة حفظ المحادثة
def save_conversation(token, input_type, input_content, output_content, risk_level, confidence):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post("http://localhost:8000/save_conversation", json={
        "input_type": input_type,
        "input_content": input_content,
        "output_content": output_content,
        "risk_level": risk_level,
        "confidence_score": float(confidence) if confidence else None
    }, headers=headers)
    return response.json()

# وظيفة رفع ملف PDF
def upload_pdf(file, token):
    headers = {"Authorization": f"Bearer {token}"}
    files = {"file": (file.name, open(file.name, "rb"), "application/pdf")}
    response = requests.post("http://localhost:8000/upload_pdf", files=files, headers=headers)
    return response.json()

# وظيفة رفع ملف Excel
def upload_excel(file, token):
    headers = {"Authorization": f"Bearer {token}"}
    files = {"file": (file.name, open(file.name, "rb"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}
    response = requests.post("http://localhost:8000/upload_excel", files=files, headers=headers)
    return response.json()

# وظيفة رفع ملف صوت
def upload_audio(file, token):
    headers = {"Authorization": f"Bearer {token}"}
    files = {"file": (file.name, open(file.name, "rb"), "audio/mpeg")}
    response = requests.post("http://localhost:8000/upload_audio", files=files, headers=headers)
    return response.json()

# وظيفة إضافة تقييم
def add_feedback(token, conversation_id, actual_result, user_feedback, rating):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post("http://localhost:8000/add_feedback", json={
        "conversation_id": int(conversation_id),
        "actual_result": actual_result,
        "user_feedback": user_feedback,
        "rating": int(rating) if rating else None
    }, headers=headers)
    return response.json()

# وظيفة إنشاء حساب جديد
def register_user(username, password, email, role, first_name, last_name):
    try:
        response = requests.post("http://localhost:8000/register", json={
            "username": username,
            "password": password,
            "email": email,
            "role": role,
            "first_name": first_name,
            "last_name": last_name
        })
        return response.json()
    except Exception as e:
        return {"error": str(e)}

# وظيفة إنشاء نسخة احتياطية
def create_backup(token):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post("http://localhost:8000/create_backup", headers=headers)
    return response.json()

# وظيفة تحديث النظام
def update_system(token):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post("http://localhost:8000/update_system", headers=headers)
    return response.json()

# وظيفة الحصول على إحصائيات النظام
def get_system_stats():
    response = requests.get("http://localhost:8000/system_stats")
    return response.json()

# وظيفة البحث في المحادثات
def search_conversations(query, token):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"http://localhost:8000/search/conversations?query={query}", headers=headers)
    return response.json()

# وظيفة الحصول على محادثات المستخدم
def get_user_conversations(token):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get("http://localhost:8000/user/conversations", headers=headers)
    return response.json()

# وظيفة إنشاء تحليل تفاعلي
def create_interactive_analysis(text_content, analysis_type):
    # تحليل تفاعلي محسن
    return {
        "text": text_content[:100] + "...",
        "type": analysis_type,
        "risk_level": "Medium Risk",
        "confidence": 0.75,
        "key_findings": ["تحليل محتوى", "تحليل مخاطر", "تحليل اقتراحات"],
        "timestamp": datetime.now().isoformat()
    }

# إنشاء رسم بياني للمخاطر
def create_risk_chart():
    fig = go.Figure(data=[go.Bar(
        x=['Low', 'Medium', 'High'],
        y=[30, 50, 20],
        marker_color=['green', 'orange', 'red']
    )])
    fig.update_layout(title="توزيع المخاطر")
    return fig

# إنشاء رسم بياني للمشاعر
def create_sentiment_chart():
    fig = px.pie(values=[40, 35, 25], names=['Positive', 'Neutral', 'Negative'])
    fig.update_layout(title="تحليل المشاعر")
    return fig

# واجهة Gradio المحسنة
with gr.Blocks(
    title="MyAIProject_v2 - النظام المحسن",
    theme=gr.themes.Soft(),
    css="""
    .gradio-container { 
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
    }
    .header {
        text-align: center;
        color: white;
        padding: 20px;
    }
    .tab-nav {
        background-color: rgba(255,255,255,0.1);
        border-radius: 10px;
    }
    .btn-primary {
        background: linear-gradient(45deg, #ff6b6b, #ee5a24);
        border: none;
        border-radius: 25px;
        padding: 10px 20px;
        font-weight: bold;
    }
    """
) as demo:
    
    gr.Markdown("""
    # 🧠 MyAIProject_v2 - النظام المحسن
    ## نظام تحليلي متقدم للبيانات المختلفة
    **نظام متكامل لتحليل البيانات الأمنية والاجتماعية**
    """)
    
    with gr.Tab("🔐 تسجيل الدخول"):
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("## 📝 تسجيل الدخول")
                username_login = gr.Textbox(label="اسم المستخدم", placeholder="أدخل اسم المستخدم")
                password_login = gr.Textbox(label="كلمة المرور", type="password", placeholder="أدخل كلمة المرور")
                login_btn = gr.Button("تسجيل الدخول", variant="primary")
                login_output = gr.Textbox(label="رسالة التسجيل", interactive=False)
                token_output = gr.Textbox(label="Token", visible=False, interactive=False)
            
            with gr.Column(scale=1):
                gr.Markdown("## 📝 التسجيل")
                username_reg = gr.Textbox(label="اسم المستخدم", placeholder="أدخل اسم المستخدم")
                password_reg = gr.Textbox(label="كلمة المرور", type="password", placeholder="أدخل كلمة المرور")
                email_reg = gr.Textbox(label="البريد الإلكتروني", placeholder="أدخل البريد الإلكتروني")
                first_name_reg = gr.Textbox(label="الاسم الأول", placeholder="أدخل الاسم الأول")
                last_name_reg = gr.Textbox(label="الاسم الأخير", placeholder="أدخل الاسم الأخير")
                role_reg = gr.Dropdown(["admin", "analyst", "viewer"], value="viewer", label="الدور")
                register_btn = gr.Button("تسجيل", variant="primary")
                register_output = gr.Textbox(label="رسالة التسجيل", interactive=False)
    
    with gr.Tab("💬 التحليل"):
        with gr.Row():
            with gr.Column(scale=2):
                gr.Markdown("## 📝 تحليل البيانات")
                input_type = gr.Dropdown(["text", "image", "audio", "video"], value="text", label="نوع المدخل")
                input_content = gr.Textbox(label="المحتوى", lines=6, placeholder="أدخل النص أو الصور أو الصوت...")
                output_content = gr.Textbox(label="النتيجة", lines=4, interactive=False)
                risk_level = gr.Dropdown(["Low", "Medium", "High"], value="Medium", label="مستوى المخاطر")
                confidence = gr.Slider(0, 1, value=0.8, label="درجة الثقة")
                save_btn = gr.Button("حفظ المحادثة", variant="primary")
                save_output = gr.Textbox(label="النتيجة", interactive=False)
            
            with gr.Column(scale=1):
                gr.Markdown("## 📊 التحليل التفاعلي")
                analysis_type = gr.Dropdown(["sentiment", "risk", "topic"], value="risk", label="نوع التحليل")
                analyze_btn = gr.Button("تحليل تفاعلي", variant="secondary")
                interactive_result = gr.JSON(label="النتائج التفاعلية")
    
    with gr.Tab("📁 رفع الملفات"):
        with gr.Tabs():
            with gr.Tab("📄 PDF"):
                with gr.Row():
                    pdf_file = gr.File(label="اختر ملف PDF")
                    upload_pdf_btn = gr.Button("رفع PDF", variant="primary")
                pdf_output = gr.Textbox(label="نتيجة الرفع", interactive=False)
            
            with gr.Tab("📊 Excel"):
                with gr.Row():
                    excel_file = gr.File(label="اختر ملف Excel")
                    upload_excel_btn = gr.Button("رفع Excel", variant="primary")
                excel_output = gr.Textbox(label="نتيجة الرفع", interactive=False)
            
            with gr.Tab("🎵 صوت"):
                with gr.Row():
                    audio_file = gr.File(label="اختر ملف صوت")
                    upload_audio_btn = gr.Button("رفع صوت", variant="primary")
                audio_output = gr.Textbox(label="نتيجة الرفع", interactive=False)
    
    with gr.Tab("📊 التقييم"):
        with gr.Row():
            conversation_id = gr.Number(label="معرف المحادثة")
            actual_result = gr.Textbox(label="النتيجة الحقيقية")
            user_feedback = gr.Textbox(label="التقييم", lines=3)
            rating = gr.Slider(1, 5, value=3, label="التقييم (1-5)")
            feedback_btn = gr.Button("إضافة تقييم", variant="primary")
        feedback_output = gr.Textbox(label="النتيجة", interactive=False)
    
    with gr.Tab("📈 الإحصائيات"):
        with gr.Row():
            stats_btn = gr.Button("عرض الإحصائيات", variant="primary")
            stats_output = gr.JSON(label="الإحصائيات")
        
        with gr.Row():
            gr.Markdown("## 📈 تحليل المخاطر")
            risk_chart = gr.Plot(label="توزيع المخاطر")
    
    with gr.Tab("⚙️ الإدارة"):
        with gr.Row():
            backup_btn = gr.Button("إنشاء نسخة احتياطية", variant="secondary")
            update_btn = gr.Button("تحديث النظام", variant="secondary")
        with gr.Row():
            backup_output = gr.Textbox(label="نتيجة النسخ الاحتياطي", interactive=False)
            update_output = gr.Textbox(label="نتيجة التحديث", interactive=False)
    
    with gr.Tab("🔍 البحث"):
        with gr.Row():
            search_query = gr.Textbox(label="كلمة البحث")
            search_btn = gr.Button("بحث", variant="primary")
        search_output = gr.JSON(label="نتائج البحث")
    
    with gr.Tab("👤 المستخدمين"):
        with gr.Row():
            user_stats_btn = gr.Button("إحصائيات المستخدمين", variant="secondary")
            user_conversations_btn = gr.Button("محادثات المستخدم", variant="secondary")
        user_stats_output = gr.JSON(label="إحصائيات المستخدمين")
        user_conversations_output = gr.JSON(label="محادثات المستخدم")
    
    # ربط الأحداث
    login_btn.click(login, inputs=[username_login, password_login], outputs=[login_output, token_output])
    register_btn.click(register_user, inputs=[username_reg, password_reg, email_reg, role_reg, first_name_reg, last_name_reg], outputs=register_output)
    
    save_btn.click(save_conversation, inputs=[token_output, input_type, input_content, output_content, risk_level, confidence], outputs=save_output)
    
    upload_pdf_btn.click(upload_pdf, inputs=[pdf_file, token_output], outputs=pdf_output)
    upload_excel_btn.click(upload_excel, inputs=[excel_file, token_output], outputs=excel_output)
    upload_audio_btn.click(upload_audio, inputs=[audio_file, token_output], outputs=audio_output)
    
    feedback_btn.click(add_feedback, inputs=[token_output, conversation_id, actual_result, user_feedback, rating], outputs=feedback_output)
    
    stats_btn.click(get_system_stats, outputs=stats_output)
    
    backup_btn.click(create_backup, inputs=[token_output], outputs=backup_output)
    update_btn.click(update_system, inputs=[token_output], outputs=update_output)
    
    search_btn.click(search_conversations, inputs=[search_query, token_output], outputs=search_output)
    
    analyze_btn.click(create_interactive_analysis, inputs=[input_content, analysis_type], outputs=interactive_result)

demo.launch()