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

Add detector-first steel ROI gate and training toolkit

Browse files
.env.example CHANGED
@@ -10,6 +10,12 @@ 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
@@ -21,3 +27,6 @@ SURFACE_MAX_MEAN_SATURATION=40
21
  SURFACE_MAX_COLORFULNESS=24
22
  SURFACE_MAX_SKIN_RATIO=0.16
23
  SURFACE_MIN_TEXTURE_VARIANCE=80
 
 
 
 
10
  HF_ROUTER_BASE_URL=https://router.huggingface.co/v1
11
  MAX_UPLOAD_SIZE_MB=8
12
  SURFACE_GATE_ENABLED=true
13
+ SURFACE_DETECTOR_PATH=
14
+ SURFACE_DETECTOR_CLASS_NAME=steel_surface
15
+ SURFACE_DETECTOR_CONFIDENCE=0.40
16
+ SURFACE_DETECTOR_MIN_AREA_RATIO=0.12
17
+ SURFACE_DETECTOR_EXPAND_RATIO=0.04
18
+ SURFACE_DETECTOR_IMAGE_SIZE=640
19
  SURFACE_CLASSIFIER_PATH=
20
  SURFACE_CLASSIFIER_STEEL_LABEL=steel
21
  SURFACE_MIN_STEEL_CONFIDENCE=0.55
 
27
  SURFACE_MAX_COLORFULNESS=24
28
  SURFACE_MAX_SKIN_RATIO=0.16
29
  SURFACE_MIN_TEXTURE_VARIANCE=80
30
+ OPENROUTER_API_KEY=
31
+ OPENROUTER_MODEL=openrouter/free
32
+ OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
README.md CHANGED
@@ -9,14 +9,15 @@ app_port: 7860
9
 
10
  # Manufacturing Monitoring System
11
 
12
- Manufacturing Monitoring System is a full-stack industrial monitoring platform for steel surface inspection. It combines AI-based defect detection, automated report generation, WebSocket-driven live updates, analytics, and a modern operator dashboard built for real-time manufacturing visibility.
13
 
14
  ## Highlights
15
 
16
  - Real-time defect detection for steel surface images
 
17
  - Browser camera inspection and uploaded image inspection
18
  - Fast real-time inspection mode with optional deep AI analysis
19
- - Ollama or Hugging Face-powered manufacturing recommendations and defect summaries
20
  - FastAPI backend with REST and WebSocket streaming
21
  - Local JSON report persistence with optional PostgreSQL logging
22
  - React + Vite + Tailwind monitoring dashboard
@@ -25,7 +26,7 @@ Manufacturing Monitoring System is a full-stack industrial monitoring platform f
25
  ## Tech Stack
26
 
27
  - Backend: FastAPI, Uvicorn, OpenCV, Ultralytics YOLO
28
- - LLM: LangGraph + LangChain with Ollama or Hugging Face Inference Providers
29
  - Frontend: React, Vite, Tailwind CSS, Recharts
30
  - Realtime: WebSocket broadcast pipeline
31
  - Storage: Local reports plus optional PostgreSQL or Supabase
@@ -39,6 +40,7 @@ core/ Config, logging, constants, database access
39
  inspection/ Inference, formatting, reporting, service layer
40
  dashboard/ React monitoring dashboard
41
  models/ Trained defect detection model
 
42
  test_images/ Sample images for local testing
43
  live_camera.py Simulation runner for offline inspection playback
44
  main.py Python entry point
@@ -56,6 +58,7 @@ main.py Python entry point
56
 
57
  - Upload an image and run inspection
58
  - Use browser camera feed for auto or manual live inspection
 
59
  - Annotated preview output for every inspected frame
60
  - Fast mode for real-time inspection and optional deep AI analysis toggle
61
  - PASS, REVIEW, and FAIL guidance with visible operator feedback
@@ -100,6 +103,9 @@ OLLAMA_TIMEOUT_SECONDS=6
100
  HF_TOKEN=
101
  HF_CHAT_MODEL=meta-llama/Llama-3.1-8B-Instruct:cerebras
102
  HF_ROUTER_BASE_URL=https://router.huggingface.co/v1
 
 
 
103
  MAX_UPLOAD_SIZE_MB=8
104
  ```
105
 
@@ -109,9 +115,28 @@ If `ENABLE_LLM_REPORTS=true`, the system can use:
109
 
110
  - `LLM_PROVIDER=ollama` for local development with Ollama
111
  - `LLM_PROVIDER=huggingface` for cloud deployment with `HF_TOKEN`
 
112
 
113
  If the configured provider is unavailable, the app falls back to a rule-based recommendation path automatically.
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  ## Deployment
116
 
117
  For a single public URL without needing any local computer:
 
9
 
10
  # Manufacturing Monitoring System
11
 
12
+ Manufacturing Monitoring System is a full-stack industrial monitoring platform for steel surface inspection. It localizes the steel ROI before defect segmentation, generates automated reports, streams live updates over WebSockets, and exposes a production-style dashboard for real-time manufacturing visibility.
13
 
14
  ## Highlights
15
 
16
  - Real-time defect detection for steel surface images
17
+ - Steel ROI gating before defect segmentation
18
  - Browser camera inspection and uploaded image inspection
19
  - Fast real-time inspection mode with optional deep AI analysis
20
+ - OpenRouter, Ollama, or Hugging Face-powered manufacturing recommendations and defect summaries
21
  - FastAPI backend with REST and WebSocket streaming
22
  - Local JSON report persistence with optional PostgreSQL logging
23
  - React + Vite + Tailwind monitoring dashboard
 
26
  ## Tech Stack
27
 
28
  - Backend: FastAPI, Uvicorn, OpenCV, Ultralytics YOLO
29
+ - LLM: LangGraph + OpenRouter, Ollama, or Hugging Face Inference Providers
30
  - Frontend: React, Vite, Tailwind CSS, Recharts
31
  - Realtime: WebSocket broadcast pipeline
32
  - Storage: Local reports plus optional PostgreSQL or Supabase
 
40
  inspection/ Inference, formatting, reporting, service layer
41
  dashboard/ React monitoring dashboard
42
  models/ Trained defect detection model
43
+ training/ Steel ROI dataset builder and detector training scripts
44
  test_images/ Sample images for local testing
45
  live_camera.py Simulation runner for offline inspection playback
46
  main.py Python entry point
 
58
 
59
  - Upload an image and run inspection
60
  - Use browser camera feed for auto or manual live inspection
61
+ - Localize the steel ROI before defect segmentation
62
  - Annotated preview output for every inspected frame
63
  - Fast mode for real-time inspection and optional deep AI analysis toggle
64
  - PASS, REVIEW, and FAIL guidance with visible operator feedback
 
103
  HF_TOKEN=
104
  HF_CHAT_MODEL=meta-llama/Llama-3.1-8B-Instruct:cerebras
105
  HF_ROUTER_BASE_URL=https://router.huggingface.co/v1
106
+ OPENROUTER_API_KEY=
107
+ OPENROUTER_MODEL=openrouter/free
108
+ OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
109
  MAX_UPLOAD_SIZE_MB=8
110
  ```
111
 
 
115
 
116
  - `LLM_PROVIDER=ollama` for local development with Ollama
117
  - `LLM_PROVIDER=huggingface` for cloud deployment with `HF_TOKEN`
118
+ - `LLM_PROVIDER=openrouter` for low-volume free cloud demos with `OPENROUTER_API_KEY`
119
 
120
  If the configured provider is unavailable, the app falls back to a rule-based recommendation path automatically.
121
 
122
+ ## Steel ROI Detector Training
123
+
124
+ The project now supports a dedicated steel ROI detector at `models/steel_surface_detector.pt`.
125
+
126
+ Training scripts are included in:
127
+
128
+ - [training/README.md](/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy/training/README.md)
129
+ - [training/prepare_surface_gate_dataset.py](/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy/training/prepare_surface_gate_dataset.py)
130
+ - [training/train_surface_gate_detector.py](/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy/training/train_surface_gate_detector.py)
131
+
132
+ The quick path uses:
133
+
134
+ - automatic NEU steel-source download
135
+ - automatic Imagenette non-steel backgrounds
136
+ - synthetic steel-on-background composites for bounding-box supervision
137
+
138
+ Use `--include-severstal` when you want a larger, slower dataset build.
139
+
140
  ## Deployment
141
 
142
  For a single public URL without needing any local computer:
agent/langgraph_agent.py CHANGED
@@ -56,6 +56,10 @@ def is_huggingface_available() -> bool:
56
  return bool(settings.HF_TOKEN and settings.HF_CHAT_MODEL and settings.HF_ROUTER_BASE_URL)
57
 
58
 
 
 
 
 
59
  def request_huggingface_recommendation(prompt: str) -> str:
60
  if not is_huggingface_available():
61
  raise RuntimeError("Hugging Face Inference Providers is not configured")
@@ -106,6 +110,45 @@ def request_huggingface_recommendation(prompt: str) -> str:
106
  raise RuntimeError("Unable to extract recommendation content from Hugging Face response")
107
 
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  # -----------------------------
110
  # NODE 1: SUMMARY
111
  # -----------------------------
@@ -169,17 +212,23 @@ Give a STRICTLY INDUSTRIAL RESPONSE:
169
  1. Defect-wise Analysis
170
  2. Severity Impact
171
  3. Action Plan (Accept / Rework / Downgrade / Reject)
172
- 4. Process Improvement Suggestions
 
173
 
174
  Rules:
175
  - Be specific to EACH defect type
176
  - Avoid generic advice
177
  - Be practical and engineering-focused
 
