Abs6187 commited on
Commit
a4c7d4c
Β·
verified Β·
1 Parent(s): 108578b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +328 -329
app.py CHANGED
@@ -1,329 +1,328 @@
1
- """
2
- Vehicle Speed Estimation and Counting - Gradio Interface
3
- =========================================================
4
-
5
- A real-time vehicle detection, tracking, counting, and speed estimation system
6
- using YOLO object detection and perspective transformation techniques.
7
-
8
- Authors:
9
- - Abhay Gupta (0205CC221005)
10
- - Aditi Lakhera (0205CC221011)
11
- - Balraj Patel (0205CC221049)
12
- - Bhumika Patel (0205CC221050)
13
-
14
- This application provides an interactive web interface for analyzing traffic videos
15
- and estimating vehicle speeds using computer vision techniques.
16
- """
17
-
18
- import os
19
- import sys
20
- import tempfile
21
- import logging
22
- from pathlib import Path
23
- from typing import Optional, Tuple
24
-
25
- import gradio as gr
26
- import cv2
27
- import numpy as np
28
-
29
- # Configure logging
30
- logging.basicConfig(
31
- level=logging.INFO,
32
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
33
- )
34
- logger = logging.getLogger(__name__)
35
-
36
- # Import application modules
37
- try:
38
- from main import process_video
39
- from config import VehicleDetectionConfig
40
- except ImportError as e:
41
- logger.error(f"Failed to import required modules: {e}")
42
- raise
43
-
44
-
45
- def validate_video_file(video_path: str) -> Tuple[bool, str]:
46
- """
47
- Validate uploaded video file.
48
-
49
- Args:
50
- video_path: Path to video file
51
-
52
- Returns:
53
- Tuple of (is_valid, error_message)
54
- """
55
- if not video_path:
56
- return False, "No video file provided"
57
-
58
- if not os.path.exists(video_path):
59
- return False, f"Video file not found: {video_path}"
60
-
61
- # Check file size (limit to 100MB for HF Spaces)
62
- file_size_mb = os.path.getsize(video_path) / (1024 * 1024)
63
- if file_size_mb > 100:
64
- return False, f"Video file too large ({file_size_mb:.1f}MB). Maximum size is 100MB"
65
-
66
- # Validate video can be opened
67
- try:
68
- cap = cv2.VideoCapture(video_path)
69
- if not cap.isOpened():
70
- return False, "Unable to open video file. Please ensure it's a valid video format"
71
-
72
- # Check if video has frames
73
- ret, _ = cap.read()
74
- cap.release()
75
-
76
- if not ret:
77
- return False, "Video file appears to be empty or corrupted"
78
-
79
- return True, ""
80
- except Exception as e:
81
- return False, f"Error validating video: {str(e)}"
82
-
83
-
84
- def estimate_vehicle_speed(
85
- video_file: str,
86
- model_choice: str,
87
- line_position: int,
88
- confidence_threshold: float,
89
- progress=gr.Progress()
90
- ) -> Tuple[Optional[str], str]:
91
- """
92
- Process video and estimate vehicle speeds.
93
-
94
- Args:
95
- video_file: Path to uploaded video
96
- model_choice: YOLO model selection
97
- line_position: Y-coordinate for counting line
98
- confidence_threshold: Detection confidence threshold
99
- progress: Gradio progress tracker
100
-
101
- Returns:
102
- Tuple of (output_video_path, statistics_text)
103
- """
104
- try:
105
- # Validate input
106
- progress(0, desc="Validating video file...")
107
- is_valid, error_msg = validate_video_file(video_file)
108
- if not is_valid:
109
- logger.error(f"Video validation failed: {error_msg}")
110
- return None, f"❌ Error: {error_msg}"
111
-
112
- # Create temporary output file
113
- output_path = tempfile.mktemp(suffix='.mp4')
114
-
115
- # Configure processing
116
- progress(0.1, desc="Configuring detection parameters...")
117
- config = VehicleDetectionConfig(
118
- input_video=video_file,
119
- output_video=output_path,
120
- model_name=model_choice,
121
- line_y=line_position,
122
- confidence_threshold=confidence_threshold
123
- )
124
-
125
- # Process video
126
- progress(0.2, desc="Processing video (this may take a few minutes)...")
127
- logger.info(f"Starting video processing: {video_file}")
128
-
129
- try:
130
- stats = process_video(
131
- config=config,
132
- progress_callback=lambda p: progress(0.2 + p * 0.7, desc=f"Processing... {int(p*100)}%")
133
- )
134
-
135
- progress(0.95, desc="Finalizing output...")
136
-
137
- # Format statistics
138
- stats_text = f"""
139
- ## πŸ“Š Processing Results
140
-
141
- ### Vehicle Count Statistics
142
- - **Total Vehicles Detected:** {stats['total_count']}
143
- - **Vehicles Entering (In):** {stats['in_count']}
144
- - **Vehicles Exiting (Out):** {stats['out_count']}
145
-
146
- ### Speed Analysis
147
- - **Average Speed:** {stats['avg_speed']:.1f} km/h
148
- - **Maximum Speed:** {stats['max_speed']:.1f} km/h
149
- - **Minimum Speed:** {stats['min_speed']:.1f} km/h
150
-
151
- ### Processing Information
152
- - **Frames Processed:** {stats['frames_processed']}
153
- - **Processing Time:** {stats['processing_time']:.2f} seconds
154
- - **Model Used:** {model_choice}
155
- - **Detection Confidence:** {confidence_threshold:.2f}
156
-
157
- βœ… **Processing completed successfully!**
158
- """
159
-
160
- progress(1.0, desc="Complete!")
161
- logger.info("Video processing completed successfully")
162
- return output_path, stats_text
163
-
164
- except Exception as e:
165
- logger.error(f"Error during video processing: {e}", exc_info=True)
166
- return None, f"❌ **Processing Error:** {str(e)}\n\nPlease try with different settings or a different video."
167
-
168
- except Exception as e:
169
- logger.error(f"Unexpected error in estimate_vehicle_speed: {e}", exc_info=True)
170
- return None, f"❌ **Unexpected Error:** {str(e)}"
171
-
172
-
173
- def create_demo_interface() -> gr.Blocks:
174
- """
175
- Create Gradio interface for vehicle speed estimation.
176
-
177
- Returns:
178
- Gradio Blocks interface
179
- """
180
- with gr.Blocks(
181
- title="Vehicle Speed Estimation & Counting",
182
- theme=gr.themes.Soft()
183
- ) as demo:
184
-
185
- gr.Markdown("""
186
- # πŸš— Vehicle Speed Estimation & Counting System
187
-
188
- An intelligent traffic analysis system that detects, tracks, counts, and estimates the speed of vehicles in video footage using advanced computer vision techniques.
189
-
190
- ### 🎯 Features
191
- - **Real-time Vehicle Detection** using YOLO
192
- - **Multi-Object Tracking** with ByteTrack
193
- - **Accurate Speed Estimation** via perspective transformation
194
- - **Vehicle Counting** with configurable detection zones
195
-
196
- ### πŸ‘₯ Developed By
197
- - **Abhay Gupta** (0205CC221005)
198
- - **Aditi Lakhera** (0205CC221011)
199
- - **Balraj Patel** (0205CC221049)
200
- - **Bhumika Patel** (0205CC221050)
201
-
202
- ---
203
- """)
204
-
205
- with gr.Row():
206
- with gr.Column(scale=1):
207
- gr.Markdown("### πŸ“€ Input Configuration")
208
-
209
- video_input = gr.Video(
210
- label="Upload Traffic Video",
211
- format="mp4"
212
- )
213
-
214
- with gr.Accordion("βš™οΈ Advanced Settings", open=False):
215
- model_choice = gr.Dropdown(
216
- choices=["yolov8n", "yolov8s", "yolov8m", "yolov8l"],
217
- value="yolov8n",
218
- label="YOLO Model",
219
- info="Larger models are more accurate but slower"
220
- )
221
-
222
- line_position = gr.Slider(
223
- minimum=100,
224
- maximum=1000,
225
- value=480,
226
- step=10,
227
- label="Counting Line Position (Y-coordinate)",
228
- info="Vertical position of the vehicle counting line"
229
- )
230
-
231
- confidence_threshold = gr.Slider(
232
- minimum=0.1,
233
- maximum=0.9,
234
- value=0.3,
235
- step=0.05,
236
- label="Detection Confidence Threshold",
237
- info="Higher values reduce false positives"
238
- )
239
-
240
- process_btn = gr.Button(
241
- "πŸš€ Process Video",
242
- variant="primary",
243
- size="lg"
244
- )
245
-
246
- gr.Markdown("""
247
- ### πŸ“‹ Instructions
248
- 1. Upload a traffic video (MP4 format, max 100MB)
249
- 2. Adjust settings if needed (optional)
250
- 3. Click "Process Video" and wait for results
251
- 4. Download the annotated video with speed estimates
252
-
253
- ### πŸ’‘ Tips
254
- - Use videos with clear vehicle visibility
255
- - Ensure consistent camera angle
256
- - Better lighting improves detection accuracy
257
- """)
258
-
259
- with gr.Column(scale=1):
260
- gr.Markdown("### πŸ“₯ Output Results")
261
-
262
- video_output = gr.Video(
263
- label="Processed Video with Annotations"
264
- )
265
-
266
- stats_output = gr.Markdown(
267
- label="Statistics",
268
- value="*Processing results will appear here...*"
269
- )
270
-
271
- # Example videos section
272
- gr.Markdown("""
273
- ---
274
- ### 🎬 Example Videos
275
- Upload your own traffic video or use sample footage to test the system.
276
- """)
277
-
278
- gr.Examples(
279
- examples=[
280
- ["./data/vehicles.mp4", "yolov8n", 480, 0.3],
281
- ],
282
- inputs=[video_input, model_choice, line_position, confidence_threshold],
283
- outputs=[video_output, stats_output],
284
- fn=estimate_vehicle_speed,
285
- cache_examples=False,
286
- label="Sample Videos"
287
- )
288
-
289
- # Connect processing function
290
- process_btn.click(
291
- fn=estimate_vehicle_speed,
292
- inputs=[video_input, model_choice, line_position, confidence_threshold],
293
- outputs=[video_output, stats_output]
294
- )
295
-
296
- gr.Markdown("""
297
- ---
298
- ### πŸ”¬ Technical Details
299
-
300
- This system uses:
301
- - **YOLO (You Only Look Once)** for real-time object detection
302
- - **ByteTrack** for multi-object tracking across frames
303
- - **Perspective Transformation** for accurate speed calculation
304
- - **OpenCV** for video processing and computer vision operations
305
-
306
- ### πŸ“š References
307
- - [Ultralytics YOLO](https://github.com/ultralytics/ultralytics)
308
- - [Supervision Library](https://github.com/roboflow/supervision)
309
- - [OpenCV](https://opencv.org/)
310
-
311
- ### πŸ“„ License
312
- MIT License - See LICENSE file for details
313
- """)
314
-
315
- return demo
316
-
317
-
318
- if __name__ == "__main__":
319
- try:
320
- logger.info("Starting Vehicle Speed Estimation application...")
321
- demo = create_demo_interface()
322
- demo.launch(
323
- server_name="0.0.0.0",
324
- server_port=7860,
325
- share=False
326
- )
327
- except Exception as e:
328
- logger.error(f"Failed to launch application: {e}", exc_info=True)
329
- sys.exit(1)
 
