lokesh341 commited on
Commit
43bba30
·
1 Parent(s): 464d88b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -40
app.py CHANGED
@@ -7,18 +7,28 @@ import random
7
  from datetime import datetime
8
  from collections import Counter
9
  from services.video_service import get_next_video_frame, reset_video_index, preload_video, release_video
10
- from services.crack_detection_service import detect_cracks_and_objects
11
- from services.overlay_service import overlay_boxes
12
  from services.metrics_service import update_metrics
 
13
  from services.salesforce_dispatcher import dispatch_to_salesforce
 
 
14
  # Under Construction services
15
  from services.under_construction.earthwork_detection import process_earthwork
16
  from services.under_construction.culvert_check import process_culverts
17
  from services.under_construction.bridge_pier_check import process_bridge_piers
18
- # Original services
19
- from services.detection_service import process_frame as process_generic
20
- from services.shadow_detection import detect_shadows
21
- from services.thermal_service import process_thermal
 
 
 
 
 
 
 
 
22
 
23
  # Globals
24
  paused = False
@@ -33,7 +43,12 @@ last_timestamp = ""
33
  last_detected_images = [] # Store up to 100+ crack images
34
  gps_coordinates = []
35
  video_loaded = False
36
- enable_under_construction = False # Toggle for under_construction services
 
 
 
 
 
37
 
38
  # Constants
39
  DEFAULT_VIDEO_PATH = "sample.mp4"
@@ -60,14 +75,14 @@ def initialize_video(video_file=None):
60
  log_entries.append(status)
61
  return status
62
 
63
- def toggle_under_construction(value):
64
  """
65
- Toggle the under_construction services.
66
  """
67
- global enable_under_construction
68
- enable_under_construction = value
69
- log_entries.append(f"Under Construction Services {'Enabled' if value else 'Disabled'}")
70
- return f"Under Construction Services: {'Enabled' if value else 'Disabled'}"
71
 
72
  def monitor_feed():
