MrA7A commited on
Commit
0ea2dda
·
verified ·
1 Parent(s): a4b9b7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -481
app.py CHANGED
@@ -28,52 +28,38 @@ app.add_middleware(
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
- "trust_remote_code": True
44
  },
45
  "coding_expert": {
46
- "name": "microsoft/DialoGPT-medium",
47
- "type": "text-generation",
48
  "description": "نموذج البرمجة والأمن السيبراني",
49
- "trust_remote_code": False
50
  },
51
  "cyber_security": {
52
- "name": "google/flan-t5-base",
53
- "type": "text2text-generation",
54
  "description": "نموذج الأمن السيبراني المتخصص",
55
- "trust_remote_code": False
56
  }
57
  }
58
-
59
- # تحميل النماذج مسبقاً عند بدء التشغيل
60
- self.preload_models()
61
-
62
- def preload_models(self):
63
- """تحميل النماذج الأساسية مسبقاً"""
64
- logger.info("🔄 جاري تحميل النماذج الأساسية مسبقاً...")
65
- try:
66
- # تحميل النموذج العربي أولاً
67
- self.load_model("arabic_general")
68
- logger.info("✅ تم تحميل النماذج الأساسية بنجاح")
69
- except Exception as e:
70
- logger.error(f"❌ فشل التحميل المسبق: {e}")
71
 
72
  def load_model(self, model_type: str):
73
- """تحميل نموذج من Hugging Face مع معالجة الأخطاء المحسنة"""
74
  with self.model_lock:
75
  if model_type in self.loaded_models:
76
- logger.info(f"✅ النموذج {model_type} محمل بالفعل")
77
  return self.loaded_models[model_type]
78
 
79
  try:
@@ -82,19 +68,16 @@ class SmartModelManager:
82
  model_config = self.models_config[model_type]
83
 
84
  if model_config["type"] == "text-generation":
85
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
86
 
87
- # تحميل النموذج مع trust_remote_code إذا لزم الأمر
88
  model = pipeline(
89
  "text-generation",
90
  model=model_config["name"],
91
- tokenizer=model_config["name"],
92
  device=-1, # استخدام CPU
93
- max_length=500,
94
  do_sample=True,
95
  temperature=0.7,
96
- trust_remote_code=model_config.get("trust_remote_code", False),
97
- torch_dtype='auto'
98
  )
99
 
100
  elif model_config["type"] == "text2text-generation":
@@ -103,10 +86,9 @@ class SmartModelManager:
103
  model = pipeline(
104
  "text2text-generation",
105
  model=model_config["name"],
106
- max_length=500,
107
  device=-1,
108
- trust_remote_code=model_config.get("trust_remote_code", False),
109
- torch_dtype='auto'
110
  )
111
 
112
  self.loaded_models[model_type] = model
@@ -115,63 +97,10 @@ class SmartModelManager:
115
 
116
  except Exception as e:
117
  logger.error(f"❌ فشل تحميل النموذج {model_type}: {e}")
118
- # استخدام نموذج بديل في حالة الفشل
119
- return self.load_fallback_model(model_type)
120
-
121
- def load_fallback_model(self, model_type: str):
122
- """تحميل نموذج بديل في حالة فشل النموذج الرئيسي"""
123
- logger.info(f"🔄 استخدام نموذج بديل لـ {model_type}")
124
-
125
- fallback_models = {
126
- "arabic_general": {
127
- "name": "microsoft/DialoGPT-small",
128
- "type": "text-generation",
129
- "trust_remote_code": False
130
- },
131
- "coding_expert": {
132
- "name": "microsoft/DialoGPT-small",
133
- "type": "text-generation",
134
- "trust_remote_code": False
135
- },
136
- "cyber_security": {
137
- "name": "google/flan-t5-small",
138
- "type": "text2text-generation",
139
- "trust_remote_code": False
140
- }
141
- }
142
-
143
- try:
144
- fallback_config = fallback_models[model_type]
145
-
146
- if fallback_config["type"] == "text-generation":
147
- from transformers import pipeline
148
- model = pipeline(
149
- "text-generation",
150
- model=fallback_config["name"],
151
- device=-1,
152
- max_length=400,
153
- trust_remote_code=fallback_config.get("trust_remote_code", False)
154
- )
155
- else:
156
- from transformers import pipeline
157
- model = pipeline(
158
- "text2text-generation",
159
- model=fallback_config["name"],
160
- device=-1,
161
- max_length=400,
162
- trust_remote_code=fallback_config.get("trust_remote_code", False)
163
- )
164
-
165
- self.loaded_models[model_type] = model
166
- logger.info(f"✅ تم تحميل النموذج البديل لـ {model_type}")
167
- return model
168
-
169
- except Exception as e:
170
- logger.error(f"❌ فشل تحميل النموذج البديل: {e}")
171
- return None
172
 
173
  def unload_model(self, model_type: str):
174
- """إلغاء تحميل النموذج لتحرير الذاكرة"""
175
  with self.model_lock:
176
  if model_type in self.loaded_models:
177
  del self.loaded_models[model_type]
@@ -181,14 +110,8 @@ class SmartModelManager:
181
  def unload_all_models(self):
