Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329"""Vehicle Speed Estimation and Counting - Gradio Interface=========================================================A real-time vehicle detection, tracking, counting, and speed estimation systemusing YOLO object detection and perspective transformation techniques.Authors:- Abhay Gupta (0205CC221005)- Aditi Lakhera (0205CC221011)- Balraj Patel (0205CC221049)- Bhumika Patel (0205CC221050)This application provides an interactive web interface for analyzing traffic videosand estimating vehicle speeds using computer vision techniques."""import osimport sysimport tempfileimport loggingfrom pathlib import Pathfrom typing import Optional, Tupleimport gradio as grimport cv2import numpy as np# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Import application modulestry:from main import process_videofrom config import VehicleDetectionConfigexcept ImportError as e:logger.error(f"Failed to import required modules: {e}")raisedef validate_video_file(video_path: str) -> Tuple[bool, str]:"""Validate uploaded video file.Args:video_path: Path to video fileReturns:Tuple of (is_valid, error_message)"""if not video_path:return False, "No video file provided"if not os.path.exists(video_path):return False, f"Video file not found: {video_path}"# Check file size (limit to 100MB for HF Spaces)file_size_mb = os.path.getsize(video_path) / (1024 * 1024)if file_size_mb > 100:return False, f"Video file too large ({file_size_mb:.1f}MB). Maximum size is 100MB"# Validate video can be openedtry:cap = cv2.VideoCapture(video_path)if not cap.isOpened():return False, "Unable to open video file. Please ensure it's a valid video format"# Check if video has framesret, _ = cap.read()cap.release()if not ret:return False, "Video file appears to be empty or corrupted"return True, ""except Exception as e:return False, f"Error validating video: {str(e)}"def estimate_vehicle_speed(video_file: str,model_choice: str,line_position: int,confidence_threshold: float,progress=gr.Progress()) -> Tuple[Optional[str], str]:"""Process video and estimate vehicle speeds.Args:video_file: Path to uploaded videomodel_choice: YOLO model selectionline_position: Y-coordinate for counting lineconfidence_threshold: Detection confidence thresholdprogress: Gradio progress trackerReturns:Tuple of (output_video_path, statistics_text)"""try:# Validate inputprogress(0, desc="Validating video file...")is_valid, error_msg = validate_video_file(video_file)if not is_valid:logger.error(f"Video validation failed: {error_msg}")return None, f"β Error: {error_msg}"# Create temporary output fileoutput_path = tempfile.mktemp(suffix='.mp4')# Configure processingprogress(0.1, desc="Configuring detection parameters...")config = VehicleDetectionConfig(input_video=video_file,output_video=output_path,model_name=model_choice,line_y=line_position,confidence_threshold=confidence_threshold)# Process videoprogress(0.2, desc="Processing video (this may take a few minutes)...")logger.info(f"Starting video processing: {video_file}")try:stats = process_video(config=config,progress_callback=lambda p: progress(0.2 + p * 0.7, desc=f"Processing... {int(p*100)}%"))progress(0.95, desc="Finalizing output...")# Format statisticsstats_text = f"""## π Processing Results### Vehicle Count Statistics- **Total Vehicles Detected:** {stats['total_count']}- **Vehicles Entering (In):** {stats['in_count']}- **Vehicles Exiting (Out):** {stats['out_count']}### Speed Analysis- **Average Speed:** {stats['avg_speed']:.1f} km/h- **Maximum Speed:** {stats['max_speed']:.1f} km/h- **Minimum Speed:** {stats['min_speed']:.1f} km/h### Processing Information- **Frames Processed:** {stats['frames_processed']}- **Processing Time:** {stats['processing_time']:.2f} seconds- **Model Used:** {model_choice}- **Detection Confidence:** {confidence_threshold:.2f}β **Processing completed successfully!**"""progress(1.0, desc="Complete!")logger.info("Video processing completed successfully")return output_path, stats_textexcept Exception as e:logger.error(f"Error during video processing: {e}", exc_info=True)return None, f"β **Processing Error:** {str(e)}\n\nPlease try with different settings or a different video."except Exception as e:logger.error(f"Unexpected error in estimate_vehicle_speed: {e}", exc_info=True)return None, f"β **Unexpected Error:** {str(e)}"def create_demo_interface() -> gr.Blocks:"""Create Gradio interface for vehicle speed estimation.Returns:Gradio Blocks interface"""with gr.Blocks(title="Vehicle Speed Estimation & Counting",theme=gr.themes.Soft()) as demo:gr.Markdown("""# π Vehicle Speed Estimation & Counting SystemAn intelligent traffic analysis system that detects, tracks, counts, and estimates the speed of vehicles in video footage using advanced computer vision techniques.### π― Features- **Real-time Vehicle Detection** using YOLO- **Multi-Object Tracking** with ByteTrack- **Accurate Speed Estimation** via perspective transformation- **Vehicle Counting** with configurable detection zones### π₯ Developed By- **Abhay Gupta** (0205CC221005)- **Aditi Lakhera** (0205CC221011)- **Balraj Patel** (0205CC221049)- **Bhumika Patel** (0205CC221050)---""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π€ Input Configuration")video_input = gr.Video(label="Upload Traffic Video",format="mp4")with gr.Accordion("βοΈ Advanced Settings", open=False):model_choice = gr.Dropdown(choices=["yolov8n", "yolov8s", "yolov8m", "yolov8l"],value="yolov8n",label="YOLO Model",info="Larger models are more accurate but slower")line_position = gr.Slider(minimum=100,maximum=1000,value=480,step=10,label="Counting Line Position (Y-coordinate)",info="Vertical position of the vehicle counting line")confidence_threshold = gr.Slider(minimum=0.1,maximum=0.9,value=0.3,step=0.05,label="Detection Confidence Threshold",info="Higher values reduce false positives")process_btn = gr.Button("π Process Video",variant="primary",size="lg")gr.Markdown("""### π Instructions1. Upload a traffic video (MP4 format, max 100MB)2. Adjust settings if needed (optional)3. Click "Process Video" and wait for results4. Download the annotated video with speed estimates### π‘ Tips- Use videos with clear vehicle visibility- Ensure consistent camera angle- Better lighting improves detection accuracy""")with gr.Column(scale=1):gr.Markdown("### π₯ Output Results")video_output = gr.Video(label="Processed Video with Annotations")stats_output = gr.Markdown(label="Statistics",value="*Processing results will appear here...*")# Example videos sectiongr.Markdown("""---### π¬ Example VideosUpload your own traffic video or use sample footage to test the system.""")gr.Examples(examples=[["./data/vehicles.mp4", "yolov8n", 480, 0.3],],inputs=[video_input, model_choice, line_position, confidence_threshold],outputs=[video_output, stats_output],fn=estimate_vehicle_speed,cache_examples=False,label="Sample Videos")# Connect processing functionprocess_btn.click(fn=estimate_vehicle_speed,inputs=[video_input, model_choice, line_position, confidence_threshold],outputs=[video_output, stats_output])gr.Markdown("""---### π¬ Technical DetailsThis system uses:- **YOLO (You Only Look Once)** for real-time object detection- **ByteTrack** for multi-object tracking across frames- **Perspective Transformation** for accurate speed calculation- **OpenCV** for video processing and computer vision operations### π References- [Ultralytics YOLO](https://github.com/ultralytics/ultralytics)- [Supervision Library](https://github.com/roboflow/supervision)- [OpenCV](https://opencv.org/)### π LicenseMIT License - See LICENSE file for details""")return demoif __name__ == "__main__":try:logger.info("Starting Vehicle Speed Estimation application...")demo = create_demo_interface()demo.launch(server_name="0.0.0.0",server_port=7860,share=False)except Exception as e:logger.error(f"Failed to launch application: {e}", exc_info=True)sys.exit(1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328"""Vehicle Speed Estimation and Counting - Gradio Interface=========================================================A real-time vehicle detection, tracking, counting, and speed estimation systemusing YOLO object detection and perspective transformation techniques.Authors:- Abhay Gupta (0205CC221005)- Aditi Lakhera (0205CC221011)- Balraj Patel (0205CC221049)- Bhumika Patel (0205CC221050)This application provides an interactive web interface for analyzing traffic videosand estimating vehicle speeds using computer vision techniques."""import osimport sysimport tempfileimport loggingfrom pathlib import Pathfrom typing import Optional, Tupleimport gradio as grimport cv2import numpy as np# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Import application modulestry:from main import process_videofrom config import VehicleDetectionConfigexcept ImportError as e:logger.error(f"Failed to import required modules: {e}")raisedef validate_video_file(video_path: str) -> Tuple[bool, str]:"""Validate uploaded video file.Args:video_path: Path to video fileReturns:Tuple of (is_valid, error_message)"""if not video_path:return False, "No video file provided"if not os.path.exists(video_path):return False, f"Video file not found: {video_path}"# Check file size (limit to 100MB for HF Spaces)file_size_mb = os.path.getsize(video_path) / (1024 * 1024)if file_size_mb > 100:return False, f"Video file too large ({file_size_mb:.1f}MB). Maximum size is 100MB"# Validate video can be openedtry:cap = cv2.VideoCapture(video_path)if not cap.isOpened():return False, "Unable to open video file. Please ensure it's a valid video format"# Check if video has framesret, _ = cap.read()cap.release()if not ret:return False, "Video file appears to be empty or corrupted"return True, ""except Exception as e:return False, f"Error validating video: {str(e)}"def estimate_vehicle_speed(video_file: str,model_choice: str,line_position: int,confidence_threshold: float,progress=gr.Progress()) -> Tuple[Optional[str], str]:"""Process video and estimate vehicle speeds.Args:video_file: Path to uploaded videomodel_choice: YOLO model selectionline_position: Y-coordinate for counting lineconfidence_threshold: Detection confidence thresholdprogress: Gradio progress trackerReturns:Tuple of (output_video_path, statistics_text)"""try:# Validate inputprogress(0, desc="Validating video file...")is_valid, error_msg = validate_video_file(video_file)if not is_valid:logger.error(f"Video validation failed: {error_msg}")return None, f"β Error: {error_msg}"# Create temporary output fileoutput_path = tempfile.mktemp(suffix='.mp4')# Configure processingprogress(0.1, desc="Configuring detection parameters...")config = VehicleDetectionConfig(input_video=video_file,output_video=output_path,model_name=model_choice,line_y=line_position,confidence_threshold=confidence_threshold)# Process videoprogress(0.2, desc="Processing video (this may take a few minutes)...")logger.info(f"Starting video processing: {video_file}")try:stats = process_video(config=config,progress_callback=lambda p: progress(0.2 + p * 0.7, desc=f"Processing... {int(p*100)}%"))progress(0.95, desc="Finalizing output...")# Format statisticsstats_text = f"""## π Processing Results### Vehicle Count Statistics- **Total Vehicles Detected:** {stats['total_count']}- **Vehicles Entering (In):** {stats['in_count']}- **Vehicles Exiting (Out):** {stats['out_count']}### Speed Analysis- **Average Speed:** {stats['avg_speed']:.1f} km/h- **Maximum Speed:** {stats['max_speed']:.1f} km/h- **Minimum Speed:** {stats['min_speed']:.1f} km/h### Processing Information- **Frames Processed:** {stats['frames_processed']}- **Processing Time:** {stats['processing_time']:.2f} seconds- **Model Used:** {model_choice}- **Detection Confidence:** {confidence_threshold:.2f}β **Processing completed successfully!**"""progress(1.0, desc="Complete!")logger.info("Video processing completed successfully")return output_path, stats_textexcept Exception as e:logger.error(f"Error during video processing: {e}", exc_info=True)return None, f"β **Processing Error:** {str(e)}\n\nPlease try with different settings or a different video."except Exception as e:logger.error(f"Unexpected error in estimate_vehicle_speed: {e}", exc_info=True)return None, f"β **Unexpected Error:** {str(e)}"def create_demo_interface() -> gr.Blocks:"""Create Gradio interface for vehicle speed estimation.Returns:Gradio Blocks interface"""with gr.Blocks(title="Vehicle Speed Estimation & Counting") as demo:gr.Markdown("""# π Vehicle Speed Estimation & Counting SystemAn intelligent traffic analysis system that detects, tracks, counts, and estimates the speed of vehicles in video footage using advanced computer vision techniques.### π― Features- **Real-time Vehicle Detection** using YOLO- **Multi-Object Tracking** with ByteTrack- **Accurate Speed Estimation** via perspective transformation- **Vehicle Counting** with configurable detection zones### π₯ Developed By- **Abhay Gupta** (0205CC221005)- **Aditi Lakhera** (0205CC221011)- **Balraj Patel** (0205CC221049)- **Bhumika Patel** (0205CC221050)---""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π€ Input Configuration")video_input = gr.Video(label="Upload Traffic Video",format="mp4")with gr.Accordion("βοΈ Advanced Settings", open=False):model_choice = gr.Dropdown(choices=["yolov8n", "yolov8s", "yolov8m", "yolov8l"],value="yolov8n",label="YOLO Model",info="Larger models are more accurate but slower")line_position = gr.Slider(minimum=100,maximum=1000,value=480,step=10,label="Counting Line Position (Y-coordinate)",info="Vertical position of the vehicle counting line")confidence_threshold = gr.Slider(minimum=0.1,maximum=0.9,value=0.3,step=0.05,label="Detection Confidence Threshold",info="Higher values reduce false positives")process_btn = gr.Button("π Process Video",variant="primary",size="lg")gr.Markdown("""### π Instructions1. Upload a traffic video (MP4 format, max 100MB)2. Adjust settings if needed (optional)3. Click "Process Video" and wait for results4. Download the annotated video with speed estimates### π‘ Tips- Use videos with clear vehicle visibility- Ensure consistent camera angle- Better lighting improves detection accuracy""")with gr.Column(scale=1):gr.Markdown("### π₯ Output Results")video_output = gr.Video(label="Processed Video with Annotations")stats_output = gr.Markdown(label="Statistics",value="*Processing results will appear here...*")# Example videos sectiongr.Markdown("""---### π¬ Example VideosUpload your own traffic video or use sample footage to test the system.""")gr.Examples(examples=[["./data/vehicles.mp4", "yolov8n", 480, 0.3],],inputs=[video_input, model_choice, line_position, confidence_threshold],outputs=[video_output, stats_output],fn=estimate_vehicle_speed,cache_examples=False,label="Sample Videos")# Connect processing functionprocess_btn.click(fn=estimate_vehicle_speed,inputs=[video_input, model_choice, line_position, confidence_threshold],outputs=[video_output, stats_output])gr.Markdown("""---### π¬ Technical DetailsThis system uses:- **YOLO (You Only Look Once)** for real-time object detection- **ByteTrack** for multi-object tracking across frames- **Perspective Transformation** for accurate speed calculation- **OpenCV** for video processing and computer vision operations### π References- [Ultralytics YOLO](https://github.com/ultralytics/ultralytics)- [Supervision Library](https://github.com/roboflow/supervision)- [OpenCV](https://opencv.org/)### π LicenseMIT License - See LICENSE file for details""")return demoif __name__ == "__main__":try:logger.info("Starting Vehicle Speed Estimation application...")demo = create_demo_interface()demo.launch(server_name="0.0.0.0",server_port=7860,share=False)except Exception as e:logger.error(f"Failed to launch application: {e}", exc_info=True)sys.exit(1)
app.py+328-329