73
  """
@@ -92,24 +107,38 @@ def monitor_feed():
92
  # Initialize detected items list
93
  all_detected_items = []
94
 
95
- # Always run crack detection (primary focus)
96
- crack_items = detect_cracks_and_objects(frame)
97
- frame = overlay_boxes(frame, crack_items)
98
- all_detected_items.extend(crack_items)
99
-
100
- # Run Under Construction services if enabled
101
- if enable_under_construction:
102
  earthwork_dets, frame = process_earthwork(frame)
103
  culvert_dets, frame = process_culverts(frame)
104
  bridge_pier_dets, frame = process_bridge_piers(frame)
105
  all_detected_items.extend(earthwork_dets + culvert_dets + bridge_pier_dets)
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  # Fallback: Run generic detection if no items detected
108
  if not all_detected_items:
109
  generic_dets, frame = process_generic(frame)
110
  all_detected_items.extend(generic_dets)
111
 
112
- # Optional: Run shadow detection (only log results for now)
113
  shadow_results = detect_shadows(frame)
114
  shadow_dets = shadow_results["detections"]
115
  frame = shadow_results["frame"]
@@ -130,8 +159,8 @@ def monitor_feed():
130
  gps_coord = [17.385044 + random.uniform(-0.001, 0.001), 78.486671 + frame_count * 0.0001]
131
  gps_coordinates.append(gps_coord)
132
 
133
- # Save frame if cracks are detected
134
- if any(item['type'] == 'crack' for item in crack_items):
135
  captured_frame_path = os.path.join(CAPTURED_FRAMES_DIR, f"crack_{frame_count}.jpg")
136
  cv2.imwrite(captured_frame_path, frame)
137
  last_detected_images.append(captured_frame_path)
@@ -159,13 +188,15 @@ def monitor_feed():
159
  last_frame = frame.copy()
160
  last_detections = metrics
161
 
162
- # Update logs and stats
163
- crack_detected = len([item for item in crack_items if item['type'] == 'crack'])
164
- crack_severity_all.extend([
165
- item['severity']
166
- for item in crack_items
167
- if item['type'] == 'crack' and 'severity' in item
168
- ])
 
 
169
 
170
  log_entries.append(f"{last_timestamp} - Frame {frame_count} - Cracks: {crack_detected} - Total Detections: {len(all_detected_items)} - GPS: {gps_coord} - Avg Conf: {metrics['avg_confidence']:.2f}")
171
  crack_counts.append(crack_detected)
@@ -182,9 +213,12 @@ def monitor_feed():
182
  cv2.putText(frame, f"Frame: {frame_count}", (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
183
  cv2.putText(frame, f"{last_timestamp}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
184
 
185
- # Generate charts
186
- line_chart = generate_line_chart()
187
- pie_chart = generate_pie_chart()
 
 
 
188
 
189
  return frame[:, :, ::-1], json.dumps(last_detections, indent=2), "\n".join(log_entries[-10:]), line_chart, pie_chart, last_detected_images
190
 
@@ -285,10 +319,20 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
285
  load_button = gr.Button("Load Video")
286
  video_status = gr.Textbox(label="Video Load Status", value="Please upload a video file or ensure 'sample.mp4' exists in the root directory.")
287
 
288
- # Toggle for Under Construction services
289
  with gr.Row():
290
- under_construction_toggle = gr.Checkbox(label="Enable Under Construction Services", value=False)
291
- toggle_status = gr.Textbox(label="Toggle Status", value="Under Construction Services: Disabled")
 
 
 
 
 
 
 
 
 
 
292
 
293
  status_text = gr.Markdown("**Status:** 🟢 Ready (Upload a video to start)")
294
 
@@ -335,10 +379,25 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
335
  outputs=[video_status]
336
  )
337
 
338
- under_construction_toggle.change(
339
- toggle_under_construction,
340
- inputs=[under_construction_toggle],
341
- outputs=[toggle_status]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
  )
343
 
344
  pause_btn.click(toggle_pause, outputs=status_text)
 
7
  from datetime import datetime
8
  from collections import Counter
9
  from services.video_service import get_next_video_frame, reset_video_index, preload_video, release_video
10
+ from services.detection_service import process_frame as process_generic
 
11
  from services.metrics_service import update_metrics
12
+ from services.overlay_service import overlay_boxes
13
  from services.salesforce_dispatcher import dispatch_to_salesforce
14
+ from services.shadow_detection import detect_shadows
15
+ from services.thermal_service import process_thermal
16
  # Under Construction services
17
  from services.under_construction.earthwork_detection import process_earthwork
18
  from services.under_construction.culvert_check import process_culverts
19
  from services.under_construction.bridge_pier_check import process_bridge_piers
20
+ # Operations Maintenance services
21
+ from services.operations_maintenance.crack_detection import detect_cracks_and_objects
22
+ from services.operations_maintenance.pothole_detection import process_potholes
23
+ from services.operations_maintenance.signage_check import process_signages
24
+ # Road Safety services
25
+ from services.road_safety.barrier_check import process_barriers
26
+ from services.road_safety.lighting_check import process_lighting
27
+ from services.road_safety.accident_spot_check import process_accident_spots
28
+ # Plantation services
29
+ from services.plantation.plant_count import process_plants
30
+ from services.plantation.plant_health import process_plant_health
31
+ from services.plantation.missing_patch_check import process_missing_patches
32
 
33
  # Globals
34
  paused = False
 
43
  last_detected_images = [] # Store up to 100+ crack images
44
  gps_coordinates = []
45
  video_loaded = False
46
+ service_toggles = {
47
+ "under_construction": False,
48
+ "operations_maintenance": True, # Default to crack detection focus
49
+ "road_safety": False,
50
+ "plantation": False
51
+ }
52
 
53
  # Constants
54
  DEFAULT_VIDEO_PATH = "sample.mp4"
 
75
  log_entries.append(status)
76
  return status
77
 
78
+ def toggle_service(service_name, value):
79
  """
80
+ Toggle a service category.
81
  """
82
+ global service_toggles
83
+ service_toggles[service_name] = value
84
+ log_entries.append(f"{service_name.replace('_', ' ').title()} Services {'Enabled' if value else 'Disabled'}")
85
+ return f"{service_name.replace('_', ' ').title()} Services: {'Enabled' if value else 'Disabled'}"
86
 
87
  def monitor_feed():
88
  """
 
107
  # Initialize detected items list
108
  all_detected_items = []
109
 
110
+ # Run services based on toggles
111
+ if service_toggles["under_construction"]:
 
 
 
 
 
112
  earthwork_dets, frame = process_earthwork(frame)
113
  culvert_dets, frame = process_culverts(frame)
114
  bridge_pier_dets, frame = process_bridge_piers(frame)
115
  all_detected_items.extend(earthwork_dets + culvert_dets + bridge_pier_dets)
116
 
117
+ if service_toggles["operations_maintenance"]:
118
+ crack_items = detect_cracks_and_objects(frame)
119
+ frame = overlay_boxes(frame, crack_items)
120
+ pothole_dets, frame = process_potholes(frame)
121
+ signage_dets, frame = process_signages(frame)
122
+ all_detected_items.extend(crack_items + pothole_dets + signage_dets)
123
+
124
+ if service_toggles["road_safety"]:
125
+ barrier_dets, frame = process_barriers(frame)
126
+ lighting_dets, frame = process_lighting(frame)
127
+ accident_dets, frame = process_accident_spots(frame)
128
+ all_detected_items.extend(barrier_dets + lighting_dets + accident_dets)
129
+
130
+ if service_toggles["plantation"]:
131
+ plant_dets, frame = process_plants(frame)
132
+ health_dets, frame = process_plant_health(frame)
133
+ missing_dets, frame = process_missing_patches(frame)
134
+ all_detected_items.extend(plant_dets + health_dets + missing_dets)
135
+
136
  # Fallback: Run generic detection if no items detected