182
  """إلغاء تحميل جميع النماذج"""
183
  with self.model_lock:
184
- model_types = list(self.loaded_models.keys())
185
- for model_type in model_types:
186
  self.unload_model(model_type)
187
- logger.info("🧹 تم إلغاء تحميل جميع النماذج")
188
-
189
- def get_loaded_models(self):
190
- """الحصول على قائمة النماذج المحملة"""
191
- return list(self.loaded_models.keys())
192
 
193
  # هياكل البيانات
194
  class ChatRequest(BaseModel):
@@ -212,433 +135,183 @@ class ClientRegistration(BaseModel):
212
 
213
  # 🔥 نظام الذاكرة المتقدم
214
  model_manager = SmartModelManager()
215
- client_memories = {}
216
  conversation_contexts = {}
217
 
218
- # 🔥 نظام البحث المتكامل المحسن
219
- async def search_web(query: str, max_results: int = 3) -> List[Dict]:
220
- """بحث ذكي على الويب مع معالجة محسنة للأخطاء"""
221
- try:
222
- async with aiohttp.ClientSession() as session:
223
- # استخدام DuckDuckGo API مجاني
224
- url = f"https://api.duckduckgo.com/?q={query}&format=json"
225
-
226
- try:
227
- async with session.get(url, timeout=10) as response:
228
- if response.status == 200:
229
- data = await response.json()
230
- results = []
231
-
232
- # استخراج النتائج من DuckDuckGo
233
- if 'Results' in data:
234
- for item in data['Results'][:max_results]:
235
- results.append({
236
- "title": item.get('Text', ''),
237
- "url": item.get('FirstURL', ''),
238
- "snippet": item.get('Text', '')[:200]
239
- })
240
-
241
- # إذا لم توجد نتائج، استخدام Abstract
242
- if not results and 'Abstract' in data:
243
- results.append({
244
- "title": data.get('Heading', 'نتيجة البحث'),
245
- "url": data.get('AbstractURL', ''),
246
- "snippet": data.get('Abstract', '')[:200]
247
- })
248
-
249
- return results
250
- except Exception as e:
251
- logger.warning(f"⚠️ خطأ في البحث من DuckDuckGo: {e}")
252
-
253
- # استخدام fallback محسن
254
- return [
255
- {
256
- "title": f"نتائج البحث عن: {query}",
257
- "url": "",
258
- "snippet": "أقوم بمعالجة طلبك بناءً على معرفتي التقنية في الأمن السيبراني وتطوير البوتات."
259
- }
260
- ]
261
-
262
- except Exception as e:
263
- logger.error(f"❌ خطأ في البحث: {e}")
264
- return []
265
-
266
- # 🔥 نظام التفكير المتقدم المحسن
267
  class AdvancedThinker:
268
  def __init__(self):
269
  self.thinking_steps = []
270
- self.knowledge_base = {
271
- "cybersecurity": [
272
- "تعديل الذاكرة: استخدام Cheat Engine، قراءة/كتابة الذاكرة",
273
- "الهندسة العكسية: IDA Pro، x64dbg، تحليل assembly",
274
- "تحليل الشبكات: Wireshark، تحليل الحزم",
275
- "تطوير البوتات: OpenCV للكشف، PyAutoGUI للأتمتة"
276
- ],
277
- "game_hacking": [
278
- "البحث عن القيم في الذاكرة: المال، الصحة، الذخيرة",
279
- "تعديل المتغيرات: float، int، string",
280
- "حقن الـ DLL: تعديل السلوك أثناء التشغيل",
281
- "تخطي الحماية: Anti-Cheat bypass"
282
- ],
283
- "programming": [
284
- "Python: pyautogui, opencv, pymem, requests",
285
- "C++: كتابة برامج تعديل الذاكرة",
286
- "C#: تطوير أدوات الويندوز",
287
- "التجميع: فهم التعليمات المنخفضة المستوى"
288
- ]
289
- }
290
 
291
- def analyze_request(self, user_message: str, context: List[Dict]) -> Dict:
292
- """تحليل متقدم للطلب مع معالجة محسنة"""
293
  self.thinking_steps = []
294
 
295
- # الخطوة 1: فهم النية الأساسية
296
  intent = self._detect_intent(user_message)
297
  self.thinking_steps.append(f"📝 النية المكتشفة: {intent}")
298
 
299
- # الخطوة 2: تحليل السياق
300
- context_analysis = self._analyze_context(context)
301
- self.thinking_steps.append(f"🔍 تحليل السياق: {context_analysis}")
302
-
303
- # الخطوة 3: تحديد النموذج المطلوب
304
- required_model = self._determine_model(intent, user_message)
305
  self.thinking_steps.append(f"🤖 النموذج المطلوب: {required_model}")
306
 
307
- # الخطوة 4: تحديد الإجراءات
308
  required_actions = self._determine_actions(intent, user_message)
309
  self.thinking_steps.append(f"⚡ الإجراءات المطلوبة: {len(required_actions)} إجراء")
310
 
