File size: 12,256 Bytes
a15c6cd
f94e52c
d4bee33
9a4de8f
a15c6cd
bb7fdff
9a4de8f
d4bee33
bb7fdff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a4de8f
bb7fdff
 
 
 
 
9a4de8f
bb7fdff
 
 
 
9a4de8f
bb7fdff
 
 
 
cbe507b
bb7fdff
 
 
 
 
9a4de8f
0521615
 
bb7fdff
9a4de8f
bb7fdff
 
 
 
9a4de8f
bb7fdff
 
9a4de8f
 
bb7fdff
9a4de8f
 
bb7fdff
0521615
bb7fdff
9a4de8f
bb7fdff
 
9a4de8f
 
 
 
 
 
bb7fdff
 
9a4de8f
bb7fdff
0521615
bb7fdff
cbe507b
bb7fdff
 
 
 
cbe507b
bb7fdff
cbe507b
bb7fdff
 
 
 
cbe507b
bb7fdff
 
 
 
 
 
 
cbe507b
bb7fdff
 
 
 
cbe507b
bb7fdff
 
 
 
 
cbe507b
bb7fdff
 
 
 
 
9a4de8f
 
d4bee33
9a4de8f
c7bc6f3
d4bee33
f94e52c
 
 
 
 
d4bee33
9a4de8f
 
0521615
9a4de8f
 
 
 
d4bee33
c7bc6f3
d4bee33
cbe507b
0521615
 
 
 
 
 
 
 
 
 
 
 
9a4de8f
 
bb7fdff
 
9a4de8f
bb7fdff
9a4de8f
 
 
 
0521615
 
9a4de8f
 
 
 
0521615
 
 
 
 
 
 
 
 
9a4de8f
 
 
 
 
0521615
 
 
 
 
 
 
 
 
 
 
bb7fdff
0521615
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb7fdff
0521615
bb7fdff
0521615
bb7fdff
9a4de8f
 
bb7fdff
9a4de8f
 
c7bc6f3
f94e52c
 
c7bc6f3
 
9a4de8f
f94e52c
 
 
 
9a4de8f
 
 
 
 
 
 
cbe507b
9a4de8f
 
 
0521615
 
9a4de8f
 
 
0521615
 
 
 
 
 
 
 
9a4de8f
f94e52c
 
 
 
 
0521615
 
 
cfcd21e
cbe507b
0521615
 
 
 
 
 
 
 
 
 
 
 
 
 
cbe507b
0521615
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a4de8f
0521615
 
9a4de8f
 
13f4a27
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import streamlit as st
from openai import OpenAI
import time
import json

# إعداد الصفحة
st.set_page_config(page_title="Genisi - Chatbot", page_icon="🤖", layout="wide")

# اختيار الوضع (فاتح/داكن) من الشريط الجانبي
with st.sidebar:
    theme = st.radio("🎨 الوضع", ["فاتح", "داكن"], index=0)

# تطبيق الأنماط حسب الوضع المختار
if theme == "فاتح":
    bg_color = "#FFFFFF"  # أبيض كامل للخلفية
    text_color = "#000000"  # أسود كامل للنصوص
    border_color = "#E0E0E0"  # رمادي فاتح جداً للحدود فقط
    secondary_bg = "#FFFFFF"  # نفس الأبيض
else:  # داكن
    bg_color = "#000000"  # أسود كامل للخلفية
    text_color = "#FFFFFF"  # أبيض كامل للنصوص
    border_color = "#333333"  # رمادي غامق جداً للحدود فقط
    secondary_bg = "#000000"  # نفس الأسود