178
  """
179
 
180
  try:
181
- if settings.LLM_PROVIDER.strip().lower() == "huggingface":
 
 
182
  response = request_huggingface_recommendation(prompt)
 
 
183
  else:
184
  llm = get_llm()
185
  response = llm.invoke(prompt)
@@ -303,6 +352,10 @@ def run_agent(input_data: Dict[str, Any], *, llm_mode: str = "auto") -> Dict[str
303
  if not is_huggingface_available():
304
  logger.warning("Hugging Face Inference Providers is unavailable. Using fallback inspection recommendation.")
305
  return fallback
 
 
 
 
306
  else:
307
  if OllamaLLM is None:
308
  logger.warning("Ollama dependencies are unavailable. Using fallback inspection recommendation.")
@@ -324,8 +377,20 @@ def run_agent(input_data: Dict[str, Any], *, llm_mode: str = "auto") -> Dict[str
324
  return {
325
  **result,
326
  "agent_mode": "llm",
327
- "agent_provider": "Hugging Face Inference Providers" if provider == "huggingface" else "Ollama",
328
- "agent_model": settings.HF_CHAT_MODEL if provider == "huggingface" else settings.OLLAMA_MODEL,
 
 
 
 
 
 
 
 
 
 
 
 
329
  }
330
 
331
  except Exception as e:
 
56
  return bool(settings.HF_TOKEN and settings.HF_CHAT_MODEL and settings.HF_ROUTER_BASE_URL)
57
 
58
 
59
+ def is_openrouter_available() -> bool:
60
+ return bool(settings.OPENROUTER_API_KEY and settings.OPENROUTER_MODEL and settings.OPENROUTER_BASE_URL)
61
+
62
+
63
  def request_huggingface_recommendation(prompt: str) -> str:
64
  if not is_huggingface_available():
65
  raise RuntimeError("Hugging Face Inference Providers is not configured")
 
110
  raise RuntimeError("Unable to extract recommendation content from Hugging Face response")
111
 
112
 
113
+ def request_openrouter_recommendation(prompt: str) -> str:
114
+ if not is_openrouter_available():
115
+ raise RuntimeError("OpenRouter is not configured")
116
+
117
+ payload = json.dumps({
118
+ "model": settings.OPENROUTER_MODEL,
119
+ "messages": [
120
+ {
121
+ "role": "user",
122
+ "content": prompt,
123
+ }
124
+ ],
125
+ "max_tokens": 220,
126
+ }).encode("utf-8")
127
+
128
+ request = Request(
129
+ f"{settings.OPENROUTER_BASE_URL.rstrip('/')}/chat/completions",
130
+ data=payload,
131
+ headers={
132
+ "Authorization": f"Bearer {settings.OPENROUTER_API_KEY}",
133
+ "Content-Type": "application/json",
134
+ },
135
+ method="POST",
136
+ )
137
+
138
+ with urlopen(request, timeout=settings.OLLAMA_TIMEOUT_SECONDS) as response:
139
+ body = json.loads(response.read().decode("utf-8"))
140
+
141
+ choices = body.get("choices") or []
142
+ if not choices:
143
+ raise RuntimeError("No choices were returned by OpenRouter")
144
+
145
+ message = choices[0].get("message") or {}
146
+ content = message.get("content", "")
147
+ if not content:
148
+ raise RuntimeError("Unable to extract recommendation content from OpenRouter")
149
+ return str(content)
150
+
151
+
152
  # -----------------------------
153
  # NODE 1: SUMMARY
154
  # -----------------------------
 
212
  1. Defect-wise Analysis
213
  2. Severity Impact
214
  3. Action Plan (Accept / Rework / Downgrade / Reject)
215
+ 4. Material Disposition Recommendation
216
+ 5. Process Improvement Suggestions
217
 
218
  Rules:
219
  - Be specific to EACH defect type
220
  - Avoid generic advice
221
  - Be practical and engineering-focused
222
+ - Include whether the material can still be downgraded for a lower-grade use case
223
  """
224
 
225
  try:
226
+ provider = settings.LLM_PROVIDER.strip().lower()
227
+
228
+ if provider == "huggingface":
229
  response = request_huggingface_recommendation(prompt)
230
+ elif provider == "openrouter":
231
+ response = request_openrouter_recommendation(prompt)
232
  else:
233
  llm = get_llm()
234
  response = llm.invoke(prompt)
 
352
  if not is_huggingface_available():
353
  logger.warning("Hugging Face Inference Providers is unavailable. Using fallback inspection recommendation.")
354
  return fallback
355
+ elif provider == "openrouter":
356
+ if not is_openrouter_available():
357
+ logger.warning("OpenRouter is unavailable. Using fallback inspection recommendation.")
358
+ return fallback
359
  else:
360
  if OllamaLLM is None:
361
  logger.warning("Ollama dependencies are unavailable. Using fallback inspection recommendation.")
 
377
  return {
378
  **result,
379
  "agent_mode": "llm",
380
+ "agent_provider": (
381
+ "Hugging Face Inference Providers"
382
+ if provider == "huggingface"
383
+ else "OpenRouter"
384
+ if provider == "openrouter"
385
+ else "Ollama"
386
+ ),
387
+ "agent_model": (
388
+ settings.HF_CHAT_MODEL
389
+ if provider == "huggingface"
390
+ else settings.OPENROUTER_MODEL
391
+ if provider == "openrouter"
392
+ else settings.OLLAMA_MODEL
393
+ ),
394
  }
395
 
396
  except Exception as e:
core/config.py CHANGED
@@ -103,6 +103,27 @@ class Settings:
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",
@@ -175,6 +196,13 @@ class Settings:
175
  HF_ROUTER_BASE_URL: str = field(
176
  default_factory=lambda: os.getenv("HF_ROUTER_BASE_URL", "https://router.huggingface.co/v1")
177
  )
 
 
 
 
 
 
 
178
 
179
  # -----------------------------
180
  # DATABASE
 
103
  SURFACE_GATE_ENABLED: bool = field(
104
  default_factory=lambda: _parse_bool("SURFACE_GATE_ENABLED", True)
105
  )
106
+ SURFACE_DETECTOR_PATH: str | None = field(
107
+ default_factory=lambda: _resolve_optional_path(
108
+ "SURFACE_DETECTOR_PATH",
109
+ "models/steel_surface_detector.pt",
110
+ )
111
+ )
112
+ SURFACE_DETECTOR_CLASS_NAME: str = field(
113
+ default_factory=lambda: os.getenv("SURFACE_DETECTOR_CLASS_NAME", "steel_surface")
114
+ )
115
+ SURFACE_DETECTOR_CONFIDENCE: float = field(
116
+ default_factory=lambda: float(os.getenv("SURFACE_DETECTOR_CONFIDENCE", "0.40"))
117
+ )
118
+ SURFACE_DETECTOR_MIN_AREA_RATIO: float = field(
119
+ default_factory=lambda: float(os.getenv("SURFACE_DETECTOR_MIN_AREA_RATIO", "0.12"))
120
+ )
121
+ SURFACE_DETECTOR_EXPAND_RATIO: float = field(
122
+ default_factory=lambda: float(os.getenv("SURFACE_DETECTOR_EXPAND_RATIO", "0.04"))
123
+ )
124
+ SURFACE_DETECTOR_IMAGE_SIZE: int = field(
125
+ default_factory=lambda: int(os.getenv("SURFACE_DETECTOR_IMAGE_SIZE", "640"))
126
+ )
127
  SURFACE_CLASSIFIER_PATH: str | None = field(
128
  default_factory=lambda: _resolve_optional_path(
129
  "SURFACE_CLASSIFIER_PATH",
 
196
  HF_ROUTER_BASE_URL: str = field(
197
  default_factory=lambda: os.getenv("HF_ROUTER_BASE_URL", "https://router.huggingface.co/v1")
198
  )
199
+ OPENROUTER_API_KEY: str | None = field(default_factory=lambda: os.getenv("OPENROUTER_API_KEY"))
200
+ OPENROUTER_MODEL: str = field(
201
+ default_factory=lambda: os.getenv("OPENROUTER_MODEL", "openrouter/free")
202
+ )
203
+ OPENROUTER_BASE_URL: str = field(
204
+ default_factory=lambda: os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")
205
+ )
206
 
207
  # -----------------------------
208
  # DATABASE
dashboard/src/components/Sidebar.jsx CHANGED
@@ -51,8 +51,8 @@ export default function Sidebar({ mobileOpen, onClose }) {
51
  </div>
52
 
53
  <p className="mt-4 text-sm leading-7 text-slate-300">
54
- AI-based inspection, automated reporting, live dashboard monitoring, database logging,
55
- and WebSocket-driven real-time streaming for steel surface quality operations.
56
  </p>
57
  </div>
58
 
 
51
  </div>
52
 
53
  <p className="mt-4 text-sm leading-7 text-slate-300">
54
+ Steel ROI localization, defect segmentation, automated reporting, live monitoring,
55
+ and decision support for production-facing quality operations.
56
  </p>
57
  </div>
58
 
dashboard/src/content/systemBrief.js CHANGED
@@ -1,15 +1,15 @@
1
  export const systemBrief = {
2
  title: "Manufacturing Monitoring System",
3
  goal:
4
- "A real-time industrial monitoring platform for steel surface quality with AI-based inspection, automated reporting, live dashboard monitoring, database logging, and WebSocket-driven streaming.",
5
  architectureFlow: [
6
  {
7
  title: "Camera and Image Intake",
8
  detail: "Collect uploaded inspection images or live browser camera frames from the shop floor.",
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",
@@ -79,11 +79,11 @@ export const systemBrief = {
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",
@@ -146,6 +146,7 @@ export const systemBrief = {
146
  currentState: {
147
  working: [
148
  "AI detection pipeline",
 
149
  "Local report persistence",
150
  "REST API",
151
  "Frontend routing",
@@ -154,8 +155,8 @@ export const systemBrief = {
154
  "Upload and camera inspection endpoints",
155
  ],
156
  inProgress: [
157
- "Database configuration per deployment",
158
- "Factory-floor data source integration",
159
  ],
160
  },
161
  improvements: {
@@ -176,10 +177,11 @@ export const systemBrief = {
176
  ],
177
  features: [
178
  "Live monitoring with upload and camera options.",
 
179
  "Analytics with inspection trends.",
180
  "Alerts with visual and audio cues.",
181
  ],
182
  },
183
  finalSummary:
184
- "This is a full-stack AI-powered manufacturing monitoring system that detects steel surface defects in real time, stores inspection data, and visualizes live operations through a responsive monitoring dashboard.",
185
  }
 
1
  export const systemBrief = {
2
  title: "Manufacturing Monitoring System",
3
  goal:
4
+ "A real-time industrial monitoring platform for steel quality inspection with ROI localization, defect segmentation, automated reporting, database logging, and WebSocket-driven live operations.",
5
  architectureFlow: [
6
  {
7
  title: "Camera and Image Intake",
8
  detail: "Collect uploaded inspection images or live browser camera frames from the shop floor.",
9
  },
10
  {
11
+ title: "Steel ROI and Defect Engine",
12
+ detail: "Localize the steel inspection region first, then run defect segmentation only inside that ROI to reduce false positives.",
13
  },
14
  {
15
  title: "Inspection Formatter",
 
79
  },
80
  {
81
  title: "Validate Surface",
82
+ detail: "Localize the steel ROI or reject the frame before segmentation so faces, tools, and background objects do not enter the defect pipeline.",
83
  },
84
  {
85
  title: "Infer",
86
+ detail: "Run segmentation only inside the approved steel ROI and extract contours, defect boxes, severity, and geometry.",
87
  },
88
  {
89
  title: "Decide",
 
146
  currentState: {
147
  working: [
148
  "AI detection pipeline",
149
+ "Steel ROI gate before defect segmentation",
150
  "Local report persistence",
151
  "REST API",
152
  "Frontend routing",
 
155
  "Upload and camera inspection endpoints",
156
  ],
157
  inProgress: [
158
+ "Detector model training with larger curated steel data",
159
+ "Cloud LLM API key configuration per deployment",
160
  ],
161
  },
162
  improvements: {
 
177
  ],
178
  features: [
179
  "Live monitoring with upload and camera options.",
180
+ "Steel ROI localization before segmentation.",
181
  "Analytics with inspection trends.",
182
  "Alerts with visual and audio cues.",
183
  ],
184
  },
185
  finalSummary:
186
+ "This is a full-stack manufacturing monitoring system that localizes the steel inspection region, detects surface defects in real time, stores inspection data, and visualizes live operations through a responsive dashboard.",
187
  }
dashboard/src/pages/Dashboard.jsx CHANGED
@@ -16,7 +16,7 @@ const FALLBACK_INSPECTION = {
16
  critical: 0,
17
  decision: "PASS",
18
  recommendation: "Waiting for the first inspection event.",
19
- summary_text: "AI copilot analysis will appear after the first completed inspection.",
20
  agent_mode: "heuristic",
21
  agent_provider: "Rule-Based Safety Engine",
22
  agent_model: "fallback",
@@ -58,7 +58,7 @@ export default function Dashboard() {
58
  <div>
59
  <p className="eyebrow">{systemBrief.title}</p>
60
  <h2 className="hero-title mt-3">
61
- Real-time manufacturing monitoring, reporting, and industrial-grade visibility for steel surface quality.
62
  </h2>
63
  <p className="body-copy mt-5 max-w-3xl">{systemBrief.goal}</p>
64
 
@@ -95,7 +95,7 @@ export default function Dashboard() {
95
  </div>
96
 
97
  <div className="surface-card p-6">
98
- <p className="eyebrow">Current State</p>
99
  <div className="mt-4 space-y-5">
100
  <div>
101
  <p className="text-sm font-medium uppercase tracking-[0.24em] text-emerald-200/80">Working</p>
@@ -171,15 +171,21 @@ export default function Dashboard() {
171
  <div className="mt-5 rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5">
172
  <div className="flex flex-wrap items-center gap-3">
173
  <StatusBadge
174
- label={inspection.agent_mode === "llm" ? "Ollama AI" : "Fallback AI"}
175
- tone={inspection.agent_mode === "llm" ? "info" : "warning"}
 
 
 
 
 
 
176
  />
177
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">
178
  {inspection.agent_provider} {inspection.agent_model && inspection.agent_model !== "fallback" ? `· ${inspection.agent_model}` : ""}
179
  </div>
180
  </div>
181
  <p className="mt-4 text-sm leading-7 text-cyan-50/95">
182
- {inspection.summary_text || "AI copilot analysis will appear after the next completed inspection."}
183
  </p>
184
  </div>
185
 
 
16
  critical: 0,
17
  decision: "PASS",
18
  recommendation: "Waiting for the first inspection event.",
19
+ summary_text: "Decision support guidance will appear after the first completed inspection.",
20
  agent_mode: "heuristic",
21
  agent_provider: "Rule-Based Safety Engine",
22
  agent_model: "fallback",
 
58
  <div>
59
  <p className="eyebrow">{systemBrief.title}</p>
60
  <h2 className="hero-title mt-3">
61
+ Production-grade monitoring, reporting, and decision support for steel surface inspection.
62
  </h2>
63
  <p className="body-copy mt-5 max-w-3xl">{systemBrief.goal}</p>
64
 
 
95
  </div>
96
 
97
  <div className="surface-card p-6">
98
+ <p className="eyebrow">Platform Scope</p>
99
  <div className="mt-4 space-y-5">
100
  <div>
101
  <p className="text-sm font-medium uppercase tracking-[0.24em] text-emerald-200/80">Working</p>
 
171
  <div className="mt-5 rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5">
172
  <div className="flex flex-wrap items-center gap-3">
173
  <StatusBadge
174
+ label={
175
+ inspection.agent_mode === "llm"
176
+ ? "Decision Copilot"
177
+ : inspection.agent_mode === "surface_gate"
178
+ ? "Surface Gate"
179
+ : "Rules Engine"
180
+ }
181
+ tone={inspection.agent_mode === "llm" || inspection.agent_mode === "surface_gate" ? "info" : "warning"}
182
  />
183
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">
184
  {inspection.agent_provider} {inspection.agent_model && inspection.agent_model !== "fallback" ? `· ${inspection.agent_model}` : ""}
185
  </div>
186
  </div>
187
  <p className="mt-4 text-sm leading-7 text-cyan-50/95">
188
+ {inspection.summary_text || "Decision support guidance will appear after the next completed inspection."}
189
  </p>
190
  </div>
191
 
dashboard/src/pages/History.jsx CHANGED
@@ -69,7 +69,7 @@ export default function History() {
69
  <p className="eyebrow">Inspection Logs</p>
70
  <h2 className="hero-title mt-3">Trace each inspection event, defect mix, and final decision in one organized log.</h2>
71
  <p className="body-copy mt-5 max-w-3xl">
72
- History is pulled from the reporting layer and shows timestamp, severity counts, defect classes, and decision context for every saved inspection.
73
  </p>
74
  </div>
75
 
@@ -179,15 +179,21 @@ export default function History() {
179
  <div className="rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5">
180
  <div className="flex flex-wrap items-center gap-3">
181
  <StatusBadge
182
- label={selectedReport.agent_mode === "llm" ? "Ollama AI" : "Fallback AI"}
183
- tone={selectedReport.agent_mode === "llm" ? "info" : "warning"}
 
 
 
 
 
 
184
  />
185
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">
186
  {selectedReport.agent_provider} {selectedReport.agent_model && selectedReport.agent_model !== "fallback" ? `· ${selectedReport.agent_model}` : ""}
187
  </div>
188
  </div>
189
  <p className="mt-4 text-sm leading-7 text-cyan-50/95">
190
- {selectedReport.summary_text || "No AI copilot summary was stored for this inspection."}
191
  </p>
192
  </div>
193
 
 
69
  <p className="eyebrow">Inspection Logs</p>
70
  <h2 className="hero-title mt-3">Trace each inspection event, defect mix, and final decision in one organized log.</h2>
71
  <p className="body-copy mt-5 max-w-3xl">
72
+ History is pulled from the reporting layer and shows timestamp, severity counts, defect classes, inspection source, and disposition context for every saved inspection.
73
  </p>
74
  </div>
75
 
 
179
  <div className="rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5">
180
  <div className="flex flex-wrap items-center gap-3">
181
  <StatusBadge
182
+ label={
183
+ selectedReport.agent_mode === "llm"
184
+ ? "Decision Copilot"
185
+ : selectedReport.agent_mode === "surface_gate"
186
+ ? "Surface Gate"
187
+ : "Rules Engine"
188
+ }
189
+ tone={selectedReport.agent_mode === "llm" || selectedReport.agent_mode === "surface_gate" ? "info" : "warning"}
190
  />
191
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">
192
  {selectedReport.agent_provider} {selectedReport.agent_model && selectedReport.agent_model !== "fallback" ? `· ${selectedReport.agent_model}` : ""}
193
  </div>
194
  </div>
195
  <p className="mt-4 text-sm leading-7 text-cyan-50/95">
196
+ {selectedReport.summary_text || "No decision support summary was stored for this inspection."}
197
  </p>
198
  </div>
199
 
dashboard/src/pages/Live.jsx CHANGED
@@ -258,7 +258,7 @@ export default function Live() {
258
  <h2 className="hero-title mt-3">Upload images or use the browser camera for organized, real-time manufacturing inspection.</h2>
259
  <p className="body-copy mt-5 max-w-3xl">
260
  The live workspace below lets operators analyze still images, stream camera frames for continuous
261
- detection, and capture both AI inspection decisions and LLM-assisted manufacturing recommendations.
262
  </p>
263
 
264
  <div className="mt-6 flex flex-wrap gap-3">
@@ -338,7 +338,7 @@ export default function Live() {
338
  </label>
339
 
340
  <div className="rounded-3xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-7 text-amber-50">
341
- Fast mode is optimized for real-time detection. Turn on deep analysis only when you want the slower Ollama-based recommendation layer.
342
  </div>
343
  </div>
344
  ) : (
@@ -425,10 +425,10 @@ export default function Live() {
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>
433
  </div>
434
  </div>
@@ -470,6 +470,11 @@ export default function Live() {
470
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300">
471
  {formatDateTime(inspectionResult.timestamp)}
472
  </div>
 
 
 
 
 
473
  </div>
474
 
475
  <p className="text-sm leading-7 text-slate-300">{inspectionResult.recommendation}</p>
@@ -479,10 +484,10 @@ export default function Live() {
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"
@@ -497,7 +502,7 @@ export default function Live() {
497
  </div>
498
  </div>
499
  <p className="mt-4 text-sm leading-7 text-cyan-50/95">
500
- {inspectionResult.summary_text || "AI copilot summary is not available for this inspection yet."}
501
  </p>
502
  </div>
503
 
 
258
  <h2 className="hero-title mt-3">Upload images or use the browser camera for organized, real-time manufacturing inspection.</h2>
259
  <p className="body-copy mt-5 max-w-3xl">
260
  The live workspace below lets operators analyze still images, stream camera frames for continuous
261
+ inspection, localize the steel ROI before defect segmentation, and capture both QA decisions and optional GenAI guidance.
262
  </p>
263
 
264
  <div className="mt-6 flex flex-wrap gap-3">
 
338
  </label>
339
 
340
  <div className="rounded-3xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-7 text-amber-50">
341
+ Fast mode is optimized for real-time monitoring. Turn on deep analysis only when you want the slower cloud GenAI recommendation layer.
342
  </div>
343
  </div>
344
  ) : (
 
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. When a steel ROI is localized, only that region is forwarded to defect segmentation. Faces, hands, machinery, and background clutter are skipped upstream.
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 response. Turn it on only when you want a slower GenAI disposition note for a specific frame.
432
  </div>
433
  </div>
434
  </div>
 
470
  <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300">
471
  {formatDateTime(inspectionResult.timestamp)}
472
  </div>
473
+ {inspectionResult.inspection_region ? (
474
+ <div className="rounded-full border border-cyan-300/20 bg-cyan-400/10 px-4 py-2 text-sm text-cyan-50">
475
+ Steel ROI localized before segmentation
476
+ </div>
477
+ ) : null}
478
  </div>
479
 
480
  <p className="text-sm leading-7 text-slate-300">{inspectionResult.recommendation}</p>
 
484
  <StatusBadge
485
  label={
486
  inspectionResult.agent_mode === "llm"
487
+ ? "Decision Copilot"
488
  : inspectionResult.agent_mode === "surface_gate"
489
+ ? "Steel ROI Gate"
490
+ : "Rules Engine"
491
  }
492
  tone={
493
  inspectionResult.agent_mode === "llm"
 
502
  </div>
503
  </div>
504
  <p className="mt-4 text-sm leading-7 text-cyan-50/95">
505
+ {inspectionResult.summary_text || "Decision support guidance is not available for this inspection yet."}
506
  </p>
507
  </div>
508
 
inspection/service.py CHANGED
@@ -117,14 +117,67 @@ def _build_serializable_defects(detections: list[dict[str, Any]], image_shape: t
117
  return public_defects, drawable_defects
118
 
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  def annotate_image(
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  for defect in defects:
129
  x, y, w, h = defect["bbox"]
130
  color = SEVERITY_COLOR.get(defect["severity"], (122, 122, 122))
@@ -214,6 +267,8 @@ def build_surface_gate_result(
214
  [],
215
  output["decision"],
216
  note=surface_result.reason,
 
 
217
  )
218
 
219
  return {
@@ -257,9 +312,33 @@ def inspect_image_array(
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,
@@ -275,7 +354,13 @@ def inspect_image_array(
275
  output["agent_provider"] = agent_result.get("agent_provider", "Rule-Based Safety Engine")
276
  output["agent_model"] = agent_result.get("agent_model", "fallback")
277
 
278
- annotated_image = annotate_image(image, drawable_defects, output["decision"])
 
 
 
 
 
 
279
 
280
  if persist:
281
  persist_inspection(output)
@@ -288,6 +373,7 @@ def inspect_image_array(
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
  ),
 
117
  return public_defects, drawable_defects
118
 
119
 
120
+ def _translate_defects_to_full_frame(
121
+ public_defects: list[dict[str, Any]],
122
+ drawable_defects: list[dict[str, Any]],
123
+ x_offset: int,
124
+ y_offset: int,
125
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
126
+ translated_public: list[dict[str, Any]] = []
127
+ translated_drawable: list[dict[str, Any]] = []
128
+
129
+ for defect in public_defects:
130
+ x, y, w, h = defect["bbox"]
131
+ translated_public.append(
132
+ {
133
+ **defect,
134
+ "bbox": [x + x_offset, y + y_offset, w, h],
135
+ }
136
+ )
137
+
138
+ contour_offset = np.array([[[x_offset, y_offset]]], dtype=np.int32)
139
+ for defect in drawable_defects:
140
+ x, y, w, h = defect["bbox"]
141
+ translated_drawable.append(
142
+ {
143
+ **defect,
144
+ "bbox": (x + x_offset, y + y_offset, w, h),
145
+ "contour": defect["contour"].astype(np.int32) + contour_offset,
146
+ }
147
+ )
148
+
149
+ return translated_public, translated_drawable
150
+
151
+
152
  def annotate_image(
153
  image: np.ndarray,
154
  defects: list[dict[str, Any]],
155
  decision: str,
156
  note: str | None = None,
157
+ surface_bbox: tuple[int, int, int, int] | None = None,
158
+ surface_confidence: float | None = None,
159
  ) -> np.ndarray:
160
  annotated = image.copy()
161
 
162
+ if surface_bbox:
163
+ sx, sy, sw, sh = surface_bbox
164
+ surface_color = (255, 215, 0)
165
+ cv2.rectangle(annotated, (sx, sy), (sx + sw, sy + sh), surface_color, 2)
166
+ surface_label = (
167
+ f"Steel ROI {surface_confidence:.2f}"
168
+ if surface_confidence is not None
169
+ else "Steel ROI"
170
+ )
171
+ cv2.putText(
172
+ annotated,
173
+ surface_label,
174
+ (sx, max(30, sy - 10)),
175
+ cv2.FONT_HERSHEY_SIMPLEX,
176
+ 0.6,
177
+ surface_color,
178
+ 2,
179
+ )
180
+
181
  for defect in defects:
182
  x, y, w, h = defect["bbox"]
183
  color = SEVERITY_COLOR.get(defect["severity"], (122, 122, 122))
 
267
  [],
268
  output["decision"],
269
  note=surface_result.reason,
270
+ surface_bbox=surface_result.roi_bbox,
271
+ surface_confidence=surface_result.confidence,
272
  )
273
 
274
  return {
 
312
  surface_result=surface_result,
313
  )
314
 
315
+ inspection_image = image
316
+ inspection_region = None
317
+ if surface_gate is not None and surface_result.roi_bbox:
318
+ x_offset, y_offset, roi_width, roi_height = surface_result.roi_bbox
319
+ inspection_image = image[y_offset:y_offset + roi_height, x_offset:x_offset + roi_width]
320
+ inspection_region = {
321
+ "x": x_offset,
322
+ "y": y_offset,
323
+ "width": roi_width,
324
+ "height": roi_height,
325
+ }
326
+ resolved_metadata["inspection_region"] = inspection_region
327
+
328
  inspector = get_inspector()
329
+ detections = inspector.inspect_image(inspection_image)
330
+ public_defects, drawable_defects = _build_serializable_defects(
331
+ detections,
332
+ inspection_image.shape,
333
+ )
334
+
335
+ if inspection_region is not None:
336
+ public_defects, drawable_defects = _translate_defects_to_full_frame(
337
+ public_defects,
338
+ drawable_defects,
339
+ inspection_region["x"],
340
+ inspection_region["y"],
341
+ )
342
 
343
  output = format_inspection_output(
344
  public_defects,
 
354
  output["agent_provider"] = agent_result.get("agent_provider", "Rule-Based Safety Engine")
355
  output["agent_model"] = agent_result.get("agent_model", "fallback")
356
 
357
+ annotated_image = annotate_image(
358
+ image,
359
+ drawable_defects,
360
+ output["decision"],
361
+ surface_bbox=surface_result.roi_bbox if surface_gate is not None else None,
362
+ surface_confidence=surface_result.confidence if surface_gate is not None else None,
363
+ )
364
 
365
  if persist:
366
  persist_inspection(output)
 
373
  "moderate": output["summary"]["Moderate"],
374
  "critical": output["summary"]["Critical"],
375
  "surface_gate": resolved_metadata.get("surface_gate"),
376
+ "inspection_region": inspection_region,
377
  "inspection_state": (
378
  "defects_detected" if output["total_defects"] > 0 else "clear_frame"
379
  ),
inspection/surface_gate.py CHANGED
@@ -24,6 +24,8 @@ class SurfaceGateResult:
24
  label: str
25
  reason: str
26
  metrics: dict[str, float]
 
 
27
 
28
  def to_metadata(self) -> dict[str, Any]:
29
  return {
@@ -33,51 +35,181 @@ class SurfaceGateResult:
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")
@@ -87,11 +219,7 @@ class SteelSurfaceGate:
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()
@@ -122,6 +250,8 @@ class SteelSurfaceGate:
122
  label=label,
123
  reason=reason,
124
  metrics={},
 
 
125
  )
126
 
127
  def _evaluate_with_heuristic(self, image: np.ndarray) -> SurfaceGateResult:
@@ -166,8 +296,35 @@ class SteelSurfaceGate:
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))
 
24
  label: str
25
  reason: str
26
  metrics: dict[str, float]
27
+ roi_bbox: tuple[int, int, int, int] | None = None
28
+ roi_area_ratio: float | None = None
29
 
30
  def to_metadata(self) -> dict[str, Any]:
31
  return {
 
35
  "label": self.label,
36
  "reason": self.reason,
37
  "metrics": self.metrics,
38
+ "roi_bbox": list(self.roi_bbox) if self.roi_bbox else None,
39
+ "roi_area_ratio": round(self.roi_area_ratio, 4) if self.roi_area_ratio is not None else None,
40
  }
41
 
42
 
43
  class SteelSurfaceGate:
44
+ def __init__(self) -> None:
45
+ self.detector_model = self._load_model(settings.SURFACE_DETECTOR_PATH, "detector")
46
+ self.classifier_model = self._load_model(settings.SURFACE_CLASSIFIER_PATH, "classifier")
 
47
 
48
+ def _load_model(self, model_path: str | None, kind: str):
49
+ if not model_path:
50
+ return None
51
 
52
+ resolved_path = Path(model_path)
53
  if not resolved_path.exists():
54
+ logger.warning("Surface %s path does not exist: %s", kind, resolved_path)
55
+ return None
 
 
 
56
 
57
  if YOLO is None:
58
+ logger.warning("Ultralytics is unavailable for the surface %s model", kind)
59
+ return None
60
 
61
  try:
62
+ model = YOLO(str(resolved_path))
63
+ logger.info("Surface %s model loaded from: %s", kind, resolved_path)
64
+ return model
65
  except Exception as exc: # pragma: no cover - defensive runtime fallback
66
+ logger.warning("Surface %s model failed to load: %s", kind, exc)
67
+ return None
68
 
69
  def evaluate(self, image: np.ndarray) -> SurfaceGateResult:
70
+ if self.detector_model is not None:
71
+ return self._evaluate_with_detector(image)
72
+
73
+ if self.classifier_model is not None:
74
+ return self._evaluate_with_classifier(image)
75
 
76
  return self._evaluate_with_heuristic(image)
77
 
78
+ def _evaluate_with_detector(self, image: np.ndarray) -> SurfaceGateResult:
79
+ results = self.detector_model(
80
+ image,
81
+ conf=settings.SURFACE_DETECTOR_CONFIDENCE,
82
+ imgsz=settings.SURFACE_DETECTOR_IMAGE_SIZE,
83
+ verbose=False,
84
+ )
85
+ result = results[0]
86
+ boxes = getattr(result, "boxes", None)
87
+ names = getattr(result, "names", None) or getattr(self.detector_model, "names", {})
88
+
89
+ if boxes is None or len(boxes) == 0:
90
+ return SurfaceGateResult(
91
+ is_steel=False,
92
+ confidence=0.99,
93
+ mode="detector",
94
+ label="non_steel",
95
+ reason=(
96
+ "Frame skipped because no steel-surface region was localized. Aim the camera closer to the sheet or coil."
97
+ ),
98
+ metrics={"boxes_detected": 0.0},
99
+ )
100
+
101
+ height, width = image.shape[:2]
102
+ image_area = max(height * width, 1)
103
+ candidates: list[dict[str, float | tuple[int, int, int, int] | str]] = []
104
+
105
+ for raw_box in boxes:
106
+ xyxy = raw_box.xyxy[0].tolist()
107
+ x1, y1, x2, y2 = [int(round(value)) for value in xyxy]
108
+ x1 = max(0, min(x1, width - 1))
109
+ y1 = max(0, min(y1, height - 1))
110
+ x2 = max(x1 + 1, min(x2, width))
111
+ y2 = max(y1 + 1, min(y2, height))
112
+
113
+ box_width = x2 - x1
114
+ box_height = y2 - y1
115
+ area_ratio = (box_width * box_height) / image_area
116
+
117
+ cls_tensor = getattr(raw_box, "cls", None)
118
+ cls_index = int(cls_tensor[0].item()) if cls_tensor is not None else 0
119
+ label = self._resolve_label(names, cls_index)
120
+ confidence = float(raw_box.conf[0].item())
121
+
122
+ if not self._detector_label_matches(label, cls_index, names):
123
+ continue
124
+
125
+ expand_ratio = settings.SURFACE_DETECTOR_EXPAND_RATIO
126
+ pad_x = int(box_width * expand_ratio)
127
+ pad_y = int(box_height * expand_ratio)
128
+ expanded_x1 = max(0, x1 - pad_x)
129
+ expanded_y1 = max(0, y1 - pad_y)
130
+ expanded_x2 = min(width, x2 + pad_x)
131
+ expanded_y2 = min(height, y2 + pad_y)
132
+
133
+ expanded_bbox = (
134
+ expanded_x1,
135
+ expanded_y1,
136
+ expanded_x2 - expanded_x1,
137
+ expanded_y2 - expanded_y1,
138
+ )
139
+ expanded_area_ratio = (expanded_bbox[2] * expanded_bbox[3]) / image_area
140
+ selector_score = (confidence * 0.8) + (min(expanded_area_ratio / 0.55, 1.0) * 0.2)
141
+
142
+ candidates.append(
143
+ {
144
+ "confidence": confidence,
145
+ "label": label,
146
+ "bbox": expanded_bbox,
147
+ "area_ratio": expanded_area_ratio,
148
+ "selector_score": selector_score,
149
+ }
150
+ )
151
+
152
+ if not candidates:
153
+ return SurfaceGateResult(
154
+ is_steel=False,
155
+ confidence=0.99,
156
+ mode="detector",
157
+ label="non_steel",
158
+ reason=(
159
+ "Frame skipped because the localized objects did not match the expected steel-surface class."
160
+ ),
161
+ metrics={"boxes_detected": float(len(boxes))},
162
+ )
163
+
164
+ best_candidate = max(
165
+ candidates,
166
+ key=lambda candidate: (
167
+ float(candidate["selector_score"]),
168
+ float(candidate["confidence"]),
169
+ float(candidate["area_ratio"]),
170
+ ),
171
+ )
172
+
173
+ roi_area_ratio = float(best_candidate["area_ratio"])
174
+ if roi_area_ratio < settings.SURFACE_DETECTOR_MIN_AREA_RATIO:
175
+ return SurfaceGateResult(
176
+ is_steel=False,
177
+ confidence=float(best_candidate["confidence"]),
178
+ mode="detector",
179
+ label=str(best_candidate["label"]),
180
+ reason=(
181
+ "Frame skipped because the localized steel region is too small for reliable defect inspection. Move closer to the material."
182
+ ),
183
+ metrics={
184
+ "boxes_detected": float(len(candidates)),
185
+ "roi_area_ratio": round(roi_area_ratio, 4),
186
+ },
187
+ roi_bbox=best_candidate["bbox"],
188
+ roi_area_ratio=roi_area_ratio,
189
+ )
190
+
191
+ return SurfaceGateResult(
192
+ is_steel=True,
193
+ confidence=float(best_candidate["confidence"]),
194
+ mode="detector",
195
+ label=str(best_candidate["label"]),
196
+ reason=(
197
+ f"Steel-surface detector localized an inspection ROI with {float(best_candidate['confidence']):.0%} confidence."
198
+ ),
199
+ metrics={
200
+ "boxes_detected": float(len(candidates)),
201
+ "roi_area_ratio": round(roi_area_ratio, 4),
202
+ "selector_score": round(float(best_candidate["selector_score"]), 4),
203
+ },
204
+ roi_bbox=best_candidate["bbox"],
205
+ roi_area_ratio=roi_area_ratio,
206
+ )
207
+
208
  def _evaluate_with_classifier(self, image: np.ndarray) -> SurfaceGateResult:
209
+ results = self.classifier_model(image, verbose=False)
210
  result = results[0]
211
  probs = getattr(result, "probs", None)
212
+ names = getattr(result, "names", None) or getattr(self.classifier_model, "names", {})
213
 
214
  if probs is None:
215
  raise RuntimeError("Classification model returned no probabilities")
 
219
  top_confidence = float(
220
  top_confidence_raw.item() if hasattr(top_confidence_raw, "item") else top_confidence_raw
221
  )
222
+ label = self._resolve_label(names, top_index)
 
 
 
 
223
 
224
  steel_label = settings.SURFACE_CLASSIFIER_STEEL_LABEL.strip().lower()
225
  normalized_label = label.strip().lower()
 
250
  label=label,
251
  reason=reason,
252
  metrics={},
253
+ roi_bbox=(0, 0, image.shape[1], image.shape[0]) if is_steel and meets_threshold else None,
254
+ roi_area_ratio=1.0 if is_steel and meets_threshold else None,
255
  )
256
 
257
  def _evaluate_with_heuristic(self, image: np.ndarray) -> SurfaceGateResult:
 
296
  label="steel" if is_steel else "non_steel",
297
  reason=reason,
298
  metrics={key: round(value, 4) for key, value in features.items()},
299
+ roi_bbox=(0, 0, image.shape[1], image.shape[0]) if is_steel else None,
300
+ roi_area_ratio=1.0 if is_steel else None,
301
  )
302
 
303
+ def _resolve_label(self, names: Any, index: int) -> str:
304
+ if isinstance(names, dict):
305
+ return str(names.get(index, index))
306
+ if isinstance(names, list) and 0 <= index < len(names):
307
+ return str(names[index])
308
+ return str(index)
309
+
310
+ def _detector_label_matches(self, label: str, cls_index: int, names: Any) -> bool:
311
+ target = settings.SURFACE_DETECTOR_CLASS_NAME.strip().lower()
312
+ normalized_label = label.strip().lower()
313
+
314
+ if not target:
315
+ return True
316
+
317
+ if normalized_label == target or target in normalized_label or normalized_label in target:
318
+ return True
319
+
320
+ if isinstance(names, dict) and len(names) == 1 and cls_index == 0:
321
+ return True
322
+
323
+ if isinstance(names, list) and len(names) == 1 and cls_index == 0:
324
+ return True
325
+
326
+ return False
327
+
328
  def _extract_features(self, image: np.ndarray) -> dict[str, float]:
329
  height, width = image.shape[:2]
330
  target_width = min(320, max(96, width))
live_camera.py CHANGED
@@ -67,6 +67,8 @@ def main():
67
  continue
68
 
69
  frame_count += 1
 
 
70
 
71
  if surface_gate is not None:
72
  surface_result = surface_gate.evaluate(frame)
@@ -85,8 +87,13 @@ def main():
85
  break
86
  continue
87
 
 
 
 
 
 
88
  # ---------------- DETECTION ----------------
89
- detections = inspector.inspect_image(frame)
90
  defects = tracker.update(detections)
91
 
92
  annotated = display_frame.copy()
@@ -95,7 +102,7 @@ def main():
95
  # ---------------- PROCESS DEFECTS ----------------
96
  for d in defects:
97
 
98
- geometry = analyze_defect(d["contour"], display_frame.shape)
99
 
100
  decision = classify_defect(
101
  geometry["area_pixels"],
@@ -104,6 +111,12 @@ def main():
104
  )
105
 
106
  x, y, w, h = d["bbox"]
 
 
 
 
 
 
107
 
108
  color = (
109
  (0, 0, 255) if decision["decision"] == "FAIL"
@@ -112,16 +125,16 @@ def main():
112
  )
113
 
114
  # Bounding box
115
- cv2.rectangle(annotated, (x, y), (x+w, y+h), color, 2)
116
 
117
  # ---------------- SEGMENTATION MASK (FIX) ----------------
118
  # Filled overlay
119
  overlay = annotated.copy()
120
- cv2.drawContours(overlay, [d["contour"]], -1, color, -1)
121
  cv2.addWeighted(overlay, 0.3, annotated, 0.7, 0, annotated)
122
 
123
  # Outline
124
- cv2.drawContours(annotated, [d["contour"]], -1, color, 2)
125
 
126
  severity_score = SEVERITY_SCORE[decision["severity"]]
127
 
@@ -130,7 +143,7 @@ def main():
130
  "severity": decision["severity"],
131
  "area_ratio": round(geometry["area_ratio"], 5),
132
  "length": round(geometry["length_pixels"], 2),
133
- "bbox": d["bbox"],
134
  "severity_score": severity_score
135
  })
136
 
 
67
  continue
68
 
69
  frame_count += 1
70
+ detection_frame = frame
71
+ roi_offset = (0, 0)
72
 
73
  if surface_gate is not None:
74
  surface_result = surface_gate.evaluate(frame)
 
87
  break
88
  continue
89
 
90
+ if surface_result.roi_bbox:
91
+ x0, y0, width, height = surface_result.roi_bbox
92
+ detection_frame = frame[y0:y0 + height, x0:x0 + width]
93
+ roi_offset = (x0, y0)
94
+
95
  # ---------------- DETECTION ----------------
96
+ detections = inspector.inspect_image(detection_frame)
97
  defects = tracker.update(detections)
98
 
99
  annotated = display_frame.copy()
 
102
  # ---------------- PROCESS DEFECTS ----------------
103
  for d in defects:
104
 
105
+ geometry = analyze_defect(d["contour"], detection_frame.shape)
106
 
107
  decision = classify_defect(
108
  geometry["area_pixels"],
 
111
  )
112
 
113
  x, y, w, h = d["bbox"]
114
+ draw_x = x + roi_offset[0]
115
+ draw_y = y + roi_offset[1]
116
+ draw_contour = d["contour"].astype(np.int32) + np.array(
117
+ [[[roi_offset[0], roi_offset[1]]]],
118
+ dtype=np.int32,
119
+ )
120
 
121
  color = (
122
  (0, 0, 255) if decision["decision"] == "FAIL"
 
125
  )
126
 
127
  # Bounding box
128
+ cv2.rectangle(annotated, (draw_x, draw_y), (draw_x + w, draw_y + h), color, 2)
129
 
130
  # ---------------- SEGMENTATION MASK (FIX) ----------------
131
  # Filled overlay
132
  overlay = annotated.copy()
133
+ cv2.drawContours(overlay, [draw_contour], -1, color, -1)
134
  cv2.addWeighted(overlay, 0.3, annotated, 0.7, 0, annotated)
135
 
136
  # Outline
137
+ cv2.drawContours(annotated, [draw_contour], -1, color, 2)
138
 
139
  severity_score = SEVERITY_SCORE[decision["severity"]]
140
 
 
143
  "severity": decision["severity"],
144
  "area_ratio": round(geometry["area_ratio"], 5),
145
  "length": round(geometry["length_pixels"], 2),
146
+ "bbox": (draw_x, draw_y, w, h),
147
  "severity_score": severity_score
148
  })
149
 
training/README.md ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Steel ROI Gate Training
2
+
3
+ This project now supports a **steel-surface detector** in front of defect segmentation.
4
+
5
+ Why detector and not plain classifier?
6
+
7
+ 1. A classifier can say `steel` or `non_steel`, but it cannot give the bounding box you asked for.
8
+ 2. A detector can localize the steel region, crop that ROI, and send only that region into the defect segmentation model.
9
+ 3. This is the right architecture for mixed live-camera scenes with people, tools, and background clutter.
10
+
11
+ ## What the scripts do
12
+
13
+ `prepare_surface_gate_dataset.py`
14
+
15
+ - downloads steel-positive sources automatically
16
+ - downloads non-steel backgrounds automatically
17
+ - creates a YOLO detector dataset
18
+ - generates synthetic composites so the detector learns actual steel bounding boxes
19
+ - writes `dataset.yaml`
20
+
21
+ `train_surface_gate_detector.py`
22
+
23
+ - finetunes a small YOLO detector quickly
24
+ - copies the best checkpoint into `models/steel_surface_detector.pt`
25
+ - makes the web app use that model automatically after restart
26
+
27
+ ## Automatic data sources
28
+
29
+ Positive steel sources:
30
+
31
+ - NEU mirror on Hugging Face
32
+ - local `test_images/`
33
+ - optional Severstal mirror on Hugging Face
34
+
35
+ Automatic non-steel/background source:
36
+
37
+ - Imagenette via Hugging Face Datasets
38
+
39
+ This avoids making you manually collect a non-steel dataset.
40
+
41
+ ## Recommended quick workflow
42
+
43
+ 1. Install training extras:
44
+
45
+ ```bash
46
+ cd "/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy"
47
+ venv/bin/pip install -r training/requirements.txt
48
+ ```
49
+
50
+ 2. Build the detector dataset:
51
+
52
+ ```bash
53
+ cd "/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy"
54
+ venv/bin/python training/prepare_surface_gate_dataset.py
55
+ ```
56
+
57
+ This default mode is the fastest path because it avoids downloading the larger Severstal archive.
58
+
59
+ If you want a stronger detector after the first run, rebuild with Severstal included:
60
+
61
+ ```bash
62
+ venv/bin/python training/prepare_surface_gate_dataset.py --include-severstal
63
+ ```
64
+
65
+ 3. Train the lightweight detector:
66
+
67
+ ```bash
68
+ cd "/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy"
69
+ venv/bin/python training/train_surface_gate_detector.py
70
+ ```
71
+
72
+ 4. Restart the app:
73
+
74
+ ```bash
75
+ cd "/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy"
76
+ venv/bin/uvicorn api.main:app --host 127.0.0.1 --port 8000
77
+ ```
78
+
79
+ ## Fast settings
80
+
81
+ If you want the quickest useful first model:
82
+
83
+ - `model=yolo11n.pt`
84
+ - `epochs=18`
85
+ - `imgsz=512`
86
+ - `batch=16`
87
+ - dataset build without `--include-severstal`
88
+
89
+ If you have only CPU and want to finish faster:
90
+
91
+ ```bash
92
+ venv/bin/python training/train_surface_gate_detector.py --epochs 12 --imgsz 416 --batch 8
93
+ ```
94
+
95
+ ## If you want a stronger detector later
96
+
97
+ - increase `--max-severstal`
98
+ - increase `--max-negatives`
99
+ - raise `--composite-multiplier`
100
+ - train `25-40` epochs instead of `12-18`
101
+
102
+ ## Runtime config after training
103
+
104
+ The app will automatically use:
105
+
106
+ - `models/steel_surface_detector.pt`
107
+
108
+ Relevant env keys are already supported:
109
+
110
+ - `SURFACE_DETECTOR_PATH`
111
+ - `SURFACE_DETECTOR_CLASS_NAME`
112
+ - `SURFACE_DETECTOR_CONFIDENCE`
113
+ - `SURFACE_DETECTOR_MIN_AREA_RATIO`
114
+ - `SURFACE_DETECTOR_EXPAND_RATIO`
115
+ - `SURFACE_DETECTOR_IMAGE_SIZE`
116
+
117
+ ## Important expectation
118
+
119
+ The first fast model is meant to be a practical gate, not a perfect production vision model.
120
+
121
+ The improvement loop should be:
122
+
123
+ 1. train the quick detector
124
+ 2. deploy it
125
+ 3. save false accepts / false rejects from live camera
126
+ 4. add those hard examples back into training
127
+ 5. retrain
128
+
129
+ That is the fastest route to a reliable factory-facing steel ROI gate.
training/prepare_surface_gate_dataset.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import random
6
+ import shutil
7
+ import zipfile
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import yaml
13
+ from huggingface_hub import snapshot_download
14
+ from tqdm import tqdm
15
+
16
+ try:
17
+ from datasets import load_dataset
18
+ except Exception as exc: # pragma: no cover - import guard for guidance
19
+ raise SystemExit(
20
+ "The `datasets` package is required for this script. Install training/requirements.txt first."
21
+ ) from exc
22
+
23
+
24
+ SEVERSTAL_REPO = "rohanath/severstal-steel-detection"
25
+ NEU_REPO = "LiuErXiao/NEU_valid"
26
+ IMAGENETTE_REPO = "frgfm/imagenette"
27
+
28
+
29
+ def parse_args() -> argparse.Namespace:
30
+ parser = argparse.ArgumentParser(
31
+ description="Prepare a lightweight steel-surface detector dataset with automatic negatives and synthetic composites."
32
+ )
33
+ parser.add_argument(
34
+ "--output",
35
+ default="training/data/surface_gate_detector",
36
+ help="Output folder for the YOLO dataset.",
37
+ )
38
+ parser.add_argument(
39
+ "--image-size",
40
+ type=int,
41
+ default=640,
42
+ help="Target square size for generated detector images.",
43
+ )
44
+ parser.add_argument(
45
+ "--max-severstal",
46
+ type=int,
47
+ default=900,
48
+ help="Maximum Severstal steel images to use.",
49
+ )
50
+ parser.add_argument(
51
+ "--max-neu",
52
+ type=int,
53
+ default=400,
54
+ help="Maximum NEU steel images to use.",
55
+ )
56
+ parser.add_argument(
57
+ "--include-severstal",
58
+ action="store_true",
59
+ help="Download and include the larger Severstal source for a stronger but slower dataset build.",
60
+ )
61
+ parser.add_argument(
62
+ "--max-negatives",
63
+ type=int,
64
+ default=1200,
65
+ help="Maximum Imagenette images to use as automatic non-steel backgrounds.",
66
+ )
67
+ parser.add_argument(
68
+ "--composite-multiplier",
69
+ type=float,
70
+ default=1.5,
71
+ help="How many synthetic positive composites to generate per steel image.",
72
+ )
73
+ parser.add_argument(
74
+ "--negative-multiplier",
75
+ type=float,
76
+ default=1.0,
77
+ help="How many pure background negatives to generate per steel image.",
78
+ )
79
+ parser.add_argument("--seed", type=int, default=42)
80
+ return parser.parse_args()
81
+
82
+
83
+ def ensure_clean_dir(path: Path) -> None:
84
+ path.mkdir(parents=True, exist_ok=True)
85
+
86
+
87
+ def list_images(path: Path) -> list[Path]:
88
+ suffixes = {".jpg", ".jpeg", ".png", ".bmp"}
89
+ return [file for file in path.rglob("*") if file.suffix.lower() in suffixes]
90
+
91
+
92
+ def extract_first_zip(repo_id: str, target_dir: Path) -> Path:
93
+ target_dir.mkdir(parents=True, exist_ok=True)
94
+ downloaded_dir = Path(
95
+ snapshot_download(
96
+ repo_id=repo_id,
97
+ repo_type="dataset",
98
+ allow_patterns=["*.zip"],
99
+ )
100
+ )
101
+ zip_files = sorted(downloaded_dir.rglob("*.zip"))
102
+ if not zip_files:
103
+ raise FileNotFoundError(f"No zip file found in dataset repo {repo_id}")
104
+
105
+ marker = target_dir / ".extracted"
106
+ if marker.exists():
107
+ return target_dir
108
+
109
+ with zipfile.ZipFile(zip_files[0]) as archive:
110
+ archive.extractall(target_dir)
111
+ marker.write_text("ok", encoding="utf-8")
112
+ return target_dir
113
+
114
+
115
+ def sample_paths(paths: list[Path], limit: int, rng: random.Random) -> list[Path]:
116
+ if len(paths) <= limit:
117
+ return list(paths)
118
+ return rng.sample(paths, limit)
119
+
120
+
121
+ def center_crop_and_resize(image: np.ndarray, size: int) -> np.ndarray:
122
+ height, width = image.shape[:2]
123
+ crop_size = min(height, width)
124
+ x0 = max(0, (width - crop_size) // 2)
125
+ y0 = max(0, (height - crop_size) // 2)
126
+ cropped = image[y0:y0 + crop_size, x0:x0 + crop_size]
127
+ return cv2.resize(cropped, (size, size), interpolation=cv2.INTER_AREA)
128
+
129
+
130
+ def random_steel_crop(image: np.ndarray, rng: random.Random) -> np.ndarray:
131
+ height, width = image.shape[:2]
132
+ crop_w = max(64, int(width * rng.uniform(0.35, 0.9)))
133
+ crop_h = max(64, int(height * rng.uniform(0.45, 0.95)))
134
+ x0 = rng.randint(0, max(width - crop_w, 0))
135
+ y0 = rng.randint(0, max(height - crop_h, 0))
136
+ return image[y0:y0 + crop_h, x0:x0 + crop_w]
137
+
138
+
139
+ def make_composite(
140
+ steel_image: np.ndarray,
141
+ background_image: np.ndarray,
142
+ size: int,
143
+ rng: random.Random,
144
+ ) -> tuple[np.ndarray, tuple[int, int, int, int]]:
145
+ canvas = center_crop_and_resize(background_image, size)
146
+ steel_crop = random_steel_crop(steel_image, rng)
147
+
148
+ target_w = int(size * rng.uniform(0.45, 0.92))
149
+ aspect_ratio = steel_crop.shape[0] / max(steel_crop.shape[1], 1)
150
+ target_h = int(target_w * aspect_ratio)
151
+ target_h = max(int(size * 0.18), min(target_h, int(size * 0.82)))
152
+
153
+ steel_patch = cv2.resize(steel_crop, (target_w, target_h), interpolation=cv2.INTER_AREA)
154
+ x0 = rng.randint(0, max(size - target_w, 0))
155
+ y0 = rng.randint(0, max(size - target_h, 0))
156
+
157
+ alpha = np.ones((target_h, target_w), dtype=np.float32)
158
+ alpha = cv2.GaussianBlur(alpha, (0, 0), sigmaX=5, sigmaY=5)
159
+ alpha = np.clip(alpha[..., None], 0.86, 1.0)
160
+
161
+ roi = canvas[y0:y0 + target_h, x0:x0 + target_w].astype(np.float32)
162
+ patch = steel_patch.astype(np.float32)
163
+ mixed = cv2.convertScaleAbs((patch * alpha) + (roi * (1.0 - alpha)))
164
+ canvas[y0:y0 + target_h, x0:x0 + target_w] = mixed
165
+
166
+ return canvas, (x0, y0, target_w, target_h)
167
+
168
+
169
+ def write_yolo_label(label_path: Path, bbox: tuple[int, int, int, int] | None, image_size: int) -> None:
170
+ if bbox is None:
171
+ label_path.write_text("", encoding="utf-8")
172
+ return
173
+
174
+ x, y, w, h = bbox
175
+ x_center = (x + (w / 2)) / image_size
176
+ y_center = (y + (h / 2)) / image_size
177
+ width_norm = w / image_size
178
+ height_norm = h / image_size
179
+ label_path.write_text(
180
+ f"0 {x_center:.6f} {y_center:.6f} {width_norm:.6f} {height_norm:.6f}\n",
181
+ encoding="utf-8",
182
+ )
183
+
184
+
185
+ def save_image(path: Path, image: np.ndarray) -> None:
186
+ path.parent.mkdir(parents=True, exist_ok=True)
187
+ cv2.imwrite(str(path), image)
188
+
189
+
190
+ def export_negative_pool(target_dir: Path, limit: int, rng: random.Random) -> list[Path]:
191
+ dataset = load_dataset(IMAGENETTE_REPO, "160px")
192
+ samples = list(dataset["train"]) + list(dataset["validation"])
193
+ rng.shuffle(samples)
194
+
195
+ output_paths: list[Path] = []
196
+ for index, sample in enumerate(samples[:limit]):
197
+ image = cv2.cvtColor(np.array(sample["image"]), cv2.COLOR_RGB2BGR)
198
+ destination = target_dir / f"imagenette_{index:05d}.jpg"
199
+ save_image(destination, center_crop_and_resize(image, 640))
200
+ output_paths.append(destination)
201
+
202
+ return output_paths
203
+
204
+
205
+ def build_split(
206
+ split_name: str,
207
+ steel_paths: list[Path],
208
+ negative_paths: list[Path],
209
+ images_dir: Path,
210
+ labels_dir: Path,
211
+ image_size: int,
212
+ composite_multiplier: float,
213
+ negative_multiplier: float,
214
+ rng: random.Random,
215
+ ) -> dict[str, int]:
216
+ counts = {"full_positive": 0, "synthetic_positive": 0, "background_negative": 0}
217
+ split_images = images_dir / split_name
218
+ split_labels = labels_dir / split_name
219
+ ensure_clean_dir(split_images)
220
+ ensure_clean_dir(split_labels)
221
+
222
+ for index, steel_path in enumerate(tqdm(steel_paths, desc=f"{split_name}: full-frame steel")):
223
+ image = cv2.imread(str(steel_path))
224
+ if image is None:
225
+ continue
226
+
227
+ output_image = center_crop_and_resize(image, image_size)
228
+ image_path = split_images / f"{split_name}_steel_{index:05d}.jpg"
229
+ label_path = split_labels / f"{split_name}_steel_{index:05d}.txt"
230
+ save_image(image_path, output_image)
231
+ margin = int(image_size * 0.02)
232
+ write_yolo_label(
233
+ label_path,
234
+ (margin, margin, image_size - (margin * 2), image_size - (margin * 2)),
235
+ image_size,
236
+ )
237
+ counts["full_positive"] += 1
238
+
239
+ synthetic_target = max(1, int(len(steel_paths) * composite_multiplier))
240
+ for index in tqdm(range(synthetic_target), desc=f"{split_name}: synthetic composites"):
241
+ steel_image = cv2.imread(str(rng.choice(steel_paths)))
242
+ background_image = cv2.imread(str(rng.choice(negative_paths)))
243
+ if steel_image is None or background_image is None:
244
+ continue
245
+ composite, bbox = make_composite(steel_image, background_image, image_size, rng)
246
+ image_path = split_images / f"{split_name}_composite_{index:05d}.jpg"
247
+ label_path = split_labels / f"{split_name}_composite_{index:05d}.txt"
248
+ save_image(image_path, composite)
249
+ write_yolo_label(label_path, bbox, image_size)
250
+ counts["synthetic_positive"] += 1
251
+
252
+ negative_target = max(1, int(len(steel_paths) * negative_multiplier))
253
+ negative_sample = [rng.choice(negative_paths) for _ in range(negative_target)]
254
+ for index, negative_path in enumerate(tqdm(negative_sample, desc=f"{split_name}: negative backgrounds")):
255
+ image = cv2.imread(str(negative_path))
256
+ if image is None:
257
+ continue
258
+ output_image = center_crop_and_resize(image, image_size)
259
+ image_path = split_images / f"{split_name}_negative_{index:05d}.jpg"
260
+ label_path = split_labels / f"{split_name}_negative_{index:05d}.txt"
261
+ save_image(image_path, output_image)
262
+ write_yolo_label(label_path, None, image_size)
263
+ counts["background_negative"] += 1
264
+
265
+ return counts
266
+
267
+
268
+ def write_dataset_yaml(dataset_root: Path) -> Path:
269
+ yaml_path = dataset_root / "dataset.yaml"
270
+ payload = {
271
+ "path": str(dataset_root.resolve()),
272
+ "train": "images/train",
273
+ "val": "images/val",
274
+ "test": "images/test",
275
+ "names": {0: "steel_surface"},
276
+ }
277
+ yaml_path.write_text(yaml.safe_dump(payload, sort_keys=False), encoding="utf-8")
278
+ return yaml_path
279
+
280
+
281
+ def main() -> None:
282
+ args = parse_args()
283
+ rng = random.Random(args.seed)
284
+
285
+ output_root = Path(args.output).resolve()
286
+ raw_root = output_root / "raw"
287
+ dataset_root = output_root / "yolo_dataset"
288
+ images_dir = dataset_root / "images"
289
+ labels_dir = dataset_root / "labels"
290
+
291
+ ensure_clean_dir(raw_root)
292
+ ensure_clean_dir(images_dir)
293
+ ensure_clean_dir(labels_dir)
294
+
295
+ neu_raw = extract_first_zip(NEU_REPO, raw_root / "neu")
296
+ negative_dir = raw_root / "imagenette"
297
+ ensure_clean_dir(negative_dir)
298
+
299
+ steel_paths: list[Path] = []
300
+ if args.include_severstal:
301
+ severstal_raw = extract_first_zip(SEVERSTAL_REPO, raw_root / "severstal")
302
+ steel_paths.extend(sample_paths(list_images(severstal_raw), args.max_severstal, rng))
303
+
304
+ steel_paths.extend(sample_paths(list_images(neu_raw), args.max_neu, rng))
305
+ steel_paths.extend(sorted(Path("test_images").glob("*.jpg")))
306
+ steel_paths = [path for path in steel_paths if path.exists()]
307
+ rng.shuffle(steel_paths)
308
+
309
+ if not steel_paths:
310
+ raise RuntimeError("No steel images were collected for the detector dataset.")
311
+
312
+ negative_paths = export_negative_pool(negative_dir, args.max_negatives, rng)
313
+ if not negative_paths:
314
+ raise RuntimeError("No negative background images were collected.")
315
+
316
+ total = len(steel_paths)
317
+ train_end = int(total * 0.8)
318
+ val_end = int(total * 0.9)
319
+ splits = {
320
+ "train": steel_paths[:train_end],
321
+ "val": steel_paths[train_end:val_end],
322
+ "test": steel_paths[val_end:],
323
+ }
324
+
325
+ summary = {}
326
+ for split_name, split_steel_paths in splits.items():
327
+ summary[split_name] = build_split(
328
+ split_name=split_name,
329
+ steel_paths=split_steel_paths,
330
+ negative_paths=negative_paths,
331
+ images_dir=images_dir,
332
+ labels_dir=labels_dir,
333
+ image_size=args.image_size,
334
+ composite_multiplier=args.composite_multiplier,
335
+ negative_multiplier=args.negative_multiplier,
336
+ rng=rng,
337
+ )
338
+
339
+ yaml_path = write_dataset_yaml(dataset_root)
340
+ summary_path = output_root / "dataset_summary.json"
341
+ summary_path.write_text(
342
+ json.dumps(
343
+ {
344
+ "steel_sources": len(steel_paths),
345
+ "negative_pool": len(negative_paths),
346
+ "splits": summary,
347
+ "dataset_yaml": str(yaml_path),
348
+ },
349
+ indent=2,
350
+ ),
351
+ encoding="utf-8",
352
+ )
353
+
354
+ print(f"Dataset YAML written to: {yaml_path}")
355
+ print(f"Summary written to: {summary_path}")
356
+
357
+
358
+ if __name__ == "__main__":
359
+ main()
training/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ datasets
2
+ huggingface_hub
3
+ Pillow
4
+ PyYAML
5
+ tqdm
training/train_surface_gate_detector.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+ from ultralytics import YOLO
8
+
9
+
10
+ def parse_args() -> argparse.Namespace:
11
+ parser = argparse.ArgumentParser(
12
+ description="Train a lightweight steel-surface detector and install it into the project."
13
+ )
14
+ parser.add_argument(
15
+ "--data",
16
+ default="training/data/surface_gate_detector/yolo_dataset/dataset.yaml",
17
+ help="Path to the detector dataset YAML file.",
18
+ )
19
+ parser.add_argument(
20
+ "--model",
21
+ default="yolo11n.pt",
22
+ help="Pretrained Ultralytics detector checkpoint to finetune.",
23
+ )
24
+ parser.add_argument("--epochs", type=int, default=18)
25
+ parser.add_argument("--imgsz", type=int, default=512)
26
+ parser.add_argument("--batch", default=16)
27
+ parser.add_argument("--device", default="")
28
+ parser.add_argument("--workers", type=int, default=4)
29
+ parser.add_argument("--project", default="training/runs")
30
+ parser.add_argument("--name", default="surface_gate_detector")
31
+ parser.add_argument(
32
+ "--target",
33
+ default="models/steel_surface_detector.pt",
34
+ help="Where to copy the best trained checkpoint for app inference.",
35
+ )
36
+ return parser.parse_args()
37
+
38
+
39
+ def main() -> None:
40
+ args = parse_args()
41
+ data_path = Path(args.data).resolve()
42
+ if not data_path.exists():
43
+ raise FileNotFoundError(f"Dataset YAML not found: {data_path}")
44
+
45
+ model = YOLO(args.model)
46
+ results = model.train(
47
+ data=str(data_path),
48
+ epochs=args.epochs,
49
+ imgsz=args.imgsz,
50
+ batch=args.batch,
51
+ device=args.device or None,
52
+ workers=args.workers,
53
+ project=args.project,
54
+ name=args.name,
55
+ optimizer="AdamW",
56
+ patience=5,
57
+ cos_lr=True,
58
+ close_mosaic=4,
59
+ hsv_h=0.01,
60
+ hsv_s=0.15,
61
+ hsv_v=0.15,
62
+ translate=0.05,
63
+ scale=0.15,
64
+ fliplr=0.5,
65
+ mosaic=0.3,
66
+ mixup=0.0,
67
+ cache=True,
68
+ pretrained=True,
69
+ single_cls=True,
70
+ save=True,
71
+ verbose=True,
72
+ )
73
+
74
+ best_path = Path(results.save_dir) / "weights" / "best.pt"
75
+ if not best_path.exists():
76
+ raise FileNotFoundError(f"Best checkpoint was not produced at {best_path}")
77
+
78
+ target_path = Path(args.target).resolve()
79
+ target_path.parent.mkdir(parents=True, exist_ok=True)
80
+ shutil.copy2(best_path, target_path)
81
+
82
+ print(f"Training run saved to: {results.save_dir}")
83
+ print(f"Best detector copied to: {target_path}")
84
+ print("Next step: restart the FastAPI app so the steel ROI detector is used in the inspection pipeline.")
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main()