Vansh180 commited on
Commit
5ea6336
Β·
verified Β·
1 Parent(s): a076a69

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -35
app.py CHANGED
@@ -2,6 +2,9 @@ import gradio as gr
2
  from ultralytics import YOLO
3
  import cv2
4
  from PIL import Image
 
 
 
5
 
6
  # Load the YOLO model - YOLOv11m for pothole, road damage, and garbage detection
7
  try:
@@ -10,72 +13,185 @@ except Exception as e:
10
  print(f"Error loading model: {e}")
11
  model = None
12
 
13
- def predict(image, conf_threshold):
 
14
  try:
15
  if image is None or model is None:
16
  return None, "Model not loaded or invalid image."
17
-
18
- # Run inference
19
  results = model(image, imgsz=768, conf=conf_threshold)
20
  result = results[0]
21
-
22
- # Plotting the detections on the image returns a BGR numpy array
23
  annotated_image = result.plot()
24
  annotated_image_rgb = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
25
-
26
- # Detection overview text
27
  boxes = result.boxes
28
  class_names = result.names
29
-
30
  if len(boxes) == 0:
31
  detection_summary = "No civic issues detected in this image."
32
  else:
33
- # Count detections safely
34
  detection_counts = {}
35
  for box in boxes:
36
- # box.cls is usually a tensor. Safe conversion to integer:
37
  cls_id = int(box.cls.item() if hasattr(box.cls, "item") else box.cls[0])
38
  cls_name = class_names.get(cls_id, f"Class {cls_id}")
39
  detection_counts[cls_name] = detection_counts.get(cls_name, 0) + 1
40
-
41
  summary_lines = ["**Detections:**"]
42
  for cls_name, count in detection_counts.items():
43
  summary_lines.append(f"- {count} {cls_name}(s)")
44
-
45
  detection_summary = "\n".join(summary_lines)
46
-
47
  return Image.fromarray(annotated_image_rgb), detection_summary
48
-
49
  except Exception as e:
50
  import traceback
51
  error_msg = f"ERROR during prediction: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
52
  return None, error_msg
53
 
54
- # Gradio Interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  with gr.Blocks(title="PotholeNet-YOLO11m-v1 πŸ›‘") as interface:
56
  gr.Markdown("# πŸ›‘ PotholeNet-YOLO11m-v1")
57
- gr.Markdown("**Aamchi City AI Civic System** β€” Real-time pothole, road damage, and garbage detection for Indian urban roads.")
58
- gr.Markdown("Upload an image of a road to detect infrastructure issues. The model was trained on 23,000+ street-level images.")
59
-
60
- with gr.Row():
61
- with gr.Column():
62
- input_image = gr.Image(type="pil", label="Upload Street Image")
63
- conf_slider = gr.Slider(minimum=0.01, maximum=1.0, value=0.25, step=0.01, label="Confidence Threshold")
64
- submit_btn = gr.Button("Detect Civic Issues", variant="primary")
65
-
66
- with gr.Column():
67
- output_image = gr.Image(type="pil", label="Detection Results")
68
- detection_text = gr.Textbox(label="Detection Summary", interactive=False, lines=4)
69
-
70
- submit_btn.click(
71
- fn=predict,
72
- inputs=[input_image, conf_slider],
73
- outputs=[output_image, detection_text]
74
  )
75
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  gr.Markdown("### Intended Use")
77
- gr.Markdown("Real-time pothole detection, Automated civic issue reporting, Infrastructure health monitoring.")
 
 
78
  gr.Markdown("**Developer:** Vansh Momaya")
79
 
80
  if __name__ == "__main__":
81
- interface.launch(server_name="0.0.0.0", server_port=7860)
 
2
  from ultralytics import YOLO
3
  import cv2
4
  from PIL import Image
5
+ import numpy as np
6
+ import tempfile
7
+ import os
8
 
9
  # Load the YOLO model - YOLOv11m for pothole, road damage, and garbage detection
