AnesKAM commited on
Commit
30c29b5
·
verified ·
1 Parent(s): c86081e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +918 -319
main.py CHANGED
@@ -1,332 +1,931 @@
1
- import os
2
- import base64
3
- import requests
4
- from collections import defaultdict
5
- from datetime import datetime
6
- from fastapi import FastAPI
7
- from fastapi.responses import StreamingResponse
8
- from fastapi.staticfiles import StaticFiles
9
- from pydantic import BaseModel
10
- from google import genai
11
- from google.genai import types
12
-
13
- app = FastAPI()
14
-
15
- # ============================================================
16
- # إعدادات المفاتيح
17
- # ============================================================
18
- TEXT_KEYS_RAW = os.environ.get("TEXT_API_KEYS", os.environ.get("GEMINI_API_KEY", ""))
19
- TEXT_API_KEYS = [k.strip() for k in TEXT_KEYS_RAW.split(",") if k.strip()]
20
- NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")
21
-
22
- text_clients = [genai.Client(api_key=key) for key in TEXT_API_KEYS] if TEXT_API_KEYS else []
23
- CURRENT_TEXT_KEY_INDEX = 0
24
-
25
- user_image_limits = defaultdict(lambda: {"hour": datetime.now().strftime("%Y-%m-%d %H"), "count": 0})
26
-
27
- # ============================================================
28
- # النماذج
29
- # ============================================================
30
- class FileData(BaseModel):
31
- mime_type: str
32
- data: str
33
- name: str
34
-
35
- class ChatRequest(BaseModel):
36
- user_id: str
37
- message: str
38
- history: list
39
- files: list[FileData] = []
40
- model: str = "flash"
41
-
42
- # ============================================================
43
- # تعليمات النظام
44
- # ============================================================
45
- SYSTEM_INSTRUCTION = """أنت Genisi، نموذج ذكاء اصطناعي متطور من مبادرة AnesNT.
46
-
47
- **معلومات عن AnesNT:**
48
- - مبادرة تكنولوجية جزائرية من ولاية باتنة 🇩🇿
49
- - المؤسس: أنس كامش (Anes Kameche)
50
- - حالياً أنس هو العضو الوحيد في المبادرة
51
-
52
- **تعليمات مهمة:**
53
- 1. تحدث بلغة المستخدم.
54
- 2. كن مفيداً ودوداً.
55
- 3. استخدم البحث من Google عند الحاجة.
56
- 4. استخدم الإيموجي بشكل مناسب."""
57
-
58
- # ============================================================
59
- # دوال مساعدة
60
- # ============================================================
61
- def get_text_client():
62
- """الحصول على العميل الحالي مع تدوير المفاتيح عند الحاجة"""
63
- global CURRENT_TEXT_KEY_INDEX
64
- if not text_clients:
65
- raise ValueError("لم يتم العثور على مفاتيح النصوص.")
66
- return text_clients[CURRENT_TEXT_KEY_INDEX]
67
-
68
- def build_contents(history: list, message: str, files: list) -> tuple:
69
- """بناء محتوى المحادثة للـ API"""
70
- contents = []
71
- has_images = False
72
 
73
- # بناء التاريخ
74
- for entry in history:
75
- if entry.get('user') and str(entry['user']).strip():
76
- contents.append(types.Content(role="user", parts=[types.Part.from_text(text=str(entry['user']).strip())]))
77
- if entry.get('bot') and str(entry['bot']).strip():
78
- bot_txt = entry['bot']
79
- if '<div style="text-align:center;' in bot_txt:
80
- bot_txt = "[صورة تم توليدها مسبقاً]"
81
- contents.append(types.Content(role="model", parts=[types.Part.from_text(text=bot_txt.strip())]))
82
 
83
- # بناء أجزاء المستخدم
84
- user_parts = []
85
- if files:
86
- for f in files:
87
- try:
88
- file_bytes = base64.b64decode(f.data)
89
- user_parts.append(types.Part.from_bytes(data=file_bytes, mime_type=f.mime_type))
90
- if f.mime_type.startswith('image/'):
91
- has_images = True
92
- except Exception:
93
- pass
94
-
95
- msg_text = message.strip()
96
- if msg_text:
97
- user_parts.append(types.Part.from_text(text=msg_text))
98
- elif not msg_text and files:
99
- user_parts.append(types.Part.from_text(text="يرجى تحليل المرفقات."))
100
- else:
101
- user_parts.append(types.Part.from_text(text="مرحبا"))
102
-
103
- contents.append(types.Content(role="user", parts=user_parts))
104
- return contents, has_images
105
-
106
- def get_base_config(temperature: float, thinking_level: str, tools: list):
107
- """الحصول على إعدادات النموذج الأساسية"""
108
- return types.GenerateContentConfig(
109
- temperature=temperature,
110
- thinking_config=types.ThinkingConfig(thinking_level=thinking_level),
111
- tools=tools,
112
- system_instruction=[types.Part.from_text(text=SYSTEM_INSTRUCTION)]
113
- )
114
-
115
- # ============================================================
116
- # 🌟 دالة مستقلة لنموذج FLASH (سريع ومباشر)
117
- # ============================================================
118
- async def handle_flash_model(request: ChatRequest, client, contents: list, tools: list):
119
- """نموذج Flash: استجابة سريعة ومباشرة"""
120
- chosen_model = "gemma-4-31b-it"
121
- config = get_base_config(temperature=0.7, thinking_level="MINIMAL", tools=tools)
122
 
