MrA7A commited on
Commit
627bd82
·
verified ·
1 Parent(s): dc547cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +513 -870
app.py CHANGED
@@ -8,13 +8,18 @@ from datetime import datetime
8
  import logging
9
  import re
10
  import os
 
 
 
 
 
11
 
12
  logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
15
- app = FastAPI(title="Windows AI Controller - الخادم المركزي الحقيقي")
16
 
17
- # تمكين CORS للسماح بالاتصال من تطبيبات Windows
18
  app.add_middleware(
19
  CORSMiddleware,
20
  allow_origins=["*"],
@@ -23,32 +28,96 @@ app.add_middleware(
23
  allow_headers=["*"],
24
  )
25
 
26
- # تخزين البيانات - نظام الذاكرة الكامل
27
- pending_commands = {}
28
- client_results = {}
29
- connected_clients = {}
30
-
31
- # نظام الذاكرة الجديد
32
- client_memories = {} # ذاكرة المحادثات لكل عميل
33
- game_analysis_memory = {} # ذاكرة تحليل الألعاب
34
- system_info_memory = {} # ذاكرة معلومات النظام
35
- installed_programs_memory = {} # ذاكرة البرامج المثبتة
36
- action_history_memory = {} # سجل الإجراءات
37
-
38
- class WindowsCommand(BaseModel):
39
- command_type: str
40
- target_game: Optional[str] = None
41
- action: str
42
- parameters: Dict = {}
43
- client_id: str
44
-
45
- class ClientResult(BaseModel):
46
- client_id: str
47
- command_id: str
48
- result: Dict
49
- status: str
50
-
51
- # نماذج جديدة للمحادثة
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  class ChatRequest(BaseModel):
53
  message: str
54
  client_id: str
@@ -68,789 +137,477 @@ class ClientRegistration(BaseModel):
68
  timestamp: str
69
  agent_type: str
70
 
71
- class MemoryEntry(BaseModel):
72
- timestamp: str
73
- type: str # conversation, game_analysis, system_info, action_result, installed_programs
74
- data: Dict[str, Any]
75
- client_id: str
76
-
77
- def update_client_activity(client_id: str, activity: str = "chat"):
78
- """تحديث نشاط العميل"""
79
- connected_clients[client_id] = {
80
- "last_seen": datetime.now().isoformat(),
81
- "status": "active",
82
- "last_activity": activity,
83
- "message_count": connected_clients.get(client_id, {}).get("message_count", 0) + 1
84
- }
85
- logger.info(f"📊 تم تحديث نشاط العميل {client_id}: {activity}")
86
-
87
- def save_to_memory(client_id: str, memory_type: str, data: Dict[str, Any]):
88
- """حفظ البيانات في الذاكرة"""
89
- if client_id not in client_memories:
90
- client_memories[client_id] = []
91
-
92
- memory_entry = {
93
- "timestamp": datetime.now().isoformat(),
94
- "type": memory_type,
95
- "data": data,
96
- "client_id": client_id
97
- }
98
-
99
- client_memories[client_id].append(memory_entry)
100
-
101
- # حفظ فقط آخر 1000 إدخال لكل عميل لمنع استهلاك الذاكرة
102
- if len(client_memories[client_id]) > 1000:
103
- client_memories[client_id] = client_memories[client_id][-1000:]
104
-
105
- logger.info(f"💾 تم حفظ بيانات في الذاكرة للعميل {client_id}: {memory_type}")
106
-
107
- def get_client_memory(client_id: str, memory_type: str = None, limit: int = 10):
108
- """استرجاع الذاكرة للعميل"""
109
- if client_id not in client_memories:
110
- return []
111
-
112
- memories = client_memories[client_id]
113
-
114
- if memory_type:
115
- memories = [m for m in memories if m["type"] == memory_type]
116
-
117
- return memories[-limit:]
118
-
119
- def save_game_analysis(client_id: str, game_name: str, analysis_data: Dict[str, Any]):
120
- """حفظ تحليل اللعبة في الذاكرة"""
121
- if client_id not in game_analysis_memory:
122
- game_analysis_memory[client_id] = {}
123
-
124
- if game_name not in game_analysis_memory[client_id]:
125
- game_analysis_memory[client_id][game_name] = []
126
-
127
- analysis_entry = {
128
- "timestamp": datetime.now().isoformat(),
129
- "analysis_data": analysis_data,
130
- "client_id": client_id
131
- }
132
-
133
- game_analysis_memory[client_id][game_name].append(analysis_entry)
134
-
135
- # أيضا حفظ في الذاكرة العامة
136
- save_to_memory(client_id, "game_analysis", {
137
- "game_name": game_name,
138
- "analysis_data": analysis_data
139
- })
140
-
141
- logger.info(f"🎮 تم حفظ تحليل اللعبة {game_name} للعميل {client_id}")
142
-
143
- def get_game_analysis(client_id: str, game_name: str = None):
144
- """استرجاع تحليل الألعاب"""
145
- if client_id not in game_analysis_memory:
146
- return {}
147
-
148
- if game_name:
149
- return game_analysis_memory[client_id].get(game_name, [])
150
- else:
151
- return game_analysis_memory[client_id]
152
-
153
- def save_system_info(client_id: str, system_info: Dict[str, Any]):
154
- """حفظ معلومات النظام"""
155
- system_info_memory[client_id] = {
156
- "timestamp": datetime.now().isoformat(),
157
- "system_info": system_info
158
- }
159
-
160
- # أيضا حفظ في الذاكرة العامة
161
- save_to_memory(client_id, "system_info", system_info)
162
-
163
- logger.info(f"💻 تم حفظ معلومات النظام للعميل {client_id}")
164
-
165
- def get_system_info(client_id: str):
166
- """استرجاع معلومات النظام"""
167
- return system_info_memory.get(client_id, {})
168
 
169
- def save_installed_programs(client_id: str, programs_data: Dict[str, Any]):
170
- """حفظ البرامج المثبتة"""
171
- installed_programs_memory[client_id] = {
172
- "timestamp": datetime.now().isoformat(),
173
- "programs": programs_data
174
- }
175
-
176
- # أيضا حفظ في الذاكرة العامة
177
- save_to_memory(client_id, "installed_programs", programs_data)
178
-
179
- logger.info(f"📦 تم حفظ بيانات البرامج المثبتة للعميل {client_id}")
180
-
181
- def get_installed_programs(client_id: str):
182
- """استرجاع البرامج المثبتة"""
183
- return installed_programs_memory.get(client_id, {})
184
-
185
- def save_action_history(client_id: str, action_data: Dict[str, Any]):
186
- """حفظ سجل الإجراءات"""
187
- if client_id not in action_history_memory:
188
- action_history_memory[client_id] = []
189
-
190
- action_entry = {
191
- "timestamp": datetime.now().isoformat(),
192
- "action_data": action_data
193
- }
194
-
195
- action_history_memory[client_id].append(action_entry)
196
-
197
- # أيضا حفظ في الذاكرة العامة
198
- save_to_memory(client_id, "action_history", action_data)
199
-
200
- logger.info(f"📝 تم حفظ إجراء في السجل للعميل {client_id}: {action_data.get('action_type', 'unknown')}")
201
-
202
- def get_action_history(client_id: str, limit: int = 20):
203
- """استرجاع سجل الإجراءات"""
204
- if client_id not in action_history_memory:
205
- return []
206
-
207
- return action_history_memory[client_id][-limit:]
208
-
209
- def extract_file_name(file_path: str) -> str:
210
- """استخراج اسم الملف من المسار - الإصلاح هنا"""
211
  try:
212
- if '/' in file_path:
213
- return file_path.split('/')[-1]
214
- elif '\\' in file_path:
215
- return file_path.split('\\')[-1]
216
- else:
217
- return file_path
218
- except Exception:
219
- return file_path
220
-
221
- @app.get("/")
222
- async def root():
223
- total_memories = sum(len(memories) for memories in client_memories.values())
224
- return {
225
- "status": "running",
226
- "service": "Windows AI Controller Server - النسخة الحقيقية مع الذاكرة",
227
- "timestamp": datetime.now().isoformat(),
228
- "connected_clients": len(connected_clients),
229
- "pending_commands": len(pending_commands),
230
- "active_clients": list(connected_clients.keys()),
231
- "total_memories": total_memories,
232
- "memory_stats": {
233
- "conversations": total_memories,
234
- "game_analyses": sum(len(analyses) for analyses in game_analysis_memory.values()),
235
- "system_info": len(system_info_memory),
236
- "installed_programs": len(installed_programs_memory)
237
- }
238
- }
239
-
240
- @app.post("/api/chat")
241
- async def chat_with_ai(request: ChatRequest):
242
- """نقطة النهاية للمحادثة مع الذكاء الاصطناعي - النسخة المحسنة"""
243
- try:
244
- logger.info(f"💬 طلب محادثة من العميل {request.client_id}: {request.message}")
245
- update_client_activity(request.client_id, "chat")
246
-
247
- # حفظ المحادثة في الذاكرة
248
- save_to_memory(request.client_id, "conversation", {
249
- "user_message": request.message,
250
- "timestamp": request.timestamp,
251
- "direction": "incoming"
252
- })
253
-
254
- user_message = request.message.lower()
255
-
256
- # تحليل الطلب وتحديد الإجراءات الحقيقية
257
- if "مسح" in user_message and "برامج" in user_message:
258
- return await handle_scan_programs(request)
259
- elif "مسح" in user_message and "عمليات" in user_message:
260
- return await handle_scan_processes(request)
261
- elif "هندسة عكسية" in user_message or "reverse engineer" in user_message:
262
- return await handle_reverse_engineering(request)
263
- elif "بوت" in user_message or "bot" in user_message:
264
- return await handle_bot_development(request)
265
- elif "شاشة" in user_message or "screenshot" in user_message:
266
- return await handle_screenshot(request)
267
- elif "ذاكرة" in user_message or "memory" in user_message:
268
- return await handle_memory_scan(request)
269
- elif "تثبيت" in user_message or "install" in user_message:
270
- return await handle_tool_installation(request)
271
- elif "الذاكرة" in user_message or "memory" in user_message:
272
- return await handle_memory_query(request)
273
- elif "ماذا تستطيع" in user_message or "الميزات" in user_message or "capabilities" in user_message:
274
- return await handle_capabilities_query(request)
275
- else:
276
- return await handle_general_conversation(request)
277
 
278
  except Exception as e:
279
- logger.error(f"❌ خطأ في معالجة المحادثة: {e}")
280
- raise HTTPException(status_code=500, detail=str(e))
281
 
282
- async def handle_scan_programs(request: ChatRequest):
283
- """معالجة طلب مسح البرامج"""
284
- thinking = "المستخدم يطلب مسح البرامج المثبتة. جاري إعداد أمر المسح الشامل."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
- response = ChatResponse(
287
- thinking_process=thinking,
288
- message="جاري مسح البرامج المثبتة على جهازك...",
289
- actions=[
290
- {
291
- "type": "scan_installed_programs",
292
- "description": "مسح شامل للبرامج المثبتة على النظام",
293
- "parameters": {
294
- "scan_type": "comprehensive",
295
- "include_versions": True,
296
- "save_to_memory": True
297
- }
298
- }
299
- ]
300
- )
301
- return response
302
-
303
- async def handle_scan_processes(request: ChatRequest):
304
- """معالجة طلب مسح العمليات"""
305
- thinking = "المستخدم يريد مسح العمليات النشطة. تحديد العمليات الجارية والألعاب النشطة."
 
 
 
 
 
 
 
306
 
307
- response = ChatResponse(
308
- thinking_process=thinking,
309
- message="جاري مسح العمليات النشطة على جهازك...",
310
- actions=[
311
- {
312
- "type": "scan_running_processes",
313
- "description": "مسح العمليات النشطة على النظام",
314
- "parameters": {
315
- "include_memory_usage": True,
316
- "detect_games": True,
317
- "save_to_memory": True
318
- }
319
- }
320
- ]
321
- )
322
- return response
323
-
324
- async def handle_reverse_engineering(request: ChatRequest):
325
- """معالجة طلب الهندسة العكسية"""
326
- thinking = "المستخدم يطلب هندسة عكسية لملف. تحديد المسار وتحليل المتطلبات."
 
 
 
 
 
327
 
328
- # استخراج مسار الملف من الرسالة
329
- file_path = extract_file_path(request.message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
 
331
- if not file_path:
332
- response = ChatResponse(
333
- thinking_process=thinking + " لم يتم تحديد مسار الملف. طلب التوضيح من المستخدم.",
334
- message="أحتاج إلى مسار الملف للبدء في الهندسة العكسية. مثال: `F:\\Coven Kal\\engine.exe`",
335
- actions=[
336
- {
337
- "type": "prepare_reverse_engineering",
338
- "description": "تحضير بيئة الهندسة العكسية",
339
- "parameters": {}
340
- }
341
- ]
342
- )
343
- else:
344
- # استخراج اسم الملف فقط للعرض - الإصلاح هنا
345
- file_name = extract_file_name(file_path)
346
 
347
- response = ChatResponse(
348
- thinking_process=thinking + f" تم تحديد المسار: {file_path}. جاري إعداد أدوات الهندسة العكسية.",
349
- message=f"جاري تحضير ��لهندسة العكسية للملف: `{file_path}`",
350
- actions=[
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  {
352
- "type": "reverse_engineer",
353
- "description": f"هندسة عكسية متقدمة للملف {file_name}",
354
- "parameters": {
355
- "file_path": file_path,
356
- "analysis_depth": "deep",
357
- "extract_resources": True,
358
- "analyze_imports": True,
359
- "save_to_memory": True
360
- }
361
  },
362
  {
363
- "type": "analyze_game_file",
364
- "description": fحليل بنية ملف اللعبة",
365
- "parameters": {
366
- "file_path": file_path,
367
- "save_to_memory": True
368
- }
369
- }
370
- ]
371
- )
372
-
373
- return response
374
-
375
- async def handle_bot_development(request: ChatRequest):
376
- """معالجة طلب تطوير البوت"""
377
- thinking = "المستخدم يطلب تطوير بوت. تحديد نوع البوت واللعبة المستهدفة."
378
-
379
- game_name = extract_game_name(request.message)
380
- bot_type = extract_bot_type(request.message)
381
-
382
- if not game_name:
383
- response = ChatResponse(
384
- thinking_process=thinking + " لم يتم تحديد اسم اللعبة. طلب التوضيح.",
385
- message="أخبرني اسم اللعبة ونوع البوت المطلوب (مزرعة، قتال، إلخ).",
386
- actions=[
387
- {
388
- "type": "prepare_bot_development",
389
- "description": "تحضير بيئة تطوير البوتات",
390
- "parameters": {}
391
- }
392
- ]
393
- )
394
- else:
395
- response = ChatResponse(
396
- thinking_process=thinking + f" تطوير بوت {bot_type} للعبة {game_name}.",
397
- message=f"بدأت تطوير بوت {bot_type} للعبة {game_name}.",
398
- actions=[
399
- {
400
- "type": "develop_bot",
401
- "description": f"تطوير بوت {bot_type} للعبة {game_name}",
402
- "parameters": {
403
- "game_name": game_name,
404
- "bot_type": bot_type,
405
- "features": ["auto_detection", "memory_control", "image_recognition", "screen_capture"],
406
- "save_to_memory": True
407
- }
408
  }
409
- ]
410
- )
411
-
412
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
 
414
- async def handle_screenshot(request: ChatRequest):
415
- """معالجة طلب تصوير الشاشة"""
416
- thinking = "المستخدم يطلب تصوير شاشة جهازه. إعداد أمر التقاط الصورة."
417
-
418
- response = ChatResponse(
419
- thinking_process=thinking,
420
- message="جاري التقاط صورة لشاشة جهازك...",
421
- actions=[
422
- {
423
- "type": "take_screenshot",
424
- "description": "التقا�� صورة للشاشة الحالية",
425
- "parameters": {
426
- "save_path": f"screenshots/screen_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png",
427
- "save_to_memory": True
428
- }
429
- }
430
- ]
431
- )
432
- return response
433
 
434
- async def handle_memory_scan(request: ChatRequest):
435
- """معالجة طلب مسح الذاكرة"""
436
- thinking = "المستخدم يريد مسح ذاكرة لعبة. تحديد اسم العملية المستهدفة."
437
-
438
- process_name = extract_process_name(request.message)
439
-
440
- if not process_name:
441
- response = ChatResponse(
442
- thinking_process=thinking + " لم يتم تحديد اسم العملية. طلب التوضيح.",
443
- message="أخبرني اسم العملية أو اللعبة التي تريد مسح ذاكرتها.",
444
- actions=[]
445
- )
446
- else:
447
- response = ChatResponse(
448
- thinking_process=thinking + f" مسح ذاكرة العملية: {process_name}.",
449
- message=f"جاري مسح ذاكرة اللعبة: {process_name}",
450
- actions=[
451
- {
452
- "type": "scan_game_memory",
453
- "description": f"مسح ذاكرة العملية {process_name}",
454
- "parameters": {
455
- "process_name": process_name,
456
- "scan_for": ["money", "health", "ammo", "experience"],
457
- "save_to_memory": True
458
- }
459
- }
460
- ]
461
- )
462
-
463
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
 
465
- async def handle_tool_installation(request: ChatRequest):
466
- """معالجة طلب تثبيت الأدوات"""
467
- thinking = "المستخدم يريد تثبيت أداة. تحديد الأداة المطلوبة."
468
 
469
- tool_name = extract_tool_name(request.message)
 
 
 
 
 
 
 
 
 
470
 
471
- if not tool_name:
472
- response = ChatResponse(
473
- thinking_process=thinking + " لم يتم تحديد الأداة. عرض القائمة.",
474
- message="الأدوات المتاحة: cheatengine, python, ida, x64dbg. ما الأداة التي تريدها؟",
475
- actions=[]
476
- )
477
- else:
478
- response = ChatResponse(
479
- thinking_process=thinking + f" تثبيت الأداة: {tool_name}.",
480
- message=f"جاري تثبيت الأداة: {tool_name}",
481
- actions=[
482
- {
483
- "type": "install_tool",
484
- "description": f"تثبيت أداة {tool_name}",
485
- "parameters": {
486
- "tool_name": tool_name,
487
- "save_to_memory": True
488
- }
489
- }
490
- ]
491
- )
492
 
493
- return response
494
-
495
- async def handle_capabilities_query(request: ChatRequest):
496
- """معالجة استعلام الميزات"""
497
- thinking = "المستخدم يطلب معرفة الميزات المتاحة."
498
 
499
- response = ChatResponse(
500
- thinking_process=thinking,
501
- message="**الميزات المتاحة:**\n\n• 🔍 مسح البرامج والعمليات\n• 🎮 تحليل ذاكرة الألعاب\n• 🤖 تطوير البوتات\n• 🔬 الهندسة العكسية\n• 📸 تصوير الشاشة\n• ⚡ تثبيت الأدوات\n\nما الذي تريد القيام به؟",
502
- actions=[]
503
- )
504
- return response
505
 
506
- async def handle_memory_query(request: ChatRequest):
507
- """معالجة استعلامات الذاكرة"""
508
- thinking = "المستخدم يطلب معلومات عن الذاكرة. تجهيز إحصائيات الذاكرة."
509
 
510
- memory_stats = await get_memory_stats_for_client(request.client_id)
511
 
512
- response = ChatResponse(
513
- thinking_process=thinking,
514
- message=f"**إحصائيات الذاكرة:**\n• المحادثات: {memory_stats['conversations']}\n• تحليلات الألعاب: {memory_stats['game_analyses']}\n• الإجراءات: {memory_stats['actions']}",
515
- actions=[]
516
- )
517
- return response
518
 
519
- async def handle_general_conversation(request: ChatRequest):
520
- """معالجة المحادثة العامة - النسخة المحسنة"""
521
- thinking = "تحليل رسالة المستخدم العامة والرد بشكل طبيعي مع تحديد الإجراءات المناسبة."
522
-
523
- # تحليل نية المستخدم من الرسالة
524
- user_intent = analyze_user_intent(request.message)
525
-
526
- if user_intent == "greeting":
527
- response = ChatResponse(
528
- thinking_process=thinking + " المستخدم يرسل تحية. الرد بترحيب بسيط.",
529
- message="مرحباً! كيف يمكنني مساعدتك اليوم؟",
530
- actions=[]
531
- )
532
- elif user_intent == "thanks":
533
- response = ChatResponse(
534
- thinking_process=thinking + " المستخدم يشكر. الرد بأدب.",
535
- message="على الرحب والسعة! هل هناك شيء آخر تحتاج المساعدة فيه؟",
536
- actions=[]
537
- )
538
- elif user_intent == "question":
539
- response = ChatResponse(
540
- thinking_process=thinking + " المستخدم يطرح سؤالاً عاماً. تقديم إجابة مفيدة.",
541
- message="أفهم سؤالك. يمكنني مساعدتك في مهام مثل تحليل البرامج، تطوير البوتات، الهندسة العكسية، وغيرها. هل يمكنك توضيح طلبك أكثر؟",
542
- actions=[]
543
- )
544
- else:
545
- response = ChatResponse(
546
- thinking_process=thinking + " رسالة عامة. الرد بشكل طبيعي وتقديم المساعدة.",
547
- message="فهمت ما تقصد. سأقوم بمساعدتك في هذا الأمر. هل يمكنك إعطائي المزيد من التفاصيل أو توضيح ما تريد بالضبط؟",
548
- actions=[
549
- {
550
- "type": "general_analysis",
551
- "description": "تحليل المهمة العامة وتحديد المتطلبات",
552
- "parameters": {
553
- "user_message": request.message,
554
- "analysis_type": "comprehensive",
555
- "save_to_memory": True
556
- }
557
- }
558
- ]
559
- )
560
-
561
- return response
562
 
563
- def analyze_user_intent(message: str) -> str:
564
- """تحليل نية المستخدم من الرسالة"""
565
- message_lower = message.lower()
566
-
567
- greeting_words = ["مرحبا", "اهلا", "سلام", "السلام", "hello", "hi", "hey"]
568
- thanks_words = ["شكرا", "متشكر", "thanks", "thank you"]
569
- question_words = ["كيف", "لماذا", "متى", "أين", "ماذا", "هل", "?", "what", "how", "when", "where", "why"]
570
-
571
- if any(word in message_lower for word in greeting_words):
572
- return "greeting"
573
- elif any(word in message_lower for word in thanks_words):
574
- return "thanks"
575
- elif any(word in message_lower for word in question_words):
576
- return "question"
577
- else:
578
- return "general"
579
 
580
- async def get_memory_stats_for_client(client_id: str):
581
- """الحصول على إحصائيات الذاكرة للعميل"""
582
- conversations = len(get_client_memory(client_id, "conversation"))
583
- game_analyses = len(get_client_memory(client_id, "game_analysis"))
584
- system_info = 1 if client_id in system_info_memory else 0
585
- installed_programs = 1 if client_id in installed_programs_memory else 0
586
- actions = len(get_action_history(client_id))
587
 
588
- return {
589
- "conversations": conversations,
590
- "game_analyses": game_analyses,
591
- "system_info": system_info,
592
- "installed_programs": installed_programs,
593
- "actions": actions
594
- }
 
595
 
596
- def extract_file_path(message: str) -> str:
597
- """استخراج مسار الملف من الرسالة"""
598
- # البحث عن أنماط المسارات في النص
599
- patterns = [
600
- r'[A-Z]:\\[^\s]+',
601
- r'/[^\s]+',
602
- r'~[^\s]+'
603
- ]
604
-
605
- for pattern in patterns:
606
- matches = re.findall(pattern, message)
607
- if matches:
608
- return matches[0]
609
-
610
- return ""
611
 
612
- def extract_game_name(message: str) -> str:
613
- """استخراج اسم اللعبة من الرسالة"""
614
- games = ["Genshin Impact", "Minecraft", "Among Us", "VALORANT", "Overwatch", "Coven Kal", "Fortnite", "Cyberpunk", "Witcher"]
615
 
616
- for game in games:
617
- if game.lower() in message.lower():
618
- return game
619
-
620
- return ""
 
 
621
 
622
- def extract_bot_type(message: str) -> str:
623
- """استخراج نوع البوت من الرسالة"""
624
- bot_types = {
625
- "مزرعة": "farming",
626
- "زراعة": "farming",
627
- "قتال": "combat",
628
- "قتل": "combat",
629
- "تجارة": "trading",
630
- "تلقائي": "auto",
631
- "حماية": "defense"
632
- }
633
-
634
- for arabic_type, english_type in bot_types.items():
635
- if arabic_type in message:
636
- return english_type
637
-
638
- if "farm" in message.lower():
639
- return "farming"
640
- elif "combat" in message.lower():
641
- return "combat"
642
- elif "trade" in message.lower():
643
- return "trading"
644
-
645
- return "auto"
646
 
647
- def extract_process_name(message: str) -> str:
648
- """استخراج اسم العملية من الرسالة"""
649
- # البحث عن أسماء العمليات الشائعة
650
- common_processes = ["GenshinImpact", "Minecraft", "AmongUs", "VALORANT", "Overwatch", "Fortnite"]
651
-
652
- for process in common_processes:
653
- if process.lower() in message.lower():
654
- return process + ".exe"
655
-
656
- # البحث عن نمط .exe في النص
657
- exe_pattern = r'(\w+\.exe)'
658
- matches = re.findall(exe_pattern, message, re.IGNORECASE)
659
- if matches:
660
- return matches[0]
661
 
662
- return ""
663
 
664
- def extract_tool_name(message: str) -> str:
665
- """استخراج اسم الأداة من الرسالة"""
666
- tools = {
667
- "cheat engine": "cheatengine",
668
- "cheatengine": "cheatengine",
669
- "python": "python",
670
- "ida": "ida",
671
- "x64dbg": "x64dbg",
672
- "process hacker": "processhacker",
673
- "processhacker": "processhacker"
674
- }
675
 
676
- for tool_name, tool_id in tools.items():
677
- if tool_name.lower() in message.lower():
678
- return tool_id
679
 
680
- return ""
681
-
682
- # نقاط النهاية الجديدة للذاكرة
683
- @app.get("/api/memory/{client_id}")
684
- async def get_client_memory_endpoint(client_id: str, memory_type: str = None, limit: int = 10):
685
- """الحصول على ذاكرة العميل"""
686
- try:
687
- memories = get_client_memory(client_id, memory_type, limit)
688
- return {
689
- "success": True,
690
- "client_id": client_id,
691
- "memories": memories,
692
- "total": len(memories)
693
- }
694
- except Exception as e:
695
- logger.error(f"❌ خطأ في استرجاع الذاكرة: {e}")
696
- raise HTTPException(status_code=500, detail=str(e))
697
-
698
- @app.get("/api/game-analysis/{client_id}")
699
- async def get_game_analysis_endpoint(client_id: str, game_name: str = None):
700
- """الحصول على تحليل الألعاب"""
701
- try:
702
- analysis = get_game_analysis(client_id, game_name)
703
- return {
704
- "success": True,
705
- "client_id": client_id,
706
- "game_analysis": analysis
707
- }
708
- except Exception as e:
709
- logger.error(f"❌ خطأ في استرجاع تحليل الألعاب: {e}")
710
- raise HTTPException(status_code=500, detail=str(e))
711
-
712
- @app.post("/api/save-system-info/{client_id}")
713
- async def save_system_info_endpoint(client_id: str, system_info: Dict[str, Any]):
714
- """حفظ معلومات النظام"""
715
  try:
716
- save_system_info(client_id, system_info)
717
- return {
718
- "success": True,
719
- "message": "تم حفظ معلومات النظام بنجاح"
720
- }
721
- except Exception as e:
722
- logger.error(f"❌ خطأ في حفظ معلومات النظام: {e}")
723
- raise HTTPException(status_code=500, detail=str(e))
724
-
725
- @app.get("/api/system-info/{client_id}")
726
- async def get_system_info_endpoint(client_id: str):
727
- """الحصول على معلومات النظام"""
728
- try:
729
- system_info = get_system_info(client_id)
730
- return {
731
- "success": True,
732
- "client_id": client_id,
733
- "system_info": system_info
734
- }
735
- except Exception as e:
736
- logger.error(f"❌ خطأ في استرجاع معلومات النظام: {e}")
737
- raise HTTPException(status_code=500, detail=str(e))
738
-
739
- @app.post("/api/save-installed-programs/{client_id}")
740
- async def save_installed_programs_endpoint(client_id: str, programs_data: Dict[str, Any]):
741
- """حفظ البرامج المثبتة"""
742
- try:
743
- save_installed_programs(client_id, programs_data)
744
- return {
745
- "success": True,
746
- "message": "تم حفظ بيانات البرامج المثبتة بنجاح"
747
- }
748
- except Exception as e:
749
- logger.error(f"❌ خطأ في حفظ البرامج المثبتة: {e}")
750
- raise HTTPException(status_code=500, detail=str(e))
751
-
752
- @app.get("/api/installed-programs/{client_id}")
753
- async def get_installed_programs_endpoint(client_id: str):
754
- """الحصول على البرامج المثبتة"""
755
- try:
756
- programs = get_installed_programs(client_id)
757
  return {
758
- "success": True,
759
- "client_id": client_id,
760
- "installed_programs": programs
 
761
  }
 
762
  except Exception as e:
763
- logger.error(f"❌ خطأ في استرجاع البرامج المثبتة: {e}")
764
- raise HTTPException(status_code=500, detail=str(e))
765
-
766
- @app.post("/api/save-action-result/{client_id}")
767
- async def save_action_result_endpoint(client_id: str, action_result: Dict[str, Any]):
768
- """حفظ نتيجة الإجراء في الذاكرة"""
769
- try:
770
- save_action_history(client_id, action_result)
771
  return {
772
- "success": True,
773
- "message": "تم حفظ نتيجة الإجراء بنجاح"
 
774
  }
775
- except Exception as e:
776
- logger.error(f"❌ خطأ في حفظ نتيجة الإجراء: {e}")
777
- raise HTTPException(status_code=500, detail=str(e))
778
 
779
- @app.get("/api/action-history/{client_id}")
780
- async def get_action_history_endpoint(client_id: str, limit: int = 20):
781
- """الحصول على سجل الإجراءات"""
782
  try:
783
- history = get_action_history(client_id, limit)
784
- return {
785
- "success": True,
786
- "client_id": client_id,
787
- "action_history": history,
788
- "total": len(history)
789
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790
  except Exception as e:
791
- logger.error(f"❌ خطأ في استرجاع سجل الإجراءات: {e}")
792
  raise HTTPException(status_code=500, detail=str(e))
793
 
794
- @app.get("/api/memory-stats")
795
- async def get_memory_stats_endpoint():
796
- """إحصائيات الذاكرة"""
797
- total_memories = sum(len(memories) for memories in client_memories.values())
798
- total_clients = len(client_memories)
799
- total_game_analyses = sum(len(analyses) for analyses in game_analysis_memory.values())
800
- total_system_info = len(system_info_memory)
801
- total_installed_programs = len(installed_programs_memory)
802
 
803
  return {
804
  "success": True,
805
- "total_memories": total_memories,
806
- "total_clients": total_clients,
807
- "total_game_analyses": total_game_analyses,
808
- "total_system_info": total_system_info,
809
- "total_installed_programs": total_installed_programs,
810
- "clients_with_memory": list(client_memories.keys()),
811
- "timestamp": datetime.now().isoformat()
812
  }
813
 
814
- @app.get("/api/client-memory-stats/{client_id}")
815
- async def get_client_memory_stats_endpoint(client_id: str):
816
- """إحصائيات ذاكرة عميل محدد"""
817
  try:
818
- stats = await get_memory_stats_for_client(client_id)
819
  return {
820
  "success": True,
821
- "client_id": client_id,
822
- "memory_stats": stats,
823
- "timestamp": datetime.now().isoformat()
824
  }
825
  except Exception as e:
826
- logger.error(f"❌ خطأ في إحصائيات الذاكرة: {e}")
827
  raise HTTPException(status_code=500, detail=str(e))
828
 
829
- # نقاط النهاية القديمة (محفوظة للتوافق)
 
 
 
 
 
 
 
 
 
 
 
830
  @app.post("/api/register-client")
831
  async def register_client(registration: ClientRegistration):
832
  """تسجيل عميل جديد"""
833
  try:
834
- connected_clients[registration.client_id] = {
835
- "machine_name": registration.machine_name,
836
- "os_version": registration.os_version,
837
- "agent_type": registration.agent_type,
838
- "first_seen": registration.timestamp,
839
- "last_seen": datetime.now().isoformat(),
840
- "status": "active",
841
- "message_count": 0
842
- }
843
-
844
- # حفظ معلومات النظام الأولية في الذاكرة
845
- save_system_info(registration.client_id, {
846
- "machine_name": registration.machine_name,
847
- "os_version": registration.os_version,
848
- "agent_type": registration.agent_type,
849
- "first_seen": registration.timestamp
850
- })
851
-
852
- logger.info(f"🆕 عميل جديد مسجل: {registration.client_id} - {registration.machine_name}")
853
-
854
  return {
855
  "success": True,
856
  "message": "تم تسجيل العميل بنجاح",
@@ -860,136 +617,22 @@ async def register_client(registration: ClientRegistration):
860
  logger.error(f"❌ خطأ في تسجيل العميل: {e}")
861
  raise HTTPException(status_code=500, detail=str(e))
862
 
863
- @app.post("/api/send-command")
864
- async def send_command(command: WindowsCommand):
865
- """استقبال أمر من العميل وتخزينه"""
866
- try:
867
- command_id = f"cmd_{int(time.time())}_{command.client_id}"
868
- pending_commands[command_id] = {
869
- "type": command.command_type,
870
- "action": command.action,
871
- "target_game": command.target_game,
872
- "parameters": command.parameters,
873
- "client_id": command.client_id,
874
- "timestamp": datetime.now().isoformat(),
875
- "status": "pending"
876
- }
877
-
878
- update_client_activity(command.client_id, "command")
879
-
880
- logger.info(f"📨 تم استلام أمر من العميل {command.client_id}: {command.action}")
881
-
882
- return {
883
- "success": True,
884
- "command_id": command_id,
885
- "message": "تم استلام الأمر بنجاح"
886
- }
887
- except Exception as e:
888
- logger.error(f"❌ خطأ في استقبال الأمر: {e}")
889
- raise HTTPException(status_code=500, detail=str(e))
890
-
891
- @app.get("/api/get-commands/{client_id}")
892
- async def get_commands(client_id: str):
893
- """الحصول على الأوامر المعلقة للعميل"""
894
- try:
895
- commands = []
896
- for cmd_id, cmd in pending_commands.items():
897
- if cmd["client_id"] == client_id and cmd["status"] == "pending":
898
- commands.append({
899
- "id": cmd_id,
900
- "type": cmd["type"],
901
- "action": cmd["action"],
902
- "target_game": cmd["target_game"],
903
- "parameters": cmd["parameters"]
904
- })
905
- pending_commands[cmd_id]["status"] = "processing"
906
-
907
- return {"success": True, "commands": commands}
908
- except Exception as e:
909
- logger.error(f"❌ خطأ في إرسال الأوامر: {e}")
910
- raise HTTPException(status_code=500, detail=str(e))
911
-
912
  @app.post("/api/submit-result")
913
- async def submit_result(result: ClientResult):
914
  """استقبال النتائج من العميل"""
915
  try:
916
- client_results[result.client_id] = {
917
- "command_id": result.command_id,
918
- "result": result.result,
919
- "status": result.status,
920
- "timestamp": datetime.now().isoformat()
921
- }
922
-
923
- update_client_activity(result.client_id, "result")
924
-
925
- # حفظ نتيجة الإجراء في الذاكرة
926
- save_action_history(result.client_id, {
927
- "command_id": result.command_id,
928
- "result": result.result,
929
- "status": result.status,
930
- "type": "action_result"
931
- })
932
-
933
- logger.info(f"📊 تم استلام نتيجة من العميل {result.client_id}")
934
-
935
  return {"success": True, "message": "تم استلام النتيجة بنجاح"}
936
  except Exception as e:
937
  logger.error(f"❌ خطأ في استقبال النتيجة: {e}")
938
  raise HTTPException(status_code=500, detail=str(e))
939
 
940
- @app.get("/api/client-status/{client_id}")
941
- async def client_status(client_id: str):
942
- """الحصول على حالة العميل"""
943
- client_data = connected_clients.get(client_id, {})
944
- memory_stats = await get_memory_stats_for_client(client_id)
945
-
946
- return {
947
- "success": True,
948
- "client_id": client_id,
949
- "status": client_data.get("status", "offline"),
950
- "last_seen": client_data.get("last_seen"),
951
- "message_count": client_data.get("message_count", 0),
952
- "memory_stats": memory_stats,
953
- "timestamp": datetime.now().isoformat()
954
- }
955
-
956
- @app.get("/api/system-status")
957
- async def system_status():
958
- """حالة النظام العام"""
959
- active_clients = []
960
- for client_id, data in connected_clients.items():
961
- if data.get("status") == "active":
962
- active_clients.append({
963
- "client_id": client_id,
964
- "machine_name": data.get("machine_name"),
965
- "last_seen": data.get("last_seen"),
966
- "message_count": data.get("message_count", 0)
967
- })
968
-
969
- return {
970
- "success": True,
971
- "status": "running",
972
- "connected_clients": len(connected_clients),
973
- "active_clients": active_clients,
974
- "pending_commands": len(pending_commands),
975
- "total_results": len(client_results),
976
- "total_memories": sum(len(memories) for memories in client_memories.values()),
977
- "memory_system": "active",
978
- "server_time": datetime.now().isoformat()
979
- }
980
-
981
- @app.get("/api/debug-clients")
982
- async def debug_clients():
983
- """تصحيح الأخطاء - عرض جميع العملاء"""
984
- return {
985
- "connected_clients": connected_clients,
986
- "client_memories": {client_id: len(memories) for client_id, memories in client_memories.items()},
987
- "game_analysis_memory": {client_id: len(analyses) for client_id, analyses in game_analysis_memory.items()},
988
- "system_info_memory": list(system_info_memory.keys()),
989
- "installed_programs_memory": list(installed_programs_memory.keys()),
990
- "total": len(connected_clients)
991
- }
992
-
993
  if __name__ == "__main__":
994
  import uvicorn
995
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
8
  import logging
9
  import re
10
  import os
11
+ import requests
12
+ import asyncio
13
+ import aiohttp
14
+ import gc
15
+ import threading
16
 
17
  logging.basicConfig(level=logging.INFO)
18
  logger = logging.getLogger(__name__)
19
 
20
+ app = FastAPI(title="Windows AI Controller - النسخة الذكية المجانية")
21
 
22
+ # تمكين CORS
23
  app.add_middleware(
24
  CORSMiddleware,
25
  allow_origins=["*"],
 
28
  allow_headers=["*"],
29
  )
30
 
31
+ # 🔥 نظام إدارة النماذج الذكي
32
+ class SmartModelManager:
33
+ def __init__(self):
34
+ self.loaded_models = {}
35
+ self.model_lock = threading.Lock()
36
+
37
+ # نماذج Hugging Face المجانية الموصى بها
38
+ self.models_config = {
39
+ "arabic_general": {
40
+ "name": "aubmindlab/aragpt2-mega", # نموذج عربي قوي
41
+ "type": "text-generation",
42
+ "description": "النموذج العربي للفهم العام والردود"
43
+ },
44
+ "coding_expert": {
45
+ "name": "microsoft/DialoGPT-medium", # بديل جيد للبرمجة
46
+ "type": "text-generation",
47
+ "description": "نموذج البرمجة والأمن السيبراني"
48
+ },
49
+ "cyber_security": {
50
+ "name": "google/flan-t5-base", # نموذج متعدد المهام
51
+ "type": "text2text-generation",
52
+ "description": "نموذج الأمن السيبراني المتخصص"
53
+ }
54
+ }
55
+
56
+ def load_model(self, model_type: str):
57
+ """تحميل نموذج من Hugging Face عند الحاجة فقط"""
58
+ with self.model_lock:
59
+ if model_type in self.loaded_models:
60
+ logger.info(f"✅ النموذج {model_type} محمل بالفعل")
61
+ return self.loaded_models[model_type]
62
+
63
+ try:
64
+ logger.info(f"📥 جاري تحميل النموذج {model_type}...")
65
+
66
+ model_config = self.models_config[model_type]
67
+
68
+ if model_config["type"] == "text-generation":
69
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
70
+
71
+ # تحميل النموذج باستخدام pipeline
72
+ model = pipeline(
73
+ "text-generation",
74
+ model=model_config["name"],
75
+ tokenizer=model_config["name"],
76
+ device=-1, # استخدام CPU
77
+ max_length=500,
78
+ do_sample=True,
79
+ temperature=0.7
80
+ )
81
+
82
+ elif model_config["type"] == "text2text-generation":
83
+ from transformers import pipeline
84
+
85
+ model = pipeline(
86
+ "text2text-generation",
87
+ model=model_config["name"],
88
+ max_length=500,
89
+ device=-1
90
+ )
91
+
92
+ self.loaded_models[model_type] = model
93
+ logger.info(f"✅ تم تحميل النموذج {model_type} بنجاح")
94
+ return model
95
+
96
+ except Exception as e:
97
+ logger.error(f"❌ فشل تحميل النموذج {model_type}: {e}")
98
+ return None
99
+
100
+ def unload_model(self, model_type: str):
101
+ """إلغاء تحميل النموذج لتحرير الذاكرة"""
102
+ with self.model_lock:
103
+ if model_type in self.loaded_models:
104
+ del self.loaded_models[model_type]
105
+ gc.collect() # تنظيف الذاكرة
106
+ logger.info(f"🗑️ تم إلغاء تحميل النموذج {model_type}")
107
+
108
+ def unload_all_models(self):
109
+ """إلغاء تحمي�� جميع النماذج"""
110
+ with self.model_lock:
111
+ model_types = list(self.loaded_models.keys())
112
+ for model_type in model_types:
113
+ self.unload_model(model_type)
114
+ logger.info("🧹 تم إلغاء تحميل جميع النماذج")
115
+
116
+ def get_loaded_models(self):
117
+ """الحصول على قائمة النماذج المحملة"""
118
+ return list(self.loaded_models.keys())
119
+
120
+ # هياكل البيانات
121
  class ChatRequest(BaseModel):
122
  message: str
123
  client_id: str
 
137
  timestamp: str
138
  agent_type: str
139
 
140
+ # 🔥 نظام الذاكرة المتقدم
141
+ model_manager = SmartModelManager()
142
+ client_memories = {}
143
+ conversation_contexts = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ # 🔥 نظام البحث المتكامل
146
+ async def search_web(query: str, max_results: int = 3) -> List[Dict]:
147
+ """بحث ذكي على الويب"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  try:
149
+ async with aiohttp.ClientSession() as session:
150
+ # استخدام DuckDuckGo API مجاني
151
+ url = f"https://api.duckduckgo.com/?q={query}&format=json"
152
+
153
+ try:
154
+ async with session.get(url, timeout=10) as response:
155
+ if response.status == 200:
156
+ data = await response.json()
157
+ results = []
158
+
159
+ # استخراج النتائج من DuckDuckGo
160
+ if 'Results' in data:
161
+ for item in data['Results'][:max_results]:
162
+ results.append({
163
+ "title": item.get('Text', ''),
164
+ "url": item.get('FirstURL', ''),
165
+ "snippet": item.get('Text', '')[:200]
166
+ })
167
+
168
+ # إذا لم توجد نتائج، استخدام Abstract
169
+ if not results and 'Abstract' in data:
170
+ results.append({
171
+ "title": data.get('Heading', 'نتيجة البحث'),
172
+ "url": data.get('AbstractURL', ''),
173
+ "snippet": data.get('Abstract', '')[:200]
174
+ })
175
+
176
+ return results
177
+ except:
178
+ pass
179
+
180
+ # استخدام fallback بسيط
181
+ return [
182
+ {
183
+ "title": f"نتائج البحث عن: {query}",
184
+ "url": "",
185
+ "snippet": "يمكنني مساعدتك في هذا الموضوع بناءً على معرفتي التقنية."
186
+ }
187
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
  except Exception as e:
190
+ logger.error(f"❌ خطأ في البحث: {e}")
191
+ return []
192
 
193
+ # 🔥 نظام التفكير المتقدم المحسن
194
+ class AdvancedThinker:
195
+ def __init__(self):
196
+ self.thinking_steps = []
197
+ self.knowledge_base = {
198
+ "cybersecurity": [
199
+ "تعديل الذاكرة: استخدام Cheat Engine، قراءة/كتابة الذاكرة",
200
+ "الهندسة العكسية: IDA Pro، x64dbg، تحليل assembly",
201
+ "تحليل الشبكات: Wireshark، تحليل الحزم",
202
+ "تطوير البوتات: OpenCV للكشف، PyAutoGUI للأتمتة"
203
+ ],
204
+ "game_hacking": [
205
+ "البحث عن القيم في الذاكرة: المال، الصحة، الذخيرة",
206
+ "تعديل المتغيرات: float، int، string",
207
+ "حقن الـ DLL: تعديل السلوك أثناء التشغيل",
208
+ "تخطي الحماية: Anti-Cheat bypass"
209
+ ],
210
+ "programming": [
211
+ "Python: pyautogui, opencv, pymem, requests",
212
+ "C++: كتابة برامج تعديل الذاكرة",
213
+ "C#: تطوير أدوات الويندوز",
214
+ "التجميع: فهم التعليمات المنخفضة المستوى"
215
+ ]
216
+ }
217
 
218
+ def analyze_request(self, user_message: str, context: List[Dict]) -> Dict:
219
+ """تحليل متقدم للطلب"""
220
+ self.thinking_steps = []
221
+
222
+ # الخطوة 1: فهم النية الأساسية
223
+ intent = self._detect_intent(user_message)
224
+ self.thinking_steps.append(f"📝 النية المكتشفة: {intent}")
225
+
226
+ # الخطوة 2: تحليل السياق
227
+ context_analysis = self._analyze_context(context)
228
+ self.thinking_steps.append(f"🔍 تحليل السياق: {context_analysis}")
229
+
230
+ # الخطوة 3: تحديد النموذج المطلوب
231
+ required_model = self._determine_model(intent, user_message)
232
+ self.thinking_steps.append(f"🤖 النموذج المطلوب: {required_model}")
233
+
234
+ # الخطوة 4: تحديد الإجراءات
235
+ required_actions = self._determine_actions(intent, user_message)
236
+ self.thinking_steps.append(f"الإجراءات المطلوبة: {len(required_actions)} إجراء")
237
+
238
+ return {
239
+ "intent": intent,
240
+ "context_analysis": context_analysis,
241
+ "required_model": required_model,
242
+ "required_actions": required_actions,
243
+ "thinking_steps": self.thinking_steps
244
+ }
245
 
246
+ def _detect_intent(self, message: str) -> str:
247
+ """كشف النية بدقة"""
248
+ message_lower = message.lower()
249
+
250
+ intents = {
251
+ "counting": [r'عد\s+من\s+\d+\s+إلى\s+\d+', r'count\s+from\s+\d+\s+to\s+\d+', r'رَقِّم', r'اعدد'],
252
+ "greeting": [رحبا", "اهلا", لام", "hello", "hi", "اهلاً", "أهلاً"],
253
+ "technical_request": ["بوت", "bot", "هندسة", "reverse", "ذاكرة", "memory", "تعديل", "mod"],
254
+ "coding": ["برمجة", "code", "سكريبت", "script", "أكواد", "مشروع", "برمج", "كود"],
255
+ "game_hacking": ["تهكير", "hack", "مخترق", "هاكر", "cheat", "غش", "تعديل لعبة", "هاكينغ"],
256
+ "cybersecurity": ["أمن", "حماية", "اختراق", "هاكر", "hack", "security", "سيبر", "cyber"],
257
+ "question": ["كيف", "لماذا", "متى", "أين", "ماذا", "هل", "?"],
258
+ "research": ["ابحث", "بحث", "information", "معلومات", "دراسة", "أعطيني معلومات"]
259
+ }
260
+
261
+ for intent, patterns in intents.items():
262
+ for pattern in patterns:
263
+ if isinstance(pattern, str):
264
+ if pattern in message_lower:
265
+ return intent
266
+ else: # regex pattern
267
+ if re.search(pattern, message_lower):
268
+ return intent
269
+
270
+ return "general_conversation"
271
 
272
+ def _analyze_context(self, context: List[Dict]) -> str:
273
+ """تحليل سياق المحادثة"""
274
+ if not context:
275
+ return "محادثة جديدة"
276
+
277
+ last_messages = context[-3:]
278
+ topics = []
279
+
280
+ for msg in last_messages:
281
+ user_msg = msg.get('user', '').lower()
282
+ if any(word in user_msg for word in ["بوت", "bot"]):
283
+ topics.append("تطوير البوتات")
284
+ elif any(word in user_msg for word in ["هندسة", "reverse"]):
285
+ topics.append("الهندسة العكسية")
286
+ elif any(word in user_msg for word in ["تهكير", "hack"]):
287
+ topics.append("الأمن السيبراني")
288
+ elif any(word in user_msg for word in ["برمجة", "code"]):
289
+ topics.append("البرمجة")
290
+
291
+ return "، ".join(topics) if topics else "مواضيع عامة"
292
+
293
+ def _determine_model(self, intent: str, message: str) -> str:
294
+ """تحديد النموذج المناسب"""
295
+ if intent in ["coding", "technical_request", "game_hacking"]:
296
+ return "coding_expert"
297
+ elif intent in ["cybersecurity"]:
298
+ return "cyber_security"
299
+ else:
300
+ return "arabic_general"
301
 
302
+ def _determine_actions(self, intent: str, message: str) -> List[Dict]:
303
+ """تحديد الإجراءات المطلوبة"""
304
+ actions = []
 
 
 
 
 
 
 
 
 
 
 
 
305
 
306
+ if intent == "counting":
307
+ # لا يحتاج لإجراءات - سينفذ مباشرة
308
+ pass
309
+ elif intent == "technical_request":
310
+ if "بوت" in message.lower() or "bot" in message.lower():
311
+ actions.append({
312
+ "type": "prepare_bot_development",
313
+ "description": "تحضير بيئة تطوير البوتات المتقدمة",
314
+ "priority": "high"
315
+ })
316
+ if "هندسة" in message.lower() or "reverse" in message.lower():
317
+ actions.append({
318
+ "type": "prepare_reverse_engineering",
319
+ "description": "تحضير أدوات الهندسة العكسية المتقدمة",
320
+ "priority": "high"
321
+ })
322
+ elif intent == "game_hacking":
323
+ actions.extend([
324
  {
325
+ "type": "scan_running_processes",
326
+ "description": "مسح العمليات النشطة للألعاب",
327
+ "priority": "medium"
 
 
 
 
 
 
328
  },
329
  {
330
+ "type": "install_tool",
331
+ "description": "تثبيت أدوات التعديل",
332
+ "parameters": {"tool_name": "cheatengine"},
333
+ "priority": "high"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  }
335
+ ])
336
+ elif intent == "research":
337
+ actions.append({
338
+ "type": "web_research",
339
+ "description": "البحث عن المعلومات المطلوبة",
340
+ "parameters": {"query": message},
341
+ "priority": "medium"
342
+ })
343
+
344
+ # إجراء عام للمحادثة
345
+ if not actions:
346
+ actions.append({
347
+ "type": "general_analysis",
348
+ "description": "تحليل المهمة العامة",
349
+ "priority": "low"
350
+ })
351
+
352
+ return actions
353
 
354
+ # 🔥 النظام الرئيسي المحسن
355
+ thinker = AdvancedThinker()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
+ async def generate_with_model(model_type: str, prompt: str, max_length: int = 500) -> str:
358
+ """توليد النص باستخدام النموذج المحدد"""
359
+ try:
360
+ model = model_manager.load_model(model_type)
361
+ if model is None:
362
+ return f"عذراً، لا يمكن تحميل النموذج {model_type} حالياً."
363
+
364
+ # توليد النص بناءً على نوع النموذج
365
+ if model_type == "arabic_general":
366
+ result = model(
367
+ prompt,
368
+ max_length=max_length,
369
+ num_return_sequences=1,
370
+ temperature=0.7,
371
+ do_sample=True,
372
+ pad_token_id=50256
373
+ )
374
+ response = result[0]['generated_text']
375
+
376
+ elif model_type == "coding_expert":
377
+ result = model(
378
+ prompt,
379
+ max_length=max_length,
380
+ temperature=0.7,
381
+ do_sample=True
382
+ )
383
+ response = result[0]['generated_text']
384
+
385
+ elif model_type == "cyber_security":
386
+ result = model(prompt, max_length=max_length)
387
+ response = result[0]['generated_text']
388
+
389
+ # تنظيف الاستجابة
390
+ response = response.replace(prompt, "").strip()
391
+
392
+ # إلغاء تحميل النموذج بعد الاستخدام لتوفير الذاكرة
393
+ model_manager.unload_model(model_type)
394
+
395
+ return response if response else "أفهم طلبك، ولكن أحتاج إلى مزيد من التوضيح."
396
+
397
+ except Exception as e:
398
+ logger.error(f"❌ خطأ في توليد النص: {e}")
399
+ model_manager.unload_model(model_type) # تنظيف الذاكرة في حالة الخطأ
400
+ return "عذراً، حدث خطأ أثناء المعالجة. هل يمكنك إعادة المحاولة؟"
401
 
402
+ def handle_simple_requests(message: str) -> Optional[str]:
403
+ """معالجة الطلبات البسيطة مباشرة دون نماذج"""
404
+ message_lower = message.lower()
405
 
406
+ # طلبات العد
407
+ counting_match = re.search(r'عد\s+من\s+(\d+)\s+إلى\s+(\d+)', message_lower)
408
+ if counting_match:
409
+ start = int(counting_match.group(1))
410
+ end = int(counting_match.group(2))
411
+ if start < end:
412
+ numbers = " ".join(str(i) for i in range(start, end + 1))
413
+ return f"بالطبع: {numbers}"
414
+ else:
415
+ return "الرقم الأول يجب أن يكون أصغر من الرقم الثاني"
416
 
417
+ # تحيات بسيطة
418
+ if any(word in message_lower for word in ["مرحبا", "اهلا", "سلام", "hello", "hi"]):
419
+ return "مرحباً بك! 🚀 أنا المساعد الذكي المتخصص في الأمن السيبراني وتطوير البوتات. كيف يمكنني مساعدتك اليوم؟"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
 
421
+ # شكر
422
+ if any(word in message_lower for word in ["شكر", "thank", "مشكور"]):
423
+ return "على الرحب والسعة! 😊 هل هناك شيء آخر تحتاج المساعدة فيه؟"
 
 
424
 
425
+ return None
 
 
 
 
 
426
 
427
+ def build_smart_prompt(user_message: str, context: List[Dict], analysis: Dict, model_type: str) -> str:
428
+ """بناء prompt ذكي حسب نوع النموذج"""
 
429
 
430
+ context_text = "\n".join([f"المستخدم: {c['user']}\nالمساعد: {c['assistant']}" for c in context[-2:]])
431
 
432
+ if model_type == "arabic_general":
433
+ prompt = f"""
434
+ أنت مساعد ذكي يتحدث العربية بطلاقة. أنت متخصص في:
435
+ - الأمن السيبراني واختبار الاختراق
436
+ - تطوير البوتات وتعديل الألعاب
437
+ - البرمجة والهندسة العكسية
438
 
439
+ المحادثة السابقة:
440
+ {context_text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
 
442
+ المستخدم: {user_message}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
 
444
+ قم بالرد بشكل طبيعي ومفيد باللغة العربية:
445
+ """
 
 
 
 
 
446
 
447
+ elif model_type == "coding_expert":
448
+ prompt = f"""
449
+ You are an expert AI assistant specialized in:
450
+ - Cybersecurity and penetration testing
451
+ - Game hacking and memory modification
452
+ - Bot development and automation
453
+ - Reverse engineering and malware analysis
454
+ - Programming in Python, C++, C#, Assembly
455
 
456
+ User request: {user_message}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
457
 
458
+ Provide a detailed technical response in Arabic. Include code examples if relevant:
459
+ """
 
460
 
461
+ elif model_type == "cyber_security":
462
+ prompt = f"""
463
+ You are a cybersecurity expert specializing in:
464
+ - Memory hacking and game modification
465
+ - Reverse engineering executable files
466
+ - Developing security tools and bots
467
+ - Network analysis and packet manipulation
468
 
469
+ User: {user_message}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
 
471
+ Provide a professional cybersecurity response in Arabic:
472
+ """
 
 
 
 
 
 
 
 
 
 
 
 
473
 
474
+ return prompt
475
 
476
+ async def get_intelligent_response(user_message: str, client_id: str, context: List[Dict] = None) -> Dict[str, Any]:
477
+ """الحصول على رد ذكي من النموذج المناسب"""
 
 
 
 
 
 
 
 
 
478
 
479
+ if context is None:
480
+ context = []
 
481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482
  try:
483
+ # 🔥 التحليل المتقدم للطلب
484
+ analysis = thinker.analyze_request(user_message, context)
485
+
486
+ # 🔥 التحقق من الطلبات البسيطة أولاً
487
+ simple_response = handle_simple_requests(user_message)
488
+ if simple_response:
489
+ return {
490
+ "response": simple_response,
491
+ "actions": [],
492
+ "thinking": "طلب بسيط - معالجة مباشرة",
493
+ "analysis": analysis
494
+ }
495
+
496
+ # 🔥 البحث إذا لزم الأمر
497
+ search_results = []
498
+ if analysis["intent"] in ["research", "technical_request", "game_hacking"]:
499
+ search_results = await search_web(user_message)
500
+ analysis["thinking_steps"].append(f"🔎 نتائج البحث: {len(search_results)} نتيجة")
501
+
502
+ # 🔥 بناء prompt ذكي
503
+ prompt = build_smart_prompt(user_message, context, analysis, analysis["required_model"])
504
+
505
+ # 🔥 الحصول على الرد من النموذج المناسب
506
+ ai_response = await generate_with_model(analysis["required_model"], prompt)
507
+
508
+ # 🔥 استخراج الإجراءات
509
+ actions = analysis["required_actions"]
510
+
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  return {
512
+ "response": ai_response,
513
+ "actions": actions,
514
+ "thinking": "\n".join(analysis["thinking_steps"]),
515
+ "analysis": analysis
516
  }
517
+
518
  except Exception as e:
519
+ logger.error(f"❌ خطأ في النظام الذكي: {e}")
520
+ # تنظيف الذاكرة في حالة الخطأ
521
+ model_manager.unload_all_models()
 
 
 
 
 
522
  return {
523
+ "response": "أنا هنا لمساعدتك! حدث خطأ تقني بسيط. هل يمكنك إعادة صياغة طلبك؟",
524
+ "actions": [],
525
+ "thinking": f"خطأ في المعالجة: {e}"
526
  }
 
 
 
527
 
528
+ @app.post("/api/chat")
529
+ async def chat_with_ai(request: ChatRequest):
530
+ """نقطة النهاية للمحادثة الذكية المتقدمة"""
531
  try:
532
+ logger.info(f"💬 محادثة متقدمة من {request.client_id}: {request.message}")
533
+
534
+ # تحديث سياق المحادثة
535
+ if request.client_id not in conversation_contexts:
536
+ conversation_contexts[request.client_id] = []
537
+
538
+ context = conversation_contexts[request.client_id]
539
+
540
+ # الحصول على رد ذكي متقدم
541
+ ai_result = await get_intelligent_response(request.message, request.client_id, context)
542
+
543
+ # تحديث السياق
544
+ context.append({
545
+ "user": request.message,
546
+ "assistant": ai_result["response"],
547
+ "timestamp": datetime.now().isoformat()
548
+ })
549
+
550
+ # الحفاظ على آخر 10 رسائل فقط
551
+ if len(context) > 10:
552
+ conversation_contexts[request.client_id] = context[-10:]
553
+
554
+ response = ChatResponse(
555
+ thinking_process=ai_result["thinking"],
556
+ message=ai_result["response"],
557
+ actions=ai_result["actions"]
558
+ )
559
+
560
+ return response
561
+
562
  except Exception as e:
563
+ logger.error(f"❌ خطأ في المحادثة المتقدمة: {e}")
564
  raise HTTPException(status_code=500, detail=str(e))
565
 
566
+ @app.get("/api/system-status")
567
+ async def system_status():
568
+ """حالة النظام مع معلومات النماذج"""
569
+ loaded_models = model_manager.get_loaded_models()
 
 
 
 
570
 
571
  return {
572
  "success": True,
573
+ "status": "running",
574
+ "loaded_models": loaded_models,
575
+ "total_models_available": 3,
576
+ "memory_management": "active",
577
+ "server_time": datetime.now().isoformat()
 
 
578
  }
579
 
580
+ @app.post("/api/cleanup-memory")
581
+ async def cleanup_memory():
582
+ """تنظيف الذاكرة يدوياً"""
583
  try:
584
+ model_manager.unload_all_models()
585
  return {
586
  "success": True,
587
+ "message": "تم تنظ��ف الذاكرة بنجاح",
588
+ "loaded_models": model_manager.get_loaded_models()
 
589
  }
590
  except Exception as e:
591
+ logger.error(f"❌ خطأ في تنظيف الذاكرة: {e}")
592
  raise HTTPException(status_code=500, detail=str(e))
593
 
594
+ # نقاط النهاية الأخرى للتوافق
595
+ @app.get("/")
596
+ async def root():
597
+ loaded_models = model_manager.get_loaded_models()
598
+ return {
599
+ "status": "running",
600
+ "service": "Windows AI Controller - النسخة الذكية المجانية",
601
+ "timestamp": datetime.now().isoformat(),
602
+ "loaded_models": loaded_models,
603
+ "memory_management": "active"
604
+ }
605
+
606
  @app.post("/api/register-client")
607
  async def register_client(registration: ClientRegistration):
608
  """تسجيل عميل جديد"""
609
  try:
610
+ # يمكن إضافة منطق التسجيل هنا
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611
  return {
612
  "success": True,
613
  "message": "تم تسجيل العميل بنجاح",
 
617
  logger.error(f"❌ خطأ في تسجيل العميل: {e}")
618
  raise HTTPException(status_code=500, detail=str(e))
619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  @app.post("/api/submit-result")
621
+ async def submit_result(result: Dict[str, Any]):
622
  """استقبال النتائج من العميل"""
623
  try:
624
+ # يمكن إضافة منطق معالجة النتائج هنا
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
625
  return {"success": True, "message": "تم استلام النتيجة بنجاح"}
626
  except Exception as e:
627
  logger.error(f"❌ خطأ في استقبال النتيجة: {e}")
628
  raise HTTPException(status_code=500, detail=str(e))
629
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630
  if __name__ == "__main__":
631
  import uvicorn
632
+ port = int(os.getenv("PORT", 7860))
633
+ uvicorn.run(
634
+ "server:app",
635
+ host="0.0.0.0",
636
+ port=port,
637
+ reload=True
638
+ )