DurgaDeepak commited on
Commit
b0c7a24
·
verified ·
1 Parent(s): 98eaed9

Update models/detection/detector.py

Browse files
Files changed (1) hide show
  1. models/detection/detector.py +34 -30
models/detection/detector.py CHANGED
@@ -2,46 +2,61 @@ import logging
2
  from PIL import Image, ImageDraw
3
  from huggingface_hub import hf_hub_download
4
  from ultralytics import YOLO
 
5
  import shutil
6
 
7
-
8
-
9
  logger = logging.getLogger(__name__)
 
 
 
10
  shutil.rmtree("models/detection/weights", ignore_errors=True)
 
11
  class ObjectDetector:
12
- def __init__(self, model_key="yolov8n.pt", device="cpu"):
13
  """
14
- Initialize the Object Detection model using Ultralytics YOLO registry.
15
 
16
  Args:
17
- model_key (str): Model name supported by ultralytics, e.g. 'yolov5n', 'yolov8s', etc.
18
  device (str): 'cpu' or 'cuda'
19
  """
 
20
  alias_map = {
 
21
  "yolov8s": "yolov8s",
22
  "yolov8l": "yolov8l",
23
- "yolov11b": "yolov11b",
24
  }
25
 
26
- raw_key = model_key.lower()
27
- resolved_key = alias_map.get(raw_key, raw_key)
28
 
29
- self.device = device
30
- self.model = YOLO(f"{resolved_key}.pt")
31
- logger.info(f" Ultralytics YOLO model '{resolved_key}' initialized on {device}")
 
 
 
 
32
 
 
 
33
 
 
34
 
35
- def predict(self, image: Image.Image, conf_threshold=0.25):
36
- """
37
- Run object detection.
 
 
 
 
38
 
39
- Args:
40
- image (PIL.Image.Image): Input image.
 
41
 
42
- Returns:
43
- List[Dict]: List of detected objects with class name, confidence, and bbox.
44
- """
45
  logger.info("Running object detection")
46
  results = self.model(image)
47
  detections = []
@@ -56,17 +71,6 @@ class ObjectDetector:
56
  return detections
57
 
58
  def draw(self, image: Image.Image, detections, alpha=0.5):
59
- """
60
- Draw bounding boxes on image.
61
-
62
- Args:
63
- image (PIL.Image.Image): Input image.
64
- detections (List[Dict]): Detection results.
65
- alpha (float): Blend strength.
66
-
67
- Returns:
68
- PIL.Image.Image: Image with bounding boxes drawn.
69
- """
70
  overlay = image.copy()
71
  draw = ImageDraw.Draw(overlay)
72
  for det in detections:
 
2
  from PIL import Image, ImageDraw
3
  from huggingface_hub import hf_hub_download
4
  from ultralytics import YOLO
5
+ import os
6
  import shutil
7
 
8
+ # Setup logger
 
9
  logger = logging.getLogger(__name__)
10
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
11
+
12
+ # Optional: clear weights cache each time (only for dev use)
13
  shutil.rmtree("models/detection/weights", ignore_errors=True)
14
+
15
  class ObjectDetector:
16
+ def __init__(self, model_key="yolov8n", device="cpu"):
17
  """
18
+ Initializes an Ultralytics YOLO model using HF download path.
19
 
20
  Args:
21
+ model_key (str): e.g. 'yolov8n', 'yolov8s', etc.
22
  device (str): 'cpu' or 'cuda'
23
  """
24
+ # Optional aliasing
25
  alias_map = {
26
+ "yolov8n": "yolov8n",
27
  "yolov8s": "yolov8s",
28
  "yolov8l": "yolov8l",
29
+ "yolov11b": "yolov11b"
30
  }
31
 
32
+ resolved_key = alias_map.get(model_key.lower(), model_key.lower())
 
33
 
34
+ # HF repo map
35
+ hf_map = {
36
+ "yolov8n": ("ultralytics/yolov8", "yolov8n.pt"),
37
+ "yolov8s": ("ultralytics/yolov8", "yolov8s.pt"),
38
+ "yolov8l": ("ultralytics/yolov8", "yolov8l.pt"),
39
+ "yolov11b": ("Ultralytics/YOLO11", "yolov11b.pt"),
40
+ }
41
 
42
+ if resolved_key not in hf_map:
43
+ raise ValueError(f"Unsupported model key: {resolved_key}")
44
 
45
+ repo_id, filename = hf_map[resolved_key]
46
 
47
+ # 📥 Download from HF Hub
48
+ weights_path = hf_hub_download(
49
+ repo_id=repo_id,
50
+ filename=filename,
51
+ cache_dir="models/detection/weights",
52
+ force_download=True # Optional: change to False for reuse
53
+ )
54
 
55
+ logger.info(f"✅ Loaded YOLO model: {resolved_key} from {weights_path}")
56
+ self.device = device
57
+ self.model = YOLO(weights_path)
58
 
59
+ def predict(self, image: Image.Image, conf_threshold=0.25):
 
 
60
  logger.info("Running object detection")
61
  results = self.model(image)
62
  detections = []
 
71
  return detections
72
 
73
  def draw(self, image: Image.Image, detections, alpha=0.5):
 
 
 
 
 
 
 
 
 
 
 
74
  overlay = image.copy()
75
  draw = ImageDraw.Draw(overlay)
76
  for det in detections: