Update app.py
Browse files
app.py
CHANGED
@@ -1,28 +1,62 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
import gradio as gr
|
4 |
-
from ultralytics import YOLO
|
5 |
-
|
6 |
-
#
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import cv2
|
3 |
+
import gradio as gr
|
4 |
+
from ultralytics import YOLO
|
5 |
+
|
6 |
+
# --- Fix 1: Unzip model file (if needed) ---
|
7 |
+
# Hugging Face Spaces will automatically unzip uploaded .zip files,
|
8 |
+
# so you can skip the !unzip command in Python code.
|
9 |
+
|
10 |
+
# --- Fix 2: Use correct model path ---
|
11 |
+
# Place your model file in the same directory as app.py and use relative path
|
12 |
+
MODEL_PATH = "yolov8_model.pt" # Make sure this matches your uploaded filename
|
13 |
+
|
14 |
+
# --- Fix 3: Add error handling ---
|
15 |
+
if not os.path.exists(MODEL_PATH):
|
16 |
+
raise FileNotFoundError(f"Model file not found at {MODEL_PATH}. "
|
17 |
+
"Please upload your model file to the Space.")
|
18 |
+
|
19 |
+
# Load model
|
20 |
+
model = YOLO(MODEL_PATH)
|
21 |
+
|
22 |
+
def detect_defects(image):
|
23 |
+
"""Run object detection on input image and return annotated result."""
|
24 |
+
try:
|
25 |
+
# Run inference
|
26 |
+
results = model(image)
|
27 |
+
|
28 |
+
# Plot results (with bounding boxes)
|
29 |
+
annotated_img = results[0].plot(line_width=2)
|
30 |
+
|
31 |
+
# Convert BGR to RGB (OpenCV uses BGR by default)
|
32 |
+
annotated_img = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
|
33 |
+
return annotated_img
|
34 |
+
|
35 |
+
except Exception as e:
|
36 |
+
print(f"Error during detection: {e}")
|
37 |
+
return image # Return original image if error occurs
|
38 |
+
|
39 |
+
# Gradio UI
|
40 |
+
title = "🔍 Steel Surface Defect Detector (YOLOv8)"
|
41 |
+
description = "Upload a steel surface image to detect defects (crazing, scratches, etc.)."
|
42 |
+
|
43 |
+
# --- Fix 4: Use relative paths for example images ---
|
44 |
+
examples = [
|
45 |
+
"example1.jpg", # Make sure these exist in your Space
|
46 |
+
"example2.jpg"
|
47 |
+
]
|
48 |
+
|
49 |
+
# Create interface
|
50 |
+
interface = gr.Interface(
|
51 |
+
fn=detect_defects,
|
52 |
+
inputs=gr.Image(type="numpy"),
|
53 |
+
outputs=gr.Image(type="numpy"),
|
54 |
+
title=title,
|
55 |
+
description=description,
|
56 |
+
examples=examples,
|
57 |
+
allow_flagging="never"
|
58 |
+
)
|
59 |
+
|
60 |
+
# Launch app
|
61 |
+
if __name__ == "__main__":
|
62 |
+
interface.launch(debug=True)
|