137
  if not all_detected_items:
138
  generic_dets, frame = process_generic(frame)
139
  all_detected_items.extend(generic_dets)
140
 
141
+ # Optional: Run shadow detection
142
  shadow_results = detect_shadows(frame)
143
  shadow_dets = shadow_results["detections"]
144
  frame = shadow_results["frame"]
 
159
  gps_coord = [17.385044 + random.uniform(-0.001, 0.001), 78.486671 + frame_count * 0.0001]
160
  gps_coordinates.append(gps_coord)
161
 
162
+ # Save frame if cracks are detected (only if operations_maintenance is enabled)
163
+ if service_toggles["operations_maintenance"] and any(item['type'] == 'crack' for item in all_detected_items if 'type' in item):
164
  captured_frame_path = os.path.join(CAPTURED_FRAMES_DIR, f"crack_{frame_count}.jpg")
165
  cv2.imwrite(captured_frame_path, frame)
166
  last_detected_images.append(captured_frame_path)
 
188
  last_frame = frame.copy()
189
  last_detections = metrics
190
 
191
+ # Update logs and stats (focus on cracks if operations_maintenance is enabled)
192
+ crack_detected = 0
193
+ if service_toggles["operations_maintenance"]:
194
+ crack_detected = len([item for item in all_detected_items if 'type' in item and item['type'] == 'crack'])
195
+ crack_severity_all.extend([
196
+ item['severity']
197
+ for item in all_detected_items
198
+ if 'type' in item and item['type'] == 'crack' and 'severity' in item
199
+ ])
200
 
201
  log_entries.append(f"{last_timestamp} - Frame {frame_count} - Cracks: {crack_detected} - Total Detections: {len(all_detected_items)} - GPS: {gps_coord} - Avg Conf: {metrics['avg_confidence']:.2f}")
202
  crack_counts.append(crack_detected)
 
213
  cv2.putText(frame, f"Frame: {frame_count}", (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
214
  cv2.putText(frame, f"{last_timestamp}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
215
 
216
+ # Generate charts (only if operations_maintenance is enabled)
217
+ line_chart = None
218
+ pie_chart = None
219
+ if service_toggles["operations_maintenance"]:
220
+ line_chart = generate_line_chart()
221
+ pie_chart = generate_pie_chart()
222
 
223
  return frame[:, :, ::-1], json.dumps(last_detections, indent=2), "\n".join(log_entries[-10:]), line_chart, pie_chart, last_detected_images
224
 
 
319
  load_button = gr.Button("Load Video")
320
  video_status = gr.Textbox(label="Video Load Status", value="Please upload a video file or ensure 'sample.mp4' exists in the root directory.")
321
 
322
+ # Toggles for service categories
323
  with gr.Row():
324
+ with gr.Column():
325
+ uc_toggle = gr.Checkbox(label="Enable Under Construction Services", value=service_toggles["under_construction"])
326
+ uc_status = gr.Textbox(label="Under Construction Status", value="Under Construction Services: Disabled")
327
+ with gr.Column():
328
+ om_toggle = gr.Checkbox(label="Enable Operations Maintenance Services", value=service_toggles["operations_maintenance"])
329
+ om_status = gr.Textbox(label="Operations Maintenance Status", value="Operations Maintenance Services: Enabled")
330
+ with gr.Column():
331
+ rs_toggle = gr.Checkbox(label="Enable Road Safety Services", value=service_toggles["road_safety"])
332
+ rs_status = gr.Textbox(label="Road Safety Status", value="Road Safety Services: Disabled")
333
+ with gr.Column():
334
+ pl_toggle = gr.Checkbox(label="Enable Plantation Services", value=service_toggles["plantation"])
335
+ pl_status = gr.Textbox(label="Plantation Status", value="Plantation Services: Disabled")
336
 
337
  status_text = gr.Markdown("**Status:** 🟢 Ready (Upload a video to start)")
338
 
 
379
  outputs=[video_status]
380
  )
381
 
382
+ uc_toggle.change(
383
+ toggle_service,
384
+ inputs=[gr.State("under_construction"), uc_toggle],
385
+ outputs=[uc_status]
386
+ )
387
+ om_toggle.change(
388
+ toggle_service,
389
+ inputs=[gr.State("operations_maintenance"), om_toggle],
390
+ outputs=[om_status]
391
+ )
392
+ rs_toggle.change(
393
+ toggle_service,
394
+ inputs=[gr.State("road_safety"), rs_toggle],
395
+ outputs=[rs_status]
396
+ )
397
+ pl_toggle.change(
398
+ toggle_service,
399
+ inputs=[gr.State("plantation"), pl_toggle],
400
+ outputs=[pl_status]
401
  )
402
 
403
  pause_btn.click(toggle_pause, outputs=status_text)