Komal133 commited on
Commit
de06ce1
·
verified ·
1 Parent(s): 0d043b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -102
app.py CHANGED
@@ -1,111 +1,39 @@
1
  import gradio as gr
2
- import torch
3
  from ultralytics import YOLO
 
4
  from PIL import Image
5
- import numpy as np
6
- import cv2
7
- import logging
8
-
9
- # Set up logging
10
- logging.basicConfig(level=logging.INFO)
11
- logger = logging.getLogger(__name__)
12
 
13
- # Load the fine-tuned YOLOv8 model from Hugging Face
14
- try:
15
- model = YOLO("path/to/your/fine-tuned-yolov8-model.pt") # Replace with your model path
16
- logger.info("Model loaded successfully")
17
- except Exception as e:
18
- logger.error(f"Failed to load model: {e}")
19
- raise
20
 
21
- # Define fault types and severity mapping
22
- FAULT_CLASSES = {0: "Crack", 1: "Spalling", 2: "Corrosion"}
23
- SE prints
24
- VERITY_THRESHOLDS = {
25
- "Crack": {"Minor": 0.3, "Moderate": 0.6, "Severe": 0.9},
26
- "Spalling": {"Minor": 0.4, "Moderate": 0.7, "Severe": 0.95},
27
- "Corrosion": {"Minor": 0.35, "Moderate": 0.65, "Severe": 0.9}
28
- }
29
-
30
- def preprocess_image(image):
31
- """Preprocess the input image: resize and normalize."""
32
- try:
33
- img = np.array(image)
34
- img = cv2.resize(img, (640, 640)) # YOLOv8 default input size
35
- img = img / 255.0 # Normalize to [0, 1]
36
- logger.info("Image preprocessed successfully")
37
- return img
38
- except Exception as e:
39
- logger.error(f"Preprocessing failed: {e}")
40
- raise
41
-
42
- def get_severity(fault_type, confidence):
43
- """Determine severity based on confidence score."""
44
- thresholds = SEVERITY_THRESHOLDS.get(fault_type, {"Minor": 0.3, "Moderate": 0.6, "Severe": 0.9})
45
- if confidence >= thresholds["Severe"]:
46
- return "Severe"
47
- elif confidence >= thresholds["Moderate"]:
48
- return "Moderate"
49
- elif confidence >= thresholds["Minor"]:
50
- return "Minor"
51
- return "None"
52
 
 
53
  def detect_defects(image):
54
- """Detect structural defects and return annotated image with results."""
55
- try:
56
- # Preprocess image
57
- img_processed = preprocess_image(image)
58
-
59
- # Run inference
60
- results = model.predict(img_processed, conf=0.5) # Confidence threshold
61
- logger.info("Inference completed")
62
-
63
- # Process results
64
- annotated_img = results[0].plot() # Get annotated image with bounding boxes
65
- detections = []
66
-
67
- for result in results[0].boxes:
68
- class_id = int(result.cls)
69
- fault_type = FAULT_CLASSES.get(class_id, "Unknown")
70
- confidence = float(result.conf)
71
- severity = get_severity(fault_type, confidence)
72
- detections.append(f"{fault_type} (Severity: {severity}, Confidence: {confidence:.2f})")
73
-
74
- # Convert annotated image to PIL for Gradio
75
- annotated_img = Image.fromarray(annotated_img)
76
-
77
- # Return annotated image and detection results
78
- return annotated_img, "\n".join(detections) if detections else "No defects detected."
79
- except Exception as e:
80
- logger.error(f"Detection failed: {e}")
81
- return None, f"Error: {str(e)}"
82
-
83
- # Gradio interface using Blocks
84
- with gr.Blocks(title="Structural Defect Detection with YOLOv8") as demo:
85
- gr.Markdown("""
86
- # Structural Defect Detection
87
- Upload a high-resolution drone-captured image to detect structural defects (e.g., cracks, spalling, corrosion) with severity levels.
88
- """)
89
-
90
- with gr.Row():
91
- with gr.Column():
92
- input_image = gr.Image(type="pil", label="Upload Drone-Captured Image")
93
- submit_button = gr.Button("Detect Defects")
94
- with gr.Column():
95
- output_image = gr.Image(type="pil", label="Annotated Image")
96
- output_text = gr.Textbox(label="Detected Faults and Severity")
97
-
98
- submit_button.click(
99
- fn=detect_defects,
100
- inputs=input_image,
101
- outputs=[output_image, output_text]
102
- )
103
 
104
- # Launch the app
105
  if __name__ == "__main__":
106
- try:
107
- demo.launch()
108
- logger.info("Gradio app launched successfully")
109
- except Exception as e:
110
- logger.error(f"Failed to launch Gradio app: {e}")
111
- raise
 
1
  import gradio as gr
 
2
  from ultralytics import YOLO
3
+ import torch
4
  from PIL import Image
5
+ import os
 
 
 
 
 
 
6
 
7
+ # Load model (you can switch to 'fasterrcnn' based loading if needed)
8
+ model = YOLO("model/best.pt") # fine-tuned YOLOv8 model
 
 
 
 
 
9
 
10
+ # Define defect labels if custom
11
+ DEFECT_LABELS = ['crack', 'spalling', 'rust', 'deformation']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Inference function
14
  def detect_defects(image):
15
+ results = model(image)
16
+ annotated_img = results[0].plot() # Draw boxes
17
+ predictions = results[0].boxes.data.cpu().numpy() # [x1, y1, x2, y2, conf, class]
18
+
19
+ # Create readable output
20
+ output = []
21
+ for pred in predictions:
22
+ x1, y1, x2, y2, conf, cls_id = pred
23
+ label = DEFECT_LABELS[int(cls_id)]
24
+ output.append(f"{label}: {conf:.2f}")
25
+
26
+ return Image.fromarray(annotated_img), "\n".join(output)
27
+
28
+ # Gradio UI
29
+ interface = gr.Interface(
30
+ fn=detect_defects,
31
+ inputs=gr.Image(type="pil"),
32
+ outputs=[gr.Image(type="pil", label="Detected Image"), gr.Textbox(label="Detected Faults")],
33
+ title="Structural Defect Detection",
34
+ description="Upload drone-captured image to detect cracks, rust, spalling, and deformations.",
35
+ allow_flagging="never"
36
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
 
38
  if __name__ == "__main__":
39
+ interface.launch()