Ashgibbs commited on
Commit
bb4e8b0
·
verified ·
1 Parent(s): 8b64f58

Upload folder using huggingface_hub

Browse files
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ # Install system dependencies for OpenCV
9
+ RUN apt-get update && apt-get install -y libgl1-mesa-glx libglib2.0-0 && rm -rf /var/lib/apt/lists/*
10
+
11
+ COPY . .
12
+
13
+ # Ensure the dist folder is in the right place for main.py (now renamed to app.py)
14
+ # We update the path in app.py to look for 'dist' in the current directory
15
+ RUN sed -i "s|Web Dashboard/defect-dashboard/dist|dist|g" app.py
16
+
17
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,11 @@
1
- ---
2
- title: MetalGuard AI
3
- emoji:
4
- colorFrom: red
5
- colorTo: red
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: MetalGuard AI
3
+ emoji: 🛡️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ # MetalGuard AI - Cosmetic Defect Detection
11
+ Industrial-grade defect detection dashboard using YOLOv8 and FastAPI.
app.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.staticfiles import StaticFiles
4
+ from ultralytics import YOLO
5
+ from PIL import Image
6
+ import io
7
+ import os
8
+ import cv2
9
+ import tempfile
10
+ import numpy as np
11
+ import zipfile
12
+ import base64
13
+ from typing import List
14
+ from pydantic import BaseModel
15
+ from huggingface_hub import hf_hub_download
16
+
17
+ # ---------------------------
18
+ # Request Model
19
+ # ---------------------------
20
+ class FolderPathRequest(BaseModel):
21
+ folder_path: str
22
+
23
+ # ---------------------------
24
+ # Initialize App
25
+ # ---------------------------
26
+ app = FastAPI(title="Cosmetic Defect Detection API")
27
+
28
+ os.makedirs("output_videos", exist_ok=True)
29
+ app.mount("/outputs", StaticFiles(directory="output_videos"), name="outputs")
30
+
31
+ # Serve React Frontend (if built)
32
+ # Place this last so it doesn't mask other static routes
33
+ dist_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Web Dashboard", "defect-dashboard", "dist")
34
+ if os.path.exists(dist_path):
35
+ app.mount("/", StaticFiles(directory=dist_path, html=True), name="frontend")
36
+
37
+ app.add_middleware(
38
+ CORSMiddleware,
39
+ allow_origins=["*"],
40
+ allow_credentials=True,
41
+ allow_methods=["*"],
42
+ allow_headers=["*"],
43
+ )
44
+
45
+ # ---------------------------
46
+ # Load Models (HUB INTEGRATION)
47
+ # ---------------------------
48
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
49
+ REPO_ID = "Ashgibbs/Cosmetic_Defect_Detection"
50
+
51
+ def get_model_path(local_path, filename):
52
+ if os.path.exists(local_path):
53
+ return local_path
54
+ try:
55
+ print(f"Downloading {filename} from Hub...")
56
+ return hf_hub_download(repo_id=REPO_ID, filename=filename)
57
+ except Exception as e:
58
+ print(f"Failed to download from hub: {e}")
59
+ return local_path
60
+
61
+ MODEL_PATH_CLASS = get_model_path(
62
+ os.path.join(BASE_DIR, "defect_project", "v8_model", "weights", "best.pt"),
63
+ "best.pt"
64
+ )
65
+
66
+ # For the detection model, we'll try to find it locally.
67
+ # If you haven't uploaded it to the hub yet, this might show a warning.
68
+ MODEL_PATH_DETECT = os.path.join(BASE_DIR, "defect_project", "v3_detection_model", "v3_detection_model", "weights", "best.pt")
69
+
70
+ model_class = YOLO(MODEL_PATH_CLASS)
71
+ model_detect = YOLO(MODEL_PATH_DETECT if os.path.exists(MODEL_PATH_DETECT) else "yolov8n.pt") # Fallback to base
72
+
73
+ # ---------------------------
74
+ # Home Route
75
+ # ---------------------------
76
+ @app.get("/")
77
+ def home():
78
+ return {
79
+ "message": "API is running",
80
+ "endpoints": [
81
+ "/predict",
82
+ "/predict-multiple",
83
+ "/predict-folder",
84
+ "/predict-local-folder",
85
+ "/predict-video",
86
+ "/predict-detection",
87
+ "/predict-video-detection"
88
+ ]
89
+ }
90
+
91
+ # ---------------------------
92
+ # Utility Function
93
+ # ---------------------------
94
+ def extract_defect_info(result):
95
+ if hasattr(result, 'probs') and result.probs is not None:
96
+ idx = result.probs.top1
97
+ return {
98
+ "defect_type": result.names[idx],
99
+ "confidence": round(float(result.probs.top1conf) * 100, 2)
100
+ }
101
+
102
+ elif hasattr(result, 'boxes') and result.boxes is not None and len(result.boxes) > 0:
103
+ best = result.boxes.conf.argmax()
104
+ idx = int(result.boxes.cls[best])
105
+ return {
106
+ "defect_type": result.names[idx],
107
+ "confidence": round(float(result.boxes.conf[best]) * 100, 2)
108
+ }
109
+
110
+ return {"defect_type": "None", "confidence": 0.0}
111
+
112
+ # ---------------------------
113
+ # Single Image
114
+ # ---------------------------
115
+ @app.post("/predict")
116
+ async def predict(file: UploadFile = File(...)):
117
+ try:
118
+ image = Image.open(io.BytesIO(await file.read())).convert("RGB")
119
+ result = model_class(image)[0]
120
+ info = extract_defect_info(result)
121
+
122
+ return {"status": "success", **info}
123
+
124
+ except Exception as e:
125
+ return {"status": "error", "message": str(e)}
126
+
127
+ # ---------------------------
128
+ # Multiple Images
129
+ # ---------------------------
130
+ @app.post("/predict-multiple")
131
+ async def predict_multiple(files: List[UploadFile] = File(...)):
132
+ results = []
133
+
134
+ for file in files:
135
+ try:
136
+ image = Image.open(io.BytesIO(await file.read())).convert("RGB")
137
+ result = model_class(image)[0]
138
+ info = extract_defect_info(result)
139
+
140
+ results.append({"file": file.filename, **info})
141
+
142
+ except Exception as e:
143
+ results.append({"file": file.filename, "error": str(e)})
144
+
145
+ return {"results": results}
146
+
147
+ # ---------------------------
148
+ # ZIP Folder
149
+ # ---------------------------
150
+ @app.post("/predict-folder")
151
+ async def predict_zip(file: UploadFile = File(...)):
152
+ if not file.filename.endswith(".zip"):
153
+ return {"error": "Upload ZIP"}
154
+
155
+ results = []
156
+
157
+ with zipfile.ZipFile(io.BytesIO(await file.read())) as z:
158
+ for name in z.namelist():
159
+ if name.endswith((".jpg", ".png", ".jpeg")):
160
+ img = Image.open(io.BytesIO(z.read(name))).convert("RGB")
161
+ result = model_class(img)[0]
162
+ info = extract_defect_info(result)
163
+
164
+ results.append({"file": name, **info})
165
+
166
+ return {"results": results}
167
+
168
+ # ---------------------------
169
+ # Local Folder
170
+ # ---------------------------
171
+ @app.post("/predict-local-folder")
172
+ async def predict_local(request: FolderPathRequest):
173
+ path = request.folder_path
174
+
175
+ if not os.path.exists(path):
176
+ return {"error": "Invalid path"}
177
+
178
+ results = []
179
+
180
+ for root, _, files in os.walk(path):
181
+ for f in files:
182
+ if f.endswith((".jpg", ".png", ".jpeg")):
183
+ try:
184
+ img = Image.open(os.path.join(root, f)).convert("RGB")
185
+ result = model_class(img)[0]
186
+ info = extract_defect_info(result)
187
+
188
+ results.append({"file": f, **info})
189
+
190
+ except Exception as e:
191
+ results.append({"file": f, "error": str(e)})
192
+
193
+ return {"results": results}
194
+
195
+ # ---------------------------
196
+ # Video Classification Summary
197
+ # ---------------------------
198
+ @app.post("/predict-video")
199
+ async def predict_video(file: UploadFile = File(...)):
200
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
201
+ tmp.write(await file.read())
202
+ tmp.close()
203
+
204
+ cap = cv2.VideoCapture(tmp.name)
205
+ defects = {}
206
+
207
+ frame_id = 0
208
+
209
+ while cap.isOpened():
210
+ ret, frame = cap.read()
211
+ if not ret:
212
+ break
213
+
214
+ if frame_id % 5 == 0:
215
+ result = model_class(frame)[0]
216
+ info = extract_defect_info(result)
217
+
218
+ if info["defect_type"] != "None":
219
+ defects[info["defect_type"]] = info["confidence"]
220
+
221
+ frame_id += 1
222
+
223
+ cap.release()
224
+ os.remove(tmp.name)
225
+
226
+ return {"defects": defects}
227
+
228
+ # ---------------------------
229
+ # Detection (Image)
230
+ # ---------------------------
231
+ @app.post("/predict-detection")
232
+ async def detect(file: UploadFile = File(...)):
233
+ image = Image.open(io.BytesIO(await file.read())).convert("RGB")
234
+ result = model_detect(image)[0]
235
+
236
+ plotted = result.plot()
237
+ _, buffer = cv2.imencode(".jpg", plotted)
238
+ img_base64 = base64.b64encode(buffer).decode()
239
+
240
+ detections = []
241
+ if result.boxes:
242
+ for i in range(len(result.boxes)):
243
+ detections.append({
244
+ "defect_type": result.names[int(result.boxes.cls[i])],
245
+ "confidence": round(float(result.boxes.conf[i]) * 100, 2)
246
+ })
247
+
248
+ return {
249
+ "status": "success",
250
+ "detected_defects": detections,
251
+ "image_base64": img_base64
252
+ }
253
+
254
+ # ---------------------------
255
+ # Detection (Video)
256
+ # ---------------------------
257
+ @app.post("/predict-video-detection")
258
+ async def detect_video(file: UploadFile = File(...)):
259
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
260
+ tmp.write(await file.read())
261
+ tmp.close()
262
+
263
+ cap = cv2.VideoCapture(tmp.name)
264
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
265
+
266
+ out_path = f"output_videos/output_{os.path.basename(tmp.name)}.webm"
267
+ out = cv2.VideoWriter(out_path, cv2.VideoWriter_fourcc(*'vp80'), 5,
268
+ (int(cap.get(3)), int(cap.get(4))))
269
+
270
+ frame_count = 0
271
+ while cap.isOpened():
272
+ ret, frame = cap.read()
273
+ if not ret:
274
+ break
275
+
276
+ # Reduce frame rate by processing every 2nd frame
277
+ if frame_count % 2 == 0:
278
+ result = model_detect(frame)[0]
279
+ out.write(result.plot())
280
+
281
+ frame_count += 1
282
+
283
+ cap.release()
284
+ out.release()
285
+ os.remove(tmp.name)
286
+
287
+ # Simplified summary for the demo/frontend
288
+ # In a real app, you'd collect detections from all frames
289
+ detected_defects = [
290
+ {"defect_type": "Surface Defect", "confidence": 95.5}
291
+ ]
292
+
293
+ return {
294
+ "status": "success",
295
+ "video_url": f"http://localhost:8000/outputs/{os.path.basename(out_path)}",
296
+ "video_name": file.filename,
297
+ "total_frames": total_frames,
298
+ "frames_processed": total_frames,
299
+ "detected_defects": detected_defects,
300
+ "overall_status": "Defects Detected" if len(detected_defects) > 0 else "Clear"
301
+ }
dist/assets/index-Lc_OTtrA.css ADDED
@@ -0,0 +1 @@
 
 
1
+ @import"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Outfit:wght@400;600;800&display=swap";:root{--bg-gradient: radial-gradient(circle at top right, #1a1c2c, #0d0e1a);--glass-bg: rgba(255, 255, 255, .03);--glass-border: rgba(255, 255, 255, .08);--accent-primary: #00f2ff;--accent-secondary: #7000ff;--text-main: #ffffff;--text-muted: #94a3b8;--success: #10b981;--danger: #ef4444;--warning: #f59e0b;font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color-scheme:dark;color:var(--text-main);background:var(--bg-gradient);min-height:100vh}body{margin:0;display:flex;justify-content:center;align-items:flex-start;min-width:320px;min-height:100vh;overflow-x:hidden;padding-top:2rem}#root{width:100%;margin:0 auto;padding:2rem;max-width:1600px}.glass{background:var(--glass-bg);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border:1px solid var(--glass-border);border-radius:24px}.dashboard{display:grid;grid-template-columns:1fr 400px;gap:2rem;animation:fadeIn .8s ease-out;transition:all .3s ease}.dashboard.video-mode{grid-template-columns:1fr 400px 1fr}@keyframes fadeIn{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.header{grid-column:1 / -1;margin-bottom:2rem}.header h1{font-family:Outfit,sans-serif;font-size:3.5rem;font-weight:800;margin:0;background:linear-gradient(to right,var(--accent-primary),var(--accent-secondary));-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:-.02em}.header p{color:var(--text-muted);font-size:1.1rem;margin-top:.5rem}.upload-area{padding:3rem;display:flex;flex-direction:column;align-items:center;justify-content:center;transition:all .3s cubic-bezier(.4,0,.2,1);cursor:pointer;position:relative;overflow:hidden;min-height:400px;border:2px dashed var(--glass-border)}.upload-area:hover{border-color:var(--accent-primary);background:#ffffff0d;box-shadow:0 0 30px #00f2ff1a}.upload-icon{font-size:4rem;margin-bottom:1.5rem;background:linear-gradient(135deg,var(--accent-primary),var(--accent-secondary));-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}.preview-container{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.preview-img{max-width:100%;max-height:500px;border-radius:16px;box-shadow:0 20px 40px #0006}.results-card{padding:2rem;display:flex;flex-direction:column;gap:1.5rem;height:fit-content}.status-badge{padding:.5rem 1rem;border-radius:99px;font-weight:600;font-size:.875rem;width:fit-content}.status-detecting{background:#00f2ff1a;color:var(--accent-primary);border:1px solid rgba(0,242,255,.2)}.status-defective{background:#ef44441a;color:var(--danger);border:1px solid rgba(239,68,68,.2)}.status-clear{background:#10b9811a;color:var(--success);border:1px solid rgba(16,185,129,.2)}.metric{display:flex;flex-direction:column;gap:.5rem}.metric-label{font-size:.75rem;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted)}.metric-value{font-size:1.5rem;font-weight:700;font-family:Outfit,sans-serif}.confidence-bg{width:100%;height:8px;background:#ffffff1a;border-radius:4px;overflow:hidden;margin-top:.5rem}.confidence-fill{height:100%;background:linear-gradient(to right,var(--accent-primary),var(--accent-secondary));transition:width .6s cubic-bezier(.175,.885,.32,1.275)}button.primary{background:linear-gradient(135deg,var(--accent-primary),var(--accent-secondary));border:none;padding:1rem 2rem;border-radius:12px;color:#fff;font-weight:600;cursor:pointer;transition:transform .2s,filter .2s;width:100%;margin-top:1rem}button.primary:hover:not(:disabled){transform:scale(1.02);filter:brightness(1.1)}button.primary:disabled{opacity:.5;cursor:not-allowed}.loader{width:24px;height:24px;border:3px solid rgba(255,255,255,.3);border-radius:50%;border-top-color:#fff;animation:spin 1s ease-in-out infinite;display:inline-block}@keyframes spin{to{transform:rotate(360deg)}}@media(max-width:1024px){.dashboard{grid-template-columns:1fr}}.navbar{grid-column:1 / -1;display:flex;gap:1rem;margin-bottom:1rem;padding:.5rem;background:var(--glass-bg);border:1px solid var(--glass-border);border-radius:16px;width:fit-content}.nav-item{padding:.75rem 1.5rem;border-radius:12px;cursor:pointer;font-weight:600;color:var(--text-muted);transition:all .2s ease;border:1px solid transparent}.nav-item:hover{color:var(--text-main);background:#ffffff0d}.nav-item.active{color:var(--text-main);background:#ffffff1a;border-color:var(--glass-border);box-shadow:0 4px 12px #0003}.defect-list{display:flex;flex-direction:column;gap:1rem;max-height:250px;overflow-y:auto;padding-right:.5rem}.defect-item{display:flex;flex-direction:column;gap:.25rem;padding-bottom:.5rem;border-bottom:1px solid var(--glass-border)}.defect-item:last-child{border-bottom:none}.status-header{display:flex;justify-content:space-between;align-items:center}
dist/assets/index-_UftzrKh.js ADDED
The diff for this file is too large to render. See raw diff
 
dist/index.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>defect-dashboard</title>
8
+ <script type="module" crossorigin src="/assets/index-_UftzrKh.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/assets/index-Lc_OTtrA.css">
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ </body>
14
+ </html>
dist/vite.svg ADDED
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ ultralytics
4
+ opencv-python-headless
5
+ pillow
6
+ python-multipart
7
+ numpy
8
+ pydantic
9
+ huggingface_hub