311
  return {
312
  "intent": intent,
313
- "context_analysis": context_analysis,
314
  "required_model": required_model,
315
  "required_actions": required_actions,
316
  "thinking_steps": self.thinking_steps
317
  }
318
 
319
  def _detect_intent(self, message: str) -> str:
320
- """كشف النية بدقة محسنة"""
321
  message_lower = message.lower()
322
 
323
- intents = {
324
- "counting": [r'عد\s+من\s+\d+\s+إلى\s+\d+', r'count\s+from\s+\d+\s+to\s+\d+', r'رَقِّم', r'اعدد'],
325
- "greeting": ["مرحبا", "اهلا", "سلام", "hello", "hi", "اهلاً", "أهلاً", "السلام عليكم"],
326
- "technical_request": ["بوت", "bot", "هندسة", "reverse", "ذاكرة", "memory", "تعديل", "mod", "تطوير"],
327
- "coding": ["برمجة", "code", "سكريبت", "script", "أكواد", "مشروع", "برمج", "كود", "برنامج"],
328
- "game_hacking": ["تهكير", "hack", "مخترق", "هاكر", "cheat", "غش", "تعديل لعبة", "هاكينغ", "تعديل"],
329
- "cybersecurity": ["أمن", "حماية", "اختراق", "هاكر", "hack", "security", "سيبر", "cyber", "حماية"],
330
- "question": ["كيف", "لماذا", "متى", "أين", "ماذا", "هل", "?", "يعني", "شرح"],
331
- "research": ["ابحث", "بحث", "information", "معلومات", "دراسة", "أعطيني معلومات", "بحث عن"]
332
- }
333
-
334
- for intent, patterns in intents.items():
335
- for pattern in patterns:
336
- if isinstance(pattern, str):
337
- if pattern in message_lower:
338
- return intent
339
- else: # regex pattern
340
- if re.search(pattern, message_lower):
341
- return intent
342
-
343
- return "general_conversation"
344
-
345
- def _analyze_context(self, context: List[Dict]) -> str:
346
- """تحليل سياق المحادثة المحسن"""
347
- if not context:
348
- return "محادثة جديدة"
349
-
350
- last_messages = context[-3:]
351
- topics = []
352
-
353
- for msg in last_messages:
354
- user_msg = msg.get('user', '').lower()
355
- if any(word in user_msg for word in ["بوت", "bot", "تطوير"]):
356
- topics.append("تطوير البوتات")
357
- elif any(word in user_msg for word in ["هندسة", "reverse", "عكسية"]):
358
- topics.append("الهندسة العكسية")
359
- elif any(word in user_msg for word in ["تهكير", "hack", "تعديل"]):
360
- topics.append("الأمن السيبراني")
361
- elif any(word in user_msg for word in ["برمجة", "code", "سكريبت"]):
362
- topics.append("البرمجة")
363
- elif any(word in user_msg for word in ["بحث", "معلومات", "ابحث"]):
364
- topics.append("البحث والمعلومات")
365
-
366
- return "، ".join(topics) if topics else "مواضيع عامة"
367
-
368
- def _determine_model(self, intent: str, message: str) -> str:
369
- """تحديد النموذج المناسب مع تحسين الدقة"""
370
- if intent in ["coding", "technical_request", "game_hacking"]:
371
- return "coding_expert"
372
- elif intent in ["cybersecurity", "research"]:
373
- return "cyber_security"
374
  else:
375
- return "arabic_general"
 
 
 
 
 
 
 
 
 
 
 
376
 
377
  def _determine_actions(self, intent: str, message: str) -> List[Dict]:
378
- """تحديد الإجراءات المطلوبة مع تحسين الدقة"""
379
  actions = []
380
 
381
- if intent == "counting":
382
- # لا يحتاج لإجراءات - سينفذ مباشرة
383
- pass
384
- elif intent == "technical_request":
385
- if any(word in message.lower() for word in ["بوت", "bot", "تطوير"]):
386
- actions.append({
387
- "type": "prepare_bot_development",
388
- "description": "تحضير بيئة تطوير البوتات المتقدمة",
389
- "priority": "high"
390
- })
391
- if any(word in message.lower() for word in ["هندسة", "reverse", "عكسية"]):
392
- actions.append({
393
- "type": "prepare_reverse_engineering",
394
- "description": "تحضير أدوات الهندسة العكسية المتقدمة",
395
- "priority": "high"
396
- })
397
- elif intent == "game_hacking":
398
- actions.extend([
399
- {
400
- "type": "scan_running_processes",
401
- "description": "مسح العمليات النشطة للألعاب",
402
- "priority": "medium"
403
- },
404
- {
405
- "type": "install_tool",
406
- "description": "تثبيت أدوات التعديل",
407
- "parameters": {"tool_name": "cheatengine"},
408
- "priority": "high"
409
- }
410
- ])
411
  elif intent == "research":
412
  actions.append({
413
- "type": "web_research",
414
  "description": "البحث عن المعلومات المطلوبة",
415
  "parameters": {"query": message},
416
  "priority": "medium"
417
  })
418
 