10
  try:
 
13
  print(f"Error loading model: {e}")
14
  model = None
15
 
16
+
17
+ def predict_image(image, conf_threshold):
18
  try:
19
  if image is None or model is None:
20
  return None, "Model not loaded or invalid image."
21
+
 
22
  results = model(image, imgsz=768, conf=conf_threshold)
23
  result = results[0]
24
+
 
25
  annotated_image = result.plot()
26
  annotated_image_rgb = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
27
+
 
28
  boxes = result.boxes
29
  class_names = result.names
30
+
31
  if len(boxes) == 0:
32
  detection_summary = "No civic issues detected in this image."
33
  else:
 
34
  detection_counts = {}
35
  for box in boxes:
 
36
  cls_id = int(box.cls.item() if hasattr(box.cls, "item") else box.cls[0])
37
  cls_name = class_names.get(cls_id, f"Class {cls_id}")
38
  detection_counts[cls_name] = detection_counts.get(cls_name, 0) + 1
39
+
40
  summary_lines = ["**Detections:**"]
41
  for cls_name, count in detection_counts.items():
42
  summary_lines.append(f"- {count} {cls_name}(s)")
43
+
44
  detection_summary = "\n".join(summary_lines)
45
+
46
  return Image.fromarray(annotated_image_rgb), detection_summary
47
+
48
  except Exception as e:
49
  import traceback
50
  error_msg = f"ERROR during prediction: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
51
  return None, error_msg
52
 
53
+
54
+ def predict_video(video_path, conf_threshold, progress=gr.Progress()):
55
+ try:
56
+ if video_path is None or model is None:
57
+ return None, "Model not loaded or no video provided."
58
+
59
+ cap = cv2.VideoCapture(video_path)
60
+ if not cap.isOpened():
61
+ return None, "Could not open video file."
62
+
63
+ # Video properties
64
+ fps = cap.get(cv2.CAP_PROP_FPS) or 25
65
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
66
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
67
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
68
+
69
+ # Output temp file
70
+ out_path = tempfile.mktemp(suffix=".mp4")
71
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
72
+ out = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
73
+
74
+ all_detection_counts = {}
75
+ frame_idx = 0
76
+
77
+ while True:
78
+ ret, frame = cap.read()
79
+ if not ret:
80
+ break
81
+
82
+ # Update progress
83
+ if total_frames > 0:
84
+ progress(frame_idx / total_frames, desc=f"Processing frame {frame_idx}/{total_frames}")
85
+
86
+ # Run inference on frame (BGR numpy array works directly)
87
+ results = model(frame, imgsz=768, conf=conf_threshold, verbose=False)
88
+ result = results[0]
89
+
90
+ # Annotate frame
91
+ annotated_frame = result.plot()
92
+ out.write(annotated_frame)
93
+
94
+ # Accumulate detections
95
+ for box in result.boxes:
96
+ cls_id = int(box.cls.item() if hasattr(box.cls, "item") else box.cls[0])
97
+ cls_name = result.names.get(cls_id, f"Class {cls_id}")
98
+ all_detection_counts[cls_name] = all_detection_counts.get(cls_name, 0) + 1
99
+
100
+ frame_idx += 1
101
+
102
+ cap.release()
103
+ out.release()
104
+
105
+ # Re-encode with H.264 for browser compatibility (requires ffmpeg)
106
+ final_path = tempfile.mktemp(suffix=".mp4")
107
+ os.system(f'ffmpeg -y -i "{out_path}" -vcodec libx264 -crf 23 -preset fast "{final_path}" -loglevel quiet')
108
+ if os.path.exists(final_path) and os.path.getsize(final_path) > 0:
109
+ os.remove(out_path)
110
+ out_path = final_path
111
+
112
+ # Build summary
113
+ if not all_detection_counts:
114
+ summary = f"Processed {frame_idx} frames.\nNo civic issues detected in this video."
115
+ else:
116
+ summary_lines = [f"Processed {frame_idx} frames.\n\n**Total Detections Across All Frames:**"]
117
+ for cls_name, count in sorted(all_detection_counts.items(), key=lambda x: -x[1]):
118
+ summary_lines.append(f"- {count} {cls_name}(s)")
119
+ summary = "\n".join(summary_lines)
120
+
121
+ return out_path, summary
122
+
123
+ except Exception as e:
124
+ import traceback
125
+ error_msg = f"ERROR during video prediction: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
126
+ return None, error_msg
127
+
128
+
129
+ # ── Gradio Interface ───���──────────────────────────────────────────────────────
130
  with gr.Blocks(title="PotholeNet-YOLO11m-v1 πŸ›‘") as interface:
