Yaswanth56 commited on
Commit
faec315
·
1 Parent(s): b2d9ea7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -60
app.py CHANGED
@@ -16,6 +16,7 @@ import piexif
16
  import zipfile
17
  from reportlab.lib.pagesizes import letter
18
  from reportlab.pdfgen import canvas
 
19
 
20
  os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
21
  logging.basicConfig(filename="app.log", level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
@@ -44,58 +45,137 @@ model = YOLO('./data/best.pt').to(device)
44
  if device == "cuda":
45
  model.half()
46
 
47
- # Function to generate the PDF report with images and data, each section on a new page
48
- def generate_pdf_report(summary: str, screenshots: List[str], log_results: List[str], chart_path: str, map_path: str, pdf_path: str):
49
  c = canvas.Canvas(pdf_path, pagesize=letter)
50
  width, height = letter
51
-
52
- # Set starting position for content
53
- margin_left = 72
54
- margin_top = height - 72
55
- line_height = 14 # Height of each line of text
56
- y_position = margin_top
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  # Title Page
59
- c.setFont("Helvetica", 16)
 
60
  c.drawString(margin_left, y_position, "Drone Survey Analysis Report")
61
- y_position -= 30 # Space below the title
62
- c.showPage() # Create a new page
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Add Summary Text (New Page)
 
 
 
65
  c.setFont("Helvetica", 12)
66
- c.drawString(margin_left, y_position, "Summary:")
67
- y_position -= line_height
68
- c.drawString(margin_left, y_position, summary)
69
- y_position -= 20 # Space after summary
70
- c.showPage() # Create a new page
71
-
72
- # Add Logs for Top 5 Images (New Page)
73
- c.drawString(margin_left, y_position, "Log Results for Top 5 Images:")
74
- y_position -= line_height
75
- for log in log_results[:5]: # Display top 5 logs
76
- c.drawString(margin_left, y_position, log)
77
  y_position -= line_height
78
- y_position -= 20 # Space after logs
79
- c.showPage() # Create a new page
80
-
81
- # Add Screenshots (Top 5 Images) (New Page)
82
- c.drawString(margin_left, y_position, "Incident Screenshots:")
83
- y_position -= line_height
84
- for screenshot in screenshots[:5]: # Limit to the top 5 images
85
- c.drawImage(screenshot, margin_left, y_position, width=500, height=350) # Adjusted size of images
86
- y_position -= 370 # Space after each image
87
- y_position -= 20 # Space after images
88
- c.showPage() # Create a new page
89
-
90
- # Add Chart Image (New Page)
91
- c.drawString(margin_left, y_position, "Detection Trend Chart:")
92
- c.drawImage(chart_path, margin_left, y_position - 100, width=400, height=300)
93
- y_position -= 300 # Space after chart
94
- c.showPage() # Create a new page
95
-
96
- # Add Map Image (New Page)
97
- c.drawString(margin_left, y_position, "Issue Locations Map:")
98
- c.drawImage(map_path, margin_left, y_position - 100, width=400, height=300)
99
 
100
  c.save()
101
 
@@ -126,7 +206,7 @@ def zip_all_outputs(report_path: str, video_path: str, chart_path: str, map_path
126
 
127
  def generate_map(gps_coords: List[List[float]], items: List[Dict[str, Any]]) -> str:
128
  map_path = os.path.join(OUTPUT_DIR, f"map_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
129
- plt.figure(figsize=(5, 5)) # Adjusted figure size
130
  plt.scatter([x[1] for x in gps_coords], [x[0] for x in gps_coords], c='blue', label='GPS Points')
131
  plt.title("Issue Locations Map")
132
  plt.xlabel("Longitude")
@@ -189,7 +269,7 @@ def update_metrics(detections: List[Dict[str, Any]]) -> Dict[str, Any]:
189
  def generate_line_chart(detections: List[Dict[str, Any]]) -> Optional[str]:
190
  if not detections:
191
  return None
192
- plt.figure(figsize=(5, 3)) # Adjusted figure size
193
  detection_times = [det["frame"] for det in detections]
194
  detection_counts = [det["conf"] for det in detections]
195
  plt.plot(detection_times, detection_counts, marker='o', color='#FF8C00')
@@ -203,10 +283,6 @@ def generate_line_chart(detections: List[Dict[str, Any]]) -> Optional[str]:
203
  plt.close()
204
  return chart_path
205
 
206
- # The rest of the process_video function remains the same as before
207
-
208
-
209
-
210
  def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
211
  global frame_count, last_metrics, detected_counts, detected_issues, gps_coordinates, log_entries
212
  frame_count = 0
@@ -251,6 +327,7 @@ def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
251
  detection_frame_count = 0
252
  output_frame_count = 0
253
  last_annotated_frame = None
 
254
 
255
  while True:
256
  ret, frame = cap.read()
@@ -297,6 +374,8 @@ def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
297
  "path": os.path.join(CAPTURED_FRAMES_DIR, f"detected_{frame_count:06d}.jpg")
298
  })
299
  log_entries.append(f"Frame {frame_count} at {timestamp_str}: Detected {label} with confidence {conf:.2f}")
 
 
300
 
301
  if frame_detections:
302
  detection_frame_count += 1
@@ -305,7 +384,7 @@ def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
305
  if cv2.imwrite(captured_frame_path, annotated_frame):
306
  if write_geotag(captured_frame_path, gps_coord):
307
  detected_issues.append(captured_frame_path)
308
- if len(detected_issues) > 5: # Limit to top 5 images
309
  detected_issues.pop(0)
310
  else:
311
  log_entries.append(f"Frame {frame_count}: Geotagging failed")
@@ -352,20 +431,28 @@ def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
352
  chart_path = generate_line_chart(all_detections)
353
  map_path = generate_map(gps_coordinates[-5:], all_detections)
354
 
355
- # Generate the report
356
  pdf_path = f"{OUTPUT_DIR}/drone_analysis_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
357
- generate_pdf_report("Drone analysis completed. Top 5 detections included.", detected_issues, log_entries, chart_path, map_path, pdf_path)
 
 
 
 
 
 
 
 
358
 
359
  log_entries.append(f"Processing completed in {total_time:.2f} seconds")
360
 
361
  return (
362
- output_path, # Video
363
- json.dumps(last_metrics, indent=2), # Metrics
364
- "\n".join(log_entries[-10:]), # Logs
365
- detected_issues, # Issue gallery
366
- chart_path, # Chart image
367
- map_path, # Map image
368
- pdf_path # PDF file
369
  )
370
 
371
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange")) as iface:
 
16
  import zipfile
17
  from reportlab.lib.pagesizes import letter
18
  from reportlab.pdfgen import canvas
19
+ from reportlab.lib.units import inch
20
 
21
  os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
22
  logging.basicConfig(filename="app.log", level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
 
45
  if device == "cuda":
46
  model.half()
47
 
48
+ def generate_pdf_report(summary: str, screenshots: List[str], log_results: List[str], chart_path: str, map_path: str, pdf_path: str, additional_results: List[str] = None):
 
49
  c = canvas.Canvas(pdf_path, pagesize=letter)
50
  width, height = letter
51
+ margin_left = 0.75 * inch
52
+ margin_right = 0.75 * inch
53
+ margin_top = height - 0.75 * inch
54
+ margin_bottom = 0.75 * inch
55
+ line_height = 14
56
+ max_text_width = width - margin_left - margin_right
57
+ image_width = 5 * inch
58
+ image_height = 3.5 * inch
59
+
60
+ def new_page():
61
+ nonlocal y_position
62
+ c.showPage()
63
+ y_position = margin_top
64
+ c.setFont("Helvetica", 12)
65
+
66
+ def draw_wrapped_text(text, x, y, max_width):
67
+ nonlocal y_position
68
+ words = text.split()
69
+ line = ""
70
+ for word in words:
71
+ test_line = f"{line} {word}".strip()
72
+ if c.stringWidth(test_line, "Helvetica", 12) <= max_width:
73
+ line = test_line
74
+ else:
75
+ if line:
76
+ c.drawString(x, y, line)
77
+ y -= line_height
78
+ if y < margin_bottom:
79
+ new_page()
80
+ y = y_position
81
+ line = word
82
+ else:
83
+ c.drawString(x, y, word)
84
+ y -= line_height
85
+ if y < margin_bottom:
86
+ new_page()
87
+ y = y_position
88
+ if line:
89
+ c.drawString(x, y, line)
90
+ y -= line_height
91
+ return y
92
 
93
  # Title Page
94
+ y_position = margin_top
95
+ c.setFont("Helvetica-Bold", 16)
96
  c.drawString(margin_left, y_position, "Drone Survey Analysis Report")
97
+ c.setFont("Helvetica", 12)
98
+ y_position -= 30
99
+ c.drawString(margin_left, y_position, f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
100
+ new_page()
101
+
102
+ # Summary Page
103
+ c.setFont("Helvetica-Bold", 14)
104
+ c.drawString(margin_left, y_position, "Summary")
105
+ y_position -= line_height * 1.5
106
+ c.setFont("Helvetica", 12)
107
+ y_position = draw_wrapped_text(summary, margin_left, y_position, max_text_width)
108
+ y_position -= 20
109
+ new_page()
110
+
111
+ # Log Results Page
112
+ c.setFont("Helvetica-Bold", 14)
113
+ c.drawString(margin_left, y_position, "Log Results for Top 5 Images")
114
+ y_position -= line_height * 1.5
115
+ c.setFont("Helvetica", 12)
116
+ for log in log_results[:5]:
117
+ y_position = draw_wrapped_text(log, margin_left, y_position, max_text_width)
118
+ y_position -= line_height
119
+ if y_position < margin_bottom:
120
+ new_page()
121
+ y_position -= 20
122
+ new_page()
123
+
124
+ # Screenshots Page
125
+ c.setFont("Helvetica-Bold", 14)
126
+ c.drawString(margin_left, y_position, "Incident Screenshots")
127
+ y_position -= line_height * 1.5
128
+ c.setFont("Helvetica", 12)
129
+ for screenshot in screenshots[:5]:
130
+ if os.path.exists(screenshot):
131
+ c.drawImage(screenshot, margin_left, y_position - image_height, width=image_width, height=image_height, preserveAspectRatio=True)
132
+ y_position -= image_height + 20
133
+ if y_position < margin_bottom:
134
+ new_page()
135
+ else:
136
+ y_position = draw_wrapped_text(f"Image not found: {screenshot}", margin_left, y_position, max_text_width)
137
+ y_position -= line_height
138
+ if y_position < margin_bottom:
139
+ new_page()
140
+ new_page()
141
+
142
+ # Chart Page
143
+ c.setFont("Helvetica-Bold", 14)
144
+ c.drawString(margin_left, y_position, "Detection Trend Chart")
145
+ y_position -= line_height * 1.5
146
+ c.setFont("Helvetica", 12)
147
+ if os.path.exists(chart_path):
148
+ c.drawImage(chart_path, margin_left, y_position - 4 * inch, width=4 * inch, height=3 * inch, preserveAspectRatio=True)
149
+ y_position -= 4 * inch + 20
150
+ else:
151
+ y_position = draw_wrapped_text("Chart not found", margin_left, y_position, max_text_width)
152
+ y_position -= line_height
153
+ new_page()
154
 
155
+ # Map Page
156
+ c.setFont("Helvetica-Bold", 14)
157
+ c.drawString(margin_left, y_position, "Issue Locations Map")
158
+ y_position -= line_height * 1.5
159
  c.setFont("Helvetica", 12)
160
+ if os.path.exists(map_path):
161
+ c.drawImage(map_path, margin_left, y_position - 4 * inch, width=4 * inch, height=3 * inch, preserveAspectRatio=True)
162
+ y_position -= 4 * inch + 20
163
+ else:
164
+ y_position = draw_wrapped_text("Map not found", margin_left, y_position, max_text_width)
 
 
 
 
 
 
165
  y_position -= line_height
166
+ new_page()
167
+
168
+ # Additional Results Page
169
+ if additional_results:
170
+ c.setFont("Helvetica-Bold", 14)
171
+ c.drawString(margin_left, y_position, "Additional Analysis Results")
172
+ y_position -= line_height * 1.5
173
+ c.setFont("Helvetica", 12)
174
+ for result in additional_results:
175
+ y_position = draw_wrapped_text(result, margin_left, y_position, max_text_width)
176
+ y_position -= line_height
177
+ if y_position < margin_bottom:
178
+ new_page()
 
 
 
 
 
 
 
 
179
 
180
  c.save()
181
 
 
206
 
207
  def generate_map(gps_coords: List[List[float]], items: List[Dict[str, Any]]) -> str:
208
  map_path = os.path.join(OUTPUT_DIR, f"map_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
209
+ plt.figure(figsize=(5, 5))
210
  plt.scatter([x[1] for x in gps_coords], [x[0] for x in gps_coords], c='blue', label='GPS Points')
211
  plt.title("Issue Locations Map")
212
  plt.xlabel("Longitude")
 
269
  def generate_line_chart(detections: List[Dict[str, Any]]) -> Optional[str]:
270
  if not detections:
271
  return None
272
+ plt.figure(figsize=(5, 3))
273
  detection_times = [det["frame"] for det in detections]
274
  detection_counts = [det["conf"] for det in detections]
275
  plt.plot(detection_times, detection_counts, marker='o', color='#FF8C00')
 
283
  plt.close()
284
  return chart_path
285
 
 
 
 
 
286
  def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
287
  global frame_count, last_metrics, detected_counts, detected_issues, gps_coordinates, log_entries
288
  frame_count = 0
 
327
  detection_frame_count = 0
328
  output_frame_count = 0
329
  last_annotated_frame = None
330
+ additional_results = []
331
 
332
  while True:
333
  ret, frame = cap.read()
 
374
  "path": os.path.join(CAPTURED_FRAMES_DIR, f"detected_{frame_count:06d}.jpg")
375
  })
376
  log_entries.append(f"Frame {frame_count} at {timestamp_str}: Detected {label} with confidence {conf:.2f}")
377
+ if label == "Pothole":
378
+ additional_results.append(f"Pothole detected with quality score: {conf:.2f}")
379
 
380
  if frame_detections:
381
  detection_frame_count += 1
 
384
  if cv2.imwrite(captured_frame_path, annotated_frame):
385
  if write_geotag(captured_frame_path, gps_coord):
386
  detected_issues.append(captured_frame_path)
387
+ if len(detected_issues) > 5:
388
  detected_issues.pop(0)
389
  else:
390
  log_entries.append(f"Frame {frame_count}: Geotagging failed")
 
431
  chart_path = generate_line_chart(all_detections)
432
  map_path = generate_map(gps_coordinates[-5:], all_detections)
433
 
434
+ # Generate the report with additional results
435
  pdf_path = f"{OUTPUT_DIR}/drone_analysis_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
436
+ generate_pdf_report(
437
+ "Drone analysis completed. Top 5 detections included.",
438
+ detected_issues,
439
+ log_entries,
440
+ chart_path,
441
+ map_path,
442
+ pdf_path,
443
+ additional_results
444
+ )
445
 
446
  log_entries.append(f"Processing completed in {total_time:.2f} seconds")
447
 
448
  return (
449
+ output_path,
450
+ json.dumps(last_metrics, indent=2),
451
+ "\n".join(log_entries[-10:]),
452
+ detected_issues,
453
+ chart_path,
454
+ map_path,
455
+ pdf_path
456
  )
457
 
458
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange")) as iface: