Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -13,7 +13,7 @@ from ultralytics import YOLO
|
|
| 13 |
import ultralytics
|
| 14 |
import time
|
| 15 |
|
| 16 |
-
# Set YOLO config directory
|
| 17 |
os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
|
| 18 |
|
| 19 |
# Set up logging
|
|
@@ -38,11 +38,12 @@ detected_issues: List[str] = []
|
|
| 38 |
gps_coordinates: List[List[float]] = []
|
| 39 |
last_metrics: Dict[str, Any] = {}
|
| 40 |
frame_count: int = 0
|
|
|
|
| 41 |
|
| 42 |
# Debug: Check environment
|
| 43 |
print(f"Torch version: {torch.__version__}")
|
| 44 |
print(f"Gradio version: {gr.__version__}")
|
| 45 |
-
print(f"Ultralytics version: {ultralytics.__version__}")
|
| 46 |
print(f"CUDA available: {torch.cuda.is_available()}")
|
| 47 |
|
| 48 |
# Load custom YOLO model
|
|
@@ -58,7 +59,7 @@ def generate_map(gps_coords: List[List[float]], items: List[Dict[str, Any]]) ->
|
|
| 58 |
map_path = "map_temp.png"
|
| 59 |
plt.figure(figsize=(4, 4))
|
| 60 |
plt.scatter([x[1] for x in gps_coords], [x[0] for x in gps_coords], c='blue', label='GPS Points')
|
| 61 |
-
plt.title("
|
| 62 |
plt.xlabel("Longitude")
|
| 63 |
plt.ylabel("Latitude")
|
| 64 |
plt.legend()
|
|
@@ -67,7 +68,7 @@ def generate_map(gps_coords: List[List[float]], items: List[Dict[str, Any]]) ->
|
|
| 67 |
return map_path
|
| 68 |
|
| 69 |
def send_to_salesforce(data: Dict[str, Any]) -> None:
|
| 70 |
-
|
| 71 |
|
| 72 |
def update_metrics(detections: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 73 |
counts = Counter([det["label"] for det in detections])
|
|
@@ -129,6 +130,8 @@ def process_video(video, resize_width=320, resize_height=240, frame_skip=5):
|
|
| 129 |
|
| 130 |
processed_frames = 0
|
| 131 |
all_detections = []
|
|
|
|
|
|
|
| 132 |
|
| 133 |
while True:
|
| 134 |
ret, frame = cap.read()
|
|
@@ -138,10 +141,10 @@ def process_video(video, resize_width=320, resize_height=240, frame_skip=5):
|
|
| 138 |
if frame_count % frame_skip != 0:
|
| 139 |
continue
|
| 140 |
processed_frames += 1
|
| 141 |
-
|
| 142 |
|
| 143 |
frame = cv2.resize(frame, (out_width, out_height))
|
| 144 |
-
results = model(frame, verbose=False, conf=0.5, iou=0.7)
|
| 145 |
annotated_frame = results[0].plot()
|
| 146 |
|
| 147 |
frame_detections = []
|
|
@@ -155,20 +158,16 @@ def process_video(video, resize_width=320, resize_height=240, frame_skip=5):
|
|
| 155 |
logging.info(f"Frame {frame_count}: Detected {label} with confidence {conf:.2f}")
|
| 156 |
|
| 157 |
if frame_detections:
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
gps_coordinates.append(gps_coord)
|
| 169 |
-
for det in frame_detections:
|
| 170 |
-
det["gps"] = gps_coord
|
| 171 |
-
all_detections.extend(frame_detections)
|
| 172 |
|
| 173 |
out.write(annotated_frame)
|
| 174 |
if frame_skip > 1:
|
|
@@ -178,27 +177,34 @@ def process_video(video, resize_width=320, resize_height=240, frame_skip=5):
|
|
| 178 |
frame_count += 1
|
| 179 |
|
| 180 |
detected_counts.append(len(frame_detections))
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
detection_summary = {
|
| 183 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 184 |
"frame": frame_count,
|
| 185 |
"cracks": sum(1 for det in frame_detections if det["label"] == "crack"),
|
| 186 |
"potholes": sum(1 for det in frame_detections if det["label"] == "pothole"),
|
| 187 |
"gps": gps_coord,
|
| 188 |
-
"processing_time_ms":
|
| 189 |
}
|
| 190 |
log_entries.append(json.dumps(detection_summary, indent=2))
|
| 191 |
-
|
| 192 |
-
if len(log_entries) > 100:
|
| 193 |
log_entries.pop(0)
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
| 202 |
|
| 203 |
cap.release()
|
| 204 |
out.release()
|
|
@@ -209,10 +215,14 @@ def process_video(video, resize_width=320, resize_height=240, frame_skip=5):
|
|
| 209 |
output_duration = output_frames / output_fps
|
| 210 |
cap.release()
|
| 211 |
|
|
|
|
|
|
|
| 212 |
log_entries.append(f"Output video: {output_frames} frames, {output_fps} FPS, {output_duration:.2f} seconds")
|
|
|
|
| 213 |
logging.info(f"Output video: {output_frames} frames, {output_fps} FPS, {output_duration:.2f} seconds")
|
|
|
|
| 214 |
print(f"Output video: {output_frames} frames, {output_fps} FPS, {output_duration:.2f} seconds")
|
| 215 |
-
print(f"
|
| 216 |
|
| 217 |
chart_path = generate_line_chart()
|
| 218 |
map_path = generate_map(gps_coordinates[-5:], all_detections)
|
|
@@ -232,20 +242,20 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange")) as iface:
|
|
| 232 |
with gr.Row():
|
| 233 |
with gr.Column(scale=3):
|
| 234 |
video_input = gr.Video(label="Upload Video")
|
| 235 |
-
width_slider = gr.Slider(320,
|
| 236 |
-
height_slider = gr.Slider(240,
|
| 237 |
skip_slider = gr.Slider(1, 10, value=5, label="Frame Skip", step=1)
|
| 238 |
process_btn = gr.Button("Process Video", variant="primary")
|
| 239 |
with gr.Column(scale=1):
|
| 240 |
-
metrics_output = gr.Textbox(label="Detection Metrics", lines=
|
| 241 |
with gr.Row():
|
| 242 |
video_output = gr.Video(label="Processed Video")
|
| 243 |
-
issue_gallery = gr.Gallery(label="Detected Issues", columns=4, height="auto")
|
| 244 |
with gr.Row():
|
| 245 |
chart_output = gr.Image(label="Detection Trend")
|
| 246 |
map_output = gr.Image(label="Issue Locations Map")
|
| 247 |
with gr.Row():
|
| 248 |
-
logs_output = gr.Textbox(label="Logs", lines=
|
| 249 |
|
| 250 |
process_btn.click(
|
| 251 |
process_video,
|
|
|
|
| 13 |
import ultralytics
|
| 14 |
import time
|
| 15 |
|
| 16 |
+
# Set YOLO config directory
|
| 17 |
os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
|
| 18 |
|
| 19 |
# Set up logging
|
|
|
|
| 38 |
gps_coordinates: List[List[float]] = []
|
| 39 |
last_metrics: Dict[str, Any] = {}
|
| 40 |
frame_count: int = 0
|
| 41 |
+
SAVE_IMAGE_INTERVAL = 1 # Save every frame with detections
|
| 42 |
|
| 43 |
# Debug: Check environment
|
| 44 |
print(f"Torch version: {torch.__version__}")
|
| 45 |
print(f"Gradio version: {gr.__version__}")
|
| 46 |
+
print(f"Ultralytics version: {ultralytics.__version__}")
|
| 47 |
print(f"CUDA available: {torch.cuda.is_available()}")
|
| 48 |
|
| 49 |
# Load custom YOLO model
|
|
|
|
| 59 |
map_path = "map_temp.png"
|
| 60 |
plt.figure(figsize=(4, 4))
|
| 61 |
plt.scatter([x[1] for x in gps_coords], [x[0] for x in gps_coords], c='blue', label='GPS Points')
|
| 62 |
+
plt.title("Issue Locations Map")
|
| 63 |
plt.xlabel("Longitude")
|
| 64 |
plt.ylabel("Latitude")
|
| 65 |
plt.legend()
|
|
|
|
| 68 |
return map_path
|
| 69 |
|
| 70 |
def send_to_salesforce(data: Dict[str, Any]) -> None:
|
| 71 |
+
pass # Minimal mock
|
| 72 |
|
| 73 |
def update_metrics(detections: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 74 |
counts = Counter([det["label"] for det in detections])
|
|
|
|
| 130 |
|
| 131 |
processed_frames = 0
|
| 132 |
all_detections = []
|
| 133 |
+
frame_times = []
|
| 134 |
+
detection_frame_count = 0
|
| 135 |
|
| 136 |
while True:
|
| 137 |
ret, frame = cap.read()
|
|
|
|
| 141 |
if frame_count % frame_skip != 0:
|
| 142 |
continue
|
| 143 |
processed_frames += 1
|
| 144 |
+
frame_start = time.time()
|
| 145 |
|
| 146 |
frame = cv2.resize(frame, (out_width, out_height))
|
| 147 |
+
results = model(frame, verbose=False, conf=0.5, iou=0.7) # Lower thresholds
|
| 148 |
annotated_frame = results[0].plot()
|
| 149 |
|
| 150 |
frame_detections = []
|
|
|
|
| 158 |
logging.info(f"Frame {frame_count}: Detected {label} with confidence {conf:.2f}")
|
| 159 |
|
| 160 |
if frame_detections:
|
| 161 |
+
detection_frame_count += 1
|
| 162 |
+
if detection_frame_count % SAVE_IMAGE_INTERVAL == 0:
|
| 163 |
+
captured_frame_path = os.path.join(CAPTURED_FRAMES_DIR, f"detected_{frame_count}.jpg")
|
| 164 |
+
if not cv2.imwrite(captured_frame_path, annotated_frame):
|
| 165 |
+
log_entries.append(f"Error: Failed to save {captured_frame_path}")
|
| 166 |
+
logging.error(f"Failed to save {captured_frame_path}")
|
| 167 |
+
else:
|
| 168 |
+
detected_issues.append(captured_frame_path)
|
| 169 |
+
if len(detected_issues) > 100:
|
| 170 |
+
detected_issues.pop(0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
out.write(annotated_frame)
|
| 173 |
if frame_skip > 1:
|
|
|
|
| 177 |
frame_count += 1
|
| 178 |
|
| 179 |
detected_counts.append(len(frame_detections))
|
| 180 |
+
gps_coord = [17.385044 + (frame_count * 0.0001), 78.486671 + (frame_count * 0.0001)]
|
| 181 |
+
gps_coordinates.append(gps_coord)
|
| 182 |
+
for det in frame_detections:
|
| 183 |
+
det["gps"] = gps_coord
|
| 184 |
+
all_detections.extend(frame_detections)
|
| 185 |
+
|
| 186 |
+
frame_time = (time.time() - frame_start) * 1000
|
| 187 |
+
frame_times.append(frame_time)
|
| 188 |
detection_summary = {
|
| 189 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 190 |
"frame": frame_count,
|
| 191 |
"cracks": sum(1 for det in frame_detections if det["label"] == "crack"),
|
| 192 |
"potholes": sum(1 for det in frame_detections if det["label"] == "pothole"),
|
| 193 |
"gps": gps_coord,
|
| 194 |
+
"processing_time_ms": frame_time
|
| 195 |
}
|
| 196 |
log_entries.append(json.dumps(detection_summary, indent=2))
|
| 197 |
+
if len(log_entries) > 50:
|
|
|
|
| 198 |
log_entries.pop(0)
|
| 199 |
|
| 200 |
+
last_metrics = update_metrics(all_detections)
|
| 201 |
+
send_to_salesforce({
|
| 202 |
+
"detections": all_detections,
|
| 203 |
+
"metrics": last_metrics,
|
| 204 |
+
"timestamp": detection_summary["timestamp"] if all_detections else datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 205 |
+
"frame_count": frame_count,
|
| 206 |
+
"gps_coordinates": gps_coordinates[-1] if gps_coordinates else [0, 0]
|
| 207 |
+
})
|
| 208 |
|
| 209 |
cap.release()
|
| 210 |
out.release()
|
|
|
|
| 215 |
output_duration = output_frames / output_fps
|
| 216 |
cap.release()
|
| 217 |
|
| 218 |
+
total_time = time.time() - start_time
|
| 219 |
+
avg_frame_time = sum(frame_times) / len(frame_times) if frame_times else 0
|
| 220 |
log_entries.append(f"Output video: {output_frames} frames, {output_fps} FPS, {output_duration:.2f} seconds")
|
| 221 |
+
log_entries.append(f"Total processing time: {total_time:.2f} seconds, Avg frame time: {avg_frame_time:.2f} ms, Detection frames: {detection_frame_count}")
|
| 222 |
logging.info(f"Output video: {output_frames} frames, {output_fps} FPS, {output_duration:.2f} seconds")
|
| 223 |
+
logging.info(f"Total processing time: {total_time:.2f} seconds, Avg frame time: {avg_frame_time:.2f} ms, Detection frames: {detection_frame_count}")
|
| 224 |
print(f"Output video: {output_frames} frames, {output_fps} FPS, {output_duration:.2f} seconds")
|
| 225 |
+
print(f"Total processing time: {total_time:.2f} seconds, Avg frame time: {avg_frame_time:.2f} ms, Detection frames: {detection_frame_count}")
|
| 226 |
|
| 227 |
chart_path = generate_line_chart()
|
| 228 |
map_path = generate_map(gps_coordinates[-5:], all_detections)
|
|
|
|
| 242 |
with gr.Row():
|
| 243 |
with gr.Column(scale=3):
|
| 244 |
video_input = gr.Video(label="Upload Video")
|
| 245 |
+
width_slider = gr.Slider(320, 640, value=320, label="Output Width", step=1)
|
| 246 |
+
height_slider = gr.Slider(240, 480, value=240, label="Output Height", step=1)
|
| 247 |
skip_slider = gr.Slider(1, 10, value=5, label="Frame Skip", step=1)
|
| 248 |
process_btn = gr.Button("Process Video", variant="primary")
|
| 249 |
with gr.Column(scale=1):
|
| 250 |
+
metrics_output = gr.Textbox(label="Detection Metrics", lines=5, interactive=False)
|
| 251 |
with gr.Row():
|
| 252 |
video_output = gr.Video(label="Processed Video")
|
| 253 |
+
issue_gallery = gr.Gallery(label="Detected Issues", columns=4, height="auto", object_fit="contain")
|
| 254 |
with gr.Row():
|
| 255 |
chart_output = gr.Image(label="Detection Trend")
|
| 256 |
map_output = gr.Image(label="Issue Locations Map")
|
| 257 |
with gr.Row():
|
| 258 |
+
logs_output = gr.Textbox(label="Logs", lines=5, interactive=False)
|
| 259 |
|
| 260 |
process_btn.click(
|
| 261 |
process_video,
|