Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -8,7 +8,7 @@ import numpy as np
|
|
8 |
from datetime import datetime
|
9 |
from collections import Counter
|
10 |
from services.video_service import get_next_video_frame, reset_video_index
|
11 |
-
from services.crack_detection_service import
|
12 |
from services.overlay_service import overlay_boxes
|
13 |
from services.metrics_service import update_metrics
|
14 |
from services.map_service import generate_map
|
@@ -16,7 +16,7 @@ from services.utils import simulate_gps_coordinates
|
|
16 |
|
17 |
# Globals
|
18 |
paused = False
|
19 |
-
frame_rate =
|
20 |
frame_count = 0
|
21 |
log_entries = []
|
22 |
crack_counts = []
|
@@ -31,11 +31,19 @@ gps_coordinates = []
|
|
31 |
TEMP_IMAGE_PATH = "temp.jpg"
|
32 |
CAPTURED_FRAMES_DIR = "captured_frames"
|
33 |
os.makedirs(CAPTURED_FRAMES_DIR, exist_ok=True)
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
# Core monitor function
|
37 |
def monitor_feed():
|
38 |
-
global paused, frame_count, last_frame, last_metrics, last_timestamp, gps_coordinates
|
39 |
|
40 |
if paused and last_frame is not None:
|
41 |
frame = last_frame.copy()
|
@@ -47,36 +55,32 @@ def monitor_feed():
|
|
47 |
log_entries.append(f"Error: {str(e)}")
|
48 |
return None, last_metrics, "\n".join(log_entries[-10:]), None, None, last_detected_images, None
|
49 |
|
50 |
-
|
51 |
-
frame = overlay_boxes(frame,
|
52 |
cv2.imwrite(TEMP_IMAGE_PATH, frame, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
|
53 |
-
metrics = update_metrics(
|
54 |
|
55 |
frame_count += 1
|
56 |
last_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
57 |
gps_coord = simulate_gps_coordinates(frame_count)
|
58 |
gps_coordinates.append(gps_coord)
|
59 |
|
60 |
-
if
|
61 |
-
captured_frame_path = os.path.join(CAPTURED_FRAMES_DIR, f"
|
62 |
cv2.imwrite(captured_frame_path, frame)
|
63 |
last_detected_images.append(captured_frame_path)
|
64 |
-
if len(last_detected_images) >
|
65 |
-
|
66 |
-
try:
|
67 |
-
os.remove(oldest_image)
|
68 |
-
except:
|
69 |
-
pass # Ignore if file can't be deleted
|
70 |
|
71 |
last_frame = frame.copy()
|
72 |
last_metrics = metrics.copy()
|
73 |
|
74 |
# Update logs and stats
|
75 |
-
crack_detected = len(last_metrics.get('
|
76 |
crack_severity_all.extend([
|
77 |
-
|
78 |
-
for
|
79 |
-
if
|
80 |
])
|
81 |
|
82 |
log_entries.append(f"{last_timestamp} - Frame {frame_count} - Cracks: {crack_detected} - GPS: {gps_coord}")
|
@@ -89,11 +93,11 @@ def monitor_feed():
|
|
89 |
if len(crack_severity_all) > 500:
|
90 |
crack_severity_all.pop(0)
|
91 |
|
92 |
-
frame = cv2.resize(last_frame, (
|
93 |
-
cv2.putText(frame, f"Frame: {frame_count}", (
|
94 |
-
cv2.putText(frame, f"{last_timestamp}", (
|
95 |
|
96 |
-
map_path = generate_map(gps_coordinates[-5:], last_metrics.get('
|
97 |
|
98 |
return frame[:, :, ::-1], last_metrics, "\n".join(log_entries[-10:]), generate_line_chart(), generate_pie_chart(), last_detected_images, map_path
|
99 |
|
@@ -101,14 +105,15 @@ def monitor_feed():
|
|
101 |
def generate_line_chart():
|
102 |
if not crack_counts:
|
103 |
return None
|
104 |
-
fig, ax = plt.subplots(figsize=(
|
105 |
-
ax.plot(crack_counts[-50:], marker='o')
|
106 |
-
ax.set_title("Cracks Over Time")
|
107 |
-
ax.set_xlabel("Frame")
|
108 |
-
ax.set_ylabel("Count")
|
|
|
109 |
fig.tight_layout()
|
110 |
chart_path = "chart_temp.png"
|
111 |
-
fig.savefig(chart_path)
|
112 |
plt.close(fig)
|
113 |
return chart_path
|
114 |
|
@@ -116,42 +121,43 @@ def generate_line_chart():
|
|
116 |
def generate_pie_chart():
|
117 |
if not crack_severity_all:
|
118 |
return None
|
119 |
-
fig, ax = plt.subplots(figsize=(
|
120 |
count = Counter(crack_severity_all[-200:])
|
121 |
labels, sizes = zip(*count.items())
|
122 |
-
|
|
|
123 |
ax.axis('equal')
|
124 |
fig.tight_layout()
|
125 |
pie_path = "pie_temp.png"
|
126 |
-
fig.savefig(pie_path)
|
127 |
plt.close(fig)
|
128 |
return pie_path
|
129 |
|
130 |
# Gradio UI
|
131 |
-
with gr.Blocks(theme=
|
132 |
-
gr.Markdown("#
|
133 |
-
|
134 |
-
status_text = gr.Markdown("**Status:** 🟢 Running")
|
135 |
|
136 |
with gr.Row():
|
137 |
with gr.Column(scale=3):
|
138 |
-
video_output = gr.Image(label="Live Drone Feed", width=
|
139 |
-
with gr.Column(scale=
|
140 |
-
metrics_output = gr.Textbox(label="Crack Metrics", lines=
|
141 |
|
142 |
with gr.Row():
|
143 |
-
logs_output = gr.Textbox(label="Live Logs", lines=
|
144 |
-
chart_output = gr.Image(label="Crack Trend")
|
145 |
-
pie_output = gr.Image(label="Crack Severity")
|
146 |
|
147 |
with gr.Row():
|
148 |
-
map_output = gr.Image(label="Crack Locations Map")
|
149 |
-
captured_images = gr.Gallery(label=
|
150 |
|
151 |
with gr.Row():
|
152 |
-
pause_btn = gr.Button("⏸️ Pause")
|
153 |
-
resume_btn = gr.Button("▶️ Resume")
|
154 |
-
frame_slider = gr.Slider(0.
|
155 |
|
156 |
def toggle_pause():
|
157 |
global paused
|
|
|
8 |
from datetime import datetime
|
9 |
from collections import Counter
|
10 |
from services.video_service import get_next_video_frame, reset_video_index
|
11 |
+
from services.crack_detection_service import detect_cracks_and_objects
|
12 |
from services.overlay_service import overlay_boxes
|
13 |
from services.metrics_service import update_metrics
|
14 |
from services.map_service import generate_map
|
|
|
16 |
|
17 |
# Globals
|
18 |
paused = False
|
19 |
+
frame_rate = 0.5
|
20 |
frame_count = 0
|
21 |
log_entries = []
|
22 |
crack_counts = []
|
|
|
31 |
TEMP_IMAGE_PATH = "temp.jpg"
|
32 |
CAPTURED_FRAMES_DIR = "captured_frames"
|
33 |
os.makedirs(CAPTURED_FRAMES_DIR, exist_ok=True)
|
34 |
+
|
35 |
+
# Custom Gradio theme
|
36 |
+
custom_theme = gr.themes.Soft(
|
37 |
+
primary_hue="red",
|
38 |
+
secondary_hue="green",
|
39 |
+
neutral_hue="black",
|
40 |
+
text_size="lg",
|
41 |
+
radius_size="lg",
|
42 |
+
)
|
43 |
|
44 |
# Core monitor function
|
45 |
def monitor_feed():
|
46 |
+
global paused, frame_count, last_frame, last_metrics, last_timestamp, gps_coordinates
|
47 |
|
48 |
if paused and last_frame is not None:
|
49 |
frame = last_frame.copy()
|
|
|
55 |
log_entries.append(f"Error: {str(e)}")
|
56 |
return None, last_metrics, "\n".join(log_entries[-10:]), None, None, last_detected_images, None
|
57 |
|
58 |
+
detected_items = detect_cracks_and_objects(frame)
|
59 |
+
frame = overlay_boxes(frame, detected_items)
|
60 |
cv2.imwrite(TEMP_IMAGE_PATH, frame, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
|
61 |
+
metrics = update_metrics(detected_items)
|
62 |
|
63 |
frame_count += 1
|
64 |
last_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
65 |
gps_coord = simulate_gps_coordinates(frame_count)
|
66 |
gps_coordinates.append(gps_coord)
|
67 |
|
68 |
+
if detected_items:
|
69 |
+
captured_frame_path = os.path.join(CAPTURED_FRAMES_DIR, f"frame_{frame_count}.jpg")
|
70 |
cv2.imwrite(captured_frame_path, frame)
|
71 |
last_detected_images.append(captured_frame_path)
|
72 |
+
if len(last_detected_images) > 100:
|
73 |
+
last_detected_images.pop(0)
|
|
|
|
|
|
|
|
|
74 |
|
75 |
last_frame = frame.copy()
|
76 |
last_metrics = metrics.copy()
|
77 |
|
78 |
# Update logs and stats
|
79 |
+
crack_detected = len([item for item in last_metrics.get('items', []) if item['type'] == 'crack'])
|
80 |
crack_severity_all.extend([
|
81 |
+
item['severity']
|
82 |
+
for item in last_metrics.get('items', [])
|
83 |
+
if item['type'] == 'crack' and 'severity' in item
|
84 |
])
|
85 |
|
86 |
log_entries.append(f"{last_timestamp} - Frame {frame_count} - Cracks: {crack_detected} - GPS: {gps_coord}")
|
|
|
93 |
if len(crack_severity_all) > 500:
|
94 |
crack_severity_all.pop(0)
|
95 |
|
96 |
+
frame = cv2.resize(last_frame, (800, 600))
|
97 |
+
cv2.putText(frame, f"Frame: {frame_count}", (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
98 |
+
cv2.putText(frame, f"{last_timestamp}", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
99 |
|
100 |
+
map_path = generate_map(gps_coordinates[-5:], last_metrics.get('items', []))
|
101 |
|
102 |
return frame[:, :, ::-1], last_metrics, "\n".join(log_entries[-10:]), generate_line_chart(), generate_pie_chart(), last_detected_images, map_path
|
103 |
|
|
|
105 |
def generate_line_chart():
|
106 |
if not crack_counts:
|
107 |
return None
|
108 |
+
fig, ax = plt.subplots(figsize=(6, 3))
|
109 |
+
ax.plot(crack_counts[-50:], marker='o', color='orange')
|
110 |
+
ax.set_title("Cracks Over Time", color='black', fontsize=14)
|
111 |
+
ax.set_xlabel("Frame", color='black', fontsize=12)
|
112 |
+
ax.set_ylabel("Count", color='black', fontsize=12)
|
113 |
+
ax.grid(True, color='pink', linestyle='--', alpha=0.5)
|
114 |
fig.tight_layout()
|
115 |
chart_path = "chart_temp.png"
|
116 |
+
fig.savefig(chart_path, bbox_inches='tight')
|
117 |
plt.close(fig)
|
118 |
return chart_path
|
119 |
|
|
|
121 |
def generate_pie_chart():
|
122 |
if not crack_severity_all:
|
123 |
return None
|
124 |
+
fig, ax = plt.subplots(figsize=(6, 3))
|
125 |
count = Counter(crack_severity_all[-200:])
|
126 |
labels, sizes = zip(*count.items())
|
127 |
+
colors = ['red', 'orange', 'green']
|
128 |
+
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140, textprops={'fontsize': 12, 'color': 'black'})
|
129 |
ax.axis('equal')
|
130 |
fig.tight_layout()
|
131 |
pie_path = "pie_temp.png"
|
132 |
+
fig.savefig(pie_path, bbox_inches='tight')
|
133 |
plt.close(fig)
|
134 |
return pie_path
|
135 |
|
136 |
# Gradio UI
|
137 |
+
with gr.Blocks(theme=custom_theme) as app:
|
138 |
+
gr.Markdown("# 🛣️ Drone Road Inspection Dashboard", _js="document.body.style.backgroundColor = '#f0f0f0';")
|
139 |
+
|
140 |
+
status_text = gr.Markdown("**Status:** 🟢 Running", elem_classes="status-text")
|
141 |
|
142 |
with gr.Row():
|
143 |
with gr.Column(scale=3):
|
144 |
+
video_output = gr.Image(label="Live Drone Feed", width=800, height=600, elem_classes="video-feed")
|
145 |
+
with gr.Column(scale=2):
|
146 |
+
metrics_output = gr.Textbox(label="Crack & Object Metrics", lines=6, elem_classes="metrics-box")
|
147 |
|
148 |
with gr.Row():
|
149 |
+
logs_output = gr.Textbox(label="Live Logs", lines=10, elem_classes="logs-box")
|
150 |
+
chart_output = gr.Image(label="Crack Trend", width=400, height=200)
|
151 |
+
pie_output = gr.Image(label="Crack Severity", width=400, height=200)
|
152 |
|
153 |
with gr.Row():
|
154 |
+
map_output = gr.Image(label="Crack & Object Locations Map", width=800, height=400)
|
155 |
+
captured_images = gr.Gallery(label="Detected Cracks & Objects (Last 100)", columns=5, height=600, object_fit="contain")
|
156 |
|
157 |
with gr.Row():
|
158 |
+
pause_btn = gr.Button("⏸️ Pause", variant="secondary", elem_classes="control-btn")
|
159 |
+
resume_btn = gr.Button("▶️ Resume", variant="primary", elem_classes="control-btn")
|
160 |
+
frame_slider = gr.Slider(0.1, 2, value=0.5, step=0.1, label="Frame Interval (seconds)", elem_classes="slider")
|
161 |
|
162 |
def toggle_pause():
|
163 |
global paused
|