ZahraFatima commited on
Commit
b1bbc91
·
verified ·
1 Parent(s): 7dde930

Update detector.py

Browse files
Files changed (1) hide show
  1. detector.py +46 -33
detector.py CHANGED
@@ -10,6 +10,10 @@ This is the DETERMINISTIC half of the pipeline. It:
10
  The VLM never decides compliance on its own — it is handed these facts. This keeps
11
  the safety-critical judgement in code that can be logged and reviewed, in line with
12
  the AiGiS design principle.
 
 
 
 
13
  """
14
  from __future__ import annotations
15
 
@@ -74,14 +78,24 @@ def _iou(a: list[float], b: list[float]) -> float:
74
  return inter / (area_a + area_b - inter)
75
 
76
 
 
 
 
 
77
  class SafetyDetector:
78
- def __init__(self, weights: str, data_yaml: str, conf: float = 0.25):
 
79
  self.model = YOLO(weights)
80
  self.conf = conf
 
81
  with open(data_yaml) as f:
82
  cfg = yaml.safe_load(f)
83
- # body_part -> expected PPE class name
84
- self.ppe_pairs: dict[str, str] = cfg.get("ppe_pairs", {})
 
 
 
 
85
 
86
  def detect(self, image_path: str) -> DetectionResult:
87
  _, det_result = self._run(image_path)
@@ -90,18 +104,16 @@ class SafetyDetector:
90
  def detect_and_annotate(self, image, name: str | None = None):
91
  """
92
  Same as detect(), but also returns a BGR numpy array with the detection
93
- boxes drawn on it (via Ultralytics' own .plot()). Runs YOLO only once,
94
- so callers can get both the JSON and the annotated image from one call.
95
-
96
- `image` can be a file path OR an in-memory BGR array (e.g. from
97
- cv2.imdecode on an uploaded file) — Ultralytics accepts both.
98
  """
99
  result, det_result = self._run(image, name=name)
100
  annotated = result.plot()
101
  return det_result, annotated
102
 
103
  def _run(self, image, name: str | None = None):
104
- result = self.model(image, conf=self.conf, verbose=False)[0]
 
105
  names = result.names
106
 
107
  dets: list[Detection] = []
@@ -123,38 +135,39 @@ class SafetyDetector:
123
 
124
  def _assess_compliance(self, dets: list[Detection]) -> list[ComplianceFinding]:
125
  """
126
- For each body part that should be protected, check whether the expected
127
- PPE was detected overlapping it. Purely rule-based and explainable.
128
  """
129
  findings: list[ComplianceFinding] = []
130
  by_cls: dict[str, list[Detection]] = {}
131
  for d in dets:
132
  by_cls.setdefault(d.cls, []).append(d)
133
 
134
- for body_part, expected in self.ppe_pairs.items():
135
  parts = by_cls.get(body_part, [])
136
  if not parts:
137
  continue # body part not visible -> nothing to assess
138
- ppe_items = by_cls.get(expected, [])
139
- for part in parts:
140
- overlap = max(
141
- (_iou(part.box_xywhn, p.box_xywhn) for p in ppe_items),
142
- default=0.0,
143
- )
144
- if overlap >= 0.10:
145
- status, detail = "present", (
146
- f"{expected} overlaps detected {body_part} (IoU {overlap:.2f})"
147
  )
148
- elif ppe_items:
149
- status, detail = "uncertain", (
150
- f"{expected} present in image but not clearly over this "
151
- f"{body_part} (max IoU {overlap:.2f})"
 
 
 
 
 
 
 
 
 
 
 
152
  )
153
- else:
154
- status, detail = "missing", (
155
- f"{body_part} detected but no {expected} found in image"
156
- )
157
- findings.append(
158
- ComplianceFinding(body_part, expected, status, detail)
159
- )
160
- return findings
 
10
  The VLM never decides compliance on its own — it is handed these facts. This keeps
11
  the safety-critical judgement in code that can be logged and reviewed, in line with
12
  the AiGiS design principle.
13
+
14
+ ppe_pairs supports MULTIPLE expected PPE items per body part, e.g.
15
+ face: [glasses, face_mask_medical]
16
+ A single string is also accepted for backwards compatibility.
17
  """
18
  from __future__ import annotations
19
 
 
78
  return inter / (area_a + area_b - inter)
79
 
80
 
81
+ # Minimum IoU for a PPE box to count as "covering" a body-part box.
82
+ MATCH_IOU = 0.10
83
+
84
+
85
  class SafetyDetector:
86
+ def __init__(self, weights: str, data_yaml: str, conf: float = 0.25,
87
+ augment: bool = False):
88
  self.model = YOLO(weights)
89
  self.conf = conf
90
+ self.augment = augment # test-time augmentation (slower, higher recall)
91
  with open(data_yaml) as f:
92
  cfg = yaml.safe_load(f)
93
+ # body_part -> expected PPE (normalize every value to a list of names)
94
+ raw_pairs = cfg.get("ppe_pairs", {})
95
+ self.ppe_pairs: dict[str, list[str]] = {
96
+ part: ([exp] if isinstance(exp, str) else list(exp))
97
+ for part, exp in raw_pairs.items()
98
+ }
99
 
100
  def detect(self, image_path: str) -> DetectionResult:
101
  _, det_result = self._run(image_path)
 
104
  def detect_and_annotate(self, image, name: str | None = None):
105
  """
106
  Same as detect(), but also returns a BGR numpy array with the detection
107
+ boxes drawn on it. Runs YOLO only once.
108
+ `image` can be a file path OR an in-memory BGR array.
 
 
 
109
  """
110
  result, det_result = self._run(image, name=name)
111
  annotated = result.plot()
112
  return det_result, annotated
113
 
114
  def _run(self, image, name: str | None = None):
115
+ result = self.model(image, conf=self.conf, augment=self.augment,
116
+ verbose=False)[0]
117
  names = result.names
118
 
119
  dets: list[Detection] = []
 
135
 
136
  def _assess_compliance(self, dets: list[Detection]) -> list[ComplianceFinding]:
137
  """
138
+ For each body part that should be protected, check whether each expected
139
+ PPE item was detected overlapping it. Purely rule-based and explainable.
140
  """
141
  findings: list[ComplianceFinding] = []
142
  by_cls: dict[str, list[Detection]] = {}
143
  for d in dets:
144
  by_cls.setdefault(d.cls, []).append(d)
145
 
146
+ for body_part, expected_list in self.ppe_pairs.items():
147
  parts = by_cls.get(body_part, [])
148
  if not parts:
149
  continue # body part not visible -> nothing to assess
150
+ for expected in expected_list:
151
+ ppe_items = by_cls.get(expected, [])
152
+ for part in parts:
153
+ overlap = max(
154
+ (_iou(part.box_xywhn, p.box_xywhn) for p in ppe_items),
155
+ default=0.0,
 
 
 
156
  )
157
+ if overlap >= MATCH_IOU:
158
+ status, detail = "present", (
159
+ f"{expected} overlaps detected {body_part} (IoU {overlap:.2f})"
160
+ )
161
+ elif ppe_items:
162
+ status, detail = "uncertain", (
163
+ f"{expected} present in image but not clearly over this "
164
+ f"{body_part} (max IoU {overlap:.2f})"
165
+ )
166
+ else:
167
+ status, detail = "missing", (
168
+ f"{body_part} detected but no {expected} found in image"
169
+ )
170
+ findings.append(
171
+ ComplianceFinding(body_part, expected, status, detail)
172
  )
173
+ return findings