# CSS بسيط جداً - لون واحد فقط
st.markdown(f"""
<style>
    /* تنسيق عام - لون واحد فقط */
    .stApp, section[data-testid="stSidebar"], .stMarkdown, 
    div[data-testid="stVerticalBlock"], div[data-testid="stChatMessage"] {{
        background-color: {bg_color} !important;
    }}
    
    /* جميع النصوص بلون واحد */
    p, h1, h2, h3, h4, h5, h6, label, span, div, .stChatMessage {{
        color: {text_color} !important;
    }}
    
    /* حدود بسيطة جداً للعناصر */
    section[data-testid="stSidebar"] {{
        border-left: 1px solid {border_color};
    }}
    
    /* الأزرار - بدون خلفية مميزة */
    .stButton button {{
        background-color: {bg_color};
        color: {text_color};
        border: 1px solid {border_color};
        border-radius: 5px;
        width: 100%;
        text-align: right;
    }}
    
    .stButton button:hover {{
        background-color: {bg_color};
        border-color: {text_color};
    }}
    
    /* عنوان الشات */
    .chat-title {{
        font-size: 24px;
        font-weight: 600;
        color: {text_color};
        margin-bottom: 20px;
        padding: 10px 20px;
        border-bottom: 1px solid {border_color};
        text-align: center;
    }}
    
    /* معلومات المطور */
    .developer-info {{
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        text-align: center;
        padding: 10px;
        background-color: {bg_color};
        color: {text_color};
        font-size: 12px;
        border-top: 1px solid {border_color};
        z-index: 999;
    }}
    
    /* مربع الإدخال */
    .stChatInputContainer {{
        background-color: {bg_color};
        border: 1px solid {border_color};
        border-radius: 5px;
    }}
    
    .stChatInputContainer input {{
        background-color: {bg_color};
        color: {text_color};
    }}
    
    /* إزالة أي ألوان مميزة من الأفاتار */
    div[data-testid="chatAvatarIcon-user"],
    div[data-testid="chatAvatarIcon-assistant"] {{
        background-color: {border_color} !important;
        color: {text_color} !important;
        border: 1px solid {border_color};
    }}
    
    /* خط فاصل بسيط */
    hr {{
        border-color: {border_color} !important;
    }}
    
    /* رسائل الشات - بدون تمييز */
    div[data-testid="stChatMessage"] {{
        border: none;
        border-bottom: 1px solid {border_color};
    }}
    
    /* إزالة أي ألوان من الروابط */
    a {{
        color: {text_color} !important;
        text-decoration: underline;
    }}
</style>
""", unsafe_allow_html=True)

# مفتاح API
API_KEY = "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"

# تهيئة العميل
client = OpenAI(
    base_url="https://integrate.api.nvidia.com/v1",
    api_key=API_KEY
)

# تهيئة حالة المحادثات
if "conversations" not in st.session_state:
    st.session_state.conversations = []

if "current_chat_id" not in st.session_state:
    st.session_state.current_chat_id = None

if "messages" not in st.session_state:
    st.session_state.messages = []

# محاولة تحميل المحادثات من localStorage
st.components.v1.html("""
<script>
const conversations = localStorage.getItem('genisi_conversations');
if (conversations) {
    window.parent.postMessage({
        type: 'streamlit:setComponentValue',
        value: conversations
    }, '*');
}
</script>
""", height=0)

# الشريط الجانبي - قائمة المحادثات
with st.sidebar:
    st.markdown(f'<p style="color: {text_color}; font-size: 20px; font-weight: bold; text-align: center; padding: 20px 20px 5px;">🤖 Genisi</p>', unsafe_allow_html=True)
    st.markdown(f'<p style="color: {text_color}; text-align: center; margin-top: -5px;">by AnesNT</p>', unsafe_allow_html=True)
    
    # زر محادثة جديدة
    if st.button("➕ محادثة جديدة", use_container_width=True):
        new_chat = {
            "id": str(time.time()),
            "title": f"محادثة جديدة {len(st.session_state.conversations) + 1}",
            "messages": [],
            "created_at": time.strftime("%Y-%m-%d %H:%M")
        }
        st.session_state.conversations.append(new_chat)
        st.session_state.current_chat_id = new_chat["id"]
        st.session_state.messages = []
        
        st.components.v1.html(f"""
        <script>
        let conversations = JSON.parse(localStorage.getItem('genisi_conversations') || '[]');
        conversations.push({json.dumps(new_chat)});
        localStorage.setItem('genisi_conversations', JSON.stringify(conversations));
        </script>
        """, height=0)
        
        st.rerun()
    
    st.markdown("---")
    
    # عرض قائمة المحادثات
    if st.session_state.conversations:
        for conv in reversed(st.session_state.conversations):
            # تحديد عنوان المحادثة
            title = conv["title"]
            if conv["messages"] and len(conv["messages"]) > 0:
                first_msg = conv["messages"][0]["content"][:30]
                title = first_msg + "..." if len(first_msg) >= 30 else first_msg
            
            # تاريخ المحادثة
            created_at = conv.get("created_at", "")
            
            # تنسيق المحادثة
            col1, col2, col3 = st.columns([5, 1, 1])
            
            with col1:
                if st.button(f"💬 {title}", key=f"chat_{conv['id']}", use_container_width=True):
                    st.session_state.current_chat_id = conv["id"]
                    st.session_state.messages = conv["messages"]
                    st.rerun()
            
            with col2:
                if st.button("📋", key=f"copy_{conv['id']}", help="نسخ المحادثة"):
                    chat_text = "\n".join([f"{m['role']}: {m['content']}" for m in conv["messages"]])
                    st.components.v1.html(f"""
                    <script>
                    navigator.clipboard.writeText({json.dumps(chat_text)});
                    alert('تم نسخ المحادثة!');
                    </script>
                    """, height=0)
            
            with col3:
                if st.button("🗑️", key=f"delete_{conv['id']}", help="حذف المحادثة"):
                    st.session_state.conversations = [c for c in st.session_state.conversations if c["id"] != conv["id"]]
                    
                    st.components.v1.html(f"""
                    <script>
                    let conversations = JSON.parse(localStorage.getItem('genisi_conversations') || '[]');
                    conversations = conversations.filter(c => c.id !== '{conv['id']}');
                    localStorage.setItem('genisi_conversations', JSON.stringify(conversations));
                    </script>
                    """, height=0)
                    
                    if conv["id"] == st.session_state.current_chat_id:
                        st.session_state.current_chat_id = None
                        st.session_state.messages = []
                    
                    st.rerun()
            
            # عرض تاريخ المحادثة
            if created_at:
                st.markdown(f'<p style="color: {text_color}; font-size: 11px; margin: -5px 0 10px 25px;">{created_at}</p>', unsafe_allow_html=True)
    else:
        st.markdown(f'<p style="color: {text_color}; text-align: center; padding: 20px;">لا توجد محادثات سابقة</p>', unsafe_allow_html=True)

