surabhic commited on
Commit
b19eb2e
·
verified ·
1 Parent(s): 0da3a83

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -40
app.py CHANGED
@@ -3,60 +3,76 @@ 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)
 
3
  import gradio as gr
4
  from ultralytics import YOLO
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  # Load model
7
+ MODEL_PATH = "yolov8_model.pt"
8
+ if not os.path.exists(MODEL_PATH):
9
+ raise FileNotFoundError(f"Model file {MODEL_PATH} not found. Please upload it to your Space.")
10
  model = YOLO(MODEL_PATH)
11
 
12
  def detect_defects(image):
13
+ """Run object detection and return annotated image with results."""
14
  try:
15
  # Run inference
16
  results = model(image)
17
 
18
+ # Get detection results
19
+ boxes = results[0].boxes
20
+ class_names = model.names
21
+ detections = []
22
+
23
+ for box in boxes:
24
+ class_id = int(box.cls)
25
+ confidence = float(box.conf)
26
+ detections.append({
27
+ "class": class_names[class_id],
28
+ "confidence": confidence,
29
+ "box": box.xyxy[0].tolist() # [x1,y1,x2,y2]
30
+ })
31
 
32
+ # Plot results
33
+ annotated_img = results[0].plot(line_width=2, font_size=10)
34
  annotated_img = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
35
+
36
+ return annotated_img, detections
37
 
38
  except Exception as e:
39
  print(f"Error during detection: {e}")
40
+ return image, []
 
 
 
 
41
 
42
+ # Custom CSS for better UI
43
+ css = """
44
+ .gradio-container {max-width: 800px !important}
45
+ .output-image {border-radius: 8px}
46
+ """
47
 
48
+ # Interface components
49
+ with gr.Blocks(css=css, title="Steel Defect Detector") as app:
50
+ gr.Markdown("## 🔍 Steel Surface Defect Detector (YOLOv8)")
51
+ gr.Markdown("Upload or drag-and-drop an image of steel surface to detect defects")
52
+
53
+ with gr.Row():
54
+ with gr.Column():
55
+ image_input = gr.Image(label="Input Image", type="numpy")
56
+ submit_btn = gr.Button("Detect Defects", variant="primary")
57
+
58
+ with gr.Column():
59
+ image_output = gr.Image(label="Detected Defects", elem_classes=["output-image"])
60
+ json_output = gr.JSON(label="Detection Results")
61
+
62
+ # Example images
63
+ gr.Examples(
64
+ examples=[["example1.jpg"], ["example2.jpg"]],
65
+ inputs=image_input,
66
+ outputs=[image_output, json_output],
67
+ fn=detect_defects,
68
+ cache_examples=False
69
+ )
70
+
71
+ submit_btn.click(
72
+ fn=detect_defects,
73
+ inputs=image_input,
74
+ outputs=[image_output, json_output]
75
+ )
76
 
 
77
  if __name__ == "__main__":
78
+ app.launch(debug=True)