123
- stream = client.models.generate_content_stream(
124
- model=chosen_model,
125
- contents=contents,
126
- config=config
127
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
- def stream_generator():
130
- try:
131
- for chunk in stream:
132
- if chunk.text:
133
- yield chunk.text
134
- except Exception as e:
135
- yield f"\n\n⚠️ **خطأ:** `{str(e)}`"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- return StreamingResponse(stream_generator(), media_type="text/plain")
138
-
139
- # ============================================================
140
- # 🌟 دالة مستقلة لنموذج PRO (تفكير متدفق + رد نهائي)
141
- # ============================================================
142
- async def handle_pro_model(request: ChatRequest, client, contents: list, tools: list):
143
- """
144
- نموذج Pro: يستخدم خاصية التفكير في Gemma ويرسلها بشكل متدفق.
145
- يرسل التفكير أولاً، ثم كلمة ' instant' لتقسيم الواجهة، ثم الرد النهائي.
146
- """
147
- chosen_model = "gemma-4-31b-it"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- # إعدادات التفكير العالي
150
- config = types.GenerateContentConfig(
151
- temperature=1.0,
152
- thinking_config=types.ThinkingConfig(thinking_level="HIGH"),
153
- tools=tools,
154
- system_instruction=[types.Part.from_text(text=SYSTEM_INSTRUCTION)]
155
- )
156
 
157
- # بدء البث المباشر من النموذج
158
- stream = client.models.generate_content_stream(
159
- model=chosen_model,
160
- contents=contents,
161
- config=config
162
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- def stream_generator():
165
- sent_instant_marker = False
166
- try:
167
- for chunk in stream:
168
- # 1. إرسال أجزاء التفكير (Thought) فور صدورها
169
- if hasattr(chunk, 'thought') and chunk.thought:
170
- yield chunk.thought
171
-
172
- # 2. إرسال الرد النهائي (Text)
173
- if chunk.text:
174
- # قبل إرسال أول جزء من النص النهائي، نرسل كلمة الفاصل للواجهة
175
- if not sent_instant_marker:
176
- yield " instant"
177
- sent_instant_marker = True
178
- yield chunk.text
179
-
180
- except Exception as e:
181
- yield f"\n\n⚠️ **خطأ في البث:** `{str(e)}`"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
- return StreamingResponse(stream_generator(), media_type="text/plain")
184
-
185
- # ============================================================
186
- # 🌟 دالة مستقلة لتوليد الصور
187
- # ============================================================
188
- async def handle_image_request(request: ChatRequest, client):
189
- """معالجة طلبات توليد الصور باستخدام NVIDIA Flux"""
190
- def generate_image_stream():
191
- current_hour = datetime.now().strftime("%Y-%m-%d %H")
192
- user_info = user_image_limits[request.user_id]
193
-
194
- if user_info.get("hour") != current_hour:
195
- user_info["hour"] = current_hour
196
- user_info["count"] = 0
197
 
198
- if user_info["count"] >= 3:
199
- yield "⚠️ **عذراً!** لقد استنفدت رصيدك الحالي لتوليد الصور (3 صور في الساعة). يرجى المحاولة لاحقاً! 🕒"
200
- return
201
-
202
- if not NVIDIA_API_KEY:
203
- yield "⚠️ **خطأ في السيرفر:** مفتاح `NVIDIA_API_KEY` غير موجود."
204
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
- try:
207
- # ترجمة الطلب للإنجليزية
208
- translation_response = client.models.generate_content(
209
- model="gemma-4-31b-it",
210
- contents=f"Translate this prompt to English for an image generator. Only return the English prompt: {request.message}"
211
- )
212
- final_prompt = translation_response.text.strip()
213
-
214
- invoke_url = "https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.2-klein-4b"
215
- headers = {
216
- "Authorization": f"Bearer {NVIDIA_API_KEY}",
217
- "Accept": "application/json",
218
- }
219
-
220
- payload = {
221
- "prompt": final_prompt,
222
- "width": 1024,
223
- "height": 1024,
224
- "seed": 0,
225
- "steps": 4
226
- }
227
-
228
- if request.files:
229
- img_file = next((f for f in request.files if f.mime_type.startswith("image/")), None)
230
- if img_file:
231
- payload["image"] = [f"data:{img_file.mime_type};base64,{img_file.data}"]
232
-
233
- response = requests.post(invoke_url, headers=headers, json=payload, timeout=60)
234
-
235
- if not response.ok:
236
- yield f"⚠️ **خطأ من سيرفر NVIDIA:**\n`{response.text}`"
237
- return
238
-
239
- response_body = response.json()
240
-
241
- def extract_img(obj):
242
- if isinstance(obj, dict):
243
- for k, v in obj.items():
244
- if k in ['b64_json', 'base64', 'image'] and isinstance(v, str) and len(v) > 100:
245
- return v.split(",", 1)[-1] if v.startswith("data:") else v
246
- elif k == 'url' and isinstance(v, str) and v.startswith('http'):
247
- return base64.b64encode(requests.get(v).content).decode('utf-8')
248
- else:
249
- res = extract_img(v)
250
- if res: return res
251
- elif isinstance(obj, list):
252
- for item in obj:
253
- res = extract_img(item)
254
- if res: return res
255
- return None
256
-
257
- b64_image = extract_img(response_body)
258
-
259
- if not b64_image:
260
- yield f"⚠️ **رد غير متوقع من الخادم (لم يتم العثور على الصورة):**"
261
- return
262
-
263
- user_info["count"] += 1
264
- rem = 3 - user_info["count"]
265
-
266
- html_response = f'''
267
- <div style="text-align:center; margin: 15px 0;">
268
- <img src="data:image/jpeg;base64,{b64_image}" style="width:100%; max-width:400px; border-radius:18px; box-shadow:0 8px 25px rgba(0,0,0,0.15);" />
269
- <br/>
270
- <a href="data:image/jpeg;base64,{b64_image}" download="Genisi_Flux_Art.jpg" style="display:inline-block; margin-top:12px; padding:10px 20px; background:linear-gradient(135deg, #4f8ef7, #7c5cf7); color:#fff; border-radius:25px; text-decoration:none; font-weight:600; font-family:'Cairo', sans-serif;">⬇️ تحميل الصورة</a>
271
- <p style="font-size:0.85rem; color:#9aa3be; margin-top:8px;">✅ تم التصميم بنجاح (المتبقي لك هذه الساعة: {rem}/3 صور)</p>
272
- </div>'''
273
- yield html_response
274
- except Exception as e:
275
- yield f"⚠️ **خطأ أثناء توليد الصورة:**\n`{str(e)}`"
276
-
277
- return StreamingResponse(generate_image_stream(), media_type="text/plain")
278
-
279
- # ============================================================
280
- # نقطة النهاية الرئيسية
281
- # ============================================================
282
- @app.post("/chat")
283
- async def chat_endpoint(request: ChatRequest):
284
- global CURRENT_TEXT_KEY_INDEX
285
-
286
- msg_lower = request.message.strip().lower()
287
- current_model = request.model
288
-
289
- # التحقق من طلبات الصور
290
- image_triggers = ["ارسم", "صمم", "تخيل", "صورة ل", "draw", "generate", "imagine", "create", "عدل", "edit", "تصميم"]
291
- is_image_request = any(msg_lower.startswith(trigger) for trigger in image_triggers)
292
-
293
- # محاولة تنفيذ الطلب مع تدوير المفاتيح
294
- attempts = 0
295
- while attempts < len(text_clients):
296
- try:
297
- client = get_text_client()
298
-
299
- # --- طلب صورة ---
300
- if is_image_request:
301
- return await handle_image_request(request, client)
302
-
303
- # --- طلب نصي ---
304
- contents, _ = build_contents(request.history, request.message, request.files)
305
- tools = [types.Tool(googleSearch=types.GoogleSearch())]
306
-
307
- # 🌟 توجيه إلى الدالة المناسبة حسب النموذج
308
- if current_model == "pro":
309
- return await handle_pro_model(request, client, contents, tools)
310
- else:
311
- return await handle_flash_model(request, client, contents, tools)
312
-
313
- except Exception as e:
314
- error_msg = str(e).lower()
315
- if "429" in error_msg or "quota" in error_msg:
316
- CURRENT_TEXT_KEY_INDEX = (CURRENT_TEXT_KEY_INDEX + 1) % len(text_clients)
317
- attempts += 1
318
- else:
319
- def err_gen(): yield f"⚠️ **خطأ في النموذج:** {str(e)}"
320
- return StreamingResponse(err_gen(), media_type="text/plain")
321
-
322
- def limit_gen(): yield "⚠️ تم الوصول للحد الأقصى لجميع المفاتيح."
323
- return StreamingResponse(limit_gen(), media_type="text/plain")
 
324
 
325
- # ============================================================
326
- # تقديم الملفات الثابتة
327
- # ============================================================
328
- app.mount("/", StaticFiles(directory=".", html=True), name="static")
 
 
 
329
 
330
- if __name__ == "__main__":
331
- import uvicorn
332
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en" dir="ltr">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Genisi AI - مساعدك الذكي</title>
7
+
8
+ <!-- 🌟 Lucide Icons -->
9
+ <script src="https://unpkg.com/lucide@latest"></script>
10
+
11
+ <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
12
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
13
+ <!-- KaTeX CSS + JS -->
14
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css"/>
15
+ <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js"></script>
16
+ <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js"></script>
17
+
18
+ <style>
19
+ :root {
20
+ --bg: #0d0f14; --surface: #161920; --surface2: #1e2230; --surface3: #252a3a;
21
+ --border: #2a2f42; --border2: #333a52;
22
+ --accent: #4f8ef7; --accent2: #7c5cf7; --accent-soft: rgba(79,142,247,0.12);
23
+ --text: #e8eaf2; --text2: #9aa3be; --text3: #5c6480;
24
+ --user-bubble: #1a2340; --bot-bubble: #161920;
25
+ --danger: #f75f5f;
26
+ --flash-color: #fbbf24; --pro-color: #a78bfa;
27
+ --thinking-bg: rgba(124, 92, 247, 0.08);
28
+ --thinking-border: rgba(124, 92, 247, 0.2);
29
+ --radius: 28px; --radius-sm: 18px; --radius-pill: 50px;
30
+ --sidebar-w: 280px; --tr: 0.3s cubic-bezier(.4,0,.2,1);
31
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ [data-theme="light"] {
34
+ --bg: #f0f2f8; --surface: #fff; --surface2: #f5f6fa; --surface3: #ebedf5;
35
+ --border: #d8dce8; --border2: #c5cad8;
36
+ --text: #1a1d2e; --text2: #4a5070; --text3: #8a90a8;
37
+ --user-bubble: #dde6ff; --bot-bubble: #fff; --accent-soft: rgba(79,142,247,0.1);
38
+ --flash-color: #d97706; --pro-color: #7c3aed;
39
+ --thinking-bg: rgba(124, 58, 237, 0.05);
40
+ --thinking-border: rgba(124, 58, 237, 0.15);
41
+ }
42
 
43
+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
44
+ html,body{height:100%;font-family:'Cairo',sans-serif;background:var(--bg);color:var(--text); scroll-behavior: smooth;}
45
+ ::-webkit-scrollbar{width:6px}::-webkit-scrollbar-track{background:transparent}
46
+ ::-webkit-scrollbar-thumb{background:var(--border2);border-radius:var(--radius-pill)}
47
+
48
+ .app{display:flex;height:100vh;overflow:hidden}
49
+
50
+ /* SIDEBAR */
51
+ .sidebar{width:var(--sidebar-w);min-width:var(--sidebar-w);background:var(--surface);
52
+ border-right:1px solid var(--border);display:flex;flex-direction:column;
53
+ transition:width var(--tr),min-width var(--tr);overflow:hidden;
54
+ border-top-right-radius: var(--radius); border-bottom-right-radius: var(--radius);}
55
+ [dir="rtl"] .sidebar { border-right:none; border-left:1px solid var(--border); border-radius: 0 var(--radius) var(--radius) 0; }
56
+ .sidebar.collapsed{width:0;min-width:0;border:none;padding:0;}
57
+ .sidebar-header{padding:24px 20px 16px;display:flex;align-items:center;gap:12px;}
58
+ .s-logo{display:flex;align-items:center;gap:12px;flex:1}
59
+ .s-logo img{width:36px;height:36px;border-radius:12px;object-fit:cover; box-shadow: 0 4px 12px var(--accent-soft);}
60
+ .s-logo-name{font-size:1.2rem;font-weight:700;background:linear-gradient(135deg,var(--accent),var(--accent2));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ .btn-new{margin:12px 16px;padding:12px 16px;background:linear-gradient(135deg,var(--accent),var(--accent2));
63
+ color:#fff;border:none;border-radius:var(--radius-pill);cursor:pointer;font-family:'Cairo',sans-serif;
64
+ font-size:.95rem;font-weight:600;display:flex;align-items:center;gap:8px; justify-content:center;
65
+ transition:all var(--tr); box-shadow: 0 4px 15px var(--accent-soft);}
66
+ .btn-new svg { width: 18px; height: 18px; }
67
+ .btn-new:hover{opacity:.9;transform:translateY(-2px)}
68
+ .s-label{padding:10px 20px;font-size:.75rem;font-weight:700;color:var(--text3);letter-spacing:.08em;text-transform:uppercase}
69
+ .chats-list{flex:1;overflow-y:auto;padding:4px 12px;display:flex;flex-direction:column;gap:6px}
70
+ .chat-item{padding:10px 16px;border-radius:var(--radius-sm);cursor:pointer;font-size:.9rem;color:var(--text2);
71
+ display:flex;align-items:center;gap:10px;transition:all var(--tr);
72
+ white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
73
+ .chat-item svg { width: 18px; height: 18px; color: var(--accent); }
74
+ .chat-item:hover{background:var(--surface2);color:var(--text); transform: translateX(4px);}[dir="rtl"] .chat-item:hover {transform: translateX(-4px);}
75
+ .chat-item.active{background:var(--accent-soft);color:var(--accent);font-weight:600;}
76
+ .chat-item .ct{flex:1;overflow:hidden;text-overflow:ellipsis}
77
+ .del-btn{opacity:0;background:none;border:none;color:var(--danger);cursor:pointer;font-size:.9rem;
78
+ padding:4px;border-radius:50%;transition:all var(--tr); display:flex; align-items:center; justify-content:center;}
79
+ .chat-item:hover .del-btn{opacity:1}
80
+ .del-btn:hover{background:rgba(247,95,95,.15); transform:scale(1.1);}
81
+ .del-btn svg { width: 16px; height: 16px; }
82
+ .s-footer{padding:16px;display:flex;align-items:center;gap:12px; justify-content: space-between; border-top: 1px solid var(--border); margin-top: auto;}
83
+ .s-footer-actions {display: flex; align-items: center; gap: 8px;}
84
+ .btn-icon{width:42px;height:42px;background:var(--surface2);border:none;
85
+ border-radius:var(--radius-pill);color:var(--text2);cursor:pointer;display:flex;
86
+ align-items:center;justify-content:center;transition:all var(--tr)}
87
+ .btn-icon svg { width: 20px; height: 20px; }
88
+ .btn-icon:hover{background:var(--surface3);color:var(--text);}
89
+ .btn-collapse-sidebar {
90
+ width: 42px; height: 42px; background: var(--surface2); border: none;
91
+ border-radius: var(--radius-pill); color: var(--text2); cursor: pointer;
92
+ display: flex; align-items: center; justify-content: center; transition: all var(--tr);
93
+ }
94
+ .btn-collapse-sidebar svg { width: 20px; height: 20px; }
95
+ .btn-collapse-sidebar:hover { background: var(--surface3); color: var(--text); }
96
+
97
+ /* MAIN */
98
+ .main{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0; background: var(--bg);}
99
+ .topbar{height:70px;padding:0 24px;display:flex;align-items:center;gap:16px; flex-shrink:0}
100
+ .btn-show-sidebar {
101
+ width: 42px; height: 42px; background: var(--surface2); border: none;
102
+ border-radius: var(--radius-pill); color: var(--text2); cursor: pointer;
103
+ display: none; align-items: center; justify-content: center; transition: all var(--tr);
104
+ }
105
+ .btn-show-sidebar svg { width: 20px; height: 20px; }
106
+ .btn-show-sidebar:hover { background: var(--surface3); color: var(--text); }
107
+ .sidebar.collapsed ~ .main .btn-show-sidebar { display: flex; }
108
+ .topbar-title{flex:1;font-size:1.05rem;font-weight:600;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
109
+
110
+ /* CHAT AREA */
111
+ .chat-area{flex:1;overflow-y:auto;padding:20px 0 40px;display:flex;flex-direction:column; scroll-behavior: smooth;}
112
 
113
+ /* WELCOME SCREEN */
114
+ .welcome{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;
115
+ gap:20px;padding:40px 24px;text-align:center; animation: fadeSlideUp 0.6s ease;}
116
+ @keyframes fadeSlideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
117
+ .w-logo{width:85px;height:85px;border-radius:24px;object-fit:cover;box-shadow:0 12px 40px var(--accent-soft)}
118
+ .w-title{font-size:2.4rem;font-weight:700;background:linear-gradient(135deg,var(--accent),var(--accent2));
119
+ -webkit-background-clip:text;-webkit-text-fill-color:transparent}
120
+ .w-sub{color:var(--text2);font-size:1.05rem}
121
+ .chips{display:flex;flex-wrap:wrap;justify-content:center;gap:10px;margin-top:12px;max-width:600px}
122
+ .chip{padding:10px 20px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-pill);
123
+ font-size:.9rem;color:var(--text);cursor:pointer;transition:all var(--tr); box-shadow: 0 4px 12px rgba(0,0,0,0.05);
124
+ display:flex; align-items:center; gap:8px;}
125
+ .chip svg { width: 18px; height: 18px; color: var(--accent); }
126
+ .chip:hover{background:var(--accent-soft);border-color:var(--accent);color:var(--accent); transform:translateY(-2px);}
127
+
128
+ /* MESSAGES */
129
+ .msg-row{display:flex;padding:8px 30px;gap:16px; animation: popIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;}
130
+ @keyframes popIn { from { opacity: 0; transform: translateY(15px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
131
+ .msg-row.user{flex-direction:row-reverse}
132
+ .msg-av{width:38px;height:38px;border-radius:14px;flex-shrink:0;display:flex;align-items:center;
133
+ justify-content:center;font-size:1.1rem;font-weight:700;margin-top:2px;overflow:hidden;
134
+ box-shadow: 0 4px 10px rgba(0,0,0,0.1);}
135
+ .msg-row.bot .msg-av{background:linear-gradient(135deg,var(--accent),var(--accent2))}
136
+ .msg-row.bot .msg-av img{width:100%;height:100%;object-fit:cover}
137
+ .msg-row.user .msg-av{background:var(--surface3);color:var(--text)}
138
+ .msg-row.user .msg-av svg { width: 20px; height: 20px; }
139
 
140
+ .bubble{max-width:min(700px,80vw);padding:16px 22px;border-radius:var(--radius);
141
+ font-size:.98rem;line-height:1.75;word-break:break-word;}
142
+ .msg-row.bot .bubble{background:transparent;border:none;padding:8px 4px;box-shadow:none;}
143
+ .msg-row.user .bubble{background:var(--user-bubble);border:none;}
144
+
145
+ /* حاوية التفكير */
146
+ .thinking-container {
147
+ margin: 16px 0;
148
+ padding: 16px 18px;
149
+ background: var(--thinking-bg);
150
+ border: 1px solid var(--thinking-border);
151
+ border-radius: var(--radius-sm);
152
+ border-left: 3px solid var(--pro-color);
153
+ }
154
+ [dir="rtl"] .thinking-container {
155
+ border-left: 1px solid var(--thinking-border);
156
+ border-right: 3px solid var(--pro-color);
157
+ }
158
+ .thinking-header {
159
+ display: flex;
160
+ align-items: center;
161
+ gap: 10px;
162
+ margin-bottom: 12px;
163
+ color: var(--pro-color);
164
+ font-weight: 600;
165
+ font-size: 0.9rem;
166
+ }
167
+ .thinking-header svg {
168
+ width: 18px;
169
+ height: 18px;
170
+ animation: pulse 1.5s ease-in-out infinite;
171
+ }
172
+ @keyframes pulse {
173
+ 0%, 100% { opacity: 0.6; transform: scale(1); }
174
+ 50% { opacity: 1; transform: scale(1.1); }
175
+ }
176
+ .thinking-content {
177
+ color: var(--text2);
178
+ font-size: 0.9rem;
179
+ line-height: 1.7;
180
+ white-space: pre-wrap;
181
+ word-break: break-word;
182
+ }
183
+ .pro-response { margin-top: 8px; }
184
+
185
+ /* CURSOR */
186
+ .genisi-cursor { display: inline-block; width: 12px; height: 12px; margin-inline-start: 6px; background: var(--accent); border-radius: 50%; animation: blink 1s infinite; }
187
+ @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }
188
+
189
+ /* MARKDOWN */
190
+ .bubble p{margin-bottom:12px}.bubble p:last-child{margin-bottom:0}
191
+ .bubble ul,.bubble ol{padding-inline-start:24px;margin:12px 0}
192
+ .bubble li {margin-bottom: 6px;}
193
+ .bubble .table-wrapper{width:100%;overflow-x:auto;margin:16px 0;border-radius:var(--radius-sm);border:1px solid var(--border);}
194
+ .bubble table{width:100%;border-collapse:collapse;min-width:400px;}
195
+ .bubble th,.bubble td{border:1px solid var(--border);padding:10px 14px;text-align:start;}
196
+ .bubble th{background:var(--surface3);font-weight:600;}
197
+
198
+ /* Code Blocks */
199
+ .code-container{position:relative;margin:16px 0;background:var(--surface3);border-radius:var(--radius-sm);border:1px solid var(--border);overflow:hidden;}
200
+ .code-header{display:flex;justify-content:space-between;align-items:center;background:#12141a;padding:8px 16px;font-size:0.8rem;color:var(--text2);}
201
+ .copy-btn{background:var(--surface2);border:none;color:var(--text);cursor:pointer;display:flex;align-items:center;gap:6px;font-size:0.8rem;padding:4px 10px;border-radius:var(--radius-pill);}
202
+ .copy-btn svg { width: 14px; height: 14px; }
203
+ .copy-btn:hover{background:var(--accent);color:#fff;}
204
+ .code-container pre{margin:0;padding:16px;overflow-x:auto;font-family:'JetBrains Mono',monospace;font-size:0.85rem;}
205
+ .bubble code:not(pre code){font-family:'JetBrains Mono',monospace;font-size:.85rem;background:var(--surface3);padding:3px 6px;border-radius:6px;color:var(--accent);}
206
+
207
+ /* KaTeX */
208
+ .katex-display{overflow-x:auto;overflow-y:hidden;padding:8px 0;}
209
+ .katex{font-size:1.05em;}
210
+
211
+ /* Files */
212
+ .file-chip {display:inline-flex; align-items:center; gap:6px; background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius-pill); padding:4px 12px; font-size:0.85rem; margin:0 4px 8px 0; color:var(--text);}
213
+ .file-chip svg { width: 14px; height: 14px; }
214
+ .file-chip button {background:none; border:none; color:var(--danger); cursor:pointer; padding:0; margin-left:4px; display: flex; align-items: center;}
215
+ .file-chip button svg { width: 12px; height: 12px; }
216
+ .file-prev {display:flex; align-items:center; gap:8px; background:var(--surface3); padding:8px 12px; border-radius:8px; margin-bottom:8px; font-size:0.85rem;}
217
+ .mem-badge{font-size:.75rem;color:var(--text3);padding:4px 30px 10px;display:flex;align-items:center;gap:6px; font-weight: 600;}
218
+
219
+ /* INPUT */
220
+ .input-area{padding:0 24px 30px; display:flex; flex-direction:column; align-items:center; flex-shrink:0;}
221
+ .input-wrapper{width:100%; max-width:850px; position:relative;}
222
+ .file-chips-container {width:100%; max-width:850px; display:flex; flex-wrap:wrap; margin-bottom:8px;}
223
+ .input-box{display:flex;align-items:flex-end;gap:12px;background:var(--surface);
224
+ border:1px solid var(--border);border-radius:32px;padding:12px 16px;
225
+ transition:all var(--tr); box-shadow: 0 8px 30px rgba(0,0,0,0.15);}
226
+ .input-box:focus-within{border-color:var(--accent); box-shadow: 0 8px 30px var(--accent-soft);}
227
 
228
+ .btn-attach{background:none; border:none; color:var(--text3); cursor:pointer; padding:6px; border-radius:50%; display:flex; align-items:center; justify-content:center;}
229
+ .btn-attach svg { width: 22px; height: 22px; }
230
+ .btn-attach:hover{color:var(--accent); background:var(--surface2);}
231
+
232
+ .input-box textarea{flex:1;background:none;border:none;outline:none;color:var(--text);
233
+ font-family:'Cairo',sans-serif;font-size:.98rem;resize:none;max-height:160px;line-height:1.6; padding: 6px 0;}
234
+ .input-box textarea::placeholder{color:var(--text3)}
235
 
236
+ .btn-send, .btn-stop {width:42px;height:42px; border:none;border-radius:50%;cursor:pointer;color:#fff;display:flex;align-items:center;justify-content:center;transition:all var(--tr); flex-shrink:0;}
237
+ .btn-send {background:linear-gradient(135deg,var(--accent),var(--accent2));}
238
+ .btn-send svg { width: 20px; height: 20px; }
239
+ .btn-send:hover{opacity:.9;transform:scale(1.08);}
240
+ .btn-send:disabled{opacity:.4;cursor:not-allowed;transform:none;}
241
+ .btn-stop {background:var(--surface3); color:var(--text); border:1px solid var(--border);}
242
+ .btn-stop svg { width: 20px; height: 20px; }
243
+ .btn-stop:hover {background:var(--danger); color:#fff;}
244
+
245
+ /* MODEL SELECTOR */
246
+ .model-selector-input { position: relative; display: flex; align-items: center; }
247
+ .model-toggle-btn {
248
+ display: flex; align-items: center; justify-content: center; width: 36px; height: 36px;
249
+ background: var(--surface2); border: 1px solid var(--border); border-radius: 50%;
250
+ cursor: pointer; transition: all var(--tr);
251
+ }
252
+ .model-toggle-btn:hover { background: var(--surface3); border-color: var(--accent); transform: scale(1.05); }
253
+ .model-toggle-btn svg { width: 18px; height: 18px; }
254
+ .model-toggle-btn.flash-active svg { color: var(--flash-color); }
255
+ .model-toggle-btn.pro-active svg { color: var(--pro-color); }
256
 
257
+ .model-dropdown-input {
258
+ position: absolute; bottom: calc(100% + 8px); left: 0; background: var(--surface);
259
+ border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 8px;
260
+ min-width: 220px; box-shadow: 0 10px 40px rgba(0,0,0,0.4); z-index: 100;
261
+ opacity: 0; visibility: hidden; transform: translateY(10px); transition: all var(--tr);
262
+ }
263
+ [dir="rtl"] .model-dropdown-input { left: auto; right: 0; }
264
+ .model-dropdown-input.show { opacity: 1; visibility: visible; transform: translateY(0); }
265
+ .model-option-input {
266
+ display: flex; align-items: center; gap: 12px; padding: 12px 14px;
267
+ border-radius: var(--radius-sm); cursor: pointer; transition: background var(--tr);
268
+ }
269
+ .model-option-input:hover { background: var(--surface2); }
270
+ .model-option-input.active { background: var(--accent-soft); border: 1px solid var(--accent); }
271
+ .model-option-input svg { width: 22px; height: 22px; flex-shrink: 0; }
272
+ .model-info-input { flex: 1; }
273
+ .model-name-input { font-weight: 600; font-size: 0.95rem; color: var(--text); display: flex; align-items: center; gap: 6px; }
274
+ .model-desc-input { font-size: 0.75rem; color: var(--text3); margin-top: 2px; }
275
+ .model-badge-input { padding: 2px 8px; border-radius: var(--radius-pill); font-size: 0.65rem; font-weight: 700; color: #fff; }
276
+
277
+ /* MODAL */
278
+ .overlay{position:fixed;inset:0;z-index:999;background:rgba(0,0,0,.6);display:flex;
279
+ align-items:center;justify-content:center;backdrop-filter:blur(8px);
280
+ opacity:0;pointer-events:none;transition:opacity var(--tr)}
281
+ .overlay.open{opacity:1;pointer-events:all}
282
+ .modal{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:32px;
283
+ width:min(440px,90vw);box-shadow:0 30px 80px rgba(0,0,0,.5);
284
+ transform:translateY(20px) scale(0.95);transition:all var(--tr)}
285
+ .overlay.open .modal{transform:translateY(0) scale(1)}
286
+ .m-header{display:flex;align-items:center;gap:12px;margin-bottom:24px}
287
+ .m-title{font-size:1.3rem;font-weight:700;flex:1}
288
+ .m-close{background:var(--surface2);border:none;color:var(--text);cursor:pointer;width:36px;height:36px; border-radius:50%; display:flex; align-items:center; justify-content:center;}
289
+ .m-close svg { width: 20px; height: 20px; }
290
+ .m-close:hover{background:var(--danger); color:#fff;}
291
+ .s-row{display:flex;align-items:center;justify-content:space-between;padding:16px 0;border-bottom:1px solid var(--border)}
292
+ .s-lbl{font-size:.95rem;font-weight:600;color:var(--text)}
293
+ .s-desc{font-size:.8rem;color:var(--text3);margin-top:4px}
294
+ .toggle{position:relative;width:48px;height:26px}
295
+ .toggle input{opacity:0;width:0;height:0}
296
+ .tslider{position:absolute;inset:0;background:var(--surface3);border-radius:var(--radius-pill);cursor:pointer;}
297
+ .tslider::before{content:'';position:absolute;width:20px;height:20px;border-radius:50%;
298
+ background:#fff;top:3px;left:4px;transition:all var(--tr);}
299
+ .toggle input:checked+.tslider{background:var(--accent)}
300
+ .toggle input:checked+.tslider::before{transform:translateX(20px)}
301
 
302
+ select.s-input { width:auto; padding:8px 16px; background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius-pill); color:var(--text); cursor:pointer; font-family:'Cairo',sans-serif;}
303
+ .btn-save{width:100%;margin-top:24px;padding:14px;background:linear-gradient(135deg,var(--accent),var(--accent2));
304
+ color:#fff;border:none;border-radius:var(--radius-pill);cursor:pointer;font-size:1rem;font-weight:700; display: flex; align-items: center; justify-content: center; gap: 8px;}
305
+ .btn-save svg { width: 18px; height: 18px; }
306
+ .btn-danger{padding:8px 18px;background:rgba(247,95,95,.12);border:1px solid var(--danger);
307
+ color:var(--danger);border-radius:var(--radius-pill);cursor:pointer;font-size:.9rem;font-weight:600; display: flex; align-items: center; gap: 6px;}
308
+ .btn-danger svg { width: 16px; height: 16px; }
309
+ .btn-danger:hover{background:var(--danger); color:#fff;}
 
 
 
 
 
 
310
 
311
+ /* RESPONSIVE */
312
+ @media (max-width: 640px) {
313
+ .msg-row { padding: 6px 12px; gap: 10px; }
314
+ .bubble { max-width: 92vw; padding: 12px 14px; font-size: .93rem; }
315
+ .topbar { height: 56px; padding: 0 14px; }
316
+ .input-area { padding: 0 10px 18px; }
317
+ .w-title { font-size: 1.8rem; }
318
+ .chips { gap: 8px; }
319
+ .chip { font-size: .82rem; padding: 8px 14px; }
320
+ }
321
+ </style>
322
+ </head>
323
+ <body>
324
+ <div class="app">
325
+
326
+ <!-- SIDEBAR -->
327
+ <aside class="sidebar collapsed" id="sidebar">
328
+ <div class="sidebar-header">
329
+ <div class="s-logo">
330
+ <img src="https://copilot.microsoft.com/th/id/BCO.f29916dd-b0c1-4089-87cd-43d099a7d1a6.png" alt="Genisi"/>
331
+ <span class="s-logo-name">Genisi AI</span>
332
+ </div>
333
+ </div>
334
+ <button class="btn-new" onclick="newChat()">
335
+ <i data-lucide="plus-circle"></i>
336
+ <span id="i18n-new-chat">✦ New Chat</span>
337
+ </button>
338
+ <div class="s-label" id="i18n-chats-label">CHATS</div>
339
+ <div class="chats-list" id="chats-list"></div>
340
+ <div class="s-footer">
341
+ <div class="s-footer-actions">
342
+ <button class="btn-icon" onclick="openSettings()"><i data-lucide="settings"></i></button>
343
+ <button class="btn-icon" id="theme-btn" onclick="toggleTheme()"><i data-lucide="moon"></i></button>
344
+ </div>
345
+ <button class="btn-collapse-sidebar" onclick="toggleSidebar()" title="إخفاء القائمة">
346
+ <i data-lucide="panel-left-close"></i>
347
+ </button>
348
+ </div>
349
+ </aside>
350
+
351
+ <!-- MAIN -->
352
+ <main class="main">
353
+ <div class="topbar">
354
+ <button class="btn-show-sidebar" onclick="toggleSidebar()" title="إظهار القائمة">
355
+ <i data-lucide="panel-left-open"></i>
356
+ </button>
357
+ <div class="topbar-title" id="topbar-title">Genisi AI</div>
358
+ </div>
359
+
360
+ <div class="chat-area" id="chat-area"></div>
361
+
362
+ <div class="input-area">
363
+ <div class="file-chips-container" id="file-chips"></div>
364
+ <div class="input-wrapper">
365
+ <div class="input-box">
366
+ <input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)" />
367
+ <button class="btn-attach" onclick="document.getElementById('file-input').click()"><i data-lucide="paperclip"></i></button>
368
+
369
+ <!-- MODEL SELECTOR -->
370
+ <div class="model-selector-input">
371
+ <div class="model-toggle-btn" id="model-toggle-btn" onclick="toggleModelDropdownInput(event)">
372
+ <i id="model-icon-input" data-lucide="zap"></i>
373
+ </div>
374
+ <div class="model-dropdown-input" id="model-dropdown-input">
375
+ <div class="model-option-input" data-model="flash" onclick="selectModelInput('flash', event)">
376
+ <i data-lucide="zap" style="color: var(--flash-color);"></i>
377
+ <div class="model-info-input">
378
+ <div class="model-name-input">
379
+ Genisi Flash
380
+ <span class="model-badge-input" style="background: var(--flash-color);">⚡ Fast</span>
381
+ </div>
382
+ <div class="model-desc-input">سريع، مثالي للمهام اليومية</div>
383
+ </div>
384
+ </div>
385
+ <div class="model-option-input" data-model="pro" onclick="selectModelInput('pro', event)">
386
+ <i data-lucide="brain" style="color: var(--pro-color);"></i>
387
+ <div class="model-info-input">
388
+ <div class="model-name-input">
389
+ Genisi Pro
390
+ <span class="model-badge-input" style="background: var(--pro-color);">💎 Pro</span>
391
+ </div>
392
+ <div class="model-desc-input">يفكر بعمق، تحليل وإبداع</div>
393
+ </div>
394
+ </div>
395
+ </div>
396
+ </div>
397
+
398
+ <textarea id="msg-input" rows="1" onkeydown="handleKey(event)" oninput="autoResize(this)" placeholder="Type a message..."></textarea>
399
+ <button class="btn-send" id="send-btn" onclick="sendMessage()"><i data-lucide="arrow-up"></i></button>
400
+ <button class="btn-stop" id="stop-btn" onclick="stopGeneration()" style="display:none;"><i data-lucide="square"></i></button>
401
+ </div>
402
+ </div>
403
+ </div>
404
+ </main>
405
+ </div>
406
+
407
+ <!-- SETTINGS MODAL -->
408
+ <div class="overlay" id="settings-modal">
409
+ <div class="modal">
410
+ <div class="m-header">
411
+ <div class="m-title" id="i18n-settings-title">Settings</div>
412
+ <button class="m-close" onclick="closeSettings()"><i data-lucide="x"></i></button>
413
+ </div>
414
+ <div class="s-row">
415
+ <div class="s-lbl" id="i18n-lang-lbl">Language</div>
416
+ <select id="lang-select" class="s-input" onchange="changeLanguage(this.value)">
417
+ <option value="en">English</option>
418
+ <option value="ar">العربية</option>
419
+ <option value="fr">Français</option>
420
+ <option value="es">Español</option>
421
+ </select>
422
+ </div>
423
+ <div class="s-row">
424
+ <div class="s-lbl" id="i18n-dark-lbl">Dark Mode</div>
425
+ <label class="toggle">
426
+ <input type="checkbox" id="dark-toggle" onchange="applyThemeToggle()"/>
427
+ <span class="tslider"></span>
428
+ </label>
429
+ </div>
430
+ <div class="s-row">
431
+ <div>
432
+ <div class="s-lbl" id="i18n-del-lbl">Delete All Chats</div>
433
+ <div class="s-desc" id="i18n-del-desc">This action cannot be undone</div>
434
+ </div>
435
+ <button class="btn-danger" onclick="clearAllChats()"><i data-lucide="trash-2"></i> <span id="i18n-del-btn">Delete</span></button>
436
+ </div>
437
+ <button class="btn-save" onclick="closeSettings()"><i data-lucide="check"></i> <span id="i18n-save-btn">Close</span></button>
438
+ </div>
439
+ </div>
440
+
441
+ <script>
442
+ // ═════════════════════════════════════════════════════════════
443
+ // 🌟 GENISI AI - مع دعم ديناميكي كامل لـ KaTeX
444
+ // ═════════════════════════════════════════════════════════════
445
+
446
+ // i18n
447
+ const i18n = {
448
+ en: {
449
+ newChat: "New Chat", chatsLabel: "CHATS", settings: "Settings", lang: "Language",
450
+ dark: "Dark Mode", del: "Delete All Chats", delDesc: "This action cannot be undone",
451
+ delBtn: "Delete", saveBtn: "Close", placeholder: "Type your message... (Enter to send)",
452
+ welcomeTitle: "Welcome to Genisi", welcomeSub: "Your smart assistant by AnesNT — Batna 🇩🇿",
453
+ c1: "What is AI?", c2: "Write Python code", c3: "Summarize a topic", c4: "Design an image in space 🚀",
454
+ errConnect: "Connection Error", memBadge: "Memory: {c}/{t} messages", stopMsg: "[Generation stopped]",
455
+ thinking: "Genisi Pro is thinking..."
456
+ },
457
+ ar: {
458
+ newChat: "محادثة جديدة", chatsLabel: "المحادثات", settings: "الإعدادات", lang: "اللغة",
459
+ dark: "الوضع الليلي", del: "حذف جميع المحادثات", delDesc: "لا يمكن التراجع عن هذا الإجراء",
460
+ delBtn: "حذف", saveBtn: "إغلاق", placeholder: "اكتب رسالتك... (Enter للإرسال)",
461
+ welcomeTitle: "مرحباً في Genisi", welcomeSub: "مساعدك الذكي من AnesNT — ولاية باتنة 🇩🇿",
462
+ c1: "ما هو الذكاء الاصطناعي؟", c2: "اكتب كود بايثون", c3: "لخص لي موضوعاً", c4: "صمم صورة بالفضاء 🚀",
463
+ errConnect: "خطأ في الاتصال", memBadge: "الذاكرة: {c}/{t} رسائل", stopMsg: "[تم إيقاف التوليد]",
464
+ thinking: "Genisi Pro يفكر..."
465
+ },
466
+ fr: {
467
+ newChat: "Nouvelle Disc.", chatsLabel: "DISCUSSIONS", settings: "Paramètres", lang: "Langue",
468
+ dark: "Mode Sombre", del: "Supprimer Tout", delDesc: "Action irréversible",
469
+ delBtn: "Supprimer", saveBtn: "Fermer", placeholder: "Écrivez votre message...",
470
+ welcomeTitle: "Bienvenue sur Genisi", welcomeSub: "Votre assistant par AnesNT — Batna 🇩🇿",
471
+ c1: "Qu'est-ce que l'IA?", c2: "Code Python", c3: "Résumer", c4: "Créer une image 🚀",
472
+ errConnect: "Erreur de connexion", memBadge: "Mémoire: {c}/{t} msgs", stopMsg: "[Génération arrêtée]",
473
+ thinking: "Genisi Pro réfléchit..."
474
+ },
475
+ es: {
476
+ newChat: "Nuevo Chat", chatsLabel: "CHATS", settings: "Ajustes", lang: "Idioma",
477
+ dark: "Modo Oscuro", del: "Borrar Todo", delDesc: "Acción irreversible",
478
+ delBtn: "Borrar", saveBtn: "Cerrar", placeholder: "Escribe tu mensaje...",
479
+ welcomeTitle: "Bienvenido a Genisi", welcomeSub: "Tu asistente por AnesNT — Batna 🇩🇿",
480
+ c1: "¿Qué es la IA?", c2: "Código Python", c3: "Resumir", c4: "Diseñar imagen 🚀",
481
+ errConnect: "Error de conexión", memBadge: "Memoria: {c}/{t} msgs", stopMsg: "[Generación detenida]",
482
+ thinking: "Genisi Pro está pensando..."
483
+ }
484
+ };
485
+
486
+ let currentLang = localStorage.getItem('genisi_lang') || 'ar';
487
+ let userId = localStorage.getItem('genisi_user_id') || ('user_' + Date.now().toString(36) + Math.random().toString(36).substring(2, 6));
488
+ localStorage.setItem('genisi_user_id', userId);
489
+
490
+ let chats = JSON.parse(localStorage.getItem('genisi_chats') || '[]');
491
+ let activeChatId = null;
492
+ let isGenerating = false;
493
+ let pendingFiles = [];
494
+ let currentAbortController = null;
495
+ let currentModel = localStorage.getItem('genisi_model') || 'flash';
496
+
497
+ // Markdown setup
498
+ const renderer = new marked.Renderer();
499
+ renderer.code = function(token) {
500
+ const codeText = typeof token === 'string' ? token : token.text || '';
501
+ const lang = typeof token === 'string' ? arguments[1] : token.lang || 'text';
502
+ const escapedCode = String(codeText).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
503
+ return `<div class="code-container"><div class="code-header"><span>${lang}</span><button class="copy-btn" onclick="copyCode(this, '${encodeURIComponent(codeText)}')"><i data-lucide="copy"></i> Copy</button></div><pre><code>${escapedCode}</code></pre></div>`;
504
+ };
505
+ marked.setOptions({ renderer, breaks: true, gfm: true });
506
+
507
+ // Helper functions
508
+ const genId = () => Date.now().toString(36) + Math.random().toString(36).substring(2, 6);
509
+ const saveChats = () => localStorage.setItem('genisi_chats', JSON.stringify(chats));
510
+ const getChat = (id) => chats.find(c => c.id === (id ?? activeChatId));
511
+ const esc = (t) => String(t).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
512
+ const scrollToBottom = () => { const area = document.getElementById('chat-area'); area.scrollTop = area.scrollHeight; };
513
+
514
+ // 🌟🌟🌟 دالة تصيير KaTeX يدوياً (التحسين الأساسي)
515
+ function renderMath(element) {
516
+ if (window.renderMathInElement) {
517
+ try {
518
+ renderMathInElement(element, {
519
+ delimiters: [
520
+ {left: '$$', right: '$$', display: true},
521
+ {left: '$', right: '$', display: false},
522
+ {left: '\\(', right: '\\)', display: false},
523
+ {left: '\\[', right: '\\]', display: true}
524
+ ],
525
+ throwOnError: false
526
+ });
527
+ } catch (e) {
528
+ console.warn('KaTeX render error:', e);
529
+ }
530
+ }
531
+ }
532
+
533
+ // Copy code
534
+ window.copyCode = function(btn, encodedCode) {
535
+ navigator.clipboard.writeText(decodeURIComponent(encodedCode)).then(() => {
536
+ btn.innerHTML = '<i data-lucide="check"></i> Copied!';
537
+ lucide.createIcons();
538
+ setTimeout(() => { btn.innerHTML = '<i data-lucide="copy"></i> Copy'; lucide.createIcons(); }, 2000);
539
+ });
540
+ };
541
+
542
+ // I18n
543
+ function applyI18n() {
544
+ const t = i18n[currentLang];
545
+ document.documentElement.dir = currentLang === 'ar' ? 'rtl' : 'ltr';
546
+ document.documentElement.lang = currentLang;
547
+
548
+ document.getElementById('i18n-new-chat').textContent = t.newChat;
549
+ document.getElementById('i18n-chats-label').textContent = t.chatsLabel;
550
+ document.getElementById('i18n-settings-title').textContent = t.settings;
551
+ document.getElementById('i18n-lang-lbl').textContent = t.lang;
552
+ document.getElementById('i18n-dark-lbl').textContent = t.dark;
553
+ document.getElementById('i18n-del-lbl').textContent = t.del;
554
+ document.getElementById('i18n-del-desc').textContent = t.delDesc;
555
+ document.getElementById('i18n-del-btn').textContent = t.delBtn;
556
+ document.getElementById('i18n-save-btn').textContent = t.saveBtn;
557
+ document.getElementById('msg-input').placeholder = t.placeholder;
558
+
559
+ if(!activeChatId) renderWelcome();
560
+ renderChatList();
561
+ setTimeout(() => lucide.createIcons(), 10);
562
+ }
563
+
564
+ function changeLanguage(val) { currentLang = val; localStorage.setItem('genisi_lang', val); applyI18n(); }
565
+
566
+ // Theme
567
+ function applyTheme(t) {
568
+ document.documentElement.setAttribute('data-theme', t);
569
+ localStorage.setItem('genisi_theme', t);
570
+ document.getElementById('theme-btn').querySelector('i').setAttribute('data-lucide', t === 'dark' ? 'moon' : 'sun');
571
+ document.getElementById('dark-toggle').checked = t === 'dark';
572
+ lucide.createIcons();
573
+ }
574
+ function toggleTheme() { applyTheme(document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark'); }
575
+ function applyThemeToggle() { applyTheme(document.getElementById('dark-toggle').checked ? 'dark' : 'light'); }
576
+
577
+ // Sidebar
578
+ function toggleSidebar() {
579
+ const sidebar = document.getElementById('sidebar');
580
+ sidebar.classList.toggle('collapsed');
581
+ const icon = sidebar.classList.contains('collapsed') ? 'panel-left-open' : 'panel-left-close';
582
+ document.querySelector('.btn-collapse-sidebar i').setAttribute('data-lucide', icon);
583
+ lucide.createIcons();
584
+ }
585
+
586
+ // Model selector
587
+ function toggleModelDropdownInput(event) {
588
+ event.stopPropagation();
589
+ document.getElementById('model-dropdown-input').classList.toggle('show');
590
+ }
591
+ function selectModelInput(model, event) {
592
+ event.stopPropagation();
593
+ currentModel = model;
594
+ localStorage.setItem('genisi_model', model);
595
+
596
+ const toggleBtn = document.getElementById('model-toggle-btn');
597
+ const icon = document.getElementById('model-icon-input');
598
+ toggleBtn.classList.remove('flash-active', 'pro-active');
599
+ icon.setAttribute('data-lucide', model === 'flash' ? 'zap' : 'brain');
600
+ toggleBtn.classList.add(model === 'flash' ? 'flash-active' : 'pro-active');
601
+
602
+ document.querySelectorAll('.model-option-input').forEach(opt => {
603
+ opt.classList.toggle('active', opt.dataset.model === model);
604
+ });
605
+
606
+ document.getElementById('model-dropdown-input').classList.remove('show');
607
+ lucide.createIcons();
608
+ }
609
+
610
+ // Files
611
+ async function handleFiles(files) {
612
+ for (let f of files) {
613
+ const isText = f.type.startsWith('text/') || f.name.match(/\.(py|js|html|css|json|md|txt|csv|cpp|java)$/i);
614
+ const reader = new FileReader();
615
+ reader.onload = (e) => {
616
+ let data = e.target.result;
617
+ if (!isText) data = data.split(',')[1];
618
+ pendingFiles.push({ name: f.name, type: f.type || 'application/octet-stream', data, isText });
619
+ renderFileChips();
620
+ };
621
+ isText ? reader.readAsText(f) : reader.readAsDataURL(f);
622
+ }
623
+ document.getElementById('file-input').value = '';
624
+ }
625
+ function renderFileChips() {
626
+ const container = document.getElementById('file-chips');
627
+ container.innerHTML = '';
628
+ pendingFiles.forEach((f, idx) => {
629
+ container.innerHTML += `<div class="file-chip"><i data-lucide="${f.isText ? 'file-text' : 'image'}"></i> ${f.name} <button onclick="removeFile(${idx})"><i data-lucide="x"></i></button></div>`;
630
+ });
631
+ lucide.createIcons();
632
+ }
633
+ function removeFile(idx) { pendingFiles.splice(idx, 1); renderFileChips(); }
634
+
635
+ // UI
636
+ function openSettings() { document.getElementById('settings-modal').classList.add('open'); document.getElementById('lang-select').value = currentLang; }
637
+ function closeSettings() { document.getElementById('settings-modal').classList.remove('open'); }
638
+
639
+ function renderChatList() {
640
+ const list = document.getElementById('chats-list');
641
+ list.innerHTML = '';
642
+ [...chats].reverse().forEach(chat => {
643
+ const div = document.createElement('div');
644
+ div.className = 'chat-item' + (chat.id === activeChatId ? ' active' : '');
645
+ div.innerHTML = `<i data-lucide="message-square"></i><span class="ct">${esc(chat.title || 'Chat')}</span><button class="del-btn" onclick="deleteChat('${chat.id}',event)"><i data-lucide="trash-2"></i></button>`;
646
+ div.onclick = () => loadChat(chat.id);
647
+ list.appendChild(div);
648
+ });
649
+ lucide.createIcons();
650
+ }
651
+
652
+ function renderWelcome() {
653
+ const t = i18n[currentLang];
654
+ document.getElementById('topbar-title').textContent = 'Genisi AI';
655
+ document.getElementById('chat-area').innerHTML = `
656
+ <div class="welcome" id="welcome">
657
+ <img src="https://copilot.microsoft.com/th/id/BCO.f29916dd-b0c1-4089-87cd-43d099a7d1a6.png" class="w-logo" alt="Genisi"/>
658
+ <div class="w-title">${t.welcomeTitle}</div>
659
+ <div class="w-sub">${t.welcomeSub}</div>
660
+ <div class="chips">
661
+ <div class="chip" onclick="quickSend('${t.c1}')"><i data-lucide="brain"></i> ${t.c1}</div>
662
+ <div class="chip" onclick="quickSend('${t.c2}')"><i data-lucide="code-2"></i> ${t.c2}</div>
663
+ <div class="chip" onclick="quickSend('${t.c3}')"><i data-lucide="list"></i> ${t.c3}</div>
664
+ <div class="chip" onclick="quickSend('${t.c4}')"><i data-lucide="palette"></i> ${t.c4}</div>
665
+ </div>
666
+ </div>`;
667
+ lucide.createIcons();
668
+ }
669
+
670
+ function newChat() {
671
+ activeChatId = null;
672
+ pendingFiles = [];
673
+ renderFileChips();
674
+ document.getElementById('msg-input').value = '';
675
+ renderWelcome();
676
+ renderChatList();
677
+ }
678
+
679
+ function loadChat(id) {
680
+ activeChatId = id;
681
+ const chat = getChat(id);
682
+ if (!chat) return;
683
+ document.getElementById('topbar-title').textContent = chat.title;
684
+ const area = document.getElementById('chat-area');
685
+ area.innerHTML = '';
686
+ chat.history.forEach((entry, idx) => {
687
+ appendBubble('user', entry.user, false, entry.uiFiles);
688
+ appendBubble('bot', entry.bot, true, null, entry.thinking);
689
+ appendMemBadge(idx + 1, chat.history.length);
690
+ });
691
+ scrollToBottom();
692
+ renderChatList();
693
+ // 🟢 إعادة تصيير الرياضيات بعد تحميل المحادثة
694
+ document.querySelectorAll('.bubble').forEach(bubble => renderMath(bubble));
695
+ }
696
+
697
+ function deleteChat(id, e) {
698
+ e.stopPropagation();
699
+ chats = chats.filter(c => c.id !== id);
700
+ saveChats();
701
+ if (activeChatId === id) newChat();
702
+ else renderChatList();
703
+ }
704
+
705
+ function clearAllChats() { chats = []; saveChats(); newChat(); closeSettings(); }
706
+ function stopGeneration() { if (currentAbortController) currentAbortController.abort(); }
707
+
708
+ // Input
709
+ function quickSend(text) { document.getElementById('msg-input').value = text; sendMessage(); }
710
+ function handleKey(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } }
711
+ function autoResize(el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 160) + 'px'; }
712
+
713
+ // Send message
714
+ async function sendMessage() {
715
+ if (isGenerating) return;
716
+ const input = document.getElementById('msg-input');
717
+ let text = input.value.trim();
718
+ if (!text && pendingFiles.length === 0) return;
719
+
720
+ const welcome = document.getElementById('welcome');
721
+ if (welcome) welcome.remove();
722
+
723
+ input.value = ''; input.style.height = 'auto';
724
+
725
+ if (!activeChatId) {
726
+ activeChatId = genId();
727
+ const title = text ? text.slice(0, 35) + '...' : (pendingFiles[0] ? pendingFiles[0].name : 'Chat');
728
+ chats.push({ id: activeChatId, title, history: [] });
729
+ document.getElementById('topbar-title').textContent = title;
730
+ }
731
+
732
+ const chat = getChat();
733
+ const uiFiles = pendingFiles.map(f => f.name);
734
+ const binaryFiles = [];
735
+
736
+ pendingFiles.forEach(f => {
737
+ if (f.isText) text += `\n\n\`\`\`${f.name.split('.').pop()}\n// File: ${f.name}\n${f.data}\n\`\`\``;
738
+ else binaryFiles.push({ name: f.name, mime_type: f.type, data: f.data });
739
+ });
740
+
741
+ appendBubble('user', text, false, uiFiles);
742
+ pendingFiles = []; renderFileChips();
743
+
744
+ isGenerating = true;
745
+ document.getElementById('send-btn').style.display = 'none';
746
+ document.getElementById('stop-btn').style.display = 'flex';
747
+
748
+ const botContentDiv = appendBubble('bot', '', true);
749
+ let thinkingContainer = null, thinkingContent = null, responseContainer = null;
750
+ let thinkingText = '', finalResponse = '', isThinkingPhase = currentModel === 'pro';
751
+
752
+ if (currentModel === 'pro') {
753
+ const t = i18n[currentLang];
754
+ thinkingContainer = document.createElement('div');
755
+ thinkingContainer.className = 'thinking-container';
756
+ thinkingContainer.innerHTML = `
757
+ <div class="thinking-header">
758
+ <i data-lucide="brain"></i>
759
+ <span>${t.thinking}</span>
760
+ </div>
761
+ <div class="thinking-content" id="thinking-content"></div>
762
+ `;
763
+ botContentDiv.appendChild(thinkingContainer);
764
+ responseContainer = document.createElement('div');
765
+ responseContainer.className = 'pro-response';
766
+ botContentDiv.appendChild(responseContainer);
767
+ thinkingContent = document.getElementById('thinking-content');
768
+ lucide.createIcons();
769
+ }
770
+
771
+ currentAbortController = new AbortController();
772
+ let fullResponse = "";
773
+
774
+ try {
775
+ const response = await fetch('/chat', {
776
+ method: 'POST',
777
+ headers: { 'Content-Type': 'application/json' },
778
+ body: JSON.stringify({
779
+ user_id: userId, message: text, history: chat.history,
780
+ files: binaryFiles, model: currentModel
781
+ }),
782
+ signal: currentAbortController.signal
783
+ });
784
+
785
+ if (!response.ok) throw new Error("Server Error");
786
+
787
+ const reader = response.body.getReader();
788
+ const decoder = new TextDecoder("utf-8");
789
+
790
+ while (true) {
791
+ const { value, done } = await reader.read();
792
+ if (done) break;
793
+
794
+ const chunk = decoder.decode(value, { stream: true });
795
+ fullResponse += chunk;
796
+
797
+ if (currentModel === 'pro') {
798
+ const markerIndex = fullResponse.indexOf(" instant");
799
 
800
+ if (markerIndex !== -1 && isThinkingPhase) {
801
+ thinkingText = fullResponse.substring(0, markerIndex);
802
+ finalResponse = fullResponse.substring(markerIndex + 8);
803
+ isThinkingPhase = false;
804
+ if (thinkingContent) thinkingContent.innerHTML = marked.parse(thinkingText);
805
+ if (responseContainer) responseContainer.innerHTML = marked.parse(finalResponse) + '<span class="genisi-cursor"></span>';
806
+ } else if (isThinkingPhase) {
807
+ thinkingText = fullResponse;
808
+ if (thinkingContent) thinkingContent.innerHTML = marked.parse(thinkingText) + '<span class="genisi-cursor"></span>';
809
+ } else {
810
+ finalResponse = fullResponse.substring(fullResponse.indexOf(" instant") + 8);
811
+ if (responseContainer) responseContainer.innerHTML = marked.parse(finalResponse) + '<span class="genisi-cursor"></span>';
812
+ }
813
+ // 🟢 تصيير الرياضيات أثناء التدفق
814
+ if (thinkingContainer) renderMath(thinkingContainer);
815
+ if (responseContainer) renderMath(responseContainer);
816
+ } else {
817
+ botContentDiv.innerHTML = marked.parse(fullResponse) + '<span class="genisi-cursor"></span>';
818
+ // 🟢 تصيير الرياضيات أثناء التدفق
819
+ renderMath(botContentDiv);
820
+ }
821
+
822
+ lucide.createIcons();
823
+ scrollToBottom();
824
+ }
825
+
826
+ document.querySelector('.genisi-cursor')?.remove();
827
+
828
+ const historyEntry = {
829
+ user: text, bot: fullResponse, uiFiles,
830
+ thinking: currentModel === 'pro' ? thinkingText : null
831
+ };
832
+ chat.history.push(historyEntry);
833
+ saveChats();
834
+ appendMemBadge(chat.history.length, chat.history.length);
835
+
836
+ } catch (err) {
837
+ if (err.name === 'AbortError') {
838
+ botContentDiv.innerHTML = marked.parse(fullResponse) + `<br><br><span style="color:var(--text3);"><i data-lucide="ban"></i> ${i18n[currentLang].stopMsg}</span>`;
839
+ chat.history.push({ user: text, bot: fullResponse + "\n\n*" + i18n[currentLang].stopMsg + "*", uiFiles });
840
+ saveChats();
841
+ } else {
842
+ botContentDiv.innerHTML = `<span style="color:var(--danger)"><i data-lucide="alert-circle"></i> ${i18n[currentLang].errConnect}: ${err.message}</span>`;
843
+ }
844
+ lucide.createIcons();
845
+ // 🟢 تصيير الرياضيات في حالة الخطأ
846
+ renderMath(botContentDiv);
847
+ } finally {
848
+ isGenerating = false;
849
+ document.getElementById('send-btn').style.display = 'flex';
850
+ document.getElementById('stop-btn').style.display = 'none';
851
+ renderChatList();
852
+ scrollToBottom();
853
+ }
854
+ }
855
+
856
+ function appendBubble(role, text, isMarkdown, filesList = [], thinkingText = null) {
857
+ const area = document.getElementById('chat-area');
858
+ const row = document.createElement('div'); row.className = `msg-row ${role}`;
859
+ const av = document.createElement('div'); av.className = 'msg-av';
860
+ av.innerHTML = role === 'bot' ? `<img src="https://copilot.microsoft.com/th/id/BCO.f29916dd-b0c1-4089-87cd-43d099a7d1a6.png" alt="G"/>` : '<i data-lucide="user"></i>';
861
+
862
+ const bub = document.createElement('div'); bub.className = 'bubble';
863
+ if (filesList?.length) {
864
+ filesList.forEach(name => { bub.innerHTML += `<div class="file-prev"><i data-lucide="file"></i> ${esc(name)}</div>`; });
865
+ }
866
+
867
+ const contentDiv = document.createElement('div');
868
+
869
+ if (thinkingText) {
870
+ const t = i18n[currentLang];
871
+ contentDiv.innerHTML = `
872
+ <div class="thinking-container">
873
+ <div class="thinking-header"><i data-lucide="brain"></i><span>${t.thinking}</span></div>
874
+ <div class="thinking-content">${marked.parse(thinkingText)}</div>
875
+ </div>
876
+ <div class="pro-response">${marked.parse(text.replace(thinkingText + " instant", ""))}</div>
877
+ `;
878
+ } else if (text) {
879
+ const safeText = String(text);
880
+ contentDiv.innerHTML = isMarkdown ? marked.parse(safeText) : esc(safeText).replace(/\n/g, '<br/>');
881
+ }
882
+
883
+ bub.appendChild(contentDiv);
884
+ row.appendChild(av); row.appendChild(bub);
885
+ area.appendChild(row);
886
+
887
+ // 🟢 تصيير الرياضيات بعد إضافة الفقاعة
888
+ renderMath(bub);
889
+
890
+ scrollToBottom();
891
+ lucide.createIcons();
892
+ return contentDiv;
893
+ }
894
+
895
+ function appendMemBadge(count, total) {
896
+ const area = document.getElementById('chat-area');
897
+ const b = document.createElement('div'); b.className = 'mem-badge';
898
+ b.innerHTML = `<i data-lucide="database"></i> ${i18n[currentLang].memBadge.replace('{c}', count).replace('{t}', total)}`;
899
+ area.appendChild(b); scrollToBottom(); lucide.createIcons();
900
+ }
901
+
902
+ // Initialize
903
+ applyTheme(localStorage.getItem('genisi_theme') || 'dark');
904
+ document.getElementById('lang-select').value = currentLang;
905
+ applyI18n();
906
+
907
+ (function loadSavedModel() {
908
+ const toggleBtn = document.getElementById('model-toggle-btn');
909
+ const icon = document.getElementById('model-icon-input');
910
+ toggleBtn.classList.remove('flash-active', 'pro-active');
911
+ icon.setAttribute('data-lucide', currentModel === 'flash' ? 'zap' : 'brain');
912
+ toggleBtn.classList.add(currentModel === 'flash' ? 'flash-active' : 'pro-active');
913
+ document.querySelectorAll('.model-option-input').forEach(opt => {
914
+ opt.classList.toggle('active', opt.dataset.model === currentModel);
915
+ });
916
+ })();
917
+
918
+ lucide.createIcons();
919
 
920
+ document.addEventListener('click', (e) => {
921
+ const selector = document.querySelector('.model-selector-input');
922
+ const dropdown = document.getElementById('model-dropdown-input');
923
+ if (selector && !selector.contains(e.target) && dropdown.classList.contains('show')) {
924
+ dropdown.classList.remove('show');
925
+ }
926
+ });
927
 
928
+ document.getElementById('sidebar').classList.add('collapsed');
929
+ </script>
930
+ </body>
931
+ </html>