# المحتوى الرئيسي
st.markdown(f'<div class="chat-title">🤖 Genisi - AI Assistant by AnesNT</div>', unsafe_allow_html=True)

# عرض المحادثة الحالية
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])

# مربع الإدخال
if prompt := st.chat_input("اكتب سؤالك هنا..."):
    # عرض سؤال المستخدم
    st.chat_message("user").markdown(prompt)
    st.session_state.messages.append({"role": "user", "content": prompt})
    
    # تحديث المحادثة الحالية
    if st.session_state.current_chat_id:
        for conv in st.session_state.conversations:
            if conv["id"] == st.session_state.current_chat_id:
                conv["messages"] = st.session_state.messages
                break
    else:
        # إنشاء محادثة جديدة
        new_chat = {
            "id": str(time.time()),
            "title": prompt[:30] + "..." if len(prompt) > 30 else prompt,
            "messages": st.session_state.messages,
            "created_at": time.strftime("%Y-%m-%d %H:%M")
        }
        st.session_state.conversations.append(new_chat)
        st.session_state.current_chat_id = new_chat["id"]
        
        st.components.v1.html(f"""
        <script>
        let conversations = JSON.parse(localStorage.getItem('genisi_conversations') || '[]');
        conversations.push({json.dumps(new_chat)});
        localStorage.setItem('genisi_conversations', JSON.stringify(conversations));
        </script>
        """, height=0)
    
    # رد المساعد
    with st.chat_message("assistant"):
        msg_placeholder = st.empty()
        full = ""
        
        try:
            # استدعاء API
            completion = client.chat.completions.create(
                model="moonshotai/kimi-k2-instruct",
                messages=st.session_state.messages,
                temperature=0.5,
                stream=True
            )
            
            # تجميع الرد
            for chunk in completion:
                if chunk.choices and chunk.choices[0].delta.content:
                    full += chunk.choices[0].delta.content
                    msg_placeholder.markdown(full + "▌")
                    time.sleep(0.01)
            
            msg_placeholder.markdown(full)
            st.session_state.messages.append({"role": "assistant", "content": full})
            
            # تحديث المحادثة الحالية
            for conv in st.session_state.conversations:
                if conv["id"] == st.session_state.current_chat_id:
                    conv["messages"] = st.session_state.messages
                    
                    st.components.v1.html(f"""
                    <script>
                    let conversations = JSON.parse(localStorage.getItem('genisi_conversations') || '[]');
                    const index = conversations.findIndex(c => c.id === '{conv["id"]}');
                    if (index !== -1) {{
                        conversations[index] = {json.dumps(conv)};
                        localStorage.setItem('genisi_conversations', JSON.stringify(conversations));
                    }}
                    </script>
                    """, height=0)
                    break
        
        except Exception as e:
            st.error(f"حدث خطأ: {str(e)}")

# معلومات المطور
st.markdown(f'<div class="developer-info"> Genisi is an AI can make mistakes </div>', unsafe_allow_html=True)