131
  gr.Markdown("# πŸ›‘ PotholeNet-YOLO11m-v1")
132
+ gr.Markdown(
133
+ "**Aamchi City AI Civic System** β€” Real-time pothole, road damage, and garbage detection for Indian urban roads."
134
+ )
135
+ gr.Markdown(
136
+ "Upload an image **or video** of a road to detect infrastructure issues. "
137
+ "The model was trained on 23,000+ street-level images."
 
 
 
 
 
 
 
 
 
 
 
138
  )
139
+
140
+ with gr.Tabs():
141
+ # ── Image Tab ────────────────────────────────────────────────────────
142
+ with gr.TabItem("πŸ–ΌοΈ Image Detection"):
143
+ with gr.Row():
144
+ with gr.Column():
145
+ input_image = gr.Image(type="pil", label="Upload Street Image")
146
+ img_conf_slider = gr.Slider(
147
+ minimum=0.01, maximum=1.0, value=0.25, step=0.01,
148
+ label="Confidence Threshold"
149
+ )
150
+ img_submit_btn = gr.Button("Detect Civic Issues", variant="primary")
151
+
152
+ with gr.Column():
153
+ output_image = gr.Image(type="pil", label="Detection Results")
154
+ img_detection_text = gr.Textbox(
155
+ label="Detection Summary", interactive=False, lines=4
156
+ )
157
+
158
+ img_submit_btn.click(
159
+ fn=predict_image,
160
+ inputs=[input_image, img_conf_slider],
161
+ outputs=[output_image, img_detection_text],
162
+ )
163
+
164
+ # ── Video Tab ────────────────────────────────────────────────────────
165
+ with gr.TabItem("🎬 Video Detection"):
166
+ gr.Markdown(
167
+ "> ⚠️ **Note:** Video processing is frame-by-frame and may take a while depending on length and hardware."
168
+ )
169
+ with gr.Row():
170
+ with gr.Column():
171
+ input_video = gr.Video(label="Upload Street Video")
172
+ vid_conf_slider = gr.Slider(
173
+ minimum=0.01, maximum=1.0, value=0.25, step=0.01,
174
+ label="Confidence Threshold"
175
+ )
176
+ vid_submit_btn = gr.Button("Detect Civic Issues in Video", variant="primary")
177
+
178
+ with gr.Column():
179
+ output_video = gr.Video(label="Annotated Video")
180
+ vid_detection_text = gr.Textbox(
181
+ label="Detection Summary", interactive=False, lines=6
182
+ )
183
+
184
+ vid_submit_btn.click(
185
+ fn=predict_video,
186
+ inputs=[input_video, vid_conf_slider],
187
+ outputs=[output_video, vid_detection_text],
188
+ )
189
+
190
  gr.Markdown("### Intended Use")
191
+ gr.Markdown(
192
+ "Real-time pothole detection, Automated civic issue reporting, Infrastructure health monitoring."
193
+ )
194
  gr.Markdown("**Developer:** Vansh Momaya")
195
 
196
  if __name__ == "__main__":
197
+ interface.launch(server_name="0.0.0.0", server_port=7860)