419
- # إجراء عام للمحادثة
420
- if not actions:
421
- actions.append({
422
- "type": "general_analysis",
423
- "description": "تحليل المهمة العامة",
424
- "priority": "low"
425
- })
426
-
427
  return actions
428
 
429
- # 🔥 النظام الرئيسي المحسن
430
  thinker = AdvancedThinker()
431
 
432
- async def generate_with_model(model_type: str, prompt: str, max_length: int = 500) -> str:
433
- """توليد النص باستخدام النموذج المحدد مع معالجة محسنة للأخطاء"""
434
  try:
 
435
  model = model_manager.load_model(model_type)
436
- if model is None:
437
- return f"أفهم طلبك، وأستطيع مساعدتك في هذا الموضوع. دعني أوضح لك كيفية التعامل مع: {prompt.split(':')[-1].strip()}"
438
 
439
- # توليد النص بناءً على نوع النموذج
440
- try:
441
- if model_type == "arabic_general":
442
- result = model(
443
- prompt,
444
- max_length=max_length,
445
- num_return_sequences=1,
446
- temperature=0.7,
447
- do_sample=True,
448
- pad_token_id=50256
449
- )
450
- response = result[0]['generated_text']
451
-
452
- elif model_type == "coding_expert":
453
- result = model(
454
- prompt,
455
- max_length=max_length,
456
- temperature=0.7,
457
- do_sample=True
458
- )
459
- response = result[0]['generated_text']
460
-
461
- elif model_type == "cyber_security":
462
- result = model(prompt, max_length=max_length)
463
- response = result[0]['generated_text']
464
-
465
- # تنظيف الاستجابة
466
- response = response.replace(prompt, "").strip()
467
-
468
- return response if response else "أفهم طلبك، وأحتاج إلى مزيد من التفاصيل لتقديم المساعدة المثلى."
469
-
470
- except Exception as generation_error:
471
- logger.error(f"❌ خطأ في توليد النص: {generation_error}")
472
- return "أستطيع مساعدتك في هذا الموضوع. دعني أوضح لك الطرق المثلى للتعامل مع هذه المهمة."
473
 
474
  except Exception as e:
475
  logger.error(f"❌ خطأ في توليد النص: {e}")
476
- return "مرحباً! أنا هنا لمساعدتك في مجالات الأمن السيبراني وتطوير البوتات والبرمجة. ما الذي تريد تحقيقه بالتحديد؟"
 
 
 
477
 
478
- def handle_simple_requests(message: str) -> Optional[str]:
479
- """معالجة الطلبات البسيطة مباشرة دون نماذج"""
480
- message_lower = message.lower()
481
-
482
- # طلبات العد
483
- counting_match = re.search(r'عد\s+من\s+(\d+)\s+إلى\s+(\d+)', message_lower)
484
- if counting_match:
485
- start = int(counting_match.group(1))
486
- end = int(counting_match.group(2))
487
- if start < end:
488
- numbers = " ".join(str(i) for i in range(start, end + 1))
489
- return f"بالطبع: {numbers}"
490
- else:
491
- return "الرقم الأول يجب أن يكون أصغر من الرقم الثاني"
492
-
493
- # تحيات بسيطة
494
- if any(word in message_lower for word in ["مرحبا", "اهلا", "سلام", "hello", "hi", "السلام عليكم"]):
495
- return "مرحباً بك! 🚀 أنا المساعد الذكي المتخصص في الأمن السيبراني وتطوير البوتات والبرمجة. كيف يمكنني مساعدتك اليوم؟"
496
-
497
- # شكر
498
- if any(word in message_lower for word in ["شكر", "thank", "مشكور", "thanks"]):
499
- return "على الرحب والسعة! 😊 أنا هنا لمساعدتك في أي وقت. هل هناك شيء آخر تحتاج المساعدة فيه؟"
500
-
501
- # سؤال عن الحالة
502
- if any(word in message_lower for word in ["كيف حالك", "اخبارك", "شونك"]):
503
- return "أنا بخير، شكراً لسؤالك! 🤖 مستعد لمساعدتك في مجالات الأمن السيبراني، تطوير البوتات، البرمجة، والهندسة العكسية. ما الذي تريد العمل عليه؟"
504
-
505
- return None
506
-
507
- def build_smart_prompt(user_message: str, context: List[Dict], analysis: Dict, model_type: str) -> str:
508
  """بناء prompt ذكي حسب نوع النموذج"""
509
 
510
- context_text = "\n".join([f"المستخدم: {c['user']}\nالمساعد: {c['assistant']}" for c in context[-2:]]) if context else "لا يوجد محادثة سابقة"
511
-
512
  if model_type == "arabic_general":
513
  prompt = f"""
514
- أنت مساعد ذكي يتحدث العربية بطلاقة. أنت متخصص في:
515
- - الأمن السيبراني واختبار الاختراق
516
- - تطوير البوتات وتعديل الألعاب
517
- - البرمجة والهندسة العكسية
518
- - تحليل الذاكرة والعمليات
519
-
520
- المحادثة السابقة:
521
- {context_text}
522
 
523
  طلب المستخدم: {user_message}
524
 
525
- قم بالرد بشكل طبيعي ومفيد باللغة العربية، مع تقديم نصائح عملية وقابلة للتنفيذ:
526
  """
