RavindranadhM commited on
Commit
fb4ca0a
·
verified ·
1 Parent(s): 154f57c

Add steel surface gate before defect segmentation

Browse files
.env.example CHANGED
@@ -9,3 +9,15 @@ HF_TOKEN=
9
  HF_CHAT_MODEL=meta-llama/Llama-3.1-8B-Instruct:cerebras
10
  HF_ROUTER_BASE_URL=https://router.huggingface.co/v1
11
  MAX_UPLOAD_SIZE_MB=8
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  HF_CHAT_MODEL=meta-llama/Llama-3.1-8B-Instruct:cerebras
10
  HF_ROUTER_BASE_URL=https://router.huggingface.co/v1
11
  MAX_UPLOAD_SIZE_MB=8
12
+ SURFACE_GATE_ENABLED=true
13
+ SURFACE_CLASSIFIER_PATH=
14
+ SURFACE_CLASSIFIER_STEEL_LABEL=steel
15
+ SURFACE_MIN_STEEL_CONFIDENCE=0.55
16
+ SURFACE_GRAY_DELTA=16
17
+ SURFACE_MIN_GRAY_RATIO=0.72
18
+ SURFACE_LOW_SAT_PIXEL_THRESHOLD=45
19
+ SURFACE_MIN_LOW_SAT_RATIO=0.78
20
+ SURFACE_MAX_MEAN_SATURATION=40
21
+ SURFACE_MAX_COLORFULNESS=24
22
+ SURFACE_MAX_SKIN_RATIO=0.16
23
+ SURFACE_MIN_TEXTURE_VARIANCE=80
core/config.py CHANGED
@@ -15,6 +15,26 @@ def _resolve_path(env_name: str, default_relative_path: str) -> str:
15
  return str(path if path.is_absolute() else (BASE_DIR / path).resolve())
