File size: 10,801 Bytes
44f7c73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e93b8c
44f7c73
9e93b8c
 
44f7c73
9e93b8c
 
 
44f7c73
 
 
9e93b8c
44f7c73
 
 
9e93b8c
44f7c73
9e93b8c
 
44f7c73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# backend/src/models/ensemble.py
"""
Real YOLO Ensemble Detector for Road Damage Detection

Uses the trained yolo11base.pt model for actual inference.
Architecture supports future expansion to 3 models (YOLO11, YOLO12, SAHI)
deployed on HuggingFace Spaces.

Current Configuration:
- yolo11: 1.0 (active - local model)
- yolo12: 0.0 (pending - training)
- sahi: 0.0 (pending - training)
"""

import os
import numpy as np
from typing import List, Dict, Any, Optional
import logging

logger = logging.getLogger(__name__)

# Configure logging to show in console
logging.basicConfig(level=logging.INFO)

# Try to import YOLO from ultralytics
try:
    from ultralytics import YOLO
    YOLO_AVAILABLE = True
    print("[ENSEMBLE] ultralytics YOLO imported successfully")
except ImportError:
    YOLO_AVAILABLE = False
    print("[ENSEMBLE] WARNING: ultralytics not installed, using mock detector")
    logger.warning("[WARN] ultralytics not installed, using mock detector")


class EnsembleDetector:
    """
    Real YOLO-based ensemble detector for road damage.
    
    Uses local YOLO11 model for inference. When additional models
    are trained and deployed to HuggingFace Spaces, they can be
    added to the ensemble with appropriate weights.
    """
    
    def __init__(self, model_path: str = None):
        """
        Initialize the ensemble detector.
        
        Args:
            model_path: Path to YOLO model weights. 
                       Defaults to models/yolo11base.pt
        """
        self.model = None
        self.model_loaded = False
        
        # Model weights configuration
        self.weights = {
            "yolo11": 1.0,   # Active - local model
            "yolo12": 0.0,   # Pending
            "sahi": 0.0      # Pending
        }
        
        # Class names from RDD2022 dataset
        self.class_names = {
            0: "D00",  # Longitudinal Crack
            1: "D10",  # Transverse Crack
            2: "D20",  # Alligator Crack
            3: "D40",  # Pothole
        }
        
        self.class_display_names = {
            "D00": "Longitudinal Crack",
            "D10": "Transverse Crack",
            "D20": "Alligator Crack",
            "D40": "Pothole",
        }
        
        # Determine model path
        if model_path is None:
            # Try multiple possible paths (local dev + HuggingFace Docker)
            possible_paths = [
                # HuggingFace Docker container paths (WORKDIR=/app)
                "/app/models/yolo11base.pt",
                "models/yolo11base.pt",
                # Local development paths
                "../models/yolo11base.pt",
                os.path.join(os.path.dirname(__file__), "../../models/yolo11base.pt"),
                os.path.join(os.path.dirname(__file__), "../../../models/yolo11base.pt"),
                "D:/Gitrepo/road-damage/models/yolo11base.pt",
            ]
            print(f"[MODEL] Searching for model in paths: {possible_paths}")
            for path in possible_paths:
                if os.path.exists(path):
                    model_path = path
                    print(f"[MODEL] Found model at: {path}")
                    break
            if model_path is None:
                print(f"[MODEL] WARNING: Model not found in any path!")
        
        # Load model
        if YOLO_AVAILABLE and model_path and os.path.exists(model_path):
            try:
                logger.info(f"[INFO] Loading YOLO model from: {model_path}")
                self.model = YOLO(model_path)
                self.model_loaded = True
                logger.info("[OK] YOLO model loaded successfully!")
                
                # Get class names from model if available
                if hasattr(self.model, 'names') and self.model.names:
                    self.class_names = self.model.names
                    logger.info(f"[INFO] Model classes: {self.class_names}")
                    
            except Exception as e:
                logger.error(f"[ERROR] Failed to load YOLO model: {e}")
                self.model_loaded = False
        else:
            if not YOLO_AVAILABLE:
                logger.warning("[WARN] ultralytics not available")
            elif not model_path:
                logger.warning("[WARN] No model path specified")
            else:
                logger.warning(f"[WARN] Model file not found: {model_path}")
    
    def predict(self, image: np.ndarray, conf_threshold: float = 0.25) -> List[Dict]:
        """
        Run inference on an image.
        
        Args:
            image: numpy array (HWC format, RGB or BGR)
            conf_threshold: Minimum confidence threshold
            
        Returns:
            List of detection dictionaries with keys:
            - box: [x1, y1, x2, y2]
            - class_name: str
            - class_id: int
            - confidence: float
            - votes: int (number of models that detected this)
        """
        
        if not self.model_loaded:
            logger.warning("[WARN] Model not loaded, returning empty results")
            return []
        
        try:
            # Run inference
            results = self.model(
                image,
                conf=conf_threshold,
                verbose=False
            )
            
            detections = []
            
            for result in results:
                boxes = result.boxes
                
                if boxes is None or len(boxes) == 0:
                    continue
                
                for i in range(len(boxes)):
                    # Get bounding box
                    box = boxes.xyxy[i].cpu().numpy()
                    x1, y1, x2, y2 = box
                    
                    # Get confidence
                    conf = float(boxes.conf[i].cpu().numpy())
                    
                    # Get class
                    cls_id = int(boxes.cls[i].cpu().numpy())
                    
                    # Get class name
                    if cls_id in self.class_names:
                        cls_name = self.class_names[cls_id]
                    else:
                        cls_name = f"class_{cls_id}"
                    
                    # Get display name
                    display_name = self.class_display_names.get(cls_name, cls_name)
                    
                    detection = {
                        "box": [float(x1), float(y1), float(x2), float(y2)],
                        "class_name": display_name,
                        "class_code": cls_name,
                        "class_id": cls_id,
                        "confidence": conf,
                        "votes": 1,  # Single model for now
                        "model": "yolo11"
                    }
                    
                    detections.append(detection)
            
            logger.info(f"[DETECT] YOLO11 detected {len(detections)} objects")
            return detections
            
        except Exception as e:
            logger.error(f"[ERROR] Inference failed: {e}")
            import traceback
            traceback.print_exc()
            return []
    
    def predict_with_ensemble(
        self, 
        image: np.ndarray,
        conf_threshold: float = 0.25
    ) -> List[Dict]:
        """
        Run ensemble inference (future: multiple models).
        
        Currently only uses YOLO11 since other models are pending.
        When YOLO12 and SAHI are ready, this method will:
        1. Call all 3 models in parallel
        2. Merge overlapping detections (NMS)
        3. Apply weighted voting
        4. Return only detections agreed by 2+ models
        
        Args:
            image: numpy array
            conf_threshold: Minimum confidence
            
        Returns:
            List of ensemble-merged detections
        """
        
        # For now, just use YOLO11
        yolo11_results = self.predict(image, conf_threshold)
        
        # Future: Add YOLO12 and SAHI results
        # yolo12_results = self._call_hf_space("yolo12", image)
        # sahi_results = self._call_hf_space("sahi", image)
        
        # Future: Merge with NMS and voting
        # merged = self._merge_detections([yolo11_results, yolo12_results, sahi_results])
        
        return yolo11_results
    
    def get_model_info(self) -> Dict[str, Any]:
        """Get information about loaded models."""
        return {
            "yolo11": {
                "loaded": self.model_loaded,
                "weight": self.weights["yolo11"],
                "type": "local"
            },
            "yolo12": {
                "loaded": False,
                "weight": self.weights["yolo12"],
                "type": "hf_space",
                "status": "pending_training"
            },
            "sahi": {
                "loaded": False,
                "weight": self.weights["sahi"],
                "type": "hf_space", 
                "status": "pending_training"
            }
        }


