-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstart_enhanced_system_v4.py
More file actions
306 lines (265 loc) · 10.8 KB
/
start_enhanced_system_v4.py
File metadata and controls
306 lines (265 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/usr/bin/env python3
"""
Enhanced Stampede Detection System Startup Script v4
Optimized for Maximum Detection Accuracy with YOLOv11 Large Model
"""
import os
import sys
import subprocess
import time
import webbrowser
from pathlib import Path
try:
import torch
CUDA_AVAILABLE = torch.cuda.is_available()
except ImportError:
CUDA_AVAILABLE = False
def check_dependencies():
"""Check if all required dependencies are installed"""
required_packages = [
'ultralytics',
'opencv-python',
'flask',
'flask-socketio',
'numpy',
'torch',
'torchvision',
'pillow',
'pandas',
'scikit-learn',
'matplotlib',
'seaborn',
'plotly',
'bcrypt',
'pyjwt',
'flask-cors',
'flask-limiter',
'scipy',
'joblib'
]
missing_packages = []
for package in required_packages:
try:
__import__(package.replace('-', '_'))
except ImportError:
missing_packages.append(package)
if missing_packages:
print("❌ Missing required packages:")
for package in missing_packages:
print(f" - {package}")
print("\n📦 Installing missing packages...")
try:
subprocess.check_call([sys.executable, '-m', 'pip', 'install'] + missing_packages)
print("✅ All packages installed successfully!")
except subprocess.CalledProcessError:
print("❌ Failed to install packages. Please run:")
print(f" pip install {' '.join(missing_packages)}")
return False
return True
def download_yolo_model():
"""Download YOLOv11 Large model if not present for best accuracy"""
model_path = Path("yolo11l.pt")
if not model_path.exists():
print("📥 Downloading YOLOv11 Large model for best accuracy...")
try:
from ultralytics import YOLO
model = YOLO("yolo11l.pt") # This will download the model
print("✅ YOLOv11 Large model downloaded successfully!")
except Exception as e:
print(f"❌ Failed to download YOLOv11 Large: {e}")
print("🔄 Falling back to YOLOv8 Large...")
try:
model = YOLO("yolov8l.pt")
print("✅ YOLOv8 Large model downloaded as fallback!")
except Exception as e2:
print(f"❌ Failed to download any model: {e2}")
return False
else:
print("✅ YOLOv11 Large model already available!")
return True
def create_directories():
"""Create necessary directories"""
directories = ['templates', 'static', 'uploads', 'logs', 'models', 'test_results']
for directory in directories:
Path(directory).mkdir(exist_ok=True)
print("✅ Directory structure created!")
def initialize_ml_system():
"""Initialize the integrated ML system"""
print("\n🤖 Initializing AI/ML Features...")
try:
# Import ML system
from integrated_ml_system import IntegratedMLSystem, SystemConfiguration
# Configure ML system
config = SystemConfiguration(
enable_adaptive_thresholds=True,
enable_anomaly_detection=True,
enable_behavior_analysis=True,
enable_density_forecasting=True,
enable_person_reid=True,
enable_smart_alerts=True,
enable_crowd_simulation=True,
enable_environmental_integration=True,
processing_mode="balanced",
update_frequency=1.0,
confidence_threshold=0.7
)
# Initialize system
ml_system = IntegratedMLSystem(config)
if ml_system.initialize_system():
print("✅ AI/ML System initialized successfully!")
print(" • Adaptive Threshold Optimization")
print(" • Anomaly Detection System")
print(" • Behavior Analysis & Panic Detection")
print(" • Predictive Density Forecasting")
print(" • Person Re-identification")
print(" • Smart Alert Threshold Learning")
print(" • Crowd Simulation & Prediction")
print(" • Environmental Integration")
return ml_system
else:
print("⚠️ ML system initialization failed - continuing with basic features")
return None
except Exception as e:
print(f"⚠️ ML system initialization error: {e}")
print(" Continuing with basic detection features...")
return None
def start_web_server(ml_system=None):
"""Start the enhanced web server with GPU acceleration"""
print("\n🚀 Starting Enhanced Stampede Detection System v4...")
print("=" * 70)
print("🎯 Model: YOLOv11 Large (GPU Accelerated) - Best Accuracy")
print("📱 Web Interface: http://localhost:5000")
# GPU Information
if CUDA_AVAILABLE:
print(f"🔥 GPU: {torch.cuda.get_device_name(0)}")
print(f"💾 GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
print(f"🚀 CUDA Version: {torch.version.cuda}")
else:
print("⚠️ CUDA not available - using CPU")
print("📹 Enhanced Features:")
print(" • Real-time webcam detection with clear dots")
print(" • Video file upload and processing")
print(" • Professional dashboard with detailed metrics")
print(" • Advanced crowd flow analysis")
print(" • Multi-factor risk assessment")
print(" • YOLOv11 Large model for superior accuracy")
print(" • Enhanced dense crowd detection (confidence: 0.15)")
print(" • Optimized resolution processing (1280px max)")
print(" • GPU acceleration for smooth performance")
print(" • Smart alert system with cooldown")
print(" • Real-time density mapping and trends")
print(" • Adaptive frame skipping for performance")
print(" • Fixed OpenCV optical flow errors")
print(" • Optimized video processing pipeline")
print(" • Improved people detection accuracy")
print(" • Smooth video playback")
if ml_system:
print(" • AI/ML-powered crowd analysis")
print(" • Predictive stampede detection")
print(" • Smart alert threshold learning")
print(" • Multi-camera person tracking")
print(" • Environmental factor integration")
print(" • Physics-based crowd simulation")
print(" • Comprehensive risk assessment")
print("=" * 70)
# Open browser after a short delay
def open_browser():
time.sleep(2)
webbrowser.open('http://localhost:5000')
import threading
browser_thread = threading.Thread(target=open_browser)
browser_thread.daemon = True
browser_thread.start()
# Start the web server
try:
# Import and start the web server
if ml_system:
# Use enhanced web server with ML features
try:
from enhanced_web_server import app, socketio
# Pass ML system to the web server
app.config['ML_SYSTEM'] = ml_system
socketio.run(app, host='0.0.0.0', port=5000, debug=False)
except ImportError:
print("⚠️ Enhanced web server not found, using basic web server")
from web_server import app, socketio
socketio.run(app, host='0.0.0.0', port=5000, debug=False)
else:
# Use basic web server
from web_server import app, socketio
socketio.run(app, host='0.0.0.0', port=5000, debug=False)
except KeyboardInterrupt:
print("\n👋 Shutting down Enhanced Stampede Detection System...")
if ml_system:
print("💾 Saving ML system state...")
ml_system.save_system_state()
except Exception as e:
print(f"❌ Error starting server: {e}")
return False
return True
def main():
"""Main startup function with enhanced features"""
print("🛡️ Enhanced Stampede Detection System v4")
print("AI-Powered Crowd Monitoring with Advanced ML Features")
print("=" * 80)
print("🔧 AI/ML Features:")
print(" • Adaptive Threshold Optimization")
print(" • Anomaly Detection & Pattern Recognition")
print(" • Behavior Analysis & Panic Detection")
print(" • Predictive Density Forecasting")
print(" • Person Re-identification Across Cameras")
print(" • Smart Alert Threshold Learning")
print(" • Crowd Simulation & Physics Modeling")
print(" • Environmental Factor Integration")
print(" • Unified Risk Assessment")
print(" • Real-time Performance Monitoring")
print("=" * 80)
# Check Python version
if sys.version_info < (3, 8):
print("❌ Python 3.8+ is required!")
sys.exit(1)
print(f"✅ Python {sys.version.split()[0]} detected")
# Check dependencies
if not check_dependencies():
sys.exit(1)
# Create directories
create_directories()
# Download model
if not download_yolo_model():
print("⚠️ Continuing with available model...")
# Initialize ML system
ml_system = initialize_ml_system()
print("\n🎉 All systems are ready!")
print(" The system now includes:")
print(" • YOLOv11 Large model for superior accuracy")
print(" • GPU acceleration for smooth performance")
print(" • Real-time detection and analysis")
print(" • Advanced error handling")
print(" • Optimized video processing pipeline")
if ml_system:
print(" • AI/ML-powered crowd analysis")
print(" • Predictive stampede detection")
print(" • Smart alert threshold learning")
print(" • Multi-camera person tracking")
print(" • Environmental factor integration")
print(" • Physics-based crowd simulation")
print(" • Comprehensive risk assessment")
else:
print(" • Basic detection features (AI/ML disabled)")
# GPU Status
if CUDA_AVAILABLE:
print(f"\n🔥 GPU Acceleration: ENABLED ({torch.cuda.get_device_name(0)})")
print(" • Smooth webcam performance")
print(" • Fast video processing")
print(" • Real-time AI/ML processing")
print(" • Optimized memory usage")
print(" • Maximum detection accuracy")
else:
print("\n⚠️ GPU Acceleration: DISABLED (CPU mode)")
print(" • Install CUDA-enabled PyTorch for better performance")
print(" • AI/ML features will be slower on CPU")
# Start web server
if not start_web_server(ml_system):
sys.exit(1)
if __name__ == "__main__":
main()