527
 
528
  elif model_type == "coding_expert":
529
  prompt = f"""
530
- You are an expert AI assistant specialized in:
531
- - Cybersecurity and penetration testing
532
- - Game hacking and memory modification
533
- - Bot development and automation
534
- - Reverse engineering and malware analysis
535
- - Programming in Python, C++, C#, Assembly
536
-
537
- Context: {context_text}
538
 
539
  User request: {user_message}
540
 
541
- Provide a detailed technical response in Arabic. Include practical steps and code examples if relevant:
542
  """
543
 
544
- elif model_type == "cyber_security":
545
  prompt = f"""
546
- You are a cybersecurity expert specializing in:
547
- - Memory hacking and game modification
548
- - Reverse engineering executable files
549
- - Developing security tools and bots
550
- - Network analysis and packet manipulation
551
-
552
- Context: {context_text}
553
 
554
  User: {user_message}
555
 
556
- Provide a professional cybersecurity response in Arabic with actionable advice:
557
  """
558
 
559
  return prompt
560
 
561
- async def get_intelligent_response(user_message: str, client_id: str, context: List[Dict] = None) -> Dict[str, Any]:
562
- """الحصول على رد ذكي من النموذج المناسب مع معالجة محسنة"""
563
-
564
- if context is None:
565
- context = []
566
 
567
  try:
568
  # 🔥 التحليل المتقدم للطلب
569
- analysis = thinker.analyze_request(user_message, context)
570
-
571
- # 🔥 التحقق من الطلبات البسيطة أولاً
572
- simple_response = handle_simple_requests(user_message)
573
- if simple_response:
574
- return {
575
- "response": simple_response,
576
- "actions": [],
577
- "thinking": "طلب بسيط - معالجة مباشرة",
578
- "analysis": analysis
579
- }
580
-
581
- # 🔥 البحث إذا لزم الأمر
582
- search_results = []
583
- if analysis["intent"] in ["research", "technical_request", "game_hacking", "cybersecurity"]:
584
- search_results = await search_web(user_message)
585
- analysis["thinking_steps"].append(f"🔎 نتائج البحث: {len(search_results)} نتيجة")
586
 
587
  # 🔥 بناء prompt ذكي
588
- prompt = build_smart_prompt(user_message, context, analysis, analysis["required_model"])
589
 
590
  # 🔥 الحصول على الرد من النموذج المناسب
591
  ai_response = await generate_with_model(analysis["required_model"], prompt)
592
 
593
- # 🔥 استخراج الإجراءات
594
- actions = analysis["required_actions"]
595
-
596
  return {
597
  "response": ai_response,
598
- "actions": actions,
599
- "thinking": "\n".join(analysis["thinking_steps"]),
600
- "analysis": analysis
601
  }
602
 
603
  except Exception as e:
604
  logger.error(f"❌ خطأ في النظام الذكي: {e}")
605
- # تنظيف الذاكرة في حالة الخطأ
606
- model_manager.unload_all_models()
607
- return {
608
- "response": "مرحباً! أنا هنا لمساعدتك في مجالات الأمن السيبراني، تطوير البوتات، والبرمجة. دعني أعرف ما الذي تريد تحقيقه وسأقدم لك أفضل الحلول.",
609
- "actions": [{
610
- "type": "general_analysis",
611
- "description": "تحليل النظام الأساسي",
612
- "priority": "low"
613
- }],
614
- "thinking": f"خطأ في المعالجة: {e}"
615
- }
616
 
617
  @app.post("/api/chat")
618
  async def chat_with_ai(request: ChatRequest):
619
- """نقطة النهاية للمحادثة الذكية المتقدمة"""
620
  try:
621
- logger.info(f"💬 محادثة متقدمة من {request.client_id}: {request.message}")
622
-
623
- # تحديث سياق المحادثة
624
- if request.client_id not in conversation_contexts:
625
- conversation_contexts[request.client_id] = []
626
-
627
- context = conversation_contexts[request.client_id]
628
-
629
- # الحصول على رد ذكي متقدم
630
- ai_result = await get_intelligent_response(request.message, request.client_id, context)
631
-
632
- # تحديث السياق
633
- context.append({
634
- "user": request.message,
635
- "assistant": ai_result["response"],
636
- "timestamp": datetime.now().isoformat()
637
- })
638
 
639
- # الحفاظ على آخر 10 رسائل فقط
640
- if len(context) > 10:
641
- conversation_contexts[request.client_id] = context[-10:]
642
 
