File size: 2,681 Bytes
c46c411
5acd124
 
 
c46c411
5acd124
 
 
 
 
 
c46c411
5acd124
 
 
c46c411
 
5acd124
 
 
c46c411
5acd124
 
c46c411
 
5acd124
c46c411
 
 
 
 
 
 
5acd124
c46c411
5acd124
 
 
c46c411
 
5acd124
c46c411
 
 
 
 
5acd124
c46c411
 
5acd124
c46c411
5acd124
 
c46c411
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# ml_engine/ranker.py (V11.1 - Layer 1 Smart Ranker with Memory Management)
import pandas as pd
import numpy as np
import os
import gc # استيراد لجمع القمامة
from typing import List, Dict, Any

try:
    import lightgbm as lgb
    LGBM_AVAILABLE = True
except ImportError:
    print("❌❌ [Ranker] مكتبة 'lightgbm' غير موجودة.")
    LGBM_AVAILABLE = False

class Layer1Ranker:
    def __init__(self, model_path: str = "ml_models/layer1_ranker.lgbm"):
        if not LGBM_AVAILABLE: raise ImportError("lightgbm required")
        self.model_path = model_path
        self.model_name = os.path.basename(model_path)
        self.model = None
        self.features_in_ = None

    async def initialize(self):
        """تحميل النموذج من الملف المحلي"""
        print(f"🔄 [Ranker] تحميل {self.model_name}...")
        try:
            if os.path.exists(self.model_path):
                self.model = lgb.Booster(model_file=self.model_path)
                self.features_in_ = self.model.feature_name()
                print(f"✅ [Ranker] تم تحميل النموذج بنجاح ({len(self.features_in_)} features).")
            else:
                print(f"❌ [Ranker] ملف النموذج غير موجود: {self.model_path}")
                self.model = None
        except Exception as e:
            print(f"❌ [Ranker] فشل تحميل النموذج: {e}")
            self.model = None

    def predict_proba(self, features_df: pd.DataFrame) -> np.ndarray:
        """التنبؤ باحتمالية الصعود"""
        if self.model is None: return np.zeros(len(features_df))
        try:
            # التأكد من ترتيب الأعمدة
            if not all(f in features_df.columns for f in self.features_in_):
                # محاولة تعبئة الميزات المفقودة بأصفار إذا لزم الأمر
                for f in self.features_in_:
                    if f not in features_df.columns: features_df[f] = 0.0
            
            aligned_df = features_df[self.features_in_]
            return self.model.predict(aligned_df)
        except Exception as e:
            print(f"❌ [Ranker] خطأ التنبؤ: {e}")
            return np.zeros(len(features_df))

    # 🔴 دالة جديدة لتنظيف الذاكرة
    def clear_memory(self):
        """تحرير نموذج LightGBM من الذاكرة"""
        self.model = None
        self.features_in_ = None
        gc.collect()
        print(f"🧹 [Ranker] تم تحرير النموذج من الذاكرة.")

print("✅ ML Module: Layer 1 Ranker V11.1 (Memory Managed) loaded.")