Sanjayraju30 commited on
Commit
b2a6c9b
·
verified ·
1 Parent(s): af188c8

Create services/fault_service.py

Browse files
Files changed (1) hide show
  1. services/fault_service.py +34 -0
services/fault_service.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ from ultralytics.nn.tasks import DetectionModel
3
+ import os
4
+ import torch.serialization
5
+
6
+ # Allowlist Ultralytics DetectionModel to avoid UnpicklingError
7
+ torch.serialization.add_safe_globals([DetectionModel])
8
+
9
+ def load_fault_model():
10
+ model_path = "pole_fault_model.pt"
11
+ if os.path.exists(model_path):
12
+ print(f"Loading custom model: {model_path}")
13
+ return YOLO(model_path)
14
+ else:
15
+ print(f"Warning: {model_path} not found. Falling back to YOLOv8s.")
16
+ return YOLO("yolov8s.pt") # Fallback to pre-trained YOLOv8s
17
+
18
+ fault_model = load_fault_model()
19
+
20
+ def detect_pole_faults(image_path):
21
+ try:
22
+ results = fault_model(image_path)
23
+ flagged = []
24
+ for r in results:
25
+ # Check if model is custom-trained with fault_type (for custom models)
26
+ if hasattr(r, 'fault_type') and r.conf > 0.6:
27
+ flagged.append({"fault_type": r.fault_type, "confidence": r.conf})
28
+ # Fallback for generic YOLOv8 models (no fault_type)
29
+ elif r.names and r.conf > 0.6:
30
+ flagged.append({"fault_type": r.names[int(r.cls)], "confidence": r.conf})
31
+ return flagged
32
+ except Exception as e:
33
+ print(f"Error in fault detection: {e}")
34
+ return []