643
  response = ChatResponse(
644
  thinking_process=ai_result["thinking"],
@@ -649,88 +322,53 @@ async def chat_with_ai(request: ChatRequest):
649
  return response
650
 
651
  except Exception as e:
652
- logger.error(f"❌ خطأ في المحادثة المتقدمة: {e}")
653
  raise HTTPException(status_code=500, detail=str(e))
654
 
655
  @app.get("/api/system-status")
656
  async def system_status():
657
- """حالة النظام مع معلومات النماذج"""
658
- loaded_models = model_manager.get_loaded_models()
659
-
660
  return {
661
  "success": True,
662
  "status": "running",
663
- "loaded_models": loaded_models,
664
- "total_models_available": 3,
665
  "memory_management": "active",
666
  "server_time": datetime.now().isoformat()
667
  }
668
 
669
  @app.post("/api/cleanup-memory")
670
  async def cleanup_memory():
671
- """تنظيف الذاكرة يدوياً"""
672
  try:
673
  model_manager.unload_all_models()
674
- return {
675
- "success": True,
676
- "message": "تم تنظيف الذاكرة بنجاح",
677
- "loaded_models": model_manager.get_loaded_models()
678
- }
679
  except Exception as e:
680
- logger.error(f"❌ خطأ في تنظيف الذاكرة: {e}")
681
  raise HTTPException(status_code=500, detail=str(e))
682
 
683
- # نقاط النهاية الأخرى للتوافق
684
  @app.get("/")
685
  async def root():
686
- loaded_models = model_manager.get_loaded_models()
687
  return {
688
  "status": "running",
689
- "service": "Windows AI Controller - النسخة الذكية المجانية",
690
- "timestamp": datetime.now().isoformat(),
691
- "loaded_models": loaded_models,
692
- "memory_management": "active"
693
  }
694
 
695
  @app.post("/api/register-client")
696
  async def register_client(registration: ClientRegistration):
697
  """تسجيل عميل جديد"""
698
- try:
699
- client_memories[registration.client_id] = {
700
- "machine_name": registration.machine_name,
701
- "os_version": registration.os_version,
702
- "registration_time": datetime.now().isoformat(),
703
- "agent_type": registration.agent_type
704
- }
705
- return {
706
- "success": True,
707
- "message": "تم تسجيل العميل بنجاح",
708
- "client_id": registration.client_id
709
- }
710
- except Exception as e:
711
- logger.error(f"❌ خطأ في تسجيل العميل: {e}")
712
- raise HTTPException(status_code=500, detail=str(e))
713
 
714
  @app.post("/api/submit-result")
715
  async def submit_result(result: Dict[str, Any]):
716
  """استقبال النتائج من العميل"""
717
- try:
718
- client_id = result.get("client_id")
719
- action_result = result.get("result", {})
720
-
721
- logger.info(f"📥 نتيجة من {client_id}: {action_result}")
722
-
723
- return {"success": True, "message": "تم استلام النتيجة بنجاح"}
724
- except Exception as e:
725
- logger.error(f"❌ خطأ في استقبال النتيجة: {e}")
726
- raise HTTPException(status_code=500, detail=str(e))
727
 
728
  if __name__ == "__main__":
729
  import uvicorn
730
  port = int(os.getenv("PORT", 7860))
731
- uvicorn.run(
732
- app,
733
- host="0.0.0.0",
734
- port=port,
735
- reload=True
736
- )
 
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 صغيرة الحجم (أقل من 2GB)
38
  self.models_config = {
39
  "arabic_general": {
40
+ "name": "UBC-NLP/AraT5-base", # نموذج عربي صغير 1.2GB
41
+ "type": "text2text-generation",
42
  "description": "النموذج العربي للفهم العام والردود",
43
+ "max_length": 512
44
  },
45
  "coding_expert": {
46
+ "name": "microsoft/DialoGPT-small", # نموذج صغير 500MB
47
+ "type": "text-generation",
48
  "description": "نموذج البرمجة والأمن السيبراني",
49
+ "max_length": 400
50
  },
51
  "cyber_security": {
52
+ "name": "google/flan-t5-small", # نموذج صغير 300MB
53
+ "type": "text2text-generation",
54
  "description": "نموذج الأمن السيبراني المتخصص",
55
+ "max_length": 512
56
  }
57
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  def load_model(self, model_type: str):
60
+ """تحميل نموذج عند الحاجة فقط"""
61
  with self.model_lock:
62
  if model_type in self.loaded_models:
 
63
  return self.loaded_models[model_type]
64
 
65
  try:
 
68
  model_config = self.models_config[model_type]
69
 
70
  if model_config["type"] == "text-generation":
71
+ from transformers import pipeline
72
 
 
73
  model = pipeline(
74
  "text-generation",
75
  model=model_config["name"],
 
76
  device=-1, # استخدام CPU
77
+ max_length=model_config["max_length"],
78
  do_sample=True,
79
  temperature=0.7,
80
+ torch_dtype="auto"
 
81
  )
82
 
83
  elif model_config["type"] == "text2text-generation":
 
86
  model = pipeline(
87
  "text2text-generation",
88
  model=model_config["name"],
89
+ max_length=model_config["max_length"],
90
  device=-1,
91
+ torch_dtype="auto"
 
92
  )
93
 
94
  self.loaded_models[model_type] = model
 
97
 
98
  except Exception as e:
99
  logger.error(f"❌ فشل تحميل النموذج {model_type}: {e}")
100
+ raise Exception(f"فشل تحميل النموذج: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  def unload_model(self, model_type: str):
103
+ """إلغاء تحميل النموذج فوراً بعد الاستخدام"""
104
  with self.model_lock:
105
  if model_type in self.loaded_models:
106
  del self.loaded_models[model_type]
 
110
  def unload_all_models(self):
111
  """إلغاء تحميل جميع النماذج"""
112
  with self.model_lock:
113
+ for model_type in list(self.loaded_models.keys()):
 
114
  self.unload_model(model_type)
 
 
 
 
 
115
 
116
  # هياكل البيانات
117
  class ChatRequest(BaseModel):
 
135
 
136
  # 🔥 نظام الذاكرة المتقدم
137
  model_manager = SmartModelManager()
 
138
  conversation_contexts = {}
139
 
140
+ # 🔥 نظام التفكير المتقدم - بدون أي fallback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  class AdvancedThinker:
142
  def __init__(self):
143
  self.thinking_steps = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ def analyze_request(self, user_message: str) -> Dict:
146
+ """تحليل متقدم للطلب - بدون fallback"""
147
  self.thinking_steps = []
148
 
 
149
  intent = self._detect_intent(user_message)
150
  self.thinking_steps.append(f"📝 النية المكتشفة: {intent}")
151
 
152
+ required_model = self._determine_model(intent)
 
 
 
 
 
153
  self.thinking_steps.append(f"🤖 النموذج المطلوب: {required_model}")
154
 
 
155
  required_actions = self._determine_actions(intent, user_message)
156
  self.thinking_steps.append(f"⚡ الإجراءات المطلوبة: {len(required_actions)} إجراء")
157
 
158
  return {
159
  "intent": intent,
 
160
  "required_model": required_model,
161
  "required_actions": required_actions,
162
  "thinking_steps": self.thinking_steps
163
  }
164
 
165
  def _detect_intent(self, message: str) -> str:
166
+ """كشف النية بدقة"""
167
  message_lower = message.lower()
168
 
169
+ if any(word in message_lower for word in ["بوت", "bot", "تطوير"]):
170
+ return "technical_request"
171
+ elif any(word in message_lower for word in ["هندسة", "reverse", "عكسية"]):
172
+ return "reverse_engineering"
173
+ elif any(word in message_lower for word in ["تهكير", "hack", "تعديل"]):
174
+ return "game_hacking"
175
+ elif any(word in message_lower for word in ["أمن", "حماية", "سيبر"]):
176
+ return "cybersecurity"
177
+ elif any(word in message_lower for word in ["برمجة", "code", "سكريبت"]):
178
+ return "coding"
179
+ elif any(word in message_lower for word in ["ابحث", "بحث", "معلومات"]):
180
+ return "research"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  else:
182
+ return "general_conversation"
183
+
184
+ def _determine_model(self, intent: str) -> str:
185
+ """تحديد النموذج المناسب"""
186
+ model_map = {
187
+ "coding": "coding_expert",
188
+ "technical_request": "coding_expert",
189
+ "game_hacking": "cyber_security",
190
+ "cybersecurity": "cyber_security",
191
+ "research": "cyber_security"
192
+ }
193
+ return model_map.get(intent, "arabic_general")
194
 
195
  def _determine_actions(self, intent: str, message: str) -> List[Dict]:
196
+ """تحديد الإجراءات المطلوبة"""
197
  actions = []
198
 
199
+ if intent == "technical_request":
200
+ actions.append({
201
+ "type": "prepare_bot_development",
202
+ "description": "تحضير بيئة تطوير البوتات المتقدمة",
203
+ "priority": "high"
204
+ })
205
+ elif intent == "reverse_engineering":
206
+ actions.append({
207
+ "type": "prepare_reverse_engineering",
208
+ "description": "تحضير أدوات الهندسة العكسية المتقدمة",
209
+ "priority": "high"
210
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  elif intent == "research":
212
  actions.append({
213
+ "type": "web_research",
214
  "description": "البحث عن المعلومات المطلوبة",
215
  "parameters": {"query": message},
216
  "priority": "medium"
217
  })
218
 
 
 
 
 
 
 
 
 
219
  return actions
220
 
221
+ # 🔥 النظام الرئيسي - بدون أي fallback
222
  thinker = AdvancedThinker()
223
 
224
+ async def generate_with_model(model_type: str, prompt: str) -> str:
225
+ """توليد النص باستخدام النموذج مع إلغاء التحميل الفوري"""
226
  try:
227
+ # تحميل النموذج
228
  model = model_manager.load_model(model_type)
 
 
229
 
230
+ # توليد النص
231
+ if model_type == "arabic_general":
232
+ result = model(prompt, max_length=512)
233
+ response = result[0]['generated_text']
234
+ elif model_type == "coding_expert":
235
+ result = model(prompt, max_length=400, temperature=0.7, do_sample=True)
236
+ response = result[0]['generated_text']
237
+ else: # cyber_security
238
+ result = model(prompt, max_length=512)
239
+ response = result[0]['generated_text']
240
+
241
+ # تنظيف الاستجابة
242
+ response = response.replace(prompt, "").strip()
243
+ return response if response else "أفهم طلبك، وأحتاج إلى مزيد من التفاصيل لتقديم المساعدة المثلى."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  except Exception as e:
246
  logger.error(f"❌ خطأ في توليد النص: {e}")
247
+ raise Exception(f"فشل في معالجة الطلب: {e}")
248
+ finally:
249
+ # 🔥 إلغاء تحميل النموذج فوراً بعد الاستخدام
250
+ model_manager.unload_model(model_type)
251
 
252
+ def build_smart_prompt(user_message: str, model_type: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  """بناء prompt ذكي حسب نوع النموذج"""
254
 
 
 
255
  if model_type == "arabic_general":
256
  prompt = f"""
257
+ أنت مساعد ذكي يتحدث العربية بطلاقة. أنت متخصص في الأمن السيبراني وتطوير البوتات والبرمجة.
 
 
 
 
 
 
 
258
 
259
  طلب المستخدم: {user_message}
260
 
261
+ قم بالرد بشكل طبيعي ومفيد باللغة العربية، مع تقديم نصائح عملية:
262
  """
263
 
264
  elif model_type == "coding_expert":
265
  prompt = f"""
266
+ You are an expert AI assistant specialized in cybersecurity and programming.
 
 
 
 
 
 
 
267
 
268
  User request: {user_message}
269
 
270
+ Provide a detailed technical response in Arabic with practical advice:
271
  """
272
 
273
+ else: # cyber_security
274
  prompt = f"""
275
+ You are a cybersecurity expert specializing in game hacking and reverse engineering.
 
 
 
 
 
 
276
 
277
  User: {user_message}
278
 
279
+ Provide a professional cybersecurity response in Arabic:
280
  """
281
 
282
  return prompt
283
 
284
+ async def get_intelligent_response(user_message: str, client_id: str) -> Dict[str, Any]:
285
+ """الحصول على رد ذكي من النموذج المناسب - بدون fallback"""
 
 
 
286
 
287
  try:
288
  # 🔥 التحليل المتقدم للطلب
289
+ analysis = thinker.analyze_request(user_message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
  # 🔥 بناء prompt ذكي
292
+ prompt = build_smart_prompt(user_message, analysis["required_model"])
293
 
294
  # 🔥 الحصول على الرد من النموذج المناسب
295
  ai_response = await generate_with_model(analysis["required_model"], prompt)
296
 
 
 
 
297
  return {
298
  "response": ai_response,
299
+ "actions": analysis["required_actions"],
300
+ "thinking": "\n".join(analysis["thinking_steps"])
 
301
  }
302
 
303
  except Exception as e:
304
  logger.error(f"❌ خطأ في النظام الذكي: {e}")
305
+ raise Exception(f"فشل في معالجة الطلب: {e}")
 
 
 
 
 
 
 
 
 
 
306
 
307
  @app.post("/api/chat")
308
  async def chat_with_ai(request: ChatRequest):
309
+ """نقطة النهاية للمحادثة الذكية - بدون fallback"""
310
  try:
311
+ logger.info(f"💬 محادثة من {request.client_id}: {request.message}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
 
313
+ # الحصول على رد ذكي
314
+ ai_result = await get_intelligent_response(request.message, request.client_id)
 
315
 
316
  response = ChatResponse(
317
  thinking_process=ai_result["thinking"],
 
322
  return response
323
 
324
  except Exception as e:
325
+ logger.error(f"❌ خطأ في المحادثة: {e}")
326
  raise HTTPException(status_code=500, detail=str(e))
327
 
328
  @app.get("/api/system-status")
329
  async def system_status():
330
+ """حالة النظام"""
 
 
331
  return {
332
  "success": True,
333
  "status": "running",
334
+ "loaded_models": [],
 
335
  "memory_management": "active",
336
  "server_time": datetime.now().isoformat()
337
  }
338
 
339
  @app.post("/api/cleanup-memory")
340
  async def cleanup_memory():
341
+ """تنظيف الذاكرة"""
342
  try:
343
  model_manager.unload_all_models()
344
+ return {"success": True, "message": "تم تنظيف الذاكرة"}
 
 
 
 
345
  except Exception as e:
 
346
  raise HTTPException(status_code=500, detail=str(e))
347
 
348
+ # نقاط النهاية الأساسية
349
  @app.get("/")
350
  async def root():
 
351
  return {
352
  "status": "running",
353
+ "service": "Windows AI Controller - النسخة الذكية",
354
+ "timestamp": datetime.now().isoformat()
 
 
355
  }
356
 
357
  @app.post("/api/register-client")
358
  async def register_client(registration: ClientRegistration):
359
  """تسجيل عميل جديد"""
360
+ return {
361
+ "success": True,
362
+ "message": "تم تسجيل العميل بنجاح",
363
+ "client_id": registration.client_id
364
+ }
 
 
 
 
 
 
 
 
 
 
365
 
366
  @app.post("/api/submit-result")
367
  async def submit_result(result: Dict[str, Any]):
368
  """استقبال النتائج من العميل"""
369
+ return {"success": True, "message": "تم استلام النتيجة"}
 
 
 
 
 
 
 
 
 
370
 
371
  if __name__ == "__main__":
372
  import uvicorn
373
  port = int(os.getenv("PORT", 7860))
374
+ uvicorn.run(app, host="0.0.0.0", port=port)