class SeverityClassifier:
    """Classify damage severity based on area and confidence."""
    
    def __init__(self):
        # Thresholds for severity classification
        self.thresholds = {
            "light": 0.05,    # < 5% of image
            "medium": 0.15,   # 5-15% of image
            # > 15% = heavy
        }
    
    def classify(self, area_ratio: float, confidence: float) -> str:
        """
        Classify severity based on damage area relative to image.
        
        Args:
            area_ratio: Damage area / image area
            confidence: Detection confidence (0-1)
            
        Returns:
            Severity string: "light", "medium", or "heavy"
        """
        # Adjust thresholds based on confidence
        # Lower confidence = more conservative severity
        conf_factor = min(1.0, confidence / 0.5)
        
        effective_ratio = area_ratio * conf_factor
        
        if effective_ratio > self.thresholds["medium"]:
            return "heavy"
        elif effective_ratio > self.thresholds["light"]:
            return "medium"
        else:
            return "light"


class TTAProcessor:
    """Test-Time Augmentation processor (optional enhancement)."""
    
    def __init__(self):
        self.enabled = False  # Disabled by default for speed
    
    def predict(self, image: np.ndarray) -> List[Dict]:
        """
        Run TTA inference (currently disabled).
        
        When enabled, this applies augmentations and averages results
        for more robust detections at the cost of speed.
        """
        if not self.enabled:
            return []
        
        # Future: Implement TTA
        # - Horizontal flip
        # - Multi-scale
        # - Merge results
        return []