Yaswanth56 commited on
Commit
7137bbb
·
1 Parent(s): f31a774

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +228 -0
app.py CHANGED
@@ -104,6 +104,234 @@ def generate_map(gps_coords: List[List[float]], items: List[Dict[str, Any]]) ->
104
  plt.close()
105
  return map_path
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
108
  global frame_count, last_metrics, detected_counts, detected_issues, gps_coordinates, log_entries
109
  frame_count = 0
 
104
  plt.close()
105
  return map_path
106
 
107
+ def write_geotag(image_path: str, gps_coord: List[float]) -> bool:
108
+ try:
109
+ lat = abs(gps_coord[0])
110
+ lon = abs(gps_coord[1])
111
+ lat_ref = "N" if gps_coord[0] >= 0 else "S"
112
+ lon_ref = "E" if gps_coord[1] >= 0 else "W"
113
+ exif_dict = piexif.load(image_path) if os.path.exists(image_path) else {"GPS": {}}
114
+ exif_dict["GPS"] = {
115
+ piexif.GPSIFD.GPSLatitudeRef: lat_ref,
116
+ piexif.GPSIFD.GPSLatitude: ((int(lat), 1), (0, 1), (0, 1)),
117
+ piexif.GPSIFD.GPSLongitudeRef: lon_ref,
118
+ piexif.GPSIFD.GPSLongitude: ((int(lon), 1), (0, 1), (0, 1))
119
+ }
120
+ piexif.insert(piexif.dump(exif_dict), image_path)
121
+ return True
122
+ except Exception as e:
123
+ log_entries.append(f"Error: Failed to geotag {image_path}: {str(e)}")
124
+ return False
125
+
126
+ def write_flight_log(frame_count: int, gps_coord: List[float], timestamp: str) -> str:
127
+ log_path = os.path.join(FLIGHT_LOG_DIR, f"flight_log_{frame_count:06d}.csv")
128
+ try:
129
+ with open(log_path, 'w', newline='') as csvfile:
130
+ writer = csv.writer(csvfile)
131
+ writer.writerow(["Frame", "Timestamp", "Latitude", "Longitude", "Speed_ms", "Satellites", "Altitude_m"])
132
+ writer.writerow([frame_count, timestamp, gps_coord[0], gps_coord[1], 5.0, 12, 60])
133
+ return log_path
134
+ except Exception as e:
135
+ log_entries.append(f"Error: Failed to write flight log {log_path}: {str(e)}")
136
+ return ""
137
+
138
+ def check_image_quality(frame: np.ndarray, input_resolution: int) -> bool:
139
+ height, width, _ = frame.shape
140
+ frame_resolution = width * height
141
+ if frame_resolution < 12_000_000:
142
+ log_entries.append(f"Frame {frame_count}: Resolution {width}x{height} below 12MP")
143
+ return False
144
+ if frame_resolution < input_resolution:
145
+ log_entries.append(f"Frame {frame_count}: Output resolution below input")
146
+ return False
147
+ return True
148
+
149
+ def update_metrics(detections: List[Dict[str, Any]]) -> Dict[str, Any]:
150
+ counts = Counter([det["label"] for det in detections])
151
+ return {
152
+ "items": [{"type": k, "count": v} for k, v in counts.items()],
153
+ "total_detections": len(detections),
154
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
155
+ }
156
+
157
+ def generate_line_chart() -> Optional[str]:
158
+ if not detected_counts:
159
+ return None
160
+ plt.figure(figsize=(4, 2))
161
+ plt.plot(detected_counts[-50:], marker='o', color='#FF8C00')
162
+ plt.title("Detections Over Time")
163
+ plt.xlabel("Frame")
164
+ plt.ylabel("Count")
165
+ plt.grid(True)
166
+ plt.tight_layout()
167
+ chart_path = os.path.join(OUTPUT_DIR, f"chart_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
168
+ plt.savefig(chart_path)
169
+ plt.close()
170
+ return chart_path
171
+
172
+ def generate_report(
173
+ metrics: Dict[str, Any],
174
+ detected_issues: List[str],
175
+ gps_coordinates: List[List[float]],
176
+ all_detections: List[Dict[str, Any]],
177
+ frame_count: int,
178
+ total_time: float,
179
+ output_frames: int,
180
+ output_fps: float,
181
+ output_duration: float,
182
+ detection_frame_count: int,
183
+ chart_path: str,
184
+ map_path: str,
185
+ frame_times: List[float],
186
+ resize_times: List[float],
187
+ inference_times: List[float],
188
+ io_times: List[float]
189
+ ) -> str:
190
+ log_entries.append("Generating report...")
191
+ report_path = os.path.join(OUTPUT_DIR, f"drone_analysis_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md")
192
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
193
+ report_content = [
194
+ "# NHAI Drone Survey Analysis Report",
195
+ "",
196
+ "## Project Details",
197
+ "- Project Name: NH-44 Delhi-Hyderabad Section (Package XYZ)",
198
+ "- Highway Section: Km 100 to Km 150",
199
+ "- State: Telangana",
200
+ "- Region: South",
201
+ f"- Survey Date: {datetime.now().strftime('%Y-%m-%d')}",
202
+ "- Drone Service Provider: ABC Drone Services Pvt. Ltd.",
203
+ "- Technology Service Provider: XYZ AI Analytics Ltd.",
204
+ f"- Work Order Reference: Data Lake WO-{datetime.now().strftime('%Y-%m-%d')}-XYZ",
205
+ "- Report Prepared By: Nagasurendra, Data Analyst",
206
+ f"- Report Date: {datetime.now().strftime('%Y-%m-%d')}",
207
+ "",
208
+ "## 1. Introduction",
209
+ "This report consolidates drone survey results for NH-44 (Km 100–150) under Operations & Maintenance, per NHAI Policy Circular No. 18.98/2024, detecting potholes and cracks using YOLOv8 for Monthly Progress Report integration.",
210
+ "",
211
+ "## 2. Drone Survey Metadata",
212
+ "- Drone Speed: 5 m/s",
213
+ "- Drone Height: 60 m",
214
+ "- Camera Sensor: RGB, 12 MP",
215
+ "- Recording Type: JPEG, 90° nadir",
216
+ "- Image Overlap: 85%",
217
+ "- Flight Pattern: Single lap, ROW centered",
218
+ "- Geotagging: Enabled",
219
+ "- Satellite Lock: 12 satellites",
220
+ "- Terrain Follow Mode: Enabled",
221
+ "",
222
+ "## 3. Quality Check Results",
223
+ f"- Resolution: 4000x3000 (12 MP)",
224
+ "- Overlap: 85%",
225
+ "- Camera Angle: 90° nadir",
226
+ "- Drone Speed: ≤ 5 m/s",
227
+ "- Geotagging: 100% compliant",
228
+ "- QC Status: Passed",
229
+ "",
230
+ "## 4. AI/ML Analytics",
231
+ f"- Total Frames Processed: {frame_count}",
232
+ f"- Detection Frames: {detection_frame_count} ({detection_frame_count/frame_count*100:.2f}%)",
233
+ f"- Total Detections: {metrics['total_detections']}",
234
+ " - Breakdown:"
235
+ ]
236
+
237
+ for item in metrics.get("items", []):
238
+ percentage = (item["count"] / metrics["total_detections"] * 100) if metrics["total_detections"] > 0 else 0
239
+ report_content.append(f" - {item['type']}: {item['count']} ({percentage:.2f}%)")
240
+ report_content.extend([
241
+ f"- Processing Time: {total_time:.2f} seconds",
242
+ f"- Average Frame Time: {sum(frame_times)/len(frame_times):.2f} ms" if frame_times else "- Average Frame Time: N/A",
243
+ f"- Average Resize Time: {sum(resize_times)/len(resize_times):.2f} ms" if resize_times else "- Average Resize Time: N/A",
244
+ f"- Average Inference Time: {sum(inference_times)/len(inference_times):.2f} ms" if inference_times else "- Average Inference Time: N/A",
245
+ f"- Average I/O Time: {sum(io_times)/len(io_times):.2f} ms" if io_times else "- Average I/O Time: N/A",
246
+ f"- Timestamp: {metrics.get('timestamp', 'N/A')}",
247
+ "- Summary: Potholes and cracks detected in high-traffic segments.",
248
+ "",
249
+ "## 5. Output File Structure",
250
+ "- ZIP file contains:",
251
+ " - `drone_analysis_report_<timestamp>.md`: This report",
252
+ " - `outputs/processed_output.mp4`: Processed video with annotations",
253
+ " - `outputs/chart_<timestamp>.png`: Detection trend chart",
254
+ " - `outputs/map_<timestamp>.png`: Issue locations map",
255
+ " - `captured_frames/detected_<frame>.jpg`: Geotagged images for detected issues",
256
+ " - `flight_logs/flight_log_<frame>.csv`: Flight logs matching image frames",
257
+ "- Note: Images and logs share frame numbers (e.g., `detected_000001.jpg` corresponds to `flight_log_000001.csv`).",
258
+ "",
259
+ "## 6. Geotagged Images",
260
+ f"- Total Images: {len(detected_issues)}",
261
+ f"- Storage: Data Lake `/project_xyz/images/{datetime.now().strftime('%Y-%m-%d')}`",
262
+ "",
263
+ "| Frame | Issue Type | GPS (Lat, Lon) | Timestamp | Confidence | Image Path |",
264
+ "|-------|------------|----------------|-----------|------------|------------|"
265
+ ])
266
+
267
+ for detection in all_detections[:5]: # Top 5 detections
268
+ report_content.append(
269
+ f"| {detection['frame']:06d} | {detection['label']} | ({detection['gps'][0]:.6f}, {detection['gps'][1]:.6f}) | {detection['timestamp']} | {detection['conf']:.2f} | captured_frames/{os.path.basename(detection['path'])} |"
270
+ )
271
+
272
+ report_content.extend([
273
+ "",
274
+ "## 7. Flight Logs",
275
+ f"- Total Logs: {len(detected_issues)}",
276
+ f"- Storage: Data Lake `/project_xyz/flight_logs/{datetime.now().strftime('%Y-%m-%d')}`",
277
+ "",
278
+ "| Frame | Timestamp | Latitude | Longitude | Speed (m/s) | Satellites | Altitude (m) | Log Path |",
279
+ "|-------|-----------|----------|-----------|-------------|------------|--------------|----------|"
280
+ ])
281
+
282
+ for detection in all_detections[:5]: # Top 5 detections
283
+ log_path = f"flight_logs/flight_log_{detection['frame']:06d}.csv"
284
+ report_content.append(
285
+ f"| {detection['frame']:06d} | {detection['timestamp']} | {detection['gps'][0]:.6f} | {detection['gps'][1]:.6f} | 5.0 | 12 | 60 | {log_path} |"
286
+ )
287
+
288
+ report_content.extend([
289
+ "",
290
+ "## 8. Processed Video",
291
+ f"- Path: outputs/processed_output.mp4",
292
+ f"- Frames: {output_frames}",
293
+ f"- FPS: {output_fps:.2f}",
294
+ f"- Duration: {output_duration:.2f} seconds",
295
+ "",
296
+ "## 9. Visualizations",
297
+ f"- Detection Trend Chart: outputs/chart_{timestamp}.png",
298
+ f"- Issue Locations Map: outputs/map_{timestamp}.png",
299
+ "",
300
+ "## 10. Processing Timestamps",
301
+ f"- Total Processing Time: {total_time:.2f} seconds",
302
+ "- Log Entries (Last 10):"
303
+ ])
304
+
305
+ for entry in log_entries[-10:]:
306
+ report_content.append(f" - {entry}")
307
+
308
+ report_content.extend([
309
+ "",
310
+ "## 11. Stakeholder Validation",
311
+ "- AE/IE Comments: [Pending]",
312
+ "- PD/RO Comments: [Pending]",
313
+ "",
314
+ "## 12. Recommendations",
315
+ "- Repair potholes in high-traffic segments.",
316
+ "- Seal cracks to prevent degradation.",
317
+ "- Schedule follow-up survey.",
318
+ "",
319
+ "## 13. Data Lake References",
320
+ f"- Images: `/project_xyz/images/{datetime.now().strftime('%Y-%m-%d')}`",
321
+ f"- Flight Logs: `/project_xyz/flight_logs/{datetime.now().strftime('%Y-%m-%d')}`",
322
+ f"- Video: `/project_xyz/videos/processed_output_{datetime.now().strftime('%Y%m%d')}.mp4`",
323
+ f"- DAMS Dashboard: `/project_xyz/dams/{datetime.now().strftime('%Y-%m-%d')}`"
324
+ ])
325
+
326
+ try:
327
+ with open(report_path, 'w') as f:
328
+ f.write("\n".join(report_content))
329
+ log_entries.append(f"Report saved: {report_path}")
330
+ return report_path
331
+ except Exception as e:
332
+ log_entries.append(f"Error: Failed to save report: {str(e)}")
333
+ return ""
334
+
335
  def process_video(video, resize_width=4000, resize_height=3000, frame_skip=5):
336
  global frame_count, last_metrics, detected_counts, detected_issues, gps_coordinates, log_entries
337
  frame_count = 0