1
+ """
2
+ Vehicle Speed Estimation and Counting - Gradio Interface
3
+ =========================================================
4
+
5
+ A real-time vehicle detection, tracking, counting, and speed estimation system
6
+ using YOLO object detection and perspective transformation techniques.
7
+
8
+ Authors:
9
+ - Abhay Gupta (0205CC221005)
10
+ - Aditi Lakhera (0205CC221011)
11
+ - Balraj Patel (0205CC221049)
12
+ - Bhumika Patel (0205CC221050)
13
+
14
+ This application provides an interactive web interface for analyzing traffic videos
15
+ and estimating vehicle speeds using computer vision techniques.
16
+ """
17
+
18
+ import os
19
+ import sys
20
+ import tempfile
21
+ import logging
22
+ from pathlib import Path
23
+ from typing import Optional, Tuple
24
+
25
+ import gradio as gr
26
+ import cv2
27
+ import numpy as np
28
+
29
+ # Configure logging
30
+ logging.basicConfig(
31
+ level=logging.INFO,
32
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
33
+ )
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # Import application modules
37
+ try:
38
+ from main import process_video
39
+ from config import VehicleDetectionConfig
40
+ except ImportError as e:
41
+ logger.error(f"Failed to import required modules: {e}")
42
+ raise
43
+
44
+
45
+ def validate_video_file(video_path: str) -> Tuple[bool, str]:
46
+ """
47
+ Validate uploaded video file.
48
+
49
+ Args:
50
+ video_path: Path to video file
51
+
52
+ Returns:
53
+ Tuple of (is_valid, error_message)
54
+ """
55
+ if not video_path:
56
+ return False, "No video file provided"
57
+
58
+ if not os.path.exists(video_path):
59
+ return False, f"Video file not found: {video_path}"
60
+
61
+ # Check file size (limit to 100MB for HF Spaces)
62
+ file_size_mb = os.path.getsize(video_path) / (1024 * 1024)
63
+ if file_size_mb > 100:
64
+ return False, f"Video file too large ({file_size_mb:.1f}MB). Maximum size is 100MB"
65
+
66
+ # Validate video can be opened
67
+ try:
68
+ cap = cv2.VideoCapture(video_path)
69
+ if not cap.isOpened():
70
+ return False, "Unable to open video file. Please ensure it's a valid video format"
71
+
72
+ # Check if video has frames
73
+ ret, _ = cap.read()
74
+ cap.release()
75
+
76
+ if not ret:
77
+ return False, "Video file appears to be empty or corrupted"
78
+
79
+ return True, ""
80
+ except Exception as e:
81
+ return False, f"Error validating video: {str(e)}"
82
+
83
+
84
+ def estimate_vehicle_speed(
85
+ video_file: str,
86
+ model_choice: str,
87
+ line_position: int,
88
+ confidence_threshold: float,
89
+ progress=gr.Progress()
90
+ ) -> Tuple[Optional[str], str]:
91
+ """
92
+ Process video and estimate vehicle speeds.
93
+
94
+ Args:
95
+ video_file: Path to uploaded video
96
+ model_choice: YOLO model selection
97
+ line_position: Y-coordinate for counting line
98
+ confidence_threshold: Detection confidence threshold
99
+ progress: Gradio progress tracker
100
+
101
+ Returns:
102
+ Tuple of (output_video_path, statistics_text)
103
+ """
104
+ try:
105
+ # Validate input
106
+ progress(0, desc="Validating video file...")
107
+ is_valid, error_msg = validate_video_file(video_file)
108
+ if not is_valid:
109
+ logger.error(f"Video validation failed: {error_msg}")
110
+ return None, f"❌ Error: {error_msg}"
111
+
112
+ # Create temporary output file
113
+ output_path = tempfile.mktemp(suffix='.mp4')
114
+
115
+ # Configure processing
116
+ progress(0.1, desc="Configuring detection parameters...")
117
+ config = VehicleDetectionConfig(
118
+ input_video=video_file,
119
+ output_video=output_path,
120
+ model_name=model_choice,
121
+ line_y=line_position,
122
+ confidence_threshold=confidence_threshold
123
+ )
124
+
125
+ # Process video
126
+ progress(0.2, desc="Processing video (this may take a few minutes)...")
127
+ logger.info(f"Starting video processing: {video_file}")
128
+
129
+ try:
130
+ stats = process_video(
131
+ config=config,
132
+ progress_callback=lambda p: progress(0.2 + p * 0.7, desc=f"Processing... {int(p*100)}%")
133
+ )
134
+
135
+ progress(0.95, desc="Finalizing output...")
136
+
137
+ # Format statistics
138
+ stats_text = f"""
139
+ ## πŸ“Š Processing Results
140
+
141
+ ### Vehicle Count Statistics
142
+ - **Total Vehicles Detected:** {stats['total_count']}
143
+ - **Vehicles Entering (In):** {stats['in_count']}
144
+ - **Vehicles Exiting (Out):** {stats['out_count']}
145
+
146
+ ### Speed Analysis
147
+ - **Average Speed:** {stats['avg_speed']:.1f} km/h
148
+ - **Maximum Speed:** {stats['max_speed']:.1f} km/h
149
+ - **Minimum Speed:** {stats['min_speed']:.1f} km/h
150
+
151
+ ### Processing Information
152
+ - **Frames Processed:** {stats['frames_processed']}
153
+ - **Processing Time:** {stats['processing_time']:.2f} seconds
154
+ - **Model Used:** {model_choice}
155
+ - **Detection Confidence:** {confidence_threshold:.2f}
156
+
157
+ βœ… **Processing completed successfully!**
158
+ """
159
+
160
+ progress(1.0, desc="Complete!")
161
+ logger.info("Video processing completed successfully")
162
+ return output_path, stats_text
163
+
164
+ except Exception as e:
165
+ logger.error(f"Error during video processing: {e}", exc_info=True)
166
+ return None, f"❌ **Processing Error:** {str(e)}\n\nPlease try with different settings or a different video."
167
+
168
+ except Exception as e:
169
+ logger.error(f"Unexpected error in estimate_vehicle_speed: {e}", exc_info=True)
170
+ return None, f"❌ **Unexpected Error:** {str(e)}"
171
+
172
+
173
+ def create_demo_interface() -> gr.Blocks:
174
+ """
175
+ Create Gradio interface for vehicle speed estimation.
176
+
177
+ Returns:
178
+ Gradio Blocks interface
179
+ """
180
+ with gr.Blocks(
181
+ title="Vehicle Speed Estimation & Counting"
182
+ ) as demo:
183
+
184
+ gr.Markdown("""
185
+ # πŸš— Vehicle Speed Estimation & Counting System
186
+
187
+ An intelligent traffic analysis system that detects, tracks, counts, and estimates the speed of vehicles in video footage using advanced computer vision techniques.
188
+
189
+ ### 🎯 Features
190
+ - **Real-time Vehicle Detection** using YOLO
191
+ - **Multi-Object Tracking** with ByteTrack
192
+ - **Accurate Speed Estimation** via perspective transformation
193
+ - **Vehicle Counting** with configurable detection zones
194
+
195
+ ### πŸ‘₯ Developed By
196
+ - **Abhay Gupta** (0205CC221005)
197
+ - **Aditi Lakhera** (0205CC221011)
198
+ - **Balraj Patel** (0205CC221049)
199
+ - **Bhumika Patel** (0205CC221050)
200
+
201
+ ---
202
+ """)
203
+
204
+ with gr.Row():
205
+ with gr.Column(scale=1):
206
+ gr.Markdown("### πŸ“€ Input Configuration")
207
+
208
+ video_input = gr.Video(
209
+ label="Upload Traffic Video",
210
+ format="mp4"
211
+ )
212
+
213
+ with gr.Accordion("βš™οΈ Advanced Settings", open=False):
214
+ model_choice = gr.Dropdown(
215
+ choices=["yolov8n", "yolov8s", "yolov8m", "yolov8l"],
216
+ value="yolov8n",
217
+ label="YOLO Model",
218
+ info="Larger models are more accurate but slower"
219
+ )
220
+
221
+ line_position = gr.Slider(
222
+ minimum=100,
223
+ maximum=1000,
224
+ value=480,
225
+ step=10,
226
+ label="Counting Line Position (Y-coordinate)",
227
+ info="Vertical position of the vehicle counting line"
228
+ )
229
+
230
+ confidence_threshold = gr.Slider(
231
+ minimum=0.1,
232
+ maximum=0.9,
233
+ value=0.3,
234
+ step=0.05,
235
+ label="Detection Confidence Threshold",
236
+ info="Higher values reduce false positives"
237
+ )
238
+
239
+ process_btn = gr.Button(
240
+ "πŸš€ Process Video",
241
+ variant="primary",
242
+ size="lg"
243
+ )
244
+
245
+ gr.Markdown("""
246
+ ### πŸ“‹ Instructions
247
+ 1. Upload a traffic video (MP4 format, max 100MB)
248
+ 2. Adjust settings if needed (optional)
249
+ 3. Click "Process Video" and wait for results
250
+ 4. Download the annotated video with speed estimates
251
+
252
+ ### πŸ’‘ Tips
253
+ - Use videos with clear vehicle visibility
254
+ - Ensure consistent camera angle
255
+ - Better lighting improves detection accuracy
256
+ """)
257
+
258
+ with gr.Column(scale=1):
259
+ gr.Markdown("### πŸ“₯ Output Results")
260
+
261
+ video_output = gr.Video(
262
+ label="Processed Video with Annotations"
263
+ )
264
+
265
+ stats_output = gr.Markdown(
266
+ label="Statistics",
267
+ value="*Processing results will appear here...*"
268
+ )
269
+
270
+ # Example videos section
271
+ gr.Markdown("""
272
+ ---
273
+ ### 🎬 Example Videos
274
+ Upload your own traffic video or use sample footage to test the system.
275
+ """)
276
+
277
+ gr.Examples(
278
+ examples=[
279
+ ["./data/vehicles.mp4", "yolov8n", 480, 0.3],
280
+ ],
281
+ inputs=[video_input, model_choice, line_position, confidence_threshold],
282
+ outputs=[video_output, stats_output],
283
+ fn=estimate_vehicle_speed,
284
+ cache_examples=False,
285
+ label="Sample Videos"
286
+ )
287
+
288
+ # Connect processing function
289
+ process_btn.click(
290
+ fn=estimate_vehicle_speed,
291
+ inputs=[video_input, model_choice, line_position, confidence_threshold],
292
+ outputs=[video_output, stats_output]
293
+ )
294
+
295
+ gr.Markdown("""
296
+ ---
297
+ ### πŸ”¬ Technical Details
298
+
299
+ This system uses:
300
+ - **YOLO (You Only Look Once)** for real-time object detection
301
+ - **ByteTrack** for multi-object tracking across frames
302
+ - **Perspective Transformation** for accurate speed calculation
303
+ - **OpenCV** for video processing and computer vision operations
304
+
305
+ ### πŸ“š References
306
+ - [Ultralytics YOLO](https://github.com/ultralytics/ultralytics)
307
+ - [Supervision Library](https://github.com/roboflow/supervision)
308
+ - [OpenCV](https://opencv.org/)
309
+
310
+ ### πŸ“„ License
311
+ MIT License - See LICENSE file for details
312
+ """)
313
+
314
+ return demo
315
+
316
+
317
+ if __name__ == "__main__":
318
+ try:
319
+ logger.info("Starting Vehicle Speed Estimation application...")
320
+ demo = create_demo_interface()
321
+ demo.launch(
322
+ server_name="0.0.0.0",
323
+ server_port=7860,
324
+ share=False
325
+ )
326
+ except Exception as e:
327
+ logger.error(f"Failed to launch application: {e}", exc_info=True)
328
+ sys.exit(1)