RavindranadhM commited on
Commit
201b13c
·
verified ·
1 Parent(s): 9b941f6

Deploy manufacturing monitoring system

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +12 -0
  2. .env.example +11 -0
  3. .gitattributes +4 -0
  4. .gitignore +26 -0
  5. Dockerfile +42 -0
  6. README.md +178 -5
  7. agent/langgraph_agent.py +333 -0
  8. api/main.py +196 -0
  9. api/realtime.py +46 -0
  10. core/config.py +130 -0
  11. core/constants.py +16 -0
  12. core/database.py +88 -0
  13. core/logger.py +15 -0
  14. dashboard/.gitignore +24 -0
  15. dashboard/README.md +16 -0
  16. dashboard/eslint.config.js +29 -0
  17. dashboard/index.html +13 -0
  18. dashboard/package-lock.json +0 -0
  19. dashboard/package.json +33 -0
  20. dashboard/postcss.config.js +6 -0
  21. dashboard/public/favicon.svg +1 -0
  22. dashboard/public/icons.svg +24 -0
  23. dashboard/src/App.css +184 -0
  24. dashboard/src/App.jsx +35 -0
  25. dashboard/src/assets/hero.png +0 -0
  26. dashboard/src/assets/react.svg +1 -0
  27. dashboard/src/assets/vite.svg +1 -0
  28. dashboard/src/components/AppShell.jsx +75 -0
  29. dashboard/src/components/MetricCard.jsx +25 -0
  30. dashboard/src/components/ProcessFlow.jsx +21 -0
  31. dashboard/src/components/Sidebar.jsx +93 -0
  32. dashboard/src/components/StatusBadge.jsx +20 -0
  33. dashboard/src/content/systemBrief.js +181 -0
  34. dashboard/src/hooks/useRealtimeInspection.js +112 -0
  35. dashboard/src/index.css +110 -0
  36. dashboard/src/lib/api.js +65 -0
  37. dashboard/src/lib/formatters.js +42 -0
  38. dashboard/src/lib/status.js +13 -0
  39. dashboard/src/main.jsx +10 -0
  40. dashboard/src/pages/Analytics.jsx +264 -0
  41. dashboard/src/pages/Dashboard.jsx +265 -0
  42. dashboard/src/pages/History.jsx +231 -0
  43. dashboard/src/pages/Live.jsx +531 -0
  44. dashboard/tailwind.config.js +10 -0
  45. dashboard/vercel.json +8 -0
  46. dashboard/vite.config.js +7 -0
  47. inspection/class_map.py +28 -0
  48. inspection/geometry.py +49 -0
  49. inspection/inference.py +111 -0
  50. inspection/lifecycle.py +100 -0
.dockerignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .gitignore
3
+ venv
4
+ __pycache__
5
+ *.pyc
6
+ .env
7
+ reports
8
+ resume
9
+ dashboard/node_modules
10
+ dashboard/dist
11
+ dashboard/.vite
12
+ reports
.env.example ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATABASE_URL=postgresql://username:password@hostname:6543/postgres
2
+ CORS_ORIGINS=http://127.0.0.1:5173,http://localhost:5173
3
+ ENABLE_LLM_REPORTS=true
4
+ LLM_PROVIDER=ollama
5
+ OLLAMA_BASE_URL=http://127.0.0.1:11434
6
+ OLLAMA_MODEL=llama3
7
+ OLLAMA_TIMEOUT_SECONDS=6
8
+ 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
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ test_images/0002cc93b.jpg filter=lfs diff=lfs merge=lfs -text
37
+ test_images/000418bfc.jpg filter=lfs diff=lfs merge=lfs -text
38
+ test_images/000789191.jpg filter=lfs diff=lfs merge=lfs -text
39
+ test_images/006f39c41.jpg filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ .env
3
+ .env.local
4
+ .python-version
5
+ __pycache__/
6
+ *.py[cod]
7
+ *.so
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+
12
+ venv/
13
+ .venv/
14
+
15
+ reports/
16
+ *.log
17
+
18
+ .idea/
19
+ .vscode/
20
+
21
+ dashboard/node_modules/
22
+ dashboard/dist/
23
+ dashboard/.vite/
24
+
25
+ *.swp
26
+ *.swo
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:20-alpine AS frontend-builder
2
+
3
+ WORKDIR /frontend
4
+
5
+ COPY dashboard/package*.json ./
6
+ RUN npm install
7
+
8
+ COPY dashboard ./
9
+ RUN npm run build
10
+
11
+ FROM python:3.11-slim
12
+
13
+ ENV PYTHONDONTWRITEBYTECODE=1
14
+ ENV PYTHONUNBUFFERED=1
15
+ ENV PORT=7860
16
+
17
+ WORKDIR /app
18
+
19
+ RUN apt-get update && apt-get install -y --no-install-recommends \
20
+ libgl1 \
21
+ libglib2.0-0 \
22
+ libgomp1 \
23
+ && rm -rf /var/lib/apt/lists/*
24
+
25
+ COPY requirements.txt ./
26
+ RUN pip install --no-cache-dir -r requirements.txt
27
+
28
+ COPY api ./api
29
+ COPY agent ./agent
30
+ COPY core ./core
31
+ COPY inspection ./inspection
32
+ COPY dashboard ./dashboard
33
+ COPY models ./models
34
+ COPY main.py ./main.py
35
+ COPY live_camera.py ./live_camera.py
36
+ COPY .env.example ./.env.example
37
+ COPY README.md ./README.md
38
+ COPY --from=frontend-builder /frontend/dist ./dashboard/dist
39
+
40
+ EXPOSE 7860
41
+
42
+ CMD ["sh", "-c", "uvicorn api.main:app --host 0.0.0.0 --port ${PORT:-7860}"]
README.md CHANGED
@@ -1,10 +1,183 @@
1
  ---
2
  title: Manufacturing Monitoring System
3
- emoji: 🐨
4
- colorFrom: purple
5
- colorTo: blue
6
  sdk: docker
7
- pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Manufacturing Monitoring System
3
+ emoji: 🏭
4
+ colorFrom: blue
5
+ colorTo: gray
6
  sdk: docker
7
+ app_port: 7860
8
  ---
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
23
+ - Analytics, history, alerts, and live command center views
24
+
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
32
+
33
+ ## Project Structure
34
+
35
+ ```text
36
+ api/ FastAPI app and WebSocket server
37
+ agent/ Recommendation and decision helpers
38
+ 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
45
+ ```
46
+
47
+ ## Features
48
+
49
+ ### Dashboard
50
+
51
+ - Live decision status and connection health
52
+ - Inspection KPIs and critical alert banners
53
+ - Organized architecture and backend overview panels
54
+
55
+ ### Live Monitoring
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
62
+
63
+ ### History
64
+
65
+ - Searchable inspection log
66
+ - Decision filtering
67
+ - Defect-level report detail view
68
+
69
+ ### Analytics
70
+
71
+ - Severity distribution
72
+ - Decision distribution
73
+ - Defect-type frequency
74
+ - Timeline charts for inspection trends
75
+
76
+ ## Backend API
77
+
78
+ ### Main endpoints
79
+
80
+ - `GET /health`
81
+ - `GET /reports`
82
+ - `GET /reports/latest`
83
+ - `GET /analytics/summary`
84
+ - `POST /inspect/image`
85
+ - `POST /inspect/frame`
86
+ - `WS /ws`
87
+
88
+ ## Environment Setup
89
+
90
+ Copy `.env.example` to `.env` if you want to configure PostgreSQL logging.
91
+
92
+ ```env
93
+ DATABASE_URL=postgresql://username:password@hostname:6543/postgres
94
+ CORS_ORIGINS=http://127.0.0.1:5173,http://localhost:5173
95
+ ENABLE_LLM_REPORTS=true
96
+ LLM_PROVIDER=ollama
97
+ OLLAMA_BASE_URL=http://127.0.0.1:11434
98
+ OLLAMA_MODEL=llama3
99
+ 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
+
106
+ `DATABASE_URL` is optional. If it is not set, the system still works and stores reports locally inside `reports/`.
107
+
108
+ 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:
118
+
119
+ - Deploy the whole app as one Docker service
120
+ - The included [Dockerfile](/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy/Dockerfile) builds the React frontend and serves it from FastAPI
121
+ - Best free option: Hugging Face Docker Spaces
122
+ - Best frontend-only option: Vercel, if you later want a split architecture
123
+
124
+ Recommended Hugging Face Space environment variables:
125
+
126
+ ```env
127
+ ENABLE_LLM_REPORTS=true
128
+ LLM_PROVIDER=huggingface
129
+ HF_TOKEN=your_huggingface_token
130
+ HF_CHAT_MODEL=meta-llama/Llama-3.1-8B-Instruct:cerebras
131
+ ```
132
+
133
+ In deployed mode, keep deep AI analysis off for continuous live camera monitoring and enable it only for manual review or uploaded images.
134
+
135
+ ## Local Run
136
+
137
+ ### 1. Backend
138
+
139
+ ```bash
140
+ cd "/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy"
141
+ python3 -m venv venv
142
+ source venv/bin/activate
143
+ pip install -r requirements.txt
144
+ venv/bin/uvicorn api.main:app --host 127.0.0.1 --port 8000
145
+ ```
146
+
147
+ ### 2. Frontend
148
+
149
+ ```bash
150
+ cd "/Users/ravindranadhm/Documents/Projects/steel-surface-inspection copy/dashboard"
151
+ npm install
152
+ npm run dev -- --host 127.0.0.1 --port 5173
153
+ ```
154
+
155
+ ### 3. Open the app
156
+
157
+ - Frontend: `http://127.0.0.1:5173`
158
+ - Backend health: `http://127.0.0.1:8000/health`
159
+
160
+ ## Verification
161
+
162
+ Recommended checks:
163
+
164
+ ```bash
165
+ python -m compileall api core inspection agent live_camera.py main.py
166
+ ```
167
+
168
+ ```bash
169
+ cd dashboard
170
+ npm run lint
171
+ npm run build
172
+ ```
173
+
174
+ ## Notes
175
+
176
+ - The provided model file `models/steel_inspection.pt` is included in the project and is small enough for a standard GitHub repository.
177
+ - Browser camera inspection requires camera permission in your browser.
178
+ - Live camera mode is optimized to always return a visible inspection result, even when no defects are found.
179
+ - The frontend automatically uses the same origin as the backend when deployed as a single Docker service.
180
+
181
+ ## Resume-Friendly Summary
182
+
183
+ Built an AI-powered manufacturing monitoring system for steel surface inspection using FastAPI, React, WebSocket streaming, OpenCV, Ultralytics YOLO, analytics dashboards, and live browser camera inspection.
agent/langgraph_agent.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TypedDict, Dict, Any
2
+ import json
3
+ from urllib.error import URLError
4
+ from urllib.request import Request, urlopen
5
+
6
+ from core.config import settings
7
+ from core.logger import logger
8
+
9
+ try:
10
+ from langgraph.graph import StateGraph, END
11
+ from langchain_ollama import OllamaLLM
12
+ except Exception: # pragma: no cover - optional dependency safety
13
+ StateGraph = None
14
+ END = None
15
+ OllamaLLM = None
16
+
17
+
18
+ # -----------------------------
19
+ # STATE DEFINITION
20
+ # -----------------------------
21
+
22
+ class InspectionState(TypedDict):
23
+ input_data: Dict[str, Any]
24
+ summary: str
25
+ decision: str
26
+ recommendation: str
27
+
28
+
29
+ # -----------------------------
30
+ # LLM FACTORY (IMPORTANT)
31
+ # -----------------------------
32
+
33
+ def get_llm():
34
+ """Create LLM instance (better than global init)."""
35
+ if OllamaLLM is None:
36
+ raise RuntimeError("LLM dependencies are not installed")
37
+ return OllamaLLM(
38
+ model=settings.OLLAMA_MODEL,
39
+ base_url=settings.OLLAMA_BASE_URL,
40
+ timeout=settings.OLLAMA_TIMEOUT_SECONDS,
41
+ )
42
+
43
+
44
+ def is_ollama_available() -> bool:
45
+ try:
46
+ with urlopen(
47
+ f"{settings.OLLAMA_BASE_URL}/api/tags",
48
+ timeout=settings.OLLAMA_TIMEOUT_SECONDS,
49
+ ) as response:
50
+ return response.status == 200
51
+ except (URLError, ValueError, TimeoutError):
52
+ return False
53
+
54
+
55
+ 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")
62
+
63
+ payload = json.dumps({
64
+ "model": settings.HF_CHAT_MODEL,
65
+ "messages": [
66
+ {
67
+ "role": "user",
68
+ "content": prompt,
69
+ }
70
+ ],
71
+ "max_tokens": 220,
72
+ "response_format": {"type": "text"},
73
+ }).encode("utf-8")
74
+
75
+ request = Request(
76
+ f"{settings.HF_ROUTER_BASE_URL.rstrip('/')}/chat/completions",
77
+ data=payload,
78
+ headers={
79
+ "Authorization": f"Bearer {settings.HF_TOKEN}",
80
+ "Content-Type": "application/json",
81
+ },
82
+ method="POST",
83
+ )
84
+
85
+ with urlopen(request, timeout=settings.OLLAMA_TIMEOUT_SECONDS) as response:
86
+ body = json.loads(response.read().decode("utf-8"))
87
+
88
+ choices = body.get("choices") or []
89
+ if not choices:
90
+ raise RuntimeError("No choices were returned by Hugging Face")
91
+
92
+ message = choices[0].get("message") or {}
93
+ content = message.get("content", "")
94
+
95
+ if isinstance(content, str):
96
+ return content
97
+
98
+ if isinstance(content, list):
99
+ text_parts: list[str] = []
100
+ for item in content:
101
+ if isinstance(item, dict) and item.get("type") == "text":
102
+ text_parts.append(str(item.get("text", "")))
103
+ if text_parts:
104
+ return "\n".join(part for part in text_parts if part)
105
+
106
+ raise RuntimeError("Unable to extract recommendation content from Hugging Face response")
107
+
108
+
109
+ # -----------------------------
110
+ # NODE 1: SUMMARY
111
+ # -----------------------------
112
+
113
+ def summarize_node(state: InspectionState) -> Dict[str, str]:
114
+
115
+ data = state["input_data"]
116
+
117
+ summary = (
118
+ f"Detected defects:\n"
119
+ f"- Minor: {data['summary'].get('Minor', 0)}\n"
120
+ f"- Moderate: {data['summary'].get('Moderate', 0)}\n"
121
+ f"- Critical: {data['summary'].get('Critical', 0)}\n"
122
+ )
123
+
124
+ return {"summary": summary}
125
+
126
+
127
+ # -----------------------------
128
+ # NODE 2: RULE-BASED DECISION
129
+ # -----------------------------
130
+
131
+ def decision_node(state: InspectionState) -> Dict[str, str]:
132
+
133
+ data = state["input_data"]
134
+
135
+ critical = data["summary"].get("Critical", 0)
136
+ moderate = data["summary"].get("Moderate", 0)
137
+
138
+ if critical > 0:
139
+ decision = "FAIL"
140
+ elif moderate > 0:
141
+ decision = "REVIEW"
142
+ else:
143
+ decision = "PASS"
144
+
145
+ return {"decision": decision}
146
+
147
+
148
+ # -----------------------------
149
+ # NODE 3: LLM RECOMMENDATION
150
+ # -----------------------------
151
+
152
+ def recommendation_node(state: InspectionState) -> Dict[str, str]:
153
+
154
+ defects = state["input_data"].get("defects", [])
155
+
156
+ prompt = f"""
157
+ You are a senior steel quality control engineer working in a manufacturing plant.
158
+
159
+ Inspection Summary:
160
+ {state['summary']}
161
+
162
+ Detected Defects (detailed):
163
+ {defects}
164
+
165
+ Final Decision: {state['decision']}
166
+
167
+ Give a STRICTLY INDUSTRIAL RESPONSE:
168
+
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)
186
+
187
+ except Exception as e:
188
+ logger.error(f"LLM failed: {e}")
189
+ response = "LLM failed to generate recommendation. Please review manually."
190
+
191
+ return {"recommendation": response}
192
+
193
+
194
+ # -----------------------------
195
+ # BUILD GRAPH (ONCE)
196
+ # -----------------------------
197
+
198
+ def build_agent():
199
+ if StateGraph is None or END is None:
200
+ raise RuntimeError("LangGraph dependencies are not installed")
201
+
202
+ builder = StateGraph(InspectionState)
203
+
204
+ builder.add_node("summarize", summarize_node)
205
+ builder.add_node("decision", decision_node)
206
+ builder.add_node("recommendation", recommendation_node)
207
+
208
+ builder.set_entry_point("summarize")
209
+
210
+ builder.add_edge("summarize", "decision")
211
+ builder.add_edge("decision", "recommendation")
212
+ builder.add_edge("recommendation", END)
213
+
214
+ return builder.compile()
215
+
216
+
217
+ AGENT = None
218
+
219
+
220
+ def _build_fallback_response(input_data: Dict[str, Any]) -> Dict[str, Any]:
221
+ summary = (
222
+ f"Detected defects:\n"
223
+ f"- Minor: {input_data.get('summary', {}).get('Minor', 0)}\n"
224
+ f"- Moderate: {input_data.get('summary', {}).get('Moderate', 0)}\n"
225
+ f"- Critical: {input_data.get('summary', {}).get('Critical', 0)}\n"
226
+ )
227
+
228
+ critical = input_data.get("summary", {}).get("Critical", 0)
229
+ moderate = input_data.get("summary", {}).get("Moderate", 0)
230
+ minor = input_data.get("summary", {}).get("Minor", 0)
231
+
232
+ if critical > 0:
233
+ decision = "FAIL"
234
+ recommendation = (
235
+ "Critical surface damage detected. Stop automatic acceptance, isolate the coil or sheet, "
236
+ "and route the material for immediate engineering review or rejection."
237
+ )
238
+ elif moderate > 0:
239
+ decision = "REVIEW"
240
+ recommendation = (
241
+ "Moderate defects detected. Hold the batch for operator review, confirm defect spread, "
242
+ "and schedule corrective process checks before release."
243
+ )
244
+ elif minor > 0:
245
+ decision = "PASS"
246
+ recommendation = (
247
+ "Only minor defects were detected. Material can proceed with monitoring and a short-term "
248
+ "process capability check to prevent escalation."
249
+ )
250
+ else:
251
+ decision = "PASS"
252
+ recommendation = (
253
+ "No actionable defects were detected. Continue production and keep the inspection line active "
254
+ "for routine monitoring."
255
+ )
256
+
257
+ return {
258
+ "summary": summary,
259
+ "decision": decision,
260
+ "recommendation": recommendation,
261
+ "agent_mode": "heuristic",
262
+ "agent_provider": "Rule-Based Safety Engine",
263
+ "agent_model": "fallback",
264
+ }
265
+
266
+
267
+ def _normalize_llm_mode(llm_mode: str | None) -> str:
268
+ normalized = (llm_mode or "auto").strip().lower()
269
+ if normalized in {"off", "auto", "always"}:
270
+ return normalized
271
+ return "auto"
272
+
273
+
274
+ # -----------------------------
275
+ # RUN AGENT
276
+ # -----------------------------
277
+
278
+ def run_agent(input_data: Dict[str, Any], *, llm_mode: str = "auto") -> Dict[str, Any]:
279
+ fallback = _build_fallback_response(input_data)
280
+ normalized_mode = _normalize_llm_mode(llm_mode)
281
+
282
+ if normalized_mode == "off":
283
+ return fallback
284
+
285
+ if normalized_mode == "auto":
286
+ source = str(input_data.get("source", "")).strip().lower()
287
+ metadata = input_data.get("metadata") or {}
288
+ persist_requested = bool(metadata.get("persist", True))
289
+
290
+ if source in {"camera", "live", "stream"} or not persist_requested:
291
+ return fallback
292
+
293
+ if not settings.ENABLE_LLM_REPORTS:
294
+ return fallback
295
+
296
+ provider = settings.LLM_PROVIDER.strip().lower()
297
+
298
+ if StateGraph is None or END is None:
299
+ logger.warning("LLM report generation is enabled, but LangGraph dependencies are unavailable.")
300
+ return fallback
301
+
302
+ if provider == "huggingface":
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.")
309
+ return fallback
310
+ if not is_ollama_available():
311
+ logger.warning("Ollama server is unavailable. Using fallback inspection recommendation.")
312
+ return fallback
313
+
314
+ try:
315
+ global AGENT
316
+
317
+ if AGENT is None:
318
+ AGENT = build_agent()
319
+
320
+ result = AGENT.invoke({
321
+ "input_data": input_data
322
+ })
323
+
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:
332
+ logger.error(f"Agent execution failed: {e}")
333
+ return fallback
api/main.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ import json
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+
7
+ from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+ from pydantic import BaseModel, Field
10
+ from fastapi.responses import FileResponse
11
+ from fastapi.staticfiles import StaticFiles
12
+ from starlette.concurrency import run_in_threadpool
13
+
14
+ from core.config import settings
15
+ from core.logger import logger, setup_logger
16
+ from api.realtime import manager
17
+ from inspection.report_repository import (
18
+ get_analytics_summary,
19
+ get_latest_report,
20
+ list_reports,
21
+ )
22
+ from inspection.service import inspect_base64_image
23
+
24
+
25
+ class InspectionRequest(BaseModel):
26
+ image_base64: str = Field(..., min_length=10)
27
+ filename: str | None = None
28
+ source: str = "upload"
29
+ persist: bool = True
30
+ llm_mode: Literal["off", "auto", "always"] = "off"
31
+
32
+
33
+ setup_logger()
34
+
35
+ FRONTEND_DIST_DIR = Path(settings.FRONTEND_DIST)
36
+ FRONTEND_INDEX = FRONTEND_DIST_DIR / "index.html"
37
+
38
+
39
+ app = FastAPI(
40
+ title="Manufacturing Monitoring System API",
41
+ version="2.0.0",
42
+ )
43
+
44
+ # -----------------------------
45
+ # CORS (IMPORTANT)
46
+ # -----------------------------
47
+ app.add_middleware(
48
+ CORSMiddleware,
49
+ allow_origins=list(settings.CORS_ORIGINS),
50
+ allow_credentials=False,
51
+ allow_methods=["*"],
52
+ allow_headers=["*"],
53
+ )
54
+
55
+ # -----------------------------
56
+ # ROOT
57
+ # -----------------------------
58
+ @app.get("/")
59
+ def root():
60
+ if FRONTEND_INDEX.exists():
61
+ return FileResponse(FRONTEND_INDEX)
62
+ return {
63
+ "message": "Manufacturing Monitoring System API running",
64
+ "timestamp": datetime.now(timezone.utc).isoformat(),
65
+ "origins": list(settings.CORS_ORIGINS),
66
+ }
67
+
68
+
69
+ @app.get("/health")
70
+ def health():
71
+ return {
72
+ "status": "ok",
73
+ "timestamp": datetime.now(timezone.utc).isoformat(),
74
+ }
75
+
76
+
77
+ # -----------------------------
78
+ # GET ALL REPORTS
79
+ # -----------------------------
80
+ @app.get("/reports")
81
+ def get_reports(limit: int = Query(default=settings.REPORT_FETCH_LIMIT, ge=1, le=200)):
82
+ return list_reports(limit=limit)
83
+
84
+
85
+ # -----------------------------
86
+ # GET LATEST REPORT
87
+ # -----------------------------
88
+ @app.get("/reports/latest")
89
+ def get_latest():
90
+ latest_report = get_latest_report()
91
+ return latest_report or {}
92
+
93
+
94
+ @app.get("/analytics/summary")
95
+ def analytics_summary(limit: int = Query(default=120, ge=1, le=500)):
96
+ return get_analytics_summary(limit=limit)
97
+
98
+
99
+ @app.post("/inspect/image")
100
+ async def inspect_image(payload: InspectionRequest):
101
+ try:
102
+ return await run_in_threadpool(
103
+ inspect_base64_image,
104
+ payload.image_base64,
105
+ source=payload.source or "upload",
106
+ metadata={"filename": payload.filename},
107
+ persist=payload.persist,
108
+ llm_mode=payload.llm_mode,
109
+ )
110
+ except ValueError as exc:
111
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
112
+ except Exception as exc:
113
+ logger.exception("Image inspection failed")
114
+ raise HTTPException(status_code=500, detail="Image inspection failed") from exc
115
+
116
+
117
+ @app.post("/inspect/frame")
118
+ async def inspect_frame(payload: InspectionRequest):
119
+ try:
120
+ return await run_in_threadpool(
121
+ inspect_base64_image,
122
+ payload.image_base64,
123
+ source=payload.source or "camera",
124
+ metadata={"filename": payload.filename},
125
+ persist=payload.persist,
126
+ llm_mode=payload.llm_mode,
127
+ )
128
+ except ValueError as exc:
129
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
130
+ except Exception as exc:
131
+ logger.exception("Camera frame inspection failed")
132
+ raise HTTPException(status_code=500, detail="Camera frame inspection failed") from exc
133
+
134
+
135
+ # -----------------------------
136
+ # WEBSOCKET ENDPOINT
137
+ # -----------------------------
138
+ @app.websocket("/ws")
139
+ async def websocket_endpoint(websocket: WebSocket):
140
+ await manager.connect(websocket)
141
+ latest_report = await run_in_threadpool(get_latest_report)
142
+
143
+ if latest_report:
144
+ await manager.send_json(
145
+ websocket,
146
+ {
147
+ "type": "inspection.snapshot",
148
+ **latest_report,
149
+ },
150
+ )
151
+ else:
152
+ await manager.send_json(
153
+ websocket,
154
+ {
155
+ "type": "connection.ready",
156
+ "timestamp": datetime.now(timezone.utc).isoformat(),
157
+ },
158
+ )
159
+
160
+ try:
161
+ while True:
162
+ message = await websocket.receive_text()
163
+
164
+ try:
165
+ payload = json.loads(message)
166
+ except json.JSONDecodeError:
167
+ payload = {"type": message}
168
+
169
+ if payload.get("type") == "ping":
170
+ await manager.send_json(
171
+ websocket,
172
+ {
173
+ "type": "pong",
174
+ "timestamp": datetime.now(timezone.utc).isoformat(),
175
+ },
176
+ )
177
+ except WebSocketDisconnect:
178
+ await manager.disconnect(websocket)
179
+ except Exception as exc:
180
+ logger.warning(f"WebSocket connection closed unexpectedly: {exc}")
181
+ await manager.disconnect(websocket)
182
+
183
+
184
+ if FRONTEND_DIST_DIR.exists():
185
+ assets_dir = FRONTEND_DIST_DIR / "assets"
186
+ if assets_dir.exists():
187
+ app.mount("/assets", StaticFiles(directory=assets_dir), name="frontend-assets")
188
+
189
+ @app.get("/{full_path:path}", include_in_schema=False)
190
+ async def frontend_routes(full_path: str):
191
+ candidate = FRONTEND_DIST_DIR / full_path
192
+ if candidate.is_file():
193
+ return FileResponse(candidate)
194
+ if FRONTEND_INDEX.exists():
195
+ return FileResponse(FRONTEND_INDEX)
196
+ raise HTTPException(status_code=404, detail="Not found")
api/realtime.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from typing import Any
3
+
4
+ from fastapi import WebSocket
5
+
6
+ from core.logger import logger
7
+
8
+
9
+ class ConnectionManager:
10
+ def __init__(self):
11
+ self._connections: set[WebSocket] = set()
12
+ self._lock = asyncio.Lock()
13
+
14
+ async def connect(self, websocket: WebSocket) -> None:
15
+ await websocket.accept()
16
+
17
+ async with self._lock:
18
+ self._connections.add(websocket)
19
+
20
+ async def disconnect(self, websocket: WebSocket) -> None:
21
+ async with self._lock:
22
+ self._connections.discard(websocket)
23
+
24
+ async def send_json(self, websocket: WebSocket, payload: dict[str, Any]) -> None:
25
+ await websocket.send_json(payload)
26
+
27
+ async def broadcast(self, payload: dict[str, Any]) -> None:
28
+ async with self._lock:
29
+ connections = list(self._connections)
30
+
31
+ stale_connections: list[WebSocket] = []
32
+
33
+ for connection in connections:
34
+ try:
35
+ await connection.send_json(payload)
36
+ except Exception as exc:
37
+ logger.warning(f"WebSocket broadcast failed: {exc}")
38
+ stale_connections.append(connection)
39
+
40
+ if stale_connections:
41
+ async with self._lock:
42
+ for connection in stale_connections:
43
+ self._connections.discard(connection)
44
+
45
+
46
+ manager = ConnectionManager()
core/config.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dataclasses import dataclass, field
3
+ from pathlib import Path
4
+
5
+ from dotenv import load_dotenv
6
+
7
+
8
+ BASE_DIR = Path(__file__).resolve().parent.parent
9
+ load_dotenv(BASE_DIR / ".env")
10
+
11
+
12
+ def _resolve_path(env_name: str, default_relative_path: str) -> str:
13
+ raw_value = os.getenv(env_name)
14
+ path = Path(raw_value) if raw_value else BASE_DIR / default_relative_path
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",
21
+ "http://127.0.0.1:5173,http://localhost:5173",
22
+ )
23
+ return tuple(
24
+ origin.strip()
25
+ for origin in raw_origins.split(",")
26
+ if origin.strip()
27
+ )
28
+
29
+
30
+ def _parse_bool(name: str, default: bool) -> bool:
31
+ raw_value = os.getenv(name)
32
+ if raw_value is None:
33
+ return default
34
+ return raw_value.strip().lower() in {"1", "true", "yes", "on"}
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Settings:
39
+ """
40
+ Central configuration for the inspection system.
41
+ """
42
+
43
+ # -----------------------------
44
+ # PATHS
45
+ # -----------------------------
46
+ BASE_DIR: str = str(BASE_DIR)
47
+ MODEL_PATH: str = field(
48
+ default_factory=lambda: _resolve_path("MODEL_PATH", "models/steel_inspection.pt")
49
+ )
50
+ IMAGE_FOLDER: str = field(
51
+ default_factory=lambda: _resolve_path("IMAGE_FOLDER", "test_images")
52
+ )
53
+ REPORT_FOLDER: str = field(
54
+ default_factory=lambda: _resolve_path("REPORT_FOLDER", "reports")
55
+ )
56
+ FRONTEND_DIST: str = field(
57
+ default_factory=lambda: _resolve_path("FRONTEND_DIST", "dashboard/dist")
58
+ )
59
+
60
+ # -----------------------------
61
+ # DEMO / SIMULATION SETTINGS
62
+ # -----------------------------
63
+ IMAGE_REPEAT: int = field(default_factory=lambda: int(os.getenv("IMAGE_REPEAT", "5")))
64
+ BLANK_FRAMES: int = field(default_factory=lambda: int(os.getenv("BLANK_FRAMES", "3")))
65
+
66
+ # -----------------------------
67
+ # TRACKING / LIFECYCLE
68
+ # -----------------------------
69
+ MAX_MISSING_FRAMES: int = field(
70
+ default_factory=lambda: int(os.getenv("MAX_MISSING_FRAMES", "5"))
71
+ )
72
+
73
+ # -----------------------------
74
+ # MODEL / INFERENCE SETTINGS
75
+ # -----------------------------
76
+ CONF_THRESHOLD: float = field(default_factory=lambda: float(os.getenv("CONF_THRESHOLD", "0.20")))
77
+ SECONDARY_CONF_THRESHOLD: float = field(
78
+ default_factory=lambda: float(os.getenv("SECONDARY_CONF_THRESHOLD", "0.25"))
79
+ )
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
86
+ # -----------------------------
87
+ CORS_ORIGINS: tuple[str, ...] = field(default_factory=_parse_origins)
88
+ REPORT_FETCH_LIMIT: int = field(
89
+ default_factory=lambda: int(os.getenv("REPORT_FETCH_LIMIT", "50"))
90
+ )
91
+ MAX_UPLOAD_SIZE_MB: int = field(
92
+ default_factory=lambda: int(os.getenv("MAX_UPLOAD_SIZE_MB", "8"))
93
+ )
94
+ WEBSOCKET_HEARTBEAT_SECONDS: int = field(
95
+ default_factory=lambda: int(os.getenv("WEBSOCKET_HEARTBEAT_SECONDS", "20"))
96
+ )
97
+ ENABLE_LLM_REPORTS: bool = field(
98
+ default_factory=lambda: _parse_bool("ENABLE_LLM_REPORTS", True)
99
+ )
100
+ LLM_PROVIDER: str = field(
101
+ default_factory=lambda: os.getenv("LLM_PROVIDER", "ollama")
102
+ )
103
+ OLLAMA_BASE_URL: str = field(
104
+ default_factory=lambda: os.getenv("OLLAMA_BASE_URL", "http://127.0.0.1:11434")
105
+ )
106
+ OLLAMA_MODEL: str = field(
107
+ default_factory=lambda: os.getenv("OLLAMA_MODEL", "llama3")
108
+ )
109
+ OLLAMA_TIMEOUT_SECONDS: float = field(
110
+ default_factory=lambda: float(os.getenv("OLLAMA_TIMEOUT_SECONDS", "6"))
111
+ )
112
+ HF_TOKEN: str | None = field(default_factory=lambda: os.getenv("HF_TOKEN"))
113
+ HF_CHAT_MODEL: str = field(
114
+ default_factory=lambda: os.getenv("HF_CHAT_MODEL", "meta-llama/Llama-3.1-8B-Instruct:cerebras")
115
+ )
116
+ HF_ROUTER_BASE_URL: str = field(
117
+ default_factory=lambda: os.getenv("HF_ROUTER_BASE_URL", "https://router.huggingface.co/v1")
118
+ )
119
+
120
+ # -----------------------------
121
+ # DATABASE
122
+ # -----------------------------
123
+ DATABASE_URL: str | None = field(default_factory=lambda: os.getenv("DATABASE_URL"))
124
+
125
+ @property
126
+ def max_upload_bytes(self) -> int:
127
+ return self.MAX_UPLOAD_SIZE_MB * 1024 * 1024
128
+
129
+
130
+ settings = Settings()
core/constants.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Project-wide constants (no logic here).
3
+ """
4
+
5
+ SEVERITY_SCORE = {
6
+ "Minor": 1,
7
+ "Moderate": 2,
8
+ "Critical": 3
9
+ }
10
+
11
+
12
+ DECISION_COLOR = {
13
+ "PASS": (0, 255, 0),
14
+ "REVIEW": (0, 165, 255),
15
+ "FAIL": (0, 0, 255)
16
+ }
core/database.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ from typing import Any, Iterator
3
+
4
+ try:
5
+ import psycopg2
6
+ from psycopg2.extras import RealDictCursor
7
+ except Exception: # pragma: no cover - optional dependency safety
8
+ psycopg2 = None
9
+ RealDictCursor = None
10
+
11
+ from core.config import settings
12
+ from core.logger import logger
13
+
14
+
15
+ class Database:
16
+ def is_configured(self) -> bool:
17
+ return bool(settings.DATABASE_URL)
18
+
19
+ def connect(self):
20
+ if psycopg2 is None or RealDictCursor is None:
21
+ raise RuntimeError("psycopg2 is not installed in the active Python environment")
22
+
23
+ if not self.is_configured():
24
+ raise RuntimeError("DATABASE_URL is not configured")
25
+
26
+ return psycopg2.connect(
27
+ settings.DATABASE_URL,
28
+ cursor_factory=RealDictCursor,
29
+ )
30
+
31
+ @contextmanager
32
+ def cursor(self) -> Iterator[Any]:
33
+ connection = None
34
+ cursor = None
35
+
36
+ try:
37
+ connection = self.connect()
38
+ cursor = connection.cursor()
39
+ yield cursor
40
+ connection.commit()
41
+ except Exception:
42
+ if connection is not None:
43
+ connection.rollback()
44
+ raise
45
+ finally:
46
+ if cursor is not None:
47
+ cursor.close()
48
+ if connection is not None:
49
+ connection.close()
50
+
51
+ def fetch_all(self, query: str, params: tuple[Any, ...] | None = None) -> list[dict[str, Any]]:
52
+ if not self.is_configured():
53
+ return []
54
+
55
+ try:
56
+ with self.cursor() as cursor:
57
+ cursor.execute(query, params or ())
58
+ return list(cursor.fetchall())
59
+ except Exception as exc:
60
+ logger.warning(f"Database fetch_all failed: {exc}")
61
+ return []
62
+
63
+ def fetch_one(self, query: str, params: tuple[Any, ...] | None = None) -> dict[str, Any] | None:
64
+ if not self.is_configured():
65
+ return None
66
+
67
+ try:
68
+ with self.cursor() as cursor:
69
+ cursor.execute(query, params or ())
70
+ return cursor.fetchone()
71
+ except Exception as exc:
72
+ logger.warning(f"Database fetch_one failed: {exc}")
73
+ return None
74
+
75
+ def execute(self, query: str, params: tuple[Any, ...] | None = None) -> bool:
76
+ if not self.is_configured():
77
+ return False
78
+
79
+ try:
80
+ with self.cursor() as cursor:
81
+ cursor.execute(query, params or ())
82
+ return True
83
+ except Exception as exc:
84
+ logger.warning(f"Database execute failed: {exc}")
85
+ return False
86
+
87
+
88
+ db = Database()
core/logger.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+
4
+ def setup_logger():
5
+ """
6
+ Configure global logging settings.
7
+ """
8
+
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format="%(asctime)s | %(levelname)s | %(message)s"
12
+ )
13
+
14
+
15
+ logger = logging.getLogger("inspection_system")
dashboard/.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
dashboard/README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # React + Vite
2
+
3
+ This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
+
5
+ Currently, two official plugins are available:
6
+
7
+ - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
8
+ - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
9
+
10
+ ## React Compiler
11
+
12
+ The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
13
+
14
+ ## Expanding the ESLint configuration
15
+
16
+ If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
dashboard/eslint.config.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import { defineConfig, globalIgnores } from 'eslint/config'
6
+
7
+ export default defineConfig([
8
+ globalIgnores(['dist']),
9
+ {
10
+ files: ['**/*.{js,jsx}'],
11
+ extends: [
12
+ js.configs.recommended,
13
+ reactHooks.configs.flat.recommended,
14
+ reactRefresh.configs.vite,
15
+ ],
16
+ languageOptions: {
17
+ ecmaVersion: 2020,
18
+ globals: globals.browser,
19
+ parserOptions: {
20
+ ecmaVersion: 'latest',
21
+ ecmaFeatures: { jsx: true },
22
+ sourceType: 'module',
23
+ },
24
+ },
25
+ rules: {
26
+ 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
27
+ },
28
+ },
29
+ ])
dashboard/index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Manufacturing Monitoring System</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.jsx"></script>
12
+ </body>
13
+ </html>
dashboard/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
dashboard/package.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "dashboard",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "lint": "eslint .",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "react": "^18.3.1",
14
+ "react-dom": "^18.3.1",
15
+ "react-router-dom": "^7.13.2",
16
+ "recharts": "^3.8.1"
17
+ },
18
+ "devDependencies": {
19
+ "@eslint/js": "^9.39.4",
20
+ "@tailwindcss/postcss": "^4.2.2",
21
+ "@types/react": "^19.2.14",
22
+ "@types/react-dom": "^19.2.3",
23
+ "@vitejs/plugin-react": "^6.0.1",
24
+ "autoprefixer": "^10.4.27",
25
+ "eslint": "^9.39.4",
26
+ "eslint-plugin-react-hooks": "^7.0.1",
27
+ "eslint-plugin-react-refresh": "^0.5.2",
28
+ "globals": "^17.4.0",
29
+ "postcss": "^8.5.8",
30
+ "tailwindcss": "^3.4.19",
31
+ "vite": "^8.0.1"
32
+ }
33
+ }
dashboard/postcss.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {},
5
+ },
6
+ }
dashboard/public/favicon.svg ADDED
dashboard/public/icons.svg ADDED
dashboard/src/App.css ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .counter {
2
+ font-size: 16px;
3
+ padding: 5px 10px;
4
+ border-radius: 5px;
5
+ color: var(--accent);
6
+ background: var(--accent-bg);
7
+ border: 2px solid transparent;
8
+ transition: border-color 0.3s;
9
+ margin-bottom: 24px;
10
+
11
+ &:hover {
12
+ border-color: var(--accent-border);
13
+ }
14
+ &:focus-visible {
15
+ outline: 2px solid var(--accent);
16
+ outline-offset: 2px;
17
+ }
18
+ }
19
+
20
+ .hero {
21
+ position: relative;
22
+
23
+ .base,
24
+ .framework,
25
+ .vite {
26
+ inset-inline: 0;
27
+ margin: 0 auto;
28
+ }
29
+
30
+ .base {
31
+ width: 170px;
32
+ position: relative;
33
+ z-index: 0;
34
+ }
35
+
36
+ .framework,
37
+ .vite {
38
+ position: absolute;
39
+ }
40
+
41
+ .framework {
42
+ z-index: 1;
43
+ top: 34px;
44
+ height: 28px;
45
+ transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
46
+ scale(1.4);
47
+ }
48
+
49
+ .vite {
50
+ z-index: 0;
51
+ top: 107px;
52
+ height: 26px;
53
+ width: auto;
54
+ transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
55
+ scale(0.8);
56
+ }
57
+ }
58
+
59
+ #center {
60
+ display: flex;
61
+ flex-direction: column;
62
+ gap: 25px;
63
+ place-content: center;
64
+ place-items: center;
65
+ flex-grow: 1;
66
+
67
+ @media (max-width: 1024px) {
68
+ padding: 32px 20px 24px;
69
+ gap: 18px;
70
+ }
71
+ }
72
+
73
+ #next-steps {
74
+ display: flex;
75
+ border-top: 1px solid var(--border);
76
+ text-align: left;
77
+
78
+ & > div {
79
+ flex: 1 1 0;
80
+ padding: 32px;
81
+ @media (max-width: 1024px) {
82
+ padding: 24px 20px;
83
+ }
84
+ }
85
+
86
+ .icon {
87
+ margin-bottom: 16px;
88
+ width: 22px;
89
+ height: 22px;
90
+ }
91
+
92
+ @media (max-width: 1024px) {
93
+ flex-direction: column;
94
+ text-align: center;
95
+ }
96
+ }
97
+
98
+ #docs {
99
+ border-right: 1px solid var(--border);
100
+
101
+ @media (max-width: 1024px) {
102
+ border-right: none;
103
+ border-bottom: 1px solid var(--border);
104
+ }
105
+ }
106
+
107
+ #next-steps ul {
108
+ list-style: none;
109
+ padding: 0;
110
+ display: flex;
111
+ gap: 8px;
112
+ margin: 32px 0 0;
113
+
114
+ .logo {
115
+ height: 18px;
116
+ }
117
+
118
+ a {
119
+ color: var(--text-h);
120
+ font-size: 16px;
121
+ border-radius: 6px;
122
+ background: var(--social-bg);
123
+ display: flex;
124
+ padding: 6px 12px;
125
+ align-items: center;
126
+ gap: 8px;
127
+ text-decoration: none;
128
+ transition: box-shadow 0.3s;
129
+
130
+ &:hover {
131
+ box-shadow: var(--shadow);
132
+ }
133
+ .button-icon {
134
+ height: 18px;
135
+ width: 18px;
136
+ }
137
+ }
138
+
139
+ @media (max-width: 1024px) {
140
+ margin-top: 20px;
141
+ flex-wrap: wrap;
142
+ justify-content: center;
143
+
144
+ li {
145
+ flex: 1 1 calc(50% - 8px);
146
+ }
147
+
148
+ a {
149
+ width: 100%;
150
+ justify-content: center;
151
+ box-sizing: border-box;
152
+ }
153
+ }
154
+ }
155
+
156
+ #spacer {
157
+ height: 88px;
158
+ border-top: 1px solid var(--border);
159
+ @media (max-width: 1024px) {
160
+ height: 48px;
161
+ }
162
+ }
163
+
164
+ .ticks {
165
+ position: relative;
166
+ width: 100%;
167
+
168
+ &::before,
169
+ &::after {
170
+ content: '';
171
+ position: absolute;
172
+ top: -4.5px;
173
+ border: 5px solid transparent;
174
+ }
175
+
176
+ &::before {
177
+ left: 0;
178
+ border-left-color: var(--border);
179
+ }
180
+ &::after {
181
+ right: 0;
182
+ border-right-color: var(--border);
183
+ }
184
+ }
dashboard/src/App.jsx ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Suspense, lazy } from "react"
2
+ import { BrowserRouter, Routes, Route } from "react-router-dom"
3
+ import AppShell from "./components/AppShell"
4
+
5
+ const Dashboard = lazy(() => import("./pages/Dashboard"))
6
+ const History = lazy(() => import("./pages/History"))
7
+ const Live = lazy(() => import("./pages/Live"))
8
+ const Analytics = lazy(() => import("./pages/Analytics"))
9
+
10
+ function App() {
11
+ return (
12
+ <BrowserRouter>
13
+ <AppShell>
14
+ <div className="mx-auto flex w-full max-w-[1600px] flex-1 flex-col px-4 pb-8 pt-4 sm:px-6 lg:px-8">
15
+ <Suspense
16
+ fallback={
17
+ <div className="surface-card p-6 text-sm text-slate-300">
18
+ Loading inspection workspace...
19
+ </div>
20
+ }
21
+ >
22
+ <Routes>
23
+ <Route path="/" element={<Dashboard />} />
24
+ <Route path="/history" element={<History />} />
25
+ <Route path="/live" element={<Live />} />
26
+ <Route path="/analytics" element={<Analytics />} />
27
+ </Routes>
28
+ </Suspense>
29
+ </div>
30
+ </AppShell>
31
+ </BrowserRouter>
32
+ )
33
+ }
34
+
35
+ export default App
dashboard/src/assets/hero.png ADDED
dashboard/src/assets/react.svg ADDED
dashboard/src/assets/vite.svg ADDED
dashboard/src/components/AppShell.jsx ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react"
2
+ import { useLocation } from "react-router-dom"
3
+ import Sidebar from "./Sidebar"
4
+
5
+ const PAGE_COPY = {
6
+ "/": {
7
+ label: "Command Center",
8
+ subtitle: "Real-time manufacturing quality monitoring, reporting, and plant visibility.",
9
+ },
10
+ "/live": {
11
+ label: "Live Monitoring",
12
+ subtitle: "Choose uploaded images or browser camera feed for inspection and monitoring.",
13
+ },
14
+ "/history": {
15
+ label: "Inspection History",
16
+ subtitle: "Trace reports, decisions, and defect signatures over time.",
17
+ },
18
+ "/analytics": {
19
+ label: "Analytics",
20
+ subtitle: "Trend performance, defect mix, and production quality signals.",
21
+ },
22
+ }
23
+
24
+ function formatHeaderTime() {
25
+ return new Intl.DateTimeFormat("en-IN", {
26
+ weekday: "short",
27
+ month: "short",
28
+ day: "numeric",
29
+ hour: "numeric",
30
+ minute: "2-digit",
31
+ }).format(new Date())
32
+ }
33
+
34
+ export default function AppShell({ children }) {
35
+ const { pathname } = useLocation()
36
+ const [mobileOpen, setMobileOpen] = useState(false)
37
+ const headerCopy = PAGE_COPY[pathname] || PAGE_COPY["/"]
38
+
39
+ return (
40
+ <div className="min-h-screen text-slate-100">
41
+ <div className="flex min-h-screen">
42
+ <Sidebar mobileOpen={mobileOpen} onClose={() => setMobileOpen(false)} />
43
+
44
+ <div className="flex min-h-screen min-w-0 flex-1 flex-col lg:pl-[320px]">
45
+ <header className="sticky top-0 z-20 border-b border-white/10 bg-slate-950/[0.55] backdrop-blur-xl">
46
+ <div className="mx-auto flex w-full max-w-[1600px] items-center justify-between gap-4 px-4 py-4 sm:px-6 lg:px-8">
47
+ <div className="flex min-w-0 items-center gap-3">
48
+ <button
49
+ type="button"
50
+ className="inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/5 text-lg text-slate-100 transition hover:border-cyan-300/40 hover:bg-cyan-400/10 lg:hidden"
51
+ onClick={() => setMobileOpen(true)}
52
+ aria-label="Open navigation"
53
+ >
54
+ ≡
55
+ </button>
56
+
57
+ <div className="min-w-0">
58
+ <p className="eyebrow">Manufacturing Monitoring System</p>
59
+ <h1 className="truncate text-xl font-semibold text-slate-50">{headerCopy.label}</h1>
60
+ <p className="hidden text-sm text-slate-400 sm:block">{headerCopy.subtitle}</p>
61
+ </div>
62
+ </div>
63
+
64
+ <div className="hidden rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300 sm:block">
65
+ {formatHeaderTime()}
66
+ </div>
67
+ </div>
68
+ </header>
69
+
70
+ <main className="flex flex-1">{children}</main>
71
+ </div>
72
+ </div>
73
+ </div>
74
+ )
75
+ }
dashboard/src/components/MetricCard.jsx ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default function MetricCard({ label, value, detail, tone = "steel" }) {
2
+ const toneClasses = {
3
+ steel: "from-slate-200/10 to-transparent text-slate-100",
4
+ success: "from-emerald-300/[0.15] to-transparent text-emerald-100",
5
+ warning: "from-amber-300/[0.15] to-transparent text-amber-100",
6
+ danger: "from-rose-300/[0.15] to-transparent text-rose-100",
7
+ accent: "from-cyan-300/[0.15] to-transparent text-cyan-100",
8
+ }
9
+
10
+ return (
11
+ <div className="surface-card p-5">
12
+ <div className={`absolute inset-x-0 top-0 h-24 bg-gradient-to-br ${toneClasses[tone] || toneClasses.steel}`} />
13
+ <div className="relative">
14
+ <p className="eyebrow">{label}</p>
15
+ <div className="mt-4 flex items-end justify-between gap-4">
16
+ <p className="font-display text-4xl font-semibold tracking-tight text-slate-50">{value}</p>
17
+ <span className="rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs uppercase tracking-[0.24em] text-slate-300">
18
+ Live
19
+ </span>
20
+ </div>
21
+ {detail ? <p className="mt-4 text-sm leading-6 text-slate-400">{detail}</p> : null}
22
+ </div>
23
+ </div>
24
+ )
25
+ }
dashboard/src/components/ProcessFlow.jsx ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default function ProcessFlow({ steps, compact = false }) {
2
+ return (
3
+ <div className={`grid gap-3 ${compact ? "" : "lg:grid-cols-2"}`}>
4
+ {steps.map((step, index) => (
5
+ <div key={step.title} className="rounded-[28px] border border-white/10 bg-white/5 p-4">
6
+ <div className="flex items-start gap-4">
7
+ <span className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-slate-950/70 text-sm font-semibold text-slate-100">
8
+ {String(index + 1).padStart(2, "0")}
9
+ </span>
10
+ <div>
11
+ <p className="text-sm font-semibold uppercase tracking-[0.2em] text-cyan-100/80">
12
+ {step.title}
13
+ </p>
14
+ <p className="mt-2 text-sm leading-7 text-slate-300">{step.detail}</p>
15
+ </div>
16
+ </div>
17
+ </div>
18
+ ))}
19
+ </div>
20
+ )
21
+ }
dashboard/src/components/Sidebar.jsx ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NavLink } from "react-router-dom"
2
+ import { systemBrief } from "../content/systemBrief"
3
+ import ProcessFlow from "./ProcessFlow"
4
+
5
+ const NAV_ITEMS = [
6
+ { to: "/", label: "Dashboard", kicker: "Plant status" },
7
+ { to: "/live", label: "Live Monitor", kicker: "Camera and upload" },
8
+ { to: "/history", label: "History", kicker: "Inspection logs" },
9
+ { to: "/analytics", label: "Analytics", kicker: "Trends and charts" },
10
+ ]
11
+
12
+ function navClasses(isActive) {
13
+ return [
14
+ "group relative overflow-hidden rounded-3xl border px-4 py-4 transition duration-300",
15
+ isActive
16
+ ? "border-cyan-300/50 bg-cyan-400/10 shadow-[0_16px_40px_rgba(34,211,238,0.12)]"
17
+ : "border-white/[0.08] bg-white/[0.04] hover:border-white/20 hover:bg-white/[0.07]",
18
+ ].join(" ")
19
+ }
20
+
21
+ export default function Sidebar({ mobileOpen, onClose }) {
22
+ return (
23
+ <>
24
+ <div
25
+ className={`fixed inset-0 z-30 bg-slate-950/70 backdrop-blur-sm transition lg:hidden ${
26
+ mobileOpen ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"
27
+ }`}
28
+ onClick={onClose}
29
+ />
30
+
31
+ <aside
32
+ className={`fixed inset-y-0 left-0 z-40 flex w-[320px] max-w-[88vw] flex-col border-r border-white/10 bg-slate-950/[0.92] px-5 py-5 shadow-[0_30px_80px_rgba(2,6,23,0.55)] backdrop-blur-2xl transition duration-300 lg:z-10 lg:translate-x-0 ${
33
+ mobileOpen ? "translate-x-0" : "-translate-x-full"
34
+ }`}
35
+ >
36
+ <div className="surface-card p-5">
37
+ <div className="flex items-start justify-between gap-4">
38
+ <div>
39
+ <p className="eyebrow">Factory Quality Ops</p>
40
+ <h2 className="text-2xl font-semibold text-slate-50">Manufacturing Monitoring System</h2>
41
+ </div>
42
+
43
+ <button
44
+ type="button"
45
+ className="inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-white/10 bg-white/5 text-slate-100 transition hover:border-cyan-300/40 hover:bg-cyan-400/10 lg:hidden"
46
+ onClick={onClose}
47
+ aria-label="Close navigation"
48
+ >
49
+ ×
50
+ </button>
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
+
59
+ <nav className="mt-6 flex flex-col gap-3">
60
+ {NAV_ITEMS.map((item, index) => (
61
+ <NavLink key={item.to} to={item.to} onClick={onClose} className={({ isActive }) => navClasses(isActive)}>
62
+ {({ isActive }) => (
63
+ <div className="relative flex items-center gap-4">
64
+ <div
65
+ className={`flex h-11 w-11 items-center justify-center rounded-2xl border text-sm font-semibold ${
66
+ isActive
67
+ ? "border-cyan-300/50 bg-cyan-300/[0.15] text-cyan-100"
68
+ : "border-white/10 bg-white/5 text-slate-300"
69
+ }`}
70
+ >
71
+ {String(index + 1).padStart(2, "0")}
72
+ </div>
73
+
74
+ <div className="min-w-0">
75
+ <p className="text-base font-medium text-slate-50">{item.label}</p>
76
+ <p className="text-sm text-slate-400">{item.kicker}</p>
77
+ </div>
78
+ </div>
79
+ )}
80
+ </NavLink>
81
+ ))}
82
+ </nav>
83
+
84
+ <div className="mt-auto surface-card p-5">
85
+ <p className="eyebrow">System Architecture</p>
86
+ <div className="mt-4">
87
+ <ProcessFlow steps={systemBrief.architectureFlow.slice(0, 3)} compact />
88
+ </div>
89
+ </div>
90
+ </aside>
91
+ </>
92
+ )
93
+ }
dashboard/src/components/StatusBadge.jsx ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const TONE_CLASSES = {
2
+ neutral: "border-white/10 bg-white/5 text-slate-200",
3
+ success: "border-emerald-300/30 bg-emerald-400/10 text-emerald-100",
4
+ warning: "border-amber-300/30 bg-amber-400/10 text-amber-100",
5
+ danger: "border-rose-300/30 bg-rose-400/10 text-rose-100",
6
+ info: "border-cyan-300/30 bg-cyan-400/10 text-cyan-100",
7
+ }
8
+
9
+ export default function StatusBadge({ label, tone = "neutral", pulse = false }) {
10
+ return (
11
+ <span
12
+ className={`inline-flex items-center gap-2 rounded-full border px-3 py-2 text-xs font-medium uppercase tracking-[0.24em] ${TONE_CLASSES[tone] || TONE_CLASSES.neutral}`}
13
+ >
14
+ <span
15
+ className={`h-2.5 w-2.5 rounded-full bg-current ${pulse ? "animate-pulse" : ""}`}
16
+ />
17
+ {label}
18
+ </span>
19
+ )
20
+ }
dashboard/src/content/systemBrief.js ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: "Run the steel defect model to identify surface anomalies, geometry, and severity.",
13
+ },
14
+ {
15
+ title: "Inspection Formatter",
16
+ detail: "Normalize decisions, recommendations, defect summaries, and annotated preview output.",
17
+ },
18
+ {
19
+ title: "Operational Data Layer",
20
+ detail: "Store JSON reports locally and persist inspection records to PostgreSQL when configured.",
21
+ },
22
+ {
23
+ title: "FastAPI Control Layer",
24
+ detail: "Expose REST endpoints for reports, analytics, uploads, camera frames, and system health.",
25
+ },
26
+ {
27
+ title: "WebSocket Event Stream",
28
+ detail: "Broadcast inspection snapshots and live updates to all connected operator dashboards.",
29
+ },
30
+ {
31
+ title: "React Monitoring Console",
32
+ detail: "Present live status, history, analytics, and camera-based inspection in a clean UI.",
33
+ },
34
+ ],
35
+ backend: {
36
+ responsibilities: [
37
+ "Serve inspection data through REST endpoints.",
38
+ "Push real-time updates through WebSocket connections.",
39
+ "Connect to PostgreSQL through Supabase or fall back to local report storage.",
40
+ ],
41
+ files: [
42
+ {
43
+ title: "api/main.py",
44
+ detail: "FastAPI app, REST endpoints, and /ws WebSocket entry point.",
45
+ },
46
+ {
47
+ title: "core/database.py",
48
+ detail: "Safe database access layer with optional runtime fallback.",
49
+ },
50
+ {
51
+ title: "core/config.py",
52
+ detail: "Environment-backed application settings and path configuration.",
53
+ },
54
+ {
55
+ title: "core/logger.py",
56
+ detail: "Structured logging for debugging and operational tracing.",
57
+ },
58
+ ],
59
+ },
60
+ aiPipeline: {
61
+ files: [
62
+ {
63
+ title: "live_camera.py",
64
+ detail: "Simulated camera loop for offline inspection playback with the trained model.",
65
+ },
66
+ {
67
+ title: "inspection/service.py",
68
+ detail: "Unified runtime service for upload inspection, camera-frame inference, and preview overlays.",
69
+ },
70
+ {
71
+ title: "inspection/output_formatter.py",
72
+ detail: "Formats defect data, writes reports, stores records, and triggers live broadcasts.",
73
+ },
74
+ ],
75
+ flow: [
76
+ {
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",
86
+ detail: "Generate PASS, REVIEW, or FAIL decisions with operational recommendations.",
87
+ },
88
+ {
89
+ title: "Persist",
90
+ detail: "Save reports locally and write to PostgreSQL when a database is configured.",
91
+ },
92
+ {
93
+ title: "Broadcast",
94
+ detail: "Stream the inspection event to dashboards through WebSocket updates.",
95
+ },
96
+ ],
97
+ },
98
+ database: {
99
+ table: "inspections",
100
+ columns: [
101
+ "id",
102
+ "timestamp",
103
+ "total_defects",
104
+ "minor",
105
+ "moderate",
106
+ "critical",
107
+ "decision",
108
+ "raw_data (JSON)",
109
+ ],
110
+ },
111
+ frontend: {
112
+ structure: [
113
+ "src/components/Sidebar.jsx",
114
+ "src/pages/Dashboard.jsx",
115
+ "src/pages/History.jsx",
116
+ "src/pages/Live.jsx",
117
+ "src/pages/Analytics.jsx",
118
+ "src/App.jsx",
119
+ ],
120
+ routing: [
121
+ "/ -> Dashboard",
122
+ "/history -> Inspection logs",
123
+ "/live -> Live monitoring",
124
+ "/analytics -> Charts and insights",
125
+ ],
126
+ features: [
127
+ "Dashboard -> live status, defect counts, active alerts, and WebSocket updates.",
128
+ "History -> searchable inspection logs with report detail selection.",
129
+ "Live -> upload detection and browser camera inspection with annotated output.",
130
+ "Analytics -> Recharts-based trends, defect mix, and source usage.",
131
+ ],
132
+ },
133
+ realtime: {
134
+ flow: [
135
+ "New inspection captured",
136
+ "Inspection formatted",
137
+ "Local and DB storage written",
138
+ "WebSocket event broadcast",
139
+ "Dashboard, history, and analytics refresh",
140
+ ],
141
+ },
142
+ currentState: {
143
+ working: [
144
+ "AI detection pipeline",
145
+ "Local report persistence",
146
+ "REST API",
147
+ "Frontend routing",
148
+ "Dashboard UI",
149
+ "WebSocket live updates",
150
+ "Upload and camera inspection endpoints",
151
+ ],
152
+ inProgress: [
153
+ "Database configuration per deployment",
154
+ "Factory-floor data source integration",
155
+ ],
156
+ },
157
+ improvements: {
158
+ backend: [
159
+ "Async-safe WebSocket broadcasting.",
160
+ "Dropped-connection handling.",
161
+ "Graceful database fallback.",
162
+ ],
163
+ frontend: [
164
+ "Organized industrial dashboard layout.",
165
+ "Clear loading and empty states.",
166
+ "Live connection feedback and camera workflow polish.",
167
+ ],
168
+ realtime: [
169
+ "WebSocket-first streaming.",
170
+ "Heartbeat and reconnect handling.",
171
+ "Inspection preview return for live camera frames.",
172
+ ],
173
+ features: [
174
+ "Live monitoring with upload and camera options.",
175
+ "Analytics with inspection trends.",
176
+ "Alerts with visual and audio cues.",
177
+ ],
178
+ },
179
+ finalSummary:
180
+ "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.",
181
+ }
dashboard/src/hooks/useRealtimeInspection.js ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react"
2
+ import { fetchLatestReport, getWebSocketUrl } from "../lib/api"
3
+
4
+ export default function useRealtimeInspection() {
5
+ const [latestInspection, setLatestInspection] = useState(null)
6
+ const [connectionState, setConnectionState] = useState("connecting")
7
+ const [lastEventAt, setLastEventAt] = useState(null)
8
+ const [streamError, setStreamError] = useState("")
9
+
10
+ useEffect(() => {
11
+ let socket
12
+ let reconnectTimer
13
+ let heartbeatTimer
14
+ let refreshTimer
15
+ let active = true
16
+ let retryCount = 0
17
+
18
+ async function hydrateLatest() {
19
+ try {
20
+ const latest = await fetchLatestReport()
21
+ if (active && latest?.timestamp) {
22
+ setLatestInspection((current) => {
23
+ if (!current || current.timestamp !== latest.timestamp) {
24
+ return latest
25
+ }
26
+ return current
27
+ })
28
+ setLastEventAt(latest.timestamp)
29
+ }
30
+ } catch {
31
+ if (active) {
32
+ setStreamError("Latest inspection snapshot is unavailable right now.")
33
+ }
34
+ }
35
+ }
36
+
37
+ function scheduleReconnect() {
38
+ if (!active) return
39
+
40
+ setConnectionState("reconnecting")
41
+ const delay = Math.min(8000, 1200 * 2 ** retryCount)
42
+ retryCount += 1
43
+ reconnectTimer = window.setTimeout(connect, delay)
44
+ }
45
+
46
+ function connect() {
47
+ if (!active) return
48
+
49
+ setConnectionState("connecting")
50
+ socket = new WebSocket(getWebSocketUrl("/ws"))
51
+
52
+ socket.onopen = () => {
53
+ retryCount = 0
54
+ setConnectionState("connected")
55
+ setStreamError("")
56
+
57
+ heartbeatTimer = window.setInterval(() => {
58
+ if (socket?.readyState === WebSocket.OPEN) {
59
+ socket.send(JSON.stringify({ type: "ping" }))
60
+ }
61
+ }, 15000)
62
+ }
63
+
64
+ socket.onmessage = (event) => {
65
+ const payload = JSON.parse(event.data)
66
+
67
+ if (payload.type === "inspection.update" || payload.type === "inspection.snapshot") {
68
+ setLatestInspection(payload)
69
+ setLastEventAt(payload.timestamp)
70
+ return
71
+ }
72
+
73
+ if (payload.type === "pong") {
74
+ setConnectionState("connected")
75
+ }
76
+ }
77
+
78
+ socket.onerror = () => {
79
+ setStreamError("Live stream interrupted. Reconnecting to the inspection server.")
80
+ }
81
+
82
+ socket.onclose = () => {
83
+ window.clearInterval(heartbeatTimer)
84
+ if (active) {
85
+ scheduleReconnect()
86
+ }
87
+ }
88
+ }
89
+
90
+ hydrateLatest()
91
+ connect()
92
+ refreshTimer = window.setInterval(hydrateLatest, 6000)
93
+
94
+ return () => {
95
+ active = false
96
+ window.clearTimeout(reconnectTimer)
97
+ window.clearInterval(heartbeatTimer)
98
+ window.clearInterval(refreshTimer)
99
+
100
+ if (socket) {
101
+ socket.close()
102
+ }
103
+ }
104
+ }, [])
105
+
106
+ return {
107
+ latestInspection,
108
+ connectionState,
109
+ lastEventAt,
110
+ streamError,
111
+ }
112
+ }
dashboard/src/index.css ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ @layer base {
6
+ :root {
7
+ color-scheme: dark;
8
+ --font-display: "Avenir Next Condensed", "Avenir Next", "Trebuchet MS", sans-serif;
9
+ --font-body: "Avenir Next", "Segoe UI", sans-serif;
10
+ --font-mono: "IBM Plex Mono", "SFMono-Regular", Consolas, monospace;
11
+ }
12
+
13
+ * {
14
+ box-sizing: border-box;
15
+ }
16
+
17
+ html {
18
+ min-height: 100%;
19
+ scroll-behavior: smooth;
20
+ }
21
+
22
+ body {
23
+ min-height: 100vh;
24
+ background:
25
+ radial-gradient(circle at top left, rgba(56, 189, 248, 0.14), transparent 24%),
26
+ radial-gradient(circle at 82% 18%, rgba(245, 158, 11, 0.11), transparent 24%),
27
+ linear-gradient(180deg, #07111d 0%, #050a12 42%, #02060d 100%);
28
+ color: #e2e8f0;
29
+ font-family: var(--font-body);
30
+ }
31
+
32
+ body::before {
33
+ content: "";
34
+ position: fixed;
35
+ inset: 0;
36
+ background-image:
37
+ linear-gradient(rgba(148, 163, 184, 0.05) 1px, transparent 1px),
38
+ linear-gradient(90deg, rgba(148, 163, 184, 0.05) 1px, transparent 1px);
39
+ background-size: 120px 120px;
40
+ opacity: 0.18;
41
+ pointer-events: none;
42
+ }
43
+
44
+ #root {
45
+ min-height: 100vh;
46
+ position: relative;
47
+ z-index: 1;
48
+ }
49
+ }
50
+
51
+ @layer components {
52
+ .surface-card {
53
+ @apply relative overflow-hidden rounded-[32px] border border-white/10 bg-slate-950/70 shadow-[0_24px_90px_rgba(2,6,23,0.5)] backdrop-blur-xl;
54
+ }
55
+
56
+ .surface-card::after {
57
+ content: "";
58
+ position: absolute;
59
+ inset: 0;
60
+ background: linear-gradient(140deg, rgba(255, 255, 255, 0.06), transparent 35%, transparent 65%, rgba(56, 189, 248, 0.05));
61
+ pointer-events: none;
62
+ }
63
+
64
+ .eyebrow {
65
+ @apply text-[0.72rem] font-medium uppercase tracking-[0.34em] text-cyan-100/70;
66
+ }
67
+
68
+ .hero-title {
69
+ font-family: var(--font-display);
70
+ @apply text-4xl font-semibold leading-tight tracking-tight text-slate-50 md:text-5xl;
71
+ }
72
+
73
+ .section-title {
74
+ font-family: var(--font-display);
75
+ @apply text-2xl font-semibold tracking-tight text-slate-50;
76
+ }
77
+
78
+ .body-copy {
79
+ @apply text-sm leading-8 text-slate-300 md:text-base;
80
+ }
81
+
82
+ .primary-btn {
83
+ @apply inline-flex items-center justify-center rounded-full border border-cyan-300/30 bg-cyan-400/10 px-5 py-3 text-sm font-medium text-cyan-50 transition hover:border-cyan-200/40 hover:bg-cyan-400/20 disabled:cursor-not-allowed disabled:opacity-60;
84
+ }
85
+
86
+ .secondary-btn {
87
+ @apply inline-flex items-center justify-center rounded-full border border-white/10 bg-white/5 px-5 py-3 text-sm font-medium text-slate-100 transition hover:border-white/20 hover:bg-white/10 disabled:cursor-not-allowed disabled:opacity-60;
88
+ }
89
+
90
+ .chip {
91
+ @apply inline-flex items-center rounded-full border border-white/10 bg-white/5 px-3 py-2 text-xs uppercase tracking-[0.22em] text-slate-200;
92
+ }
93
+
94
+ .chip-success {
95
+ @apply inline-flex items-center rounded-full border border-emerald-300/25 bg-emerald-400/10 px-3 py-2 text-xs uppercase tracking-[0.22em] text-emerald-100;
96
+ }
97
+
98
+ .chip-warning {
99
+ @apply inline-flex items-center rounded-full border border-amber-300/25 bg-amber-400/10 px-3 py-2 text-xs uppercase tracking-[0.22em] text-amber-100;
100
+ }
101
+
102
+ .font-display {
103
+ font-family: var(--font-display);
104
+ }
105
+
106
+ .glow-divider {
107
+ height: 1px;
108
+ background: linear-gradient(90deg, transparent, rgba(148, 163, 184, 0.35), transparent);
109
+ }
110
+ }
dashboard/src/lib/api.js ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const isLocalhost = typeof window !== "undefined" && ["127.0.0.1", "localhost"].includes(window.location.hostname)
2
+ const defaultApiBaseUrl = typeof window !== "undefined"
3
+ ? (isLocalhost ? "http://127.0.0.1:8000" : window.location.origin)
4
+ : "http://127.0.0.1:8000"
5
+
6
+ const API_BASE_URL = (import.meta.env.VITE_API_BASE_URL || defaultApiBaseUrl).replace(/\/$/, "")
7
+ const WS_BASE_URL = (
8
+ import.meta.env.VITE_WS_BASE_URL ||
9
+ API_BASE_URL.replace(/^http/, "ws")
10
+ ).replace(/\/$/, "")
11
+
12
+ async function request(path, options = {}) {
13
+ const response = await fetch(`${API_BASE_URL}${path}`, {
14
+ headers: {
15
+ "Content-Type": "application/json",
16
+ ...(options.headers || {}),
17
+ },
18
+ ...options,
19
+ })
20
+
21
+ if (!response.ok) {
22
+ let detail = "Request failed"
23
+
24
+ try {
25
+ const payload = await response.json()
26
+ detail = payload.detail || detail
27
+ } catch {
28
+ detail = response.statusText || detail
29
+ }
30
+
31
+ throw new Error(detail)
32
+ }
33
+
34
+ return response.json()
35
+ }
36
+
37
+ export function getWebSocketUrl(path = "/ws") {
38
+ return `${WS_BASE_URL}${path}`
39
+ }
40
+
41
+ export function fetchReports(limit = 50) {
42
+ return request(`/reports?limit=${limit}`)
43
+ }
44
+
45
+ export function fetchLatestReport() {
46
+ return request("/reports/latest")
47
+ }
48
+
49
+ export function fetchAnalyticsSummary(limit = 120) {
50
+ return request(`/analytics/summary?limit=${limit}`)
51
+ }
52
+
53
+ export function inspectImage(payload) {
54
+ return request("/inspect/image", {
55
+ method: "POST",
56
+ body: JSON.stringify(payload),
57
+ })
58
+ }
59
+
60
+ export function inspectFrame(payload) {
61
+ return request("/inspect/frame", {
62
+ method: "POST",
63
+ body: JSON.stringify(payload),
64
+ })
65
+ }
dashboard/src/lib/formatters.js ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export function formatDateTime(value) {
2
+ if (!value) return "Waiting for signal"
3
+
4
+ const parsed = new Date(value)
5
+ if (Number.isNaN(parsed.getTime())) return value
6
+
7
+ return new Intl.DateTimeFormat("en-IN", {
8
+ year: "numeric",
9
+ month: "short",
10
+ day: "numeric",
11
+ hour: "numeric",
12
+ minute: "2-digit",
13
+ second: "2-digit",
14
+ }).format(parsed)
15
+ }
16
+
17
+ export function formatShortTime(value) {
18
+ if (!value) return "--"
19
+
20
+ const parsed = new Date(value)
21
+ if (Number.isNaN(parsed.getTime())) return value
22
+
23
+ return new Intl.DateTimeFormat("en-IN", {
24
+ month: "short",
25
+ day: "numeric",
26
+ hour: "numeric",
27
+ minute: "2-digit",
28
+ }).format(parsed)
29
+ }
30
+
31
+ export function titleCase(value) {
32
+ if (!value) return "Unknown"
33
+
34
+ return value
35
+ .replace(/_/g, " ")
36
+ .replace(/\b\w/g, (letter) => letter.toUpperCase())
37
+ }
38
+
39
+ export function truncateText(value, maxLength = 140) {
40
+ if (!value || value.length <= maxLength) return value
41
+ return `${value.slice(0, maxLength - 1)}…`
42
+ }
dashboard/src/lib/status.js ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
+
8
+ export function getConnectionTone(state) {
9
+ if (state === "connected") return "success"
10
+ if (state === "reconnecting" || state === "connecting") return "warning"
11
+ if (state === "error") return "danger"
12
+ return "neutral"
13
+ }
dashboard/src/main.jsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import './index.css'
4
+ import App from './App.jsx'
5
+
6
+ createRoot(document.getElementById('root')).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ )
dashboard/src/pages/Analytics.jsx ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react"
2
+ import {
3
+ Area,
4
+ AreaChart,
5
+ Bar,
6
+ BarChart,
7
+ CartesianGrid,
8
+ Cell,
9
+ Pie,
10
+ PieChart,
11
+ ResponsiveContainer,
12
+ Tooltip,
13
+ XAxis,
14
+ YAxis,
15
+ } from "recharts"
16
+ import MetricCard from "../components/MetricCard"
17
+ import { systemBrief } from "../content/systemBrief"
18
+ import { fetchAnalyticsSummary } from "../lib/api"
19
+ import { formatShortTime, titleCase } from "../lib/formatters"
20
+
21
+ const CHART_COLORS = ["#38bdf8", "#f59e0b", "#f43f5e", "#22c55e", "#94a3b8", "#a855f7"]
22
+
23
+ export default function Analytics() {
24
+ const [analytics, setAnalytics] = useState(null)
25
+ const [loading, setLoading] = useState(true)
26
+ const [error, setError] = useState("")
27
+
28
+ useEffect(() => {
29
+ let active = true
30
+
31
+ fetchAnalyticsSummary(120)
32
+ .then((payload) => {
33
+ if (active) {
34
+ setAnalytics(payload)
35
+ }
36
+ })
37
+ .catch((requestError) => {
38
+ if (active) {
39
+ setError(requestError.message)
40
+ }
41
+ })
42
+ .finally(() => {
43
+ if (active) {
44
+ setLoading(false)
45
+ }
46
+ })
47
+
48
+ return () => {
49
+ active = false
50
+ }
51
+ }, [])
52
+
53
+ const decisionData = analytics
54
+ ? Object.entries(analytics.decision_breakdown).map(([name, value]) => ({ name, value }))
55
+ : []
56
+ const severityData = analytics
57
+ ? Object.entries(analytics.severity_totals).map(([name, value]) => ({ name, value }))
58
+ : []
59
+ const sourceData = analytics
60
+ ? Object.entries(analytics.source_breakdown).map(([name, value]) => ({ name: titleCase(name), value }))
61
+ : []
62
+ const defectData = analytics
63
+ ? Object.entries(analytics.defect_breakdown)
64
+ .map(([name, value]) => ({ name: titleCase(name), value }))
65
+ .sort((left, right) => right.value - left.value)
66
+ .slice(0, 6)
67
+ : []
68
+ const timeline = analytics
69
+ ? analytics.timeline.map((entry) => ({
70
+ ...entry,
71
+ label: formatShortTime(entry.timestamp),
72
+ }))
73
+ : []
74
+
75
+ return (
76
+ <div className="space-y-6 pb-10">
77
+ <section className="surface-card p-6 md:p-8">
78
+ <div className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
79
+ <div>
80
+ <p className="eyebrow">Analytics Page</p>
81
+ <h2 className="hero-title mt-3">Charts, trend monitoring, and quality insights for the Manufacturing Monitoring System.</h2>
82
+ <p className="body-copy mt-5 max-w-3xl">
83
+ This view turns saved inspections into trend signals so operators and engineers can understand defect mix,
84
+ decision rates, and monitoring behavior over time.
85
+ </p>
86
+ </div>
87
+
88
+ <div className="grid gap-4 sm:grid-cols-3">
89
+ <MetricCard label="Reports" value={analytics?.report_count ?? "--"} detail="Trend window size." tone="steel" />
90
+ <MetricCard label="Avg Defects" value={analytics?.average_total_defects ?? "--"} detail="Per inspection." tone="accent" />
91
+ <MetricCard label="Sources" value={sourceData.length || "--"} detail="Capture modes in the dataset." tone="warning" />
92
+ </div>
93
+ </div>
94
+ </section>
95
+
96
+ {loading ? (
97
+ <section className="surface-card p-6 text-sm text-slate-400">Loading analytics...</section>
98
+ ) : error ? (
99
+ <section className="surface-card p-6 text-sm text-rose-100">{error}</section>
100
+ ) : (
101
+ <>
102
+ <section className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
103
+ <div className="surface-card p-6">
104
+ <p className="eyebrow">Trend Over Time</p>
105
+ <h3 className="section-title mt-2">Defect volume per inspection</h3>
106
+ <div className="mt-6 h-[340px]">
107
+ <ResponsiveContainer width="100%" height="100%">
108
+ <AreaChart data={timeline}>
109
+ <defs>
110
+ <linearGradient id="totalGradient" x1="0" y1="0" x2="0" y2="1">
111
+ <stop offset="0%" stopColor="#38bdf8" stopOpacity={0.45} />
112
+ <stop offset="100%" stopColor="#38bdf8" stopOpacity={0.02} />
113
+ </linearGradient>
114
+ </defs>
115
+ <CartesianGrid stroke="rgba(148, 163, 184, 0.12)" vertical={false} />
116
+ <XAxis dataKey="label" tick={{ fill: "#94a3b8", fontSize: 12 }} axisLine={false} tickLine={false} />
117
+ <YAxis tick={{ fill: "#94a3b8", fontSize: 12 }} axisLine={false} tickLine={false} />
118
+ <Tooltip
119
+ contentStyle={{
120
+ background: "rgba(15, 23, 42, 0.96)",
121
+ border: "1px solid rgba(148, 163, 184, 0.18)",
122
+ borderRadius: "18px",
123
+ color: "#e2e8f0",
124
+ }}
125
+ />
126
+ <Area type="monotone" dataKey="total_defects" stroke="#38bdf8" strokeWidth={3} fill="url(#totalGradient)" />
127
+ </AreaChart>
128
+ </ResponsiveContainer>
129
+ </div>
130
+ </div>
131
+
132
+ <div className="surface-card p-6">
133
+ <p className="eyebrow">Decision Mix</p>
134
+ <h3 className="section-title mt-2">PASS, REVIEW, and FAIL distribution</h3>
135
+ <div className="mt-6 h-[340px]">
136
+ <ResponsiveContainer width="100%" height="100%">
137
+ <PieChart>
138
+ <Tooltip
139
+ contentStyle={{
140
+ background: "rgba(15, 23, 42, 0.96)",
141
+ border: "1px solid rgba(148, 163, 184, 0.18)",
142
+ borderRadius: "18px",
143
+ color: "#e2e8f0",
144
+ }}
145
+ />
146
+ <Pie data={decisionData} dataKey="value" nameKey="name" innerRadius={70} outerRadius={110} paddingAngle={4}>
147
+ {decisionData.map((entry, index) => (
148
+ <Cell key={entry.name} fill={CHART_COLORS[index % CHART_COLORS.length]} />
149
+ ))}
150
+ </Pie>
151
+ </PieChart>
152
+ </ResponsiveContainer>
153
+ </div>
154
+ </div>
155
+ </section>
156
+
157
+ <section className="grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">
158
+ <div className="surface-card p-6">
159
+ <p className="eyebrow">Severity Totals</p>
160
+ <h3 className="section-title mt-2">Minor, moderate, and critical volume</h3>
161
+ <div className="mt-6 h-[340px]">
162
+ <ResponsiveContainer width="100%" height="100%">
163
+ <BarChart data={severityData}>
164
+ <CartesianGrid stroke="rgba(148, 163, 184, 0.12)" vertical={false} />
165
+ <XAxis dataKey="name" tick={{ fill: "#94a3b8", fontSize: 12 }} axisLine={false} tickLine={false} />
166
+ <YAxis tick={{ fill: "#94a3b8", fontSize: 12 }} axisLine={false} tickLine={false} />
167
+ <Tooltip
168
+ contentStyle={{
169
+ background: "rgba(15, 23, 42, 0.96)",
170
+ border: "1px solid rgba(148, 163, 184, 0.18)",
171
+ borderRadius: "18px",
172
+ color: "#e2e8f0",
173
+ }}
174
+ />
175
+ <Bar dataKey="value" radius={[14, 14, 0, 0]}>
176
+ {severityData.map((entry, index) => (
177
+ <Cell key={entry.name} fill={CHART_COLORS[index % CHART_COLORS.length]} />
178
+ ))}
179
+ </Bar>
180
+ </BarChart>
181
+ </ResponsiveContainer>
182
+ </div>
183
+ </div>
184
+
185
+ <div className="surface-card p-6">
186
+ <p className="eyebrow">Defect Types</p>
187
+ <h3 className="section-title mt-2">Most frequent defect categories</h3>
188
+ <div className="mt-6 h-[340px]">
189
+ <ResponsiveContainer width="100%" height="100%">
190
+ <BarChart layout="vertical" data={defectData}>
191
+ <CartesianGrid stroke="rgba(148, 163, 184, 0.12)" horizontal={false} />
192
+ <XAxis type="number" tick={{ fill: "#94a3b8", fontSize: 12 }} axisLine={false} tickLine={false} />
193
+ <YAxis type="category" dataKey="name" tick={{ fill: "#cbd5e1", fontSize: 12 }} axisLine={false} tickLine={false} width={120} />
194
+ <Tooltip
195
+ contentStyle={{
196
+ background: "rgba(15, 23, 42, 0.96)",
197
+ border: "1px solid rgba(148, 163, 184, 0.18)",
198
+ borderRadius: "18px",
199
+ color: "#e2e8f0",
200
+ }}
201
+ />
202
+ <Bar dataKey="value" radius={[0, 14, 14, 0]}>
203
+ {defectData.map((entry, index) => (
204
+ <Cell key={entry.name} fill={CHART_COLORS[index % CHART_COLORS.length]} />
205
+ ))}
206
+ </Bar>
207
+ </BarChart>
208
+ </ResponsiveContainer>
209
+ </div>
210
+ </div>
211
+ </section>
212
+
213
+ <section className="grid gap-6 xl:grid-cols-2">
214
+ <div className="surface-card p-6">
215
+ <p className="eyebrow">Capture Sources</p>
216
+ <h3 className="section-title mt-2">Which input modes are being used</h3>
217
+ <div className="mt-5 space-y-3">
218
+ {sourceData.length ? (
219
+ sourceData.map((entry, index) => (
220
+ <div key={entry.name} className="flex items-center justify-between rounded-3xl border border-white/10 bg-white/5 px-4 py-4">
221
+ <div className="flex items-center gap-3">
222
+ <span
223
+ className="inline-flex h-3.5 w-3.5 rounded-full"
224
+ style={{ backgroundColor: CHART_COLORS[index % CHART_COLORS.length] }}
225
+ />
226
+ <p className="text-sm text-slate-200">{entry.name}</p>
227
+ </div>
228
+ <p className="text-sm font-medium text-slate-100">{entry.value}</p>
229
+ </div>
230
+ ))
231
+ ) : (
232
+ <div className="rounded-3xl border border-dashed border-white/15 bg-white/5 p-5 text-sm text-slate-400">
233
+ Source analytics will appear once reports are available.
234
+ </div>
235
+ )}
236
+ </div>
237
+ </div>
238
+
239
+ <div className="surface-card p-6">
240
+ <p className="eyebrow">What Needs Improvement</p>
241
+ <h3 className="section-title mt-2">Roadmap aligned to the project brief</h3>
242
+ <div className="mt-5 grid gap-4">
243
+ {Object.entries(systemBrief.improvements).map(([section, items]) => (
244
+ <div key={section} className="rounded-3xl border border-white/10 bg-white/5 p-4">
245
+ <p className="text-sm font-medium uppercase tracking-[0.24em] text-cyan-100/80">
246
+ {titleCase(section)}
247
+ </p>
248
+ <div className="mt-3 flex flex-wrap gap-2">
249
+ {items.map((item) => (
250
+ <span key={item} className="chip">
251
+ {item}
252
+ </span>
253
+ ))}
254
+ </div>
255
+ </div>
256
+ ))}
257
+ </div>
258
+ </div>
259
+ </section>
260
+ </>
261
+ )}
262
+ </div>
263
+ )
264
+ }
dashboard/src/pages/Dashboard.jsx ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react"
2
+ import { Link } from "react-router-dom"
3
+ import MetricCard from "../components/MetricCard"
4
+ import ProcessFlow from "../components/ProcessFlow"
5
+ import StatusBadge from "../components/StatusBadge"
6
+ import { systemBrief } from "../content/systemBrief"
7
+ import useRealtimeInspection from "../hooks/useRealtimeInspection"
8
+ import { fetchAnalyticsSummary } from "../lib/api"
9
+ import { formatDateTime, titleCase, truncateText } from "../lib/formatters"
10
+ import { getConnectionTone, getDecisionTone } from "../lib/status"
11
+
12
+ const FALLBACK_INSPECTION = {
13
+ total_defects: 0,
14
+ minor: 0,
15
+ moderate: 0,
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",
23
+ defects: [],
24
+ source: "system",
25
+ timestamp: null,
26
+ }
27
+
28
+ export default function Dashboard() {
29
+ const { latestInspection, connectionState, lastEventAt, streamError } = useRealtimeInspection()
30
+ const [analytics, setAnalytics] = useState(null)
31
+ const inspection = latestInspection || FALLBACK_INSPECTION
32
+ const isCritical = inspection.critical > 0
33
+
34
+ useEffect(() => {
35
+ let active = true
36
+
37
+ fetchAnalyticsSummary(60)
38
+ .then((payload) => {
39
+ if (active) {
40
+ setAnalytics(payload)
41
+ }
42
+ })
43
+ .catch(() => {
44
+ if (active) {
45
+ setAnalytics(null)
46
+ }
47
+ })
48
+
49
+ return () => {
50
+ active = false
51
+ }
52
+ }, [])
53
+
54
+ return (
55
+ <div className="space-y-6 pb-10">
56
+ <section className="surface-card p-6 md:p-8">
57
+ <div className="grid gap-6 xl:grid-cols-[1.35fr_0.95fr]">
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
+
65
+ <div className="mt-6 flex flex-wrap items-center gap-3">
66
+ <StatusBadge
67
+ label={`Stream ${connectionState}`}
68
+ tone={getConnectionTone(connectionState)}
69
+ pulse={connectionState === "connected"}
70
+ />
71
+ <StatusBadge
72
+ label={`Decision ${inspection.decision}`}
73
+ tone={getDecisionTone(inspection.decision)}
74
+ pulse={inspection.decision === "FAIL"}
75
+ />
76
+ <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300">
77
+ Last event: {formatDateTime(lastEventAt || inspection.timestamp)}
78
+ </div>
79
+ </div>
80
+
81
+ <div className="mt-6 flex flex-wrap gap-3">
82
+ <Link to="/live" className="primary-btn">
83
+ Start live detection
84
+ </Link>
85
+ <Link to="/history" className="secondary-btn">
86
+ Review inspection logs
87
+ </Link>
88
+ </div>
89
+
90
+ {streamError ? (
91
+ <div className="mt-6 rounded-3xl border border-amber-300/25 bg-amber-400/10 px-4 py-4 text-sm text-amber-100">
92
+ {streamError}
93
+ </div>
94
+ ) : null}
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>
102
+ <div className="mt-3 flex flex-wrap gap-2">
103
+ {systemBrief.currentState.working.map((item) => (
104
+ <span key={item} className="chip chip-success">
105
+ {item}
106
+ </span>
107
+ ))}
108
+ </div>
109
+ </div>
110
+
111
+ <div>
112
+ <p className="text-sm font-medium uppercase tracking-[0.24em] text-amber-200/80">In Progress</p>
113
+ <div className="mt-3 flex flex-wrap gap-2">
114
+ {systemBrief.currentState.inProgress.map((item) => (
115
+ <span key={item} className="chip chip-warning">
116
+ {item}
117
+ </span>
118
+ ))}
119
+ </div>
120
+ </div>
121
+
122
+ <p className="text-sm leading-7 text-slate-300">{systemBrief.finalSummary}</p>
123
+ </div>
124
+ </div>
125
+ </div>
126
+ </section>
127
+
128
+ <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
129
+ <MetricCard
130
+ label="Decision"
131
+ value={inspection.decision}
132
+ detail={`Source: ${titleCase(inspection.source)}`}
133
+ tone={getDecisionTone(inspection.decision) === "danger" ? "danger" : inspection.decision === "REVIEW" ? "warning" : "success"}
134
+ />
135
+ <MetricCard label="Total Defects" value={inspection.total_defects} detail="Latest inspection footprint." tone="accent" />
136
+ <MetricCard label="Minor" value={inspection.minor} detail="Visible but low-risk anomalies." tone="success" />
137
+ <MetricCard label="Moderate" value={inspection.moderate} detail="Escalate for operator review." tone="warning" />
138
+ <MetricCard label="Critical" value={inspection.critical} detail="Immediate intervention required." tone="danger" />
139
+ </section>
140
+
141
+ {isCritical ? (
142
+ <section className="surface-card border-rose-300/30 bg-rose-500/10 p-6">
143
+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
144
+ <div>
145
+ <p className="eyebrow text-rose-100/80">Critical Alert</p>
146
+ <h3 className="section-title mt-2 text-rose-50">Critical defect detected in the live inspection stream.</h3>
147
+ <p className="mt-3 max-w-3xl text-sm leading-7 text-rose-100/90">
148
+ The latest inspection result is a FAIL state. Hold release, isolate the material, and trigger immediate engineering review.
149
+ </p>
150
+ </div>
151
+
152
+ <Link to="/live" className="primary-btn border-rose-200/30 bg-rose-200/10 text-rose-50 hover:bg-rose-200/[0.15]">
153
+ Open live console
154
+ </Link>
155
+ </div>
156
+ </section>
157
+ ) : null}
158
+
159
+ <section className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
160
+ <div className="surface-card p-6">
161
+ <div className="flex flex-wrap items-center justify-between gap-3">
162
+ <div>
163
+ <p className="eyebrow">Live Decision Center</p>
164
+ <h3 className="section-title mt-2">Inspection recommendation and defect trace</h3>
165
+ </div>
166
+ <StatusBadge label={inspection.decision} tone={getDecisionTone(inspection.decision)} pulse={inspection.decision === "FAIL"} />
167
+ </div>
168
+
169
+ <p className="mt-4 text-base leading-8 text-slate-300">{inspection.recommendation}</p>
170
+
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
+
186
+ <div className="glow-divider mt-6" />
187
+
188
+ <div className="mt-6 grid gap-4 lg:grid-cols-2">
189
+ <div className="space-y-3">
190
+ <p className="eyebrow">Detected Defects</p>
191
+ {inspection.defects?.length ? (
192
+ inspection.defects.slice(0, 6).map((defect, index) => (
193
+ <div key={`${defect.type}-${index}`} className="rounded-3xl border border-white/10 bg-white/5 p-4">
194
+ <div className="flex items-center justify-between gap-3">
195
+ <p className="text-base font-medium text-slate-50">{titleCase(defect.type)}</p>
196
+ <StatusBadge label={defect.severity} tone={getDecisionTone(defect.decision)} />
197
+ </div>
198
+ <p className="mt-3 text-sm leading-7 text-slate-300">
199
+ Confidence {defect.confidence ?? "--"} | Area ratio {defect.area_ratio} | Length {defect.length}
200
+ </p>
201
+ </div>
202
+ ))
203
+ ) : (
204
+ <div className="rounded-3xl border border-dashed border-white/10 bg-white/5 p-5 text-sm text-slate-400">
205
+ No defects are in the latest payload yet. Start the live monitor or upload an image to populate this panel.
206
+ </div>
207
+ )}
208
+ </div>
209
+
210
+ <div className="space-y-3">
211
+ <p className="eyebrow">Program Architecture</p>
212
+ <ProcessFlow steps={systemBrief.architectureFlow} compact />
213
+ </div>
214
+ </div>
215
+ </div>
216
+
217
+ <div className="space-y-6">
218
+ <div className="surface-card p-6">
219
+ <p className="eyebrow">Backend</p>
220
+ <h3 className="section-title mt-2">FastAPI, storage, and live event responsibilities</h3>
221
+ <div className="mt-5 space-y-3 text-sm leading-7 text-slate-300">
222
+ {systemBrief.backend.responsibilities.map((item) => (
223
+ <div key={item} className="rounded-3xl border border-white/10 bg-white/5 px-4 py-3">
224
+ {item}
225
+ </div>
226
+ ))}
227
+ </div>
228
+ <div className="mt-5 flex flex-wrap gap-2">
229
+ {systemBrief.backend.files.map((item) => (
230
+ <span key={item.title} className="chip">
231
+ {item.title}
232
+ </span>
233
+ ))}
234
+ </div>
235
+ </div>
236
+
237
+ <div className="surface-card p-6">
238
+ <p className="eyebrow">System Performance</p>
239
+ <h3 className="section-title mt-2">Recent report volume</h3>
240
+ <div className="mt-5 grid gap-4 sm:grid-cols-3">
241
+ <MetricCard
242
+ label="Reports"
243
+ value={analytics?.report_count ?? "--"}
244
+ detail="Latest records in the operational window."
245
+ tone="steel"
246
+ />
247
+ <MetricCard
248
+ label="Avg Defects"
249
+ value={analytics?.average_total_defects ?? "--"}
250
+ detail="Average defects per inspection report."
251
+ tone="accent"
252
+ />
253
+ <MetricCard
254
+ label="Recent Decisions"
255
+ value={analytics?.recent_decisions?.[0] || "--"}
256
+ detail={truncateText((analytics?.recent_decisions || []).join(" -> "), 42)}
257
+ tone="warning"
258
+ />
259
+ </div>
260
+ </div>
261
+ </div>
262
+ </section>
263
+ </div>
264
+ )
265
+ }
dashboard/src/pages/History.jsx ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react"
2
+ import MetricCard from "../components/MetricCard"
3
+ import StatusBadge from "../components/StatusBadge"
4
+ import { fetchReports } from "../lib/api"
5
+ import { formatDateTime, titleCase, truncateText } from "../lib/formatters"
6
+ import { getDecisionTone } from "../lib/status"
7
+
8
+ export default function History() {
9
+ const [reports, setReports] = useState([])
10
+ const [selectedId, setSelectedId] = useState(null)
11
+ const [decisionFilter, setDecisionFilter] = useState("ALL")
12
+ const [searchText, setSearchText] = useState("")
13
+ const [loading, setLoading] = useState(true)
14
+ const [error, setError] = useState("")
15
+
16
+ useEffect(() => {
17
+ let active = true
18
+
19
+ fetchReports(80)
20
+ .then((data) => {
21
+ if (!active) return
22
+ setReports(data)
23
+ setSelectedId(data[0]?.id || null)
24
+ })
25
+ .catch((requestError) => {
26
+ if (active) {
27
+ setError(requestError.message)
28
+ }
29
+ })
30
+ .finally(() => {
31
+ if (active) {
32
+ setLoading(false)
33
+ }
34
+ })
35
+
36
+ return () => {
37
+ active = false
38
+ }
39
+ }, [])
40
+
41
+ const filteredReports = reports.filter((report) => {
42
+ const matchesDecision = decisionFilter === "ALL" || report.decision === decisionFilter
43
+ const searchTarget = `${report.source} ${report.recommendation} ${report.summary_text || ""} ${report.agent_provider || ""} ${(report.defects || [])
44
+ .map((defect) => defect.type)
45
+ .join(" ")}`
46
+ .toLowerCase()
47
+
48
+ const matchesSearch = !searchText || searchTarget.includes(searchText.toLowerCase())
49
+ return matchesDecision && matchesSearch
50
+ })
51
+
52
+ const selectedReport =
53
+ filteredReports.find((report) => report.id === selectedId) ||
54
+ filteredReports[0] ||
55
+ reports[0] ||
56
+ null
57
+
58
+ const failCount = reports.filter((report) => report.decision === "FAIL").length
59
+ const reviewCount = reports.filter((report) => report.decision === "REVIEW").length
60
+ const averageDefects = reports.length
61
+ ? (reports.reduce((sum, report) => sum + report.total_defects, 0) / reports.length).toFixed(1)
62
+ : "0.0"
63
+
64
+ return (
65
+ <div className="space-y-6 pb-10">
66
+ <section className="surface-card p-6 md:p-8">
67
+ <div className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
68
+ <div>
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
+
76
+ <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
77
+ <MetricCard label="Reports" value={reports.length} detail="Loaded in this session." tone="steel" />
78
+ <MetricCard label="FAIL" value={failCount} detail="Critical rejections." tone="danger" />
79
+ <MetricCard label="REVIEW" value={reviewCount} detail="Operator hold states." tone="warning" />
80
+ <MetricCard label="Avg Defects" value={averageDefects} detail="Per saved report." tone="accent" />
81
+ </div>
82
+ </div>
83
+ </section>
84
+
85
+ <section className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
86
+ <div className="surface-card overflow-hidden">
87
+ <div className="border-b border-white/10 px-6 py-5">
88
+ <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
89
+ <div>
90
+ <p className="eyebrow">Saved Reports</p>
91
+ <h3 className="section-title mt-2">Inspection history table</h3>
92
+ </div>
93
+
94
+ <div className="flex flex-col gap-3 sm:flex-row">
95
+ <select
96
+ value={decisionFilter}
97
+ onChange={(event) => setDecisionFilter(event.target.value)}
98
+ className="rounded-full border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-100 outline-none transition focus:border-cyan-300/40"
99
+ >
100
+ <option value="ALL">All decisions</option>
101
+ <option value="PASS">PASS</option>
102
+ <option value="REVIEW">REVIEW</option>
103
+ <option value="FAIL">FAIL</option>
104
+ </select>
105
+
106
+ <input
107
+ value={searchText}
108
+ onChange={(event) => setSearchText(event.target.value)}
109
+ placeholder="Search defect types or notes"
110
+ className="rounded-full border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-100 outline-none transition placeholder:text-slate-500 focus:border-cyan-300/40"
111
+ />
112
+ </div>
113
+ </div>
114
+ </div>
115
+
116
+ {loading ? (
117
+ <div className="p-6 text-sm text-slate-400">Loading inspection history...</div>
118
+ ) : error ? (
119
+ <div className="p-6 text-sm text-rose-100">{error}</div>
120
+ ) : filteredReports.length === 0 ? (
121
+ <div className="p-6 text-sm text-slate-400">No inspection reports match the current filters.</div>
122
+ ) : (
123
+ <div className="overflow-x-auto">
124
+ <table className="min-w-full text-left text-sm text-slate-300">
125
+ <thead className="bg-white/5 text-xs uppercase tracking-[0.24em] text-slate-400">
126
+ <tr>
127
+ <th className="px-6 py-4">Timestamp</th>
128
+ <th className="px-4 py-4">Source</th>
129
+ <th className="px-4 py-4">Total</th>
130
+ <th className="px-4 py-4">Minor</th>
131
+ <th className="px-4 py-4">Moderate</th>
132
+ <th className="px-4 py-4">Critical</th>
133
+ <th className="px-6 py-4">Decision</th>
134
+ </tr>
135
+ </thead>
136
+ <tbody>
137
+ {filteredReports.map((report) => (
138
+ <tr
139
+ key={report.id}
140
+ className={`cursor-pointer border-t border-white/[0.06] transition hover:bg-white/5 ${
141
+ selectedReport?.id === report.id ? "bg-white/[0.06]" : ""
142
+ }`}
143
+ onClick={() => setSelectedId(report.id)}
144
+ >
145
+ <td className="px-6 py-4">{formatDateTime(report.timestamp)}</td>
146
+ <td className="px-4 py-4">{titleCase(report.source)}</td>
147
+ <td className="px-4 py-4">{report.total_defects}</td>
148
+ <td className="px-4 py-4">{report.minor}</td>
149
+ <td className="px-4 py-4">{report.moderate}</td>
150
+ <td className="px-4 py-4">{report.critical}</td>
151
+ <td className="px-6 py-4">
152
+ <StatusBadge label={report.decision} tone={getDecisionTone(report.decision)} />
153
+ </td>
154
+ </tr>
155
+ ))}
156
+ </tbody>
157
+ </table>
158
+ </div>
159
+ )}
160
+ </div>
161
+
162
+ <div className="surface-card p-6">
163
+ <p className="eyebrow">Selected Report</p>
164
+ <h3 className="section-title mt-2">Recommendation and defect breakdown</h3>
165
+
166
+ {selectedReport ? (
167
+ <div className="mt-5 space-y-5">
168
+ <div className="flex flex-wrap items-center gap-3">
169
+ <StatusBadge label={selectedReport.decision} tone={getDecisionTone(selectedReport.decision)} pulse={selectedReport.decision === "FAIL"} />
170
+ <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300">
171
+ {formatDateTime(selectedReport.timestamp)}
172
+ </div>
173
+ </div>
174
+
175
+ <p className="text-sm leading-7 text-slate-300">
176
+ {selectedReport.recommendation || "No recommendation text was stored for this report."}
177
+ </p>
178
+
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
+
194
+ <div className="grid gap-4 sm:grid-cols-2">
195
+ <MetricCard label="Source" value={titleCase(selectedReport.source)} detail="Capture method for this inspection." tone="steel" />
196
+ <MetricCard label="Defects" value={selectedReport.total_defects} detail="Total anomalies in this report." tone="accent" />
197
+ </div>
198
+
199
+ <div className="space-y-3">
200
+ {(selectedReport.defects || []).length ? (
201
+ selectedReport.defects.map((defect, index) => (
202
+ <div key={`${defect.type}-${index}`} className="rounded-3xl border border-white/10 bg-white/5 px-4 py-4">
203
+ <div className="flex flex-wrap items-center justify-between gap-3">
204
+ <p className="text-base font-medium text-slate-50">{titleCase(defect.type)}</p>
205
+ <StatusBadge label={defect.severity} tone={getDecisionTone(defect.decision)} />
206
+ </div>
207
+ <p className="mt-3 text-sm leading-7 text-slate-300">
208
+ {truncateText(
209
+ `Confidence ${defect.confidence ?? "--"} | Area ratio ${defect.area_ratio} | Length ${defect.length}`,
210
+ 96,
211
+ )}
212
+ </p>
213
+ </div>
214
+ ))
215
+ ) : (
216
+ <div className="rounded-3xl border border-dashed border-white/15 bg-white/5 p-5 text-sm text-slate-400">
217
+ This report did not include detailed defect metadata.
218
+ </div>
219
+ )}
220
+ </div>
221
+ </div>
222
+ ) : (
223
+ <div className="mt-5 rounded-3xl border border-dashed border-white/15 bg-white/5 p-5 text-sm text-slate-400">
224
+ Select a report to inspect its recommendation and defect details.
225
+ </div>
226
+ )}
227
+ </div>
228
+ </section>
229
+ </div>
230
+ )
231
+ }
dashboard/src/pages/Live.jsx ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useEffect, useRef, useState } from "react"
2
+ import MetricCard from "../components/MetricCard"
3
+ import ProcessFlow from "../components/ProcessFlow"
4
+ import StatusBadge from "../components/StatusBadge"
5
+ import { systemBrief } from "../content/systemBrief"
6
+ import { inspectFrame, inspectImage } from "../lib/api"
7
+ import { formatDateTime, titleCase } from "../lib/formatters"
8
+ import { getDecisionTone } from "../lib/status"
9
+
10
+ function fileToDataUrl(file) {
11
+ return new Promise((resolve, reject) => {
12
+ const reader = new FileReader()
13
+ reader.onload = () => resolve(reader.result)
14
+ reader.onerror = () => reject(new Error("Unable to read the selected image"))
15
+ reader.readAsDataURL(file)
16
+ })
17
+ }
18
+
19
+ function playAlertTone() {
20
+ const AudioContextRef = window.AudioContext || window.webkitAudioContext
21
+ if (!AudioContextRef) return
22
+
23
+ const audioContext = new AudioContextRef()
24
+ const oscillator = audioContext.createOscillator()
25
+ const gainNode = audioContext.createGain()
26
+
27
+ oscillator.type = "triangle"
28
+ oscillator.frequency.setValueAtTime(880, audioContext.currentTime)
29
+ gainNode.gain.setValueAtTime(0.0001, audioContext.currentTime)
30
+ gainNode.gain.exponentialRampToValueAtTime(0.08, audioContext.currentTime + 0.02)
31
+ gainNode.gain.exponentialRampToValueAtTime(0.0001, audioContext.currentTime + 0.28)
32
+
33
+ oscillator.connect(gainNode)
34
+ gainNode.connect(audioContext.destination)
35
+ oscillator.start()
36
+ oscillator.stop(audioContext.currentTime + 0.3)
37
+ }
38
+
39
+ export default function Live() {
40
+ const [mode, setMode] = useState("upload")
41
+ const [selectedFile, setSelectedFile] = useState(null)
42
+ const [imagePreview, setImagePreview] = useState("")
43
+ const [inspectionResult, setInspectionResult] = useState(null)
44
+ const [isInspecting, setIsInspecting] = useState(false)
45
+ const [error, setError] = useState("")
46
+ const [cameraReady, setCameraReady] = useState(false)
47
+ const [streaming, setStreaming] = useState(false)
48
+ const [autoInspect, setAutoInspect] = useState(true)
49
+ const [persistLive, setPersistLive] = useState(false)
50
+ const [deepAnalysisEnabled, setDeepAnalysisEnabled] = useState(false)
51
+ const [alertsEnabled, setAlertsEnabled] = useState(true)
52
+ const [cameraStatus, setCameraStatus] = useState("Camera offline")
53
+ const [lastInspectedAt, setLastInspectedAt] = useState("")
54
+
55
+ const videoRef = useRef(null)
56
+ const canvasRef = useRef(null)
57
+ const streamRef = useRef(null)
58
+ const requestInFlight = useRef(false)
59
+ const lastAlertDecision = useRef("")
60
+
61
+ async function handleImageSelection(event) {
62
+ const file = event.target.files?.[0]
63
+
64
+ if (!file) return
65
+
66
+ setError("")
67
+ setSelectedFile(file)
68
+
69
+ try {
70
+ const previewUrl = await fileToDataUrl(file)
71
+ setImagePreview(previewUrl)
72
+ } catch (selectionError) {
73
+ setError(selectionError.message)
74
+ }
75
+ }
76
+
77
+ async function handleImageInspection() {
78
+ if (!selectedFile) {
79
+ setError("Select an image to run inspection.")
80
+ return
81
+ }
82
+
83
+ setIsInspecting(true)
84
+ setError("")
85
+
86
+ try {
87
+ const imageBase64 = await fileToDataUrl(selectedFile)
88
+ const result = await inspectImage({
89
+ image_base64: imageBase64,
90
+ filename: selectedFile.name,
91
+ source: "upload",
92
+ persist: true,
93
+ llm_mode: deepAnalysisEnabled ? "always" : "off",
94
+ })
95
+
96
+ setInspectionResult(result)
97
+ setLastInspectedAt(result.timestamp)
98
+ if (alertsEnabled && result.decision === "FAIL" && lastAlertDecision.current !== "FAIL") {
99
+ playAlertTone()
100
+ }
101
+ lastAlertDecision.current = result.decision
102
+ } catch (inspectionError) {
103
+ setError(inspectionError.message)
104
+ } finally {
105
+ setIsInspecting(false)
106
+ }
107
+ }
108
+
109
+ async function startCamera() {
110
+ try {
111
+ const stream = await navigator.mediaDevices.getUserMedia({
112
+ video: {
113
+ facingMode: "environment",
114
+ width: { ideal: 1280 },
115
+ height: { ideal: 720 },
116
+ },
117
+ audio: false,
118
+ })
119
+
120
+ streamRef.current = stream
121
+
122
+ if (videoRef.current) {
123
+ videoRef.current.srcObject = stream
124
+ await videoRef.current.play()
125
+ }
126
+
127
+ setCameraReady(true)
128
+ setStreaming(true)
129
+ setCameraStatus("Camera active and scanning live frames")
130
+ setError("")
131
+ } catch {
132
+ setError("Camera access was blocked or unavailable.")
133
+ }
134
+ }
135
+
136
+ function stopCamera() {
137
+ if (streamRef.current) {
138
+ streamRef.current.getTracks().forEach((track) => track.stop())
139
+ streamRef.current = null
140
+ }
141
+
142
+ if (videoRef.current) {
143
+ videoRef.current.srcObject = null
144
+ }
145
+
146
+ requestInFlight.current = false
147
+ setStreaming(false)
148
+ setCameraReady(false)
149
+ setCameraStatus("Camera offline")
150
+ }
151
+
152
+ const captureAndInspectFrame = useCallback(async ({ persist = false } = {}) => {
153
+ if (!videoRef.current || !canvasRef.current || requestInFlight.current) return
154
+ if (videoRef.current.readyState < 2) return
155
+
156
+ const canvas = canvasRef.current
157
+ const videoWidth = videoRef.current.videoWidth || 1280
158
+ const videoHeight = videoRef.current.videoHeight || 720
159
+ const targetWidth = Math.min(768, videoWidth)
160
+ const targetHeight = Math.round((videoHeight / videoWidth) * targetWidth)
161
+
162
+ canvas.width = targetWidth
163
+ canvas.height = targetHeight
164
+
165
+ const context = canvas.getContext("2d")
166
+ if (!context) {
167
+ setError("Unable to capture the current camera frame.")
168
+ return
169
+ }
170
+
171
+ context.drawImage(videoRef.current, 0, 0, targetWidth, targetHeight)
172
+
173
+ requestInFlight.current = true
174
+ setIsInspecting(true)
175
+ setCameraStatus("Inspecting live frame")
176
+ setError("")
177
+
178
+ try {
179
+ const result = await inspectFrame({
180
+ image_base64: canvas.toDataURL("image/jpeg", 0.82),
181
+ source: "camera",
182
+ persist,
183
+ llm_mode: deepAnalysisEnabled ? "always" : "off",
184
+ })
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()
196
+ }
197
+ lastAlertDecision.current = result.decision
198
+ } catch (inspectionError) {
199
+ setError(inspectionError.message)
200
+ setCameraStatus("Camera active, waiting for a successful inspection response")
201
+ } finally {
202
+ requestInFlight.current = false
203
+ setIsInspecting(false)
204
+ }
205
+ }, [alertsEnabled, deepAnalysisEnabled])
206
+
207
+ useEffect(() => {
208
+ return () => {
209
+ stopCamera()
210
+ }
211
+ }, [])
212
+
213
+ useEffect(() => {
214
+ if (mode !== "camera" || !streaming || !cameraReady || !autoInspect) return undefined
215
+
216
+ const interval = window.setInterval(() => {
217
+ captureAndInspectFrame({ persist: persistLive })
218
+ }, 2000)
219
+
220
+ return () => {
221
+ window.clearInterval(interval)
222
+ }
223
+ }, [autoInspect, cameraReady, captureAndInspectFrame, mode, persistLive, streaming])
224
+
225
+ useEffect(() => {
226
+ if (!cameraReady || mode !== "camera") return
227
+
228
+ const timer = window.setTimeout(() => {
229
+ captureAndInspectFrame({ persist: persistLive })
230
+ }, 500)
231
+
232
+ return () => {
233
+ window.clearTimeout(timer)
234
+ }
235
+ }, [cameraReady, captureAndInspectFrame, mode, persistLive])
236
+
237
+ useEffect(() => {
238
+ if (mode === "camera") {
239
+ setSelectedFile(null)
240
+ setImagePreview("")
241
+ return
242
+ }
243
+
244
+ setStreaming(false)
245
+ setCameraStatus("Camera offline")
246
+ }, [mode])
247
+
248
+ return (
249
+ <div className="space-y-6 pb-10">
250
+ <section className="surface-card p-6 md:p-8">
251
+ <div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
252
+ <div>
253
+ <p className="eyebrow">Live Monitoring Page</p>
254
+ <h2 className="hero-title mt-3">Upload images or use the browser camera for organized, real-time manufacturing inspection.</h2>
255
+ <p className="body-copy mt-5 max-w-3xl">
256
+ The live workspace below lets operators analyze still images, stream camera frames for continuous
257
+ detection, and capture both AI inspection decisions and LLM-assisted manufacturing recommendations.
258
+ </p>
259
+
260
+ <div className="mt-6 flex flex-wrap gap-3">
261
+ <button
262
+ type="button"
263
+ className={mode === "upload" ? "primary-btn" : "secondary-btn"}
264
+ onClick={() => setMode("upload")}
265
+ >
266
+ Upload images
267
+ </button>
268
+ <button
269
+ type="button"
270
+ className={mode === "camera" ? "primary-btn" : "secondary-btn"}
271
+ onClick={() => setMode("camera")}
272
+ >
273
+ Live camera feed
274
+ </button>
275
+ </div>
276
+ </div>
277
+
278
+ <div className="surface-card p-6">
279
+ <p className="eyebrow">Inspection Workflow</p>
280
+ <div className="mt-4">
281
+ <ProcessFlow steps={systemBrief.aiPipeline.flow} compact />
282
+ </div>
283
+ </div>
284
+ </div>
285
+ </section>
286
+
287
+ <section className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
288
+ <div className="surface-card p-6">
289
+ <div className="flex flex-wrap items-center justify-between gap-3">
290
+ <div>
291
+ <p className="eyebrow">Detection Workspace</p>
292
+ <h3 className="section-title mt-2">
293
+ {mode === "upload" ? "Image-based inspection" : "Camera-based live detection"}
294
+ </h3>
295
+ </div>
296
+ {inspectionResult ? (
297
+ <StatusBadge label={inspectionResult.decision} tone={getDecisionTone(inspectionResult.decision)} pulse={inspectionResult.decision === "FAIL"} />
298
+ ) : null}
299
+ </div>
300
+
301
+ {mode === "upload" ? (
302
+ <div className="mt-6 space-y-5">
303
+ <label className="flex min-h-[240px] cursor-pointer flex-col items-center justify-center rounded-[28px] border border-dashed border-white/15 bg-white/5 px-6 py-8 text-center transition hover:border-cyan-300/40 hover:bg-cyan-400/[0.08]">
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
+
311
+ {imagePreview ? (
312
+ <div className="overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/60">
313
+ <img src={imagePreview} alt="Selected inspection" className="max-h-[420px] w-full object-cover" />
314
+ </div>
315
+ ) : null}
316
+
317
+ <div className="flex flex-wrap gap-3">
318
+ <button type="button" className="primary-btn" onClick={handleImageInspection} disabled={isInspecting}>
319
+ {isInspecting ? "Inspecting image..." : "Run image inspection"}
320
+ </button>
321
+ <div className="rounded-full border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-300">
322
+ Uploaded inspections are saved as reports automatically.
323
+ </div>
324
+ </div>
325
+
326
+ <label className="flex items-center justify-between rounded-3xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-300">
327
+ <span>Enable GenAI deep analysis (slower response)</span>
328
+ <input
329
+ type="checkbox"
330
+ checked={deepAnalysisEnabled}
331
+ onChange={(event) => setDeepAnalysisEnabled(event.target.checked)}
332
+ className="h-5 w-5 accent-cyan-300"
333
+ />
334
+ </label>
335
+
336
+ <div className="rounded-3xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-7 text-amber-50">
337
+ Fast mode is optimized for real-time detection. Turn on deep analysis only when you want the slower Ollama-based recommendation layer.
338
+ </div>
339
+ </div>
340
+ ) : (
341
+ <div className="mt-6 space-y-5">
342
+ <div className="grid gap-4 lg:grid-cols-2">
343
+ <div className="overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/60">
344
+ <video ref={videoRef} className="aspect-video w-full object-cover" muted playsInline />
345
+ </div>
346
+
347
+ <div className="rounded-[28px] border border-white/10 bg-white/5 p-5">
348
+ <p className="eyebrow">Camera Controls</p>
349
+ <div className="mt-4 flex flex-wrap gap-3">
350
+ {!cameraReady ? (
351
+ <button type="button" className="primary-btn" onClick={startCamera}>
352
+ Enable camera
353
+ </button>
354
+ ) : (
355
+ <>
356
+ <button
357
+ type="button"
358
+ className={streaming ? "secondary-btn" : "primary-btn"}
359
+ onClick={() => setStreaming((current) => !current)}
360
+ >
361
+ {streaming ? "Pause live inspection" : "Start live inspection"}
362
+ </button>
363
+ <button
364
+ type="button"
365
+ className="secondary-btn"
366
+ onClick={() => captureAndInspectFrame({ persist: persistLive })}
367
+ >
368
+ Inspect current frame
369
+ </button>
370
+ <button type="button" className="secondary-btn" onClick={stopCamera}>
371
+ Stop camera
372
+ </button>
373
+ </>
374
+ )}
375
+ </div>
376
+
377
+ <div className="mt-5 space-y-3">
378
+ <label className="flex items-center justify-between rounded-3xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-300">
379
+ <span>Auto inspect every few seconds</span>
380
+ <input
381
+ type="checkbox"
382
+ checked={autoInspect}
383
+ onChange={(event) => setAutoInspect(event.target.checked)}
384
+ className="h-5 w-5 accent-cyan-300"
385
+ />
386
+ </label>
387
+ <label className="flex items-center justify-between rounded-3xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-300">
388
+ <span>Log live detections to reports and database</span>
389
+ <input
390
+ type="checkbox"
391
+ checked={persistLive}
392
+ onChange={(event) => setPersistLive(event.target.checked)}
393
+ className="h-5 w-5 accent-cyan-300"
394
+ />
395
+ </label>
396
+ <label className="flex items-center justify-between rounded-3xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-300">
397
+ <span>Enable GenAI deep analysis (slower response)</span>
398
+ <input
399
+ type="checkbox"
400
+ checked={deepAnalysisEnabled}
401
+ onChange={(event) => setDeepAnalysisEnabled(event.target.checked)}
402
+ className="h-5 w-5 accent-cyan-300"
403
+ />
404
+ </label>
405
+ <label className="flex items-center justify-between rounded-3xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-slate-300">
406
+ <span>Play alert tone on FAIL states</span>
407
+ <input
408
+ type="checkbox"
409
+ checked={alertsEnabled}
410
+ onChange={(event) => setAlertsEnabled(event.target.checked)}
411
+ className="h-5 w-5 accent-cyan-300"
412
+ />
413
+ </label>
414
+ </div>
415
+
416
+ <div className="mt-5 rounded-3xl border border-cyan-300/20 bg-cyan-400/10 px-4 py-4 text-sm text-cyan-50">
417
+ <p className="font-medium uppercase tracking-[0.2em] text-cyan-100/80">Live Status</p>
418
+ <p className="mt-2 leading-7">{cameraStatus}</p>
419
+ <p className="mt-2 text-cyan-100/80">
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>
426
+ </div>
427
+ </div>
428
+
429
+ <canvas ref={canvasRef} className="hidden" />
430
+ </div>
431
+ )}
432
+
433
+ {error ? (
434
+ <div className="mt-5 rounded-3xl border border-rose-300/30 bg-rose-400/10 px-4 py-4 text-sm text-rose-100">
435
+ {error}
436
+ </div>
437
+ ) : null}
438
+ </div>
439
+
440
+ <div className="space-y-6">
441
+ <div className="surface-card p-6">
442
+ <p className="eyebrow">Inspection Result</p>
443
+ <h3 className="section-title mt-2">Annotated output and operator guidance</h3>
444
+
445
+ {inspectionResult?.annotated_image ? (
446
+ <div className="mt-5 overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/60">
447
+ <img
448
+ src={inspectionResult.annotated_image}
449
+ alt="Annotated inspection result"
450
+ className="max-h-[420px] w-full object-cover"
451
+ />
452
+ </div>
453
+ ) : (
454
+ <div className="mt-5 rounded-[28px] border border-dashed border-white/15 bg-white/5 p-6 text-sm leading-7 text-slate-400">
455
+ Run an inspection to see the AI overlay, severity callouts, and decision banner.
456
+ </div>
457
+ )}
458
+
459
+ {inspectionResult ? (
460
+ <div className="mt-5 space-y-4">
461
+ <div className="flex flex-wrap items-center gap-3">
462
+ <StatusBadge label={inspectionResult.decision} tone={getDecisionTone(inspectionResult.decision)} pulse={inspectionResult.decision === "FAIL"} />
463
+ <div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300">
464
+ {formatDateTime(inspectionResult.timestamp)}
465
+ </div>
466
+ </div>
467
+
468
+ <p className="text-sm leading-7 text-slate-300">{inspectionResult.recommendation}</p>
469
+
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}` : ""}
478
+ </div>
479
+ </div>
480
+ <p className="mt-4 text-sm leading-7 text-cyan-50/95">
481
+ {inspectionResult.summary_text || "AI copilot summary is not available for this inspection yet."}
482
+ </p>
483
+ </div>
484
+
485
+ <div className="grid gap-4 sm:grid-cols-3">
486
+ <MetricCard label="Minor" value={inspectionResult.minor} detail="Low severity anomalies" tone="success" />
487
+ <MetricCard label="Moderate" value={inspectionResult.moderate} detail="Review threshold" tone="warning" />
488
+ <MetricCard label="Critical" value={inspectionResult.critical} detail="Immediate action" tone="danger" />
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">
496
+ <p className="text-base font-medium text-slate-50">{titleCase(defect.type)}</p>
497
+ <StatusBadge label={defect.severity} tone={getDecisionTone(defect.decision)} />
498
+ </div>
499
+ <p className="mt-3 text-sm leading-7 text-slate-300">
500
+ Confidence {defect.confidence ?? "--"} | Area ratio {defect.area_ratio} | Length {defect.length}
501
+ </p>
502
+ </div>
503
+ ))
504
+ ) : (
505
+ <div className="rounded-3xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-4 text-sm leading-7 text-emerald-50">
506
+ The latest frame is clear. The system still inspected the image and returned a PASS result with no actionable defects detected.
507
+ </div>
508
+ )}
509
+ </div>
510
+ </div>
511
+ ) : null}
512
+ </div>
513
+
514
+ <div className="surface-card p-6">
515
+ <p className="eyebrow">Real-time System</p>
516
+ <h3 className="section-title mt-2">Streaming flow and operating assumptions</h3>
517
+ <div className="mt-5">
518
+ <ProcessFlow
519
+ steps={systemBrief.realtime.flow.map((step) => ({
520
+ title: step,
521
+ detail: "This stage keeps operators, reports, and dashboards synchronized with the latest inspection state.",
522
+ }))}
523
+ compact
524
+ />
525
+ </div>
526
+ </div>
527
+ </div>
528
+ </section>
529
+ </div>
530
+ )
531
+ }
dashboard/tailwind.config.js ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+ content: [
3
+ "./index.html",
4
+ "./src/**/*.{js,jsx}",
5
+ ],
6
+ theme: {
7
+ extend: {},
8
+ },
9
+ plugins: [],
10
+ }
dashboard/vercel.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "rewrites": [
3
+ {
4
+ "source": "/(.*)",
5
+ "destination": "/index.html"
6
+ }
7
+ ]
8
+ }
dashboard/vite.config.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+
4
+ // https://vite.dev/config/
5
+ export default defineConfig({
6
+ plugins: [react()],
7
+ })
inspection/class_map.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+
3
+
4
+ # Forward mapping: model class ID → defect name
5
+ CLASS_MAP: Dict[int, str] = {
6
+ 0: "crazing",
7
+ 1: "patches",
8
+ 2: "rolled_in_scale",
9
+ 3: "pitted_surface",
10
+ }
11
+
12
+
13
+ # Reverse mapping: defect name → class ID
14
+ REVERSE_CLASS_MAP: Dict[str, int] = {v: k for k, v in CLASS_MAP.items()}
15
+
16
+
17
+ def get_class_name(class_id: int) -> str:
18
+ """
19
+ Safely get class name from class ID.
20
+ """
21
+ return CLASS_MAP.get(class_id, "unknown")
22
+
23
+
24
+ def get_class_id(class_name: str) -> int:
25
+ """
26
+ Safely get class ID from class name.
27
+ """
28
+ return REVERSE_CLASS_MAP.get(class_name, -1)
inspection/geometry.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from typing import Dict, Tuple
4
+
5
+
6
+ def analyze_defect(contour: np.ndarray, image_shape: Tuple[int, int, int]) -> Dict:
7
+ """
8
+ Analyze geometric properties of a defect contour.
9
+
10
+ Args:
11
+ contour: Contour of detected defect
12
+ image_shape: Shape of the image (H, W, C)
13
+
14
+ Returns:
15
+ Dictionary containing geometric features
16
+ """
17
+
18
+ if contour is None or len(contour) == 0:
19
+ return {
20
+ "area_pixels": 0.0,
21
+ "length_pixels": 0.0,
22
+ "width_pixels": 0.0,
23
+ "area_ratio": 0.0,
24
+ "angle": 0.0
25
+ }
26
+
27
+ # Area
28
+ area = float(cv2.contourArea(contour))
29
+
30
+ # Rotated bounding box (better than axis-aligned)
31
+ rect = cv2.minAreaRect(contour)
32
+ (cx, cy), (w, h), angle = rect
33
+
34
+ length = float(max(w, h))
35
+ width = float(min(w, h))
36
+
37
+ # Image area
38
+ height, width_img = image_shape[:2]
39
+ image_area = height * width_img
40
+
41
+ area_ratio = (area / image_area) if image_area > 0 else 0.0
42
+
43
+ return {
44
+ "area_pixels": area,
45
+ "length_pixels": length,
46
+ "width_pixels": width,
47
+ "area_ratio": area_ratio,
48
+ "angle": float(angle)
49
+ }
inspection/inference.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ import cv2
3
+ import numpy as np
4
+
5
+ from core.config import settings
6
+ from core.logger import logger
7
+
8
+
9
+ class DefectInspector:
10
+ """
11
+ Handles model inference and defect extraction.
12
+ """
13
+
14
+ def __init__(self, model_path: str):
15
+ self.model = YOLO(model_path)
16
+ logger.info(f"Model loaded from: {model_path}")
17
+
18
+ def inspect_image(self, image: np.ndarray):
19
+ """
20
+ Run inference and extract defect information.
21
+ """
22
+
23
+ try:
24
+ results = self.model(
25
+ image,
26
+ conf=settings.CONF_THRESHOLD,
27
+ imgsz=settings.IMAGE_SIZE,
28
+ verbose=False
29
+ )
30
+
31
+ result = results[0]
32
+ defects = []
33
+
34
+ if result.masks is None:
35
+ return defects
36
+
37
+ masks = result.masks.data.cpu().numpy()
38
+ classes = result.boxes.cls.cpu().numpy()
39
+ confidences = result.boxes.conf.cpu().numpy()
40
+
41
+ height, width = image.shape[:2]
42
+ image_area = height * width
43
+
44
+ for i, (mask, cls_id) in enumerate(zip(masks, classes)):
45
+
46
+ confidence = float(confidences[i])
47
+
48
+ if confidence < settings.SECONDARY_CONF_THRESHOLD:
49
+ continue
50
+
51
+ # -------------------------
52
+ # MASK PROCESSING
53
+ # -------------------------
54
+ mask = cv2.resize(mask, (width, height))
55
+ mask = (mask > 0.3).astype("uint8") * 255
56
+
57
+ kernel = np.ones((3, 3), np.uint8)
58
+ mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
59
+
60
+ # -------------------------
61
+ # CONTOUR EXTRACTION
62
+ # -------------------------
63
+ contours, _ = cv2.findContours(
64
+ mask,
65
+ cv2.RETR_EXTERNAL,
66
+ cv2.CHAIN_APPROX_SIMPLE
67
+ )
68
+
69
+ if not contours:
70
+ continue
71
+
72
+ # ✅ PICK LARGEST CONTOUR (FIX)
73
+ largest_contour = max(contours, key=cv2.contourArea)
74
+
75
+ # Optional smoothing
76
+ epsilon = 0.01 * cv2.arcLength(largest_contour, True)
77
+ largest_contour = cv2.approxPolyDP(largest_contour, epsilon, True)
78
+
79
+ cnt = largest_contour
80
+
81
+ area = cv2.contourArea(cnt)
82
+
83
+ if area < settings.MIN_DEFECT_AREA:
84
+ continue
85
+
86
+ x, y, w, h = cv2.boundingRect(cnt)
87
+
88
+ length = max(w, h)
89
+ width_def = min(w, h)
90
+
91
+ area_ratio = area / image_area
92
+
93
+ if area_ratio > settings.MAX_AREA_RATIO:
94
+ continue
95
+
96
+ defects.append({
97
+ "class_id": int(cls_id),
98
+ "confidence": confidence,
99
+ "area_pixels": float(area),
100
+ "length_pixels": float(length),
101
+ "width_pixels": float(width_def),
102
+ "area_ratio": float(area_ratio),
103
+ "bbox": (x, y, w, h),
104
+ "contour": cnt
105
+ })
106
+
107
+ return defects
108
+
109
+ except Exception as e:
110
+ logger.error(f"Inference failed: {e}")
111
+ return []
inspection/lifecycle.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional
2
+
3
+
4
+ class DefectLifecycleManager:
5
+ """
6
+ Tracks lifecycle of defects across frames.
7
+
8
+ A defect is:
9
+ - CREATED when first detected
10
+ - UPDATED when seen again
11
+ - FINALIZED when it disappears for a threshold
12
+ """
13
+
14
+ def __init__(self, max_missing_frames: int = 5, match_threshold: int = 50):
15
+ self.active_defects: Dict[int, Dict] = {}
16
+ self.next_id: int = 0
17
+
18
+ self.max_missing_frames = max_missing_frames
19
+ self.match_threshold = match_threshold
20
+
21
+ def _is_match(self, bbox1, bbox2) -> bool:
22
+ """Check if two bounding boxes belong to same defect."""
23
+ x1, y1, _, _ = bbox1
24
+ x2, y2, _, _ = bbox2
25
+
26
+ return (
27
+ abs(x1 - x2) < self.match_threshold and
28
+ abs(y1 - y2) < self.match_threshold
29
+ )
30
+
31
+ def _find_match(self, detection: Dict) -> Optional[int]:
32
+ """Find matching defect ID for a detection."""
33
+ for defect_id, data in self.active_defects.items():
34
+ if self._is_match(detection["bbox"], data["bbox"]):
35
+ return defect_id
36
+ return None
37
+
38
+ def update(self, detections: List[Dict], frame_id: int) -> List[Dict]:
39
+ """
40
+ Update lifecycle with new detections.
41
+
42
+ Args:
43
+ detections: List of processed defects
44
+ frame_id: Current frame number
45
+
46
+ Returns:
47
+ List of finalized defects
48
+ """
49
+
50
+ finalized: List[Dict] = []
51
+
52
+ # Step 1: Mark all as unseen
53
+ for defect in self.active_defects.values():
54
+ defect["seen"] = False
55
+
56
+ # Step 2: Match detections
57
+ for d in detections:
58
+
59
+ matched_id = self._find_match(d)
60
+
61
+ if matched_id is not None:
62
+ data = self.active_defects[matched_id]
63
+
64
+ data["bbox"] = d["bbox"]
65
+ data["last_seen"] = frame_id
66
+ data["frames_seen"] += 1
67
+ data["seen"] = True
68
+
69
+ # Update max severity
70
+ if d["severity_score"] > data["max_severity"]:
71
+ data["max_severity"] = d["severity_score"]
72
+ data["final_defect"] = d
73
+
74
+ else:
75
+ # Create new defect
76
+ self.active_defects[self.next_id] = {
77
+ "bbox": d["bbox"],
78
+ "last_seen": frame_id,
79
+ "frames_seen": 1,
80
+ "max_severity": d.get("severity_score", 0),
81
+ "final_defect": d,
82
+ "seen": True
83
+ }
84
+ self.next_id += 1
85
+
86
+ # Step 3: Finalize disappeared defects
87
+ to_delete = []
88
+
89
+ for defect_id, data in self.active_defects.items():
90
+
91
+ if not data["seen"]:
92
+ if frame_id - data["last_seen"] > self.max_missing_frames:
93
+ finalized.append(data["final_defect"])
94
+ to_delete.append(defect_id)
95
+
96
+ # Step 4: Cleanup
97
+ for defect_id in to_delete:
98
+ del self.active_defects[defect_id]
99
+
100
+ return finalized