16
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  def _parse_origins() -> tuple[str, ...]:
19
  raw_origins = os.getenv(
20
  "CORS_ORIGINS",
@@ -80,6 +100,45 @@ class Settings:
80
  IMAGE_SIZE: int = field(default_factory=lambda: int(os.getenv("IMAGE_SIZE", "896")))
81
  MIN_DEFECT_AREA: int = field(default_factory=lambda: int(os.getenv("MIN_DEFECT_AREA", "120")))
82
  MAX_AREA_RATIO: float = field(default_factory=lambda: float(os.getenv("MAX_AREA_RATIO", "0.12")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  # -----------------------------
85
  # API / UI
 
15
  return str(path if path.is_absolute() else (BASE_DIR / path).resolve())
16
 
17
 
18
+ def _resolve_optional_path(
19
+ env_name: str,
20
+ default_relative_path: str | None = None,
21
+ ) -> str | None:
22
+ raw_value = os.getenv(env_name)
23
+
24
+ if raw_value:
25
+ path = Path(raw_value)
26
+ return str(path if path.is_absolute() else (BASE_DIR / path).resolve())
27
+
28
+ if not default_relative_path:
29
+ return None
30
+
31
+ default_path = (BASE_DIR / default_relative_path).resolve()
32
+ if default_path.exists():
33
+ return str(default_path)
34
+
35
+ return None
36
+
37
+
38
  def _parse_origins() -> tuple[str, ...]:
39
  raw_origins = os.getenv(
40
  "CORS_ORIGINS",
 
100
  IMAGE_SIZE: int = field(default_factory=lambda: int(os.getenv("IMAGE_SIZE", "896")))
101
  MIN_DEFECT_AREA: int = field(default_factory=lambda: int(os.getenv("MIN_DEFECT_AREA", "120")))
102
  MAX_AREA_RATIO: float = field(default_factory=lambda: float(os.getenv("MAX_AREA_RATIO", "0.12")))
103
+ SURFACE_GATE_ENABLED: bool = field(
104
+ default_factory=lambda: _parse_bool("SURFACE_GATE_ENABLED", True)
105
+ )
106
+ SURFACE_CLASSIFIER_PATH: str | None = field(
107
+ default_factory=lambda: _resolve_optional_path(
108
+ "SURFACE_CLASSIFIER_PATH",
109
+ "models/steel_surface_classifier.pt",
110
+ )
111
+ )
112
+ SURFACE_CLASSIFIER_STEEL_LABEL: str = field(
113
+ default_factory=lambda: os.getenv("SURFACE_CLASSIFIER_STEEL_LABEL", "steel")
114
+ )
115
+ SURFACE_MIN_STEEL_CONFIDENCE: float = field(
116
+ default_factory=lambda: float(os.getenv("SURFACE_MIN_STEEL_CONFIDENCE", "0.55"))
117
+ )
118
+ SURFACE_GRAY_DELTA: int = field(
119
+ default_factory=lambda: int(os.getenv("SURFACE_GRAY_DELTA", "16"))
120
+ )
121
+ SURFACE_MIN_GRAY_RATIO: float = field(
122
+ default_factory=lambda: float(os.getenv("SURFACE_MIN_GRAY_RATIO", "0.72"))
123
+ )
124
+ SURFACE_LOW_SAT_PIXEL_THRESHOLD: int = field(
125
+ default_factory=lambda: int(os.getenv("SURFACE_LOW_SAT_PIXEL_THRESHOLD", "45"))
126
+ )
127
+ SURFACE_MIN_LOW_SAT_RATIO: float = field(
128
+ default_factory=lambda: float(os.getenv("SURFACE_MIN_LOW_SAT_RATIO", "0.78"))
129
+ )
130
+ SURFACE_MAX_MEAN_SATURATION: float = field(
131
+ default_factory=lambda: float(os.getenv("SURFACE_MAX_MEAN_SATURATION", "40"))
132
+ )
133
+ SURFACE_MAX_COLORFULNESS: float = field(
134
+ default_factory=lambda: float(os.getenv("SURFACE_MAX_COLORFULNESS", "24"))
135
+ )
136
+ SURFACE_MAX_SKIN_RATIO: float = field(
137
+ default_factory=lambda: float(os.getenv("SURFACE_MAX_SKIN_RATIO", "0.16"))
138
+ )
139
+ SURFACE_MIN_TEXTURE_VARIANCE: float = field(
140
+ default_factory=lambda: float(os.getenv("SURFACE_MIN_TEXTURE_VARIANCE", "80"))
141
+ )
142
 
143
  # -----------------------------
144
  # API / UI
core/constants.py CHANGED
@@ -12,5 +12,6 @@ SEVERITY_SCORE = {
12
  DECISION_COLOR = {
13
  "PASS": (0, 255, 0),
14
  "REVIEW": (0, 165, 255),
15
- "FAIL": (0, 0, 255)
16
- }
 
 
12
  DECISION_COLOR = {
13
  "PASS": (0, 255, 0),
14
  "REVIEW": (0, 165, 255),
15
+ "FAIL": (0, 0, 255),
16
+ "SKIPPED": (255, 191, 0),
17
+ }
dashboard/src/content/systemBrief.js CHANGED
@@ -9,7 +9,7 @@ export const systemBrief = {
9
  },
10
  {
11
  title: "AI Detection Engine",
12
- detail: "Run the steel defect model to identify surface anomalies, geometry, and severity.",
13
  },
14
  {
15
  title: "Inspection Formatter",
@@ -77,9 +77,13 @@ export const systemBrief = {
77
  title: "Capture",
78
  detail: "Acquire a shop-floor image from upload, live camera, or the simulation loop.",
79
  },
 
 
 
 
80
  {
81
  title: "Infer",
82
- detail: "Run segmentation and extract contours, bounding boxes, severity, and geometry.",
83
  },
84
  {
85
  title: "Decide",
 
9
  },
10
  {
11
  title: "AI Detection Engine",
12
+ detail: "Validate that the frame is really a steel surface, then run the defect model to identify anomalies, geometry, and severity.",
13
  },
14
  {
15
  title: "Inspection Formatter",
 
77
  title: "Capture",
78
  detail: "Acquire a shop-floor image from upload, live camera, or the simulation loop.",
79
  },
80
+ {
81
+ title: "Validate Surface",
82
+ detail: "Reject non-steel frames before segmentation so faces, tools, and background objects do not enter the defect pipeline.",
83
+ },
84
  {
85
  title: "Infer",
86
+ detail: "Run segmentation only on steel frames and extract contours, bounding boxes, severity, and geometry.",
87
  },
88
  {
89
  title: "Decide",
dashboard/src/lib/status.js CHANGED
@@ -2,6 +2,7 @@ export function getDecisionTone(decision) {
2
  if (decision === "FAIL") return "danger"
3
  if (decision === "REVIEW") return "warning"
4
  if (decision === "PASS") return "success"
 
5
  return "neutral"
6
  }
7
 
 
2
  if (decision === "FAIL") return "danger"
3
  if (decision === "REVIEW") return "warning"
4
  if (decision === "PASS") return "success"
5
+ if (decision === "SKIPPED") return "info"
6
  return "neutral"
7
  }
8
 
dashboard/src/pages/Live.jsx CHANGED
@@ -185,11 +185,15 @@ export default function Live() {
185
 
186
  setInspectionResult(result)
187
  setLastInspectedAt(result.timestamp)
188
- setCameraStatus(
189
- result.total_defects > 0
190
- ? `Detected ${result.total_defects} defect${result.total_defects > 1 ? "s" : ""} in the latest frame`
191
- : "No actionable defects detected in the latest frame"
192
- )
 
 
 
 
193
 
194
  if (alertsEnabled && result.decision === "FAIL" && lastAlertDecision.current !== "FAIL") {
195
  playAlertTone()
@@ -304,7 +308,7 @@ export default function Live() {
304
  <input type="file" accept="image/*" className="hidden" onChange={handleImageSelection} />
305
  <p className="text-lg font-medium text-slate-100">Drop or choose a steel surface image</p>
306
  <p className="mt-3 max-w-xl text-sm leading-7 text-slate-400">
307
- Use this mode to inspect saved surface samples, log a full report, and broadcast the result to the dashboard and history views.
308
  </p>
309
  </label>
310
 
@@ -420,6 +424,9 @@ export default function Live() {
420
  {lastInspectedAt ? `Last inspection: ${formatDateTime(lastInspectedAt)}` : "Waiting for the first live inspection result."}
421
  </p>
422
  </div>
 
 
 
423
  <div className="rounded-3xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-7 text-amber-50">
424
  Keep deep analysis off during continuous monitoring for the fastest real-time response. Turn it on only when you want a slower GenAI explanation for a specific frame.
425
  </div>
@@ -470,8 +477,20 @@ export default function Live() {
470
  <div className="rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5">
471
  <div className="flex flex-wrap items-center gap-3">
472
  <StatusBadge
473
- label={inspectionResult.agent_mode === "llm" ? "Ollama AI" : "Fallback AI"}
474
- tone={inspectionResult.agent_mode === "llm" ? "info" : "warning"}
 
 
 
 
 
 
 
 
 
 
 
 
475
  />
476
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">
477
  {inspectionResult.agent_provider} {inspectionResult.agent_model && inspectionResult.agent_model !== "fallback" ? `· ${inspectionResult.agent_model}` : ""}
@@ -489,7 +508,11 @@ export default function Live() {
489
  </div>
490
 
491
  <div className="space-y-3">
492
- {(inspectionResult.defects || []).length ? (
 
 
 
 
493
  (inspectionResult.defects || []).map((defect, index) => (
494
  <div key={`${defect.type}-${index}`} className="rounded-3xl border border-white/10 bg-white/5 px-4 py-4">
495
  <div className="flex flex-wrap items-center justify-between gap-3">
 
185
 
186
  setInspectionResult(result)
187
  setLastInspectedAt(result.timestamp)
188
+ if (result.inspection_state === "non_steel_surface") {
189
+ setCameraStatus("Non-steel frame skipped. Point the camera directly at the steel surface to continue.")
190
+ } else {
191
+ setCameraStatus(
192
+ result.total_defects > 0
193
+ ? `Detected ${result.total_defects} defect${result.total_defects > 1 ? "s" : ""} in the latest frame`
194
+ : "No actionable defects detected in the latest frame"
195
+ )
196
+ }
197
 
198
  if (alertsEnabled && result.decision === "FAIL" && lastAlertDecision.current !== "FAIL") {
199
  playAlertTone()
 
308
  <input type="file" accept="image/*" className="hidden" onChange={handleImageSelection} />
309
  <p className="text-lg font-medium text-slate-100">Drop or choose a steel surface image</p>
310
  <p className="mt-3 max-w-xl text-sm leading-7 text-slate-400">
311
+ Use this mode to inspect saved surface samples, log a full report, and broadcast the result to the dashboard and history views. Non-steel uploads are now filtered before defect segmentation starts.
312
  </p>
313
  </label>
314
 
 
424
  {lastInspectedAt ? `Last inspection: ${formatDateTime(lastInspectedAt)}` : "Waiting for the first live inspection result."}
425
  </p>
426
  </div>
427
+ <div className="rounded-3xl border border-white/10 bg-white/5 px-4 py-4 text-sm leading-7 text-slate-300">
428
+ Every live frame first passes through a steel-surface gate. If the scene contains faces, hands, machinery, or general background objects, the frame is skipped before YOLO defect segmentation runs.
429
+ </div>
430
  <div className="rounded-3xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-7 text-amber-50">
431
  Keep deep analysis off during continuous monitoring for the fastest real-time response. Turn it on only when you want a slower GenAI explanation for a specific frame.
432
  </div>
 
477
  <div className="rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5">
478
  <div className="flex flex-wrap items-center gap-3">
479
  <StatusBadge
480
+ label={
481
+ inspectionResult.agent_mode === "llm"
482
+ ? "GenAI Analysis"
483
+ : inspectionResult.agent_mode === "surface_gate"
484
+ ? "Surface Gate"
485
+ : "Fallback AI"
486
+ }
487
+ tone={
488
+ inspectionResult.agent_mode === "llm"
489
+ ? "info"
490
+ : inspectionResult.agent_mode === "surface_gate"
491
+ ? "info"
492
+ : "warning"
493
+ }
494
  />
495
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">
496
  {inspectionResult.agent_provider} {inspectionResult.agent_model && inspectionResult.agent_model !== "fallback" ? `· ${inspectionResult.agent_model}` : ""}
 
508
  </div>
509
 
510
  <div className="space-y-3">
511
+ {inspectionResult.inspection_state === "non_steel_surface" ? (
512
+ <div className="rounded-3xl border border-cyan-300/20 bg-cyan-400/10 px-4 py-4 text-sm leading-7 text-cyan-50">
513
+ The latest image was skipped before defect detection because the system could not confidently confirm a steel inspection surface. Reframe the camera closer to the metal and remove background objects from view.
514
+ </div>
515
+ ) : (inspectionResult.defects || []).length ? (
516
  (inspectionResult.defects || []).map((defect, index) => (
517
  <div key={`${defect.type}-${index}`} className="rounded-3xl border border-white/10 bg-white/5 px-4 py-4">
518
  <div className="flex flex-wrap items-center justify-between gap-3">
inspection/service.py CHANGED
@@ -1,5 +1,6 @@
1
  import base64
2
  import binascii
 
3
  from typing import Any
4
 
5
  import cv2
@@ -17,6 +18,7 @@ from inspection.output_formatter import (
17
  persist_inspection,
18
  )
19
  from inspection.severity import classify_defect
 
20
 
21
 
22
  SEVERITY_COLOR = {
@@ -26,6 +28,7 @@ SEVERITY_COLOR = {
26
  }
27
 
28
  _INSPECTOR: DefectInspector | None = None
 
29
 
30
 
31
  def get_inspector() -> DefectInspector:
@@ -37,6 +40,18 @@ def get_inspector() -> DefectInspector:
37
  return _INSPECTOR
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def decode_base64_image(data_url: str) -> np.ndarray:
41
  encoded = data_url.split(",", 1)[1] if "," in data_url else data_url
42
 
@@ -106,6 +121,7 @@ def annotate_image(
106
  image: np.ndarray,
107
  defects: list[dict[str, Any]],
108
  decision: str,
 
109
  ) -> np.ndarray:
110
  annotated = image.copy()
111
 
@@ -142,7 +158,18 @@ def annotate_image(
142
  2,
143
  )
144
 
145
- if not defects:
 
 
 
 
 
 
 
 
 
 
 
146
  cv2.putText(
147
  annotated,
148
  "No actionable defects detected in current frame",
@@ -156,6 +183,50 @@ def annotate_image(
156
  return annotated
157
 
158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  def inspect_image_array(
160
  image: np.ndarray,
161
  *,
@@ -164,14 +235,31 @@ def inspect_image_array(
164
  persist: bool = True,
165
  llm_mode: str = "auto",
166
  ) -> dict[str, Any]:
167
- inspector = get_inspector()
168
- detections = inspector.inspect_image(image)
169
- public_defects, drawable_defects = _build_serializable_defects(detections, image.shape)
170
  resolved_metadata = {
171
  **(metadata or {}),
172
  "persist": persist,
 
 
173
  "llm_mode": llm_mode,
174
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  output = format_inspection_output(
177
  public_defects,
@@ -199,6 +287,7 @@ def inspect_image_array(
199
  "minor": output["summary"]["Minor"],
200
  "moderate": output["summary"]["Moderate"],
201
  "critical": output["summary"]["Critical"],
 
202
  "inspection_state": (
203
  "defects_detected" if output["total_defects"] > 0 else "clear_frame"
204
  ),
 
1
  import base64
2
  import binascii
3
+ import textwrap
4
  from typing import Any
5
 
6
  import cv2
 
18
  persist_inspection,
19
  )
20
  from inspection.severity import classify_defect
21
+ from inspection.surface_gate import SteelSurfaceGate, SurfaceGateResult
22
 
23
 
24
  SEVERITY_COLOR = {
 
28
  }
29
 
30
  _INSPECTOR: DefectInspector | None = None
31
+ _SURFACE_GATE: SteelSurfaceGate | None = None
32
 
33
 
34
  def get_inspector() -> DefectInspector:
 
40
  return _INSPECTOR
41
 
42
 
43
+ def get_surface_gate() -> SteelSurfaceGate | None:
44
+ global _SURFACE_GATE
45
+
46
+ if not settings.SURFACE_GATE_ENABLED:
47
+ return None
48
+
49
+ if _SURFACE_GATE is None:
50
+ _SURFACE_GATE = SteelSurfaceGate()
51
+
52
+ return _SURFACE_GATE
53
+
54
+
55
  def decode_base64_image(data_url: str) -> np.ndarray:
56
  encoded = data_url.split(",", 1)[1] if "," in data_url else data_url
57
 
 
121
  image: np.ndarray,
122
  defects: list[dict[str, Any]],
123
  decision: str,
124
+ note: str | None = None,
125
  ) -> np.ndarray:
126
  annotated = image.copy()
127
 
 
158
  2,
159
  )
160
 
161
+ if note:
162
+ for index, line in enumerate(textwrap.wrap(note, width=48)[:3]):
163
+ cv2.putText(
164
+ annotated,
165
+ line,
166
+ (34, 132 + (index * 28)),
167
+ cv2.FONT_HERSHEY_SIMPLEX,
168
+ 0.56,
169
+ (225, 232, 240),
170
+ 2,
171
+ )
172
+ elif not defects:
173
  cv2.putText(
174
  annotated,
175
  "No actionable defects detected in current frame",
 
183
  return annotated
184
 
185
 
186
+ def build_surface_gate_result(
187
+ image: np.ndarray,
188
+ *,
189
+ source: str,
190
+ metadata: dict[str, Any],
191
+ surface_result: SurfaceGateResult,
192
+ ) -> dict[str, Any]:
193
+ output = format_inspection_output(
194
+ [],
195
+ source=source,
196
+ metadata={
197
+ **metadata,
198
+ "surface_gate": surface_result.to_metadata(),
199
+ },
200
+ decision="SKIPPED",
201
+ recommendation=(
202
+ "Frame skipped because the system could not confirm a steel inspection surface. "
203
+ "Point the camera only at the sheet, coil, or sample before retrying."
204
+ ),
205
+ )
206
+
207
+ output["summary_text"] = surface_result.reason
208
+ output["agent_mode"] = "surface_gate"
209
+ output["agent_provider"] = "Steel Surface Gate"
210
+ output["agent_model"] = surface_result.mode
211
+
212
+ annotated_image = annotate_image(
213
+ image,
214
+ [],
215
+ output["decision"],
216
+ note=surface_result.reason,
217
+ )
218
+
219
+ return {
220
+ **output,
221
+ "minor": 0,
222
+ "moderate": 0,
223
+ "critical": 0,
224
+ "inspection_state": "non_steel_surface",
225
+ "surface_gate": surface_result.to_metadata(),
226
+ "annotated_image": encode_image_to_data_url(annotated_image),
227
+ }
228
+
229
+
230
  def inspect_image_array(
231
  image: np.ndarray,
232
  *,
 
235
  persist: bool = True,
236
  llm_mode: str = "auto",
237
  ) -> dict[str, Any]:
 
 
 
238
  resolved_metadata = {
239
  **(metadata or {}),
240
  "persist": persist,
241
+ "persist_requested": persist,
242
+ "persist_applied": persist,
243
  "llm_mode": llm_mode,
244
  }
245
+ surface_gate = get_surface_gate()
246
+
247
+ if surface_gate is not None:
248
+ surface_result = surface_gate.evaluate(image)
249
+ resolved_metadata["surface_gate"] = surface_result.to_metadata()
250
+
251
+ if not surface_result.is_steel:
252
+ resolved_metadata["persist_applied"] = False
253
+ return build_surface_gate_result(
254
+ image,
255
+ source=source,
256
+ metadata=resolved_metadata,
257
+ surface_result=surface_result,
258
+ )
259
+
260
+ inspector = get_inspector()
261
+ detections = inspector.inspect_image(image)
262
+ public_defects, drawable_defects = _build_serializable_defects(detections, image.shape)
263
 
264
  output = format_inspection_output(
265
  public_defects,
 
287
  "minor": output["summary"]["Minor"],
288
  "moderate": output["summary"]["Moderate"],
289
  "critical": output["summary"]["Critical"],
290
+ "surface_gate": resolved_metadata.get("surface_gate"),
291
  "inspection_state": (
292
  "defects_detected" if output["total_defects"] > 0 else "clear_frame"
293
  ),
inspection/surface_gate.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import cv2
8
+ import numpy as np
9
+
10
+ from core.config import settings
11
+ from core.logger import logger
12
+
13
+ try:
14
+ from ultralytics import YOLO
15
+ except Exception: # pragma: no cover - optional import guard
16
+ YOLO = None
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class SurfaceGateResult:
21
+ is_steel: bool
22
+ confidence: float
23
+ mode: str
24
+ label: str
25
+ reason: str
26
+ metrics: dict[str, float]
27
+
28
+ def to_metadata(self) -> dict[str, Any]:
29
+ return {
30
+ "passed": self.is_steel,
31
+ "confidence": round(self.confidence, 3),
32
+ "mode": self.mode,
33
+ "label": self.label,
34
+ "reason": self.reason,
35
+ "metrics": self.metrics,
36
+ }
37
+
38
+
39
+ class SteelSurfaceGate:
40
+ def __init__(self, model_path: str | None = None):
41
+ self.model_path = model_path or settings.SURFACE_CLASSIFIER_PATH
42
+ self.model = None
43
+ self.mode = "heuristic"
44
+
45
+ if not self.model_path:
46
+ return
47
+
48
+ resolved_path = Path(self.model_path)
49
+ if not resolved_path.exists():
50
+ logger.warning(
51
+ "Surface classifier path does not exist, using heuristic gate: %s",
52
+ resolved_path,
53
+ )
54
+ return
55
+
56
+ if YOLO is None:
57
+ logger.warning("Ultralytics is unavailable for the surface classifier, using heuristic gate")
58
+ return
59
+
60
+ try:
61
+ self.model = YOLO(str(resolved_path))
62
+ self.mode = "classifier"
63
+ logger.info("Surface gate classifier loaded from: %s", resolved_path)
64
+ except Exception as exc: # pragma: no cover - defensive runtime fallback
65
+ logger.warning("Surface classifier failed to load, using heuristic gate: %s", exc)
66
+
67
+ def evaluate(self, image: np.ndarray) -> SurfaceGateResult:
68
+ if self.model is not None:
69
+ try:
70
+ return self._evaluate_with_classifier(image)
71
+ except Exception as exc: # pragma: no cover - runtime safeguard
72
+ logger.warning("Surface classifier inference failed, using heuristic gate: %s", exc)
73
+
74
+ return self._evaluate_with_heuristic(image)
75
+
76
+ def _evaluate_with_classifier(self, image: np.ndarray) -> SurfaceGateResult:
77
+ results = self.model(image, verbose=False)
78
+ result = results[0]
79
+ probs = getattr(result, "probs", None)
80
+ names = getattr(result, "names", None) or getattr(self.model, "names", {})
81
+
82
+ if probs is None:
83
+ raise RuntimeError("Classification model returned no probabilities")
84
+
85
+ top_index = int(getattr(probs, "top1", 0))
86
+ top_confidence_raw = getattr(probs, "top1conf")
87
+ top_confidence = float(
88
+ top_confidence_raw.item() if hasattr(top_confidence_raw, "item") else top_confidence_raw
89
+ )
90
+
91
+ if isinstance(names, dict):
92
+ label = str(names.get(top_index, top_index))
93
+ else:
94
+ label = str(names[top_index])
95
+
96
+ steel_label = settings.SURFACE_CLASSIFIER_STEEL_LABEL.strip().lower()
97
+ normalized_label = label.strip().lower()
98
+ is_steel = (
99
+ normalized_label == steel_label
100
+ or steel_label in normalized_label
101
+ or normalized_label in steel_label
102
+ )
103
+ meets_threshold = top_confidence >= settings.SURFACE_MIN_STEEL_CONFIDENCE
104
+
105
+ if is_steel and meets_threshold:
106
+ reason = (
107
+ f"Steel surface classifier accepted the frame with {top_confidence:.0%} confidence."
108
+ )
109
+ elif is_steel:
110
+ reason = (
111
+ "Frame resembles steel, but the classifier confidence is too low for reliable defect analysis."
112
+ )
113
+ else:
114
+ reason = (
115
+ f'Classifier labeled the frame as "{label}" instead of steel, so the defect model was skipped.'
116
+ )
117
+
118
+ return SurfaceGateResult(
119
+ is_steel=bool(is_steel and meets_threshold),
120
+ confidence=top_confidence,
121
+ mode="classifier",
122
+ label=label,
123
+ reason=reason,
124
+ metrics={},
125
+ )
126
+
127
+ def _evaluate_with_heuristic(self, image: np.ndarray) -> SurfaceGateResult:
128
+ features = self._extract_features(image)
129
+
130
+ checks = {
131
+ "gray_ratio": features["gray_ratio"] >= settings.SURFACE_MIN_GRAY_RATIO,
132
+ "low_sat_ratio": features["low_saturation_ratio"] >= settings.SURFACE_MIN_LOW_SAT_RATIO,
133
+ "mean_saturation": features["mean_saturation"] <= settings.SURFACE_MAX_MEAN_SATURATION,
134
+ "colorfulness": features["colorfulness"] <= settings.SURFACE_MAX_COLORFULNESS,
135
+ "skin_ratio": features["skin_ratio"] <= settings.SURFACE_MAX_SKIN_RATIO,
136
+ "texture_variance": features["texture_variance"] >= settings.SURFACE_MIN_TEXTURE_VARIANCE,
137
+ }
138
+
139
+ weights = {
140
+ "gray_ratio": 0.24,
141
+ "low_sat_ratio": 0.22,
142
+ "mean_saturation": 0.16,
143
+ "colorfulness": 0.16,
144
+ "skin_ratio": 0.12,
145
+ "texture_variance": 0.10,
146
+ }
147
+
148
+ score = sum(weights[name] for name, passed in checks.items() if passed)
149
+ chroma_gate = checks["gray_ratio"] and checks["low_sat_ratio"]
150
+ is_steel = score >= 0.72 and chroma_gate and checks["skin_ratio"]
151
+
152
+ failed_checks = [name for name, passed in checks.items() if not passed]
153
+ confidence = score if is_steel else min(0.99, max(0.55, 1.0 - score + 0.08 * len(failed_checks)))
154
+
155
+ if is_steel:
156
+ reason = (
157
+ f"Frame passed the steel-surface gate with {confidence:.0%} confidence and proceeded to defect segmentation."
158
+ )
159
+ else:
160
+ reason = self._build_failure_reason(features, failed_checks)
161
+
162
+ return SurfaceGateResult(
163
+ is_steel=is_steel,
164
+ confidence=confidence,
165
+ mode="heuristic",
166
+ label="steel" if is_steel else "non_steel",
167
+ reason=reason,
168
+ metrics={key: round(value, 4) for key, value in features.items()},
169
+ )
170
+
171
+ def _extract_features(self, image: np.ndarray) -> dict[str, float]:
172
+ height, width = image.shape[:2]
173
+ target_width = min(320, max(96, width))
174
+ target_height = max(96, int(height * target_width / max(width, 1)))
175
+ resized = cv2.resize(image, (target_width, target_height))
176
+
177
+ hsv = cv2.cvtColor(resized, cv2.COLOR_BGR2HSV)
178
+ gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
179
+ ycrcb = cv2.cvtColor(resized, cv2.COLOR_BGR2YCrCb)
180
+
181
+ b_channel, g_channel, r_channel = [channel.astype(np.float32) for channel in cv2.split(resized)]
182
+ saturation = hsv[:, :, 1].astype(np.float32)
183
+
184
+ gray_delta = settings.SURFACE_GRAY_DELTA
185
+ gray_mask = (
186
+ (np.abs(r_channel - g_channel) <= gray_delta)
187
+ & (np.abs(r_channel - b_channel) <= gray_delta)
188
+ & (np.abs(g_channel - b_channel) <= gray_delta)
189
+ )
190
+
191
+ rg = np.abs(r_channel - g_channel)
192
+ yb = np.abs(0.5 * (r_channel + g_channel) - b_channel)
193
+ colorfulness = (
194
+ np.sqrt(float(rg.std()) ** 2 + float(yb.std()) ** 2)
195
+ + 0.3 * np.sqrt(float(rg.mean()) ** 2 + float(yb.mean()) ** 2)
196
+ )
197
+
198
+ luminance, cr_channel, cb_channel = cv2.split(ycrcb)
199
+ skin_mask = (
200
+ (cr_channel > 135)
201
+ & (cr_channel < 180)
202
+ & (cb_channel > 85)
203
+ & (cb_channel < 135)
204
+ & (luminance > 60)
205
+ )
206
+
207
+ return {
208
+ "gray_ratio": float(gray_mask.mean()),
209
+ "low_saturation_ratio": float(
210
+ (saturation <= settings.SURFACE_LOW_SAT_PIXEL_THRESHOLD).mean()
211
+ ),
212
+ "mean_saturation": float(saturation.mean()),
213
+ "colorfulness": float(colorfulness),
214
+ "skin_ratio": float(skin_mask.mean()),
215
+ "texture_variance": float(cv2.Laplacian(gray, cv2.CV_32F).var()),
216
+ }
217
+
218
+ def _build_failure_reason(self, features: dict[str, float], failed_checks: list[str]) -> str:
219
+ if features["skin_ratio"] > settings.SURFACE_MAX_SKIN_RATIO:
220
+ return (
221
+ "Frame skipped because prominent skin-tone regions were detected. Aim the camera only at the steel surface."
222
+ )
223
+ if features["gray_ratio"] < settings.SURFACE_MIN_GRAY_RATIO:
224
+ return (
225
+ "Frame skipped because it contains too much color variation to match the expected steel surface appearance."
226
+ )
227
+ if features["low_saturation_ratio"] < settings.SURFACE_MIN_LOW_SAT_RATIO:
228
+ return (
229
+ "Frame skipped because the image is too saturated. Move closer to the metal surface and reduce background content."
230
+ )
231
+ if features["texture_variance"] < settings.SURFACE_MIN_TEXTURE_VARIANCE:
232
+ return (
233
+ "Frame skipped because the visible area is too flat or out of focus for reliable steel-surface validation."
234
+ )
235
+ if features["colorfulness"] > settings.SURFACE_MAX_COLORFULNESS:
236
+ return (
237
+ "Frame skipped because the scene looks like a general object view instead of a steel inspection close-up."
238
+ )
239
+
240
+ failed_text = ", ".join(failed_checks) if failed_checks else "multiple surface validation checks"
241
+ return (
242
+ f"Frame skipped because it did not pass the steel-surface gate ({failed_text}). Reposition the camera toward the material and retry."
243
+ )
live_camera.py CHANGED
@@ -16,6 +16,8 @@ from inspection.output_formatter import (
16
  persist_inspection,
17
  )
18
  from inspection.class_map import CLASS_MAP
 
 
19
 
20
  from agent.langgraph_agent import run_agent
21
 
@@ -26,6 +28,7 @@ setup_logger()
26
  def main():
27
 
28
  inspector = DefectInspector(settings.MODEL_PATH)
 
29
  tracker = DefectTracker()
30
  lifecycle = DefectLifecycleManager(settings.MAX_MISSING_FRAMES)
31
 
@@ -65,6 +68,23 @@ def main():
65
 
66
  frame_count += 1
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  # ---------------- DETECTION ----------------
69
  detections = inspector.inspect_image(frame)
70
  defects = tracker.update(detections)
 
16
  persist_inspection,
17
  )
18
  from inspection.class_map import CLASS_MAP
19
+ from inspection.service import annotate_image
20
+ from inspection.surface_gate import SteelSurfaceGate
21
 
22
  from agent.langgraph_agent import run_agent
23
 
 
28
  def main():
29
 
30
  inspector = DefectInspector(settings.MODEL_PATH)
31
+ surface_gate = SteelSurfaceGate() if settings.SURFACE_GATE_ENABLED else None
32
  tracker = DefectTracker()
33
  lifecycle = DefectLifecycleManager(settings.MAX_MISSING_FRAMES)
34
 
 
68
 
69
  frame_count += 1
70
 
71
+ if surface_gate is not None:
72
+ surface_result = surface_gate.evaluate(frame)
73
+ if not surface_result.is_steel:
74
+ annotated = annotate_image(
75
+ display_frame,
76
+ [],
77
+ "SKIPPED",
78
+ note=surface_result.reason,
79
+ )
80
+ cv2.imshow("Inspection System", annotated)
81
+
82
+ key = cv2.waitKey(500) & 0xFF
83
+ if key == 27 or key == ord('q'):
84
+ logger.info("Exit signal received")
85
+ break
86
+ continue
87
+
88
  # ---------------- DETECTION ----------------
89
  detections = inspector.inspect_image(frame)
90
  defects = tracker.update(detections)