-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3741 lines (3078 loc) · 154 KB
/
main.py
File metadata and controls
3741 lines (3078 loc) · 154 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Real-Time Hand Gesture Control System for Racing Games Using Computer Vision
===========================================================================
An ultra-low-latency computer vision system for controlling racing games
through precise hand gestures using advanced AI and computer vision techniques.
Author: Muhammad Kashan Tariq
LinkedIn: https://www.linkedin.com/in/muhammad-kashan-tariq
Version: 1.0.0
Date: 2025-06-28
Hardware Recommended: Intel i7 or i9 cpu + NVIDIA RTX GPU + atleast 32GB DDR4 or DDR 5 ram
Software: Python 3.10, CUDA 12.1, cuDNN 8.9.7, TensorRT 8.6.1.6
TESTED WITH FORZA HORIZON 5 - COMPATIBLE WITH ALL RACING GAMES
Gesture Mappings (Exact Specifications):
========================================
1. E-BRAKE: Both hands open (fingers spread), aligned horizontally → Spacebar
2. ACCELERATE: Both hands closed (fists), aligned horizontally → W key
3. REVERSE: Right hand open, left hand closed (fist), aligned horizontally → S key
4. START/IDLE: Right hand closed (fist), left hand open, aligned horizontally → E key
5. STEERING: Hand height differences indicate steering direction
- Left higher than right = Steer Left (A key)
- Right higher than left = Steer Right (D key)
6. COMBINED CONTROLS: Steering can be combined with any base gesture
Performance Targets:
===================
- Latency: <50ms gesture detection to game input
- FPS: 30+ frames per second processing
- Accuracy: >95% gesture classification
- Hardware Utilization: Full GPU acceleration with CUDA
"""
import cv2
import mediapipe as mp
import numpy as np
import time
import threading
import queue
import json
import logging
import os
import sys
import warnings
import math
import platform
import psutil
from datetime import datetime
from typing import Dict, List, Tuple, Optional, Union, Any, NamedTuple
from dataclasses import dataclass, field
from enum import Enum, auto
import concurrent.futures
from collections import deque, defaultdict
import configparser
import traceback
from contextlib import contextmanager
import signal
# Suppress MediaPipe and TensorFlow warnings for cleaner output
warnings.filterwarnings("ignore", category=UserWarning)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['MEDIAPIPE_DISABLE_GPU'] = '0' # Enable GPU acceleration
# Game input simulation libraries with comprehensive error handling
try:
import pynput
from pynput import keyboard, mouse
from pynput.keyboard import Key, KeyCode
PYNPUT_AVAILABLE = True
except ImportError:
print("Installing pynput for game input simulation...")
os.system("pip install pynput")
try:
import pynput
from pynput import keyboard, mouse
from pynput.keyboard import Key, KeyCode
PYNPUT_AVAILABLE = True
except ImportError:
PYNPUT_AVAILABLE = False
print("WARNING: pynput not available - input simulation disabled")
try:
import pyautogui
pyautogui.FAILSAFE = False # Disable failsafe for gaming
PYAUTOGUI_AVAILABLE = True
except ImportError:
print("Installing pyautogui for additional input methods...")
os.system("pip install pyautogui")
try:
import pyautogui
pyautogui.FAILSAFE = False
PYAUTOGUI_AVAILABLE = True
except ImportError:
PYAUTOGUI_AVAILABLE = False
print("WARNING: pyautogui not available")
# GPU acceleration support with comprehensive CUDA detection
try:
import torch
CUDA_AVAILABLE = torch.cuda.is_available()
if CUDA_AVAILABLE:
CUDA_DEVICE_COUNT = torch.cuda.device_count()
CUDA_DEVICE_NAME = torch.cuda.get_device_name(0)
CUDA_MEMORY_GB = torch.cuda.get_device_properties(0).total_memory / (1024**3)
print(f"🚀 CUDA GPU Detected: {CUDA_DEVICE_NAME}")
print(f"🚀 CUDA Memory: {CUDA_MEMORY_GB:.1f} GB")
print(f"🚀 PyTorch Version: {torch.__version__}")
else:
print("⚠️ CUDA not available - using CPU processing")
except ImportError:
CUDA_AVAILABLE = False
print("⚠️ PyTorch not available - GPU optimizations disabled")
# Performance monitoring
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
print("Installing psutil for performance monitoring...")
os.system("pip install psutil")
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
class GestureType(Enum):
"""
Comprehensive enumeration of all supported hand gestures for racing game control.
Each gesture maps to specific in-game actions as per project specifications.
"""
# Primary Gestures (Base Actions)
E_BRAKE = "e_brake" # Both hands open → Emergency brake (Spacebar)
ACCELERATE = "accelerate" # Both hands closed → Move forward (W key)
REVERSE = "reverse" # Right open, left closed → Move backward (S key)
START_IDLE = "start_idle" # Right closed, left open → Engine start/idle (E key)
# Steering Gestures (Direction Modifiers)
STEER_LEFT = "steer_left" # Left hand higher → Turn left (A key)
STEER_RIGHT = "steer_right" # Right hand higher → Turn right (D key)
# Combined Control Gestures (Revolutionary Feature)
ACCELERATE_LEFT = "accelerate_left" # Accelerate + Steer Left (W + A)
ACCELERATE_RIGHT = "accelerate_right" # Accelerate + Steer Right (W + D)
REVERSE_LEFT = "reverse_left" # Reverse + Steer Left (S + A)
REVERSE_RIGHT = "reverse_right" # Reverse + Steer Right (S + D)
BRAKE_LEFT = "brake_left" # E-brake + Steer Left (Space + A)
BRAKE_RIGHT = "brake_right" # E-brake + Steer Right (Space + D)
# Special States
NO_GESTURE = "no_gesture" # No hands detected
UNKNOWN = "unknown" # Hands detected but gesture unclear
INVALID = "invalid" # Invalid hand configuration
class GameAction(Enum):
"""Enumeration of all possible in-game actions that can be triggered."""
# Primary Actions
BRAKE = "brake" # Emergency brake (Spacebar)
ACCELERATE = "accelerate" # Move forward (W key)
REVERSE = "reverse" # Move backward (S key)
STEER_LEFT = "steer_left" # Turn left (A key)
STEER_RIGHT = "steer_right" # Turn right (D key)
ENGINE_START = "engine_start" # Start engine (E key)
# Combined Actions
ACCELERATE_AND_LEFT = "accelerate_and_left" # W + A simultaneously
ACCELERATE_AND_RIGHT = "accelerate_and_right" # W + D simultaneously
REVERSE_AND_LEFT = "reverse_and_left" # S + A simultaneously
REVERSE_AND_RIGHT = "reverse_and_right" # S + D simultaneously
BRAKE_AND_LEFT = "brake_and_left" # Space + A simultaneously
BRAKE_AND_RIGHT = "brake_and_right" # Space + D simultaneously
# System Actions
NO_ACTION = "no_action" # No input to game
EMERGENCY_STOP = "emergency_stop" # Emergency system stop
@dataclass
class HandLandmarkData:
"""
Comprehensive container for hand landmark data with advanced utility methods
for sophisticated gesture analysis and classification.
"""
landmarks: List[Tuple[float, float, float]] # (x, y, z) normalized coordinates
handedness: str # "Left" or "Right"
confidence: float # Detection confidence [0.0, 1.0]
timestamp: float = field(default_factory=time.time)
def __post_init__(self):
"""Validate landmark data on initialization."""
if len(self.landmarks) != 21:
raise ValueError(f"Expected 21 landmarks, got {len(self.landmarks)}")
if self.handedness not in ["Left", "Right"]:
raise ValueError(f"Invalid handedness: {self.handedness}")
if not 0.0 <= self.confidence <= 1.0:
raise ValueError(f"Confidence must be in [0.0, 1.0], got {self.confidence}")
def get_finger_states(self) -> Dict[str, bool]:
"""
Advanced finger state analysis using geometric relationships between landmarks.
Returns:
Dict mapping finger names to boolean states (True = extended, False = closed)
"""
# MediaPipe hand landmark indices for sophisticated finger analysis
finger_tips = [4, 8, 12, 16, 20] # Thumb, Index, Middle, Ring, Pinky tips
finger_joints = [3, 6, 10, 14, 18] # Corresponding joint positions
finger_names = ["thumb", "index", "middle", "ring", "pinky"]
finger_states = {}
for i, (tip_idx, joint_idx, name) in enumerate(zip(finger_tips, finger_joints, finger_names)):
tip = self.landmarks[tip_idx]
joint = self.landmarks[joint_idx]
if name == "thumb":
# Thumb analysis: Use X-axis movement relative to palm center
palm_center = self.get_palm_center()
tip_distance = abs(tip[0] - palm_center[0])
joint_distance = abs(joint[0] - palm_center[0])
is_extended = tip_distance > joint_distance + 0.02
else:
# Other fingers: Use Y-axis movement (tip above joint for extension)
is_extended = tip[1] < joint[1] - 0.03 # Increased threshold for reliability
finger_states[name] = is_extended
return finger_states
def is_fist(self, threshold: float = 0.8) -> bool:
"""
Determine if hand forms a closed fist using configurable threshold.
Args:
threshold: Confidence threshold for fist detection [0.0, 1.0]
Returns:
True if hand is classified as a fist
"""
finger_states = self.get_finger_states()
closed_fingers = sum(1 for extended in finger_states.values() if not extended)
fist_confidence = closed_fingers / len(finger_states)
return fist_confidence >= threshold
def is_open_hand(self, threshold: float = 0.6) -> bool:
"""
Determine if hand is open with configurable threshold.
Args:
threshold: Confidence threshold for open hand detection [0.0, 1.0]
Returns:
True if hand is classified as open
"""
finger_states = self.get_finger_states()
extended_fingers = sum(1 for extended in finger_states.values() if extended)
open_confidence = extended_fingers / len(finger_states)
return open_confidence >= threshold
def get_palm_center(self) -> Tuple[float, float]:
"""
Calculate precise palm center using multiple landmark points for accuracy.
Returns:
(x, y) coordinates of palm center
"""
# Use multiple palm landmarks for more accurate center calculation
wrist = self.landmarks[0]
index_mcp = self.landmarks[5]
middle_mcp = self.landmarks[9]
ring_mcp = self.landmarks[13]
pinky_mcp = self.landmarks[17]
# Average multiple points for robust palm center
palm_points = [wrist, index_mcp, middle_mcp, ring_mcp, pinky_mcp]
center_x = sum(point[0] for point in palm_points) / len(palm_points)
center_y = sum(point[1] for point in palm_points) / len(palm_points)
return (center_x, center_y)
def get_hand_orientation(self) -> float:
"""
Calculate hand orientation angle for advanced gesture analysis.
Returns:
Orientation angle in degrees [-180, 180]
"""
wrist = self.landmarks[0]
middle_finger_mcp = self.landmarks[9]
dx = middle_finger_mcp[0] - wrist[0]
dy = middle_finger_mcp[1] - wrist[1]
angle = math.degrees(math.atan2(dy, dx))
return angle
def calculate_hand_size(self) -> float:
"""
Estimate hand size for distance-independent gesture recognition.
Returns:
Normalized hand size metric
"""
wrist = self.landmarks[0]
middle_tip = self.landmarks[12]
# Distance from wrist to middle finger tip as size metric
dx = middle_tip[0] - wrist[0]
dy = middle_tip[1] - wrist[1]
hand_size = math.sqrt(dx*dx + dy*dy)
return hand_size
@dataclass
class GestureFrame:
"""
Comprehensive container for a complete frame of gesture analysis data
with performance metrics and temporal information.
"""
timestamp: float
left_hand: Optional[HandLandmarkData]
right_hand: Optional[HandLandmarkData]
gesture_type: GestureType
confidence: float
frame_number: int
processing_time_ms: float
camera_fps: float = 0.0
system_latency_ms: float = 0.0
def has_both_hands(self) -> bool:
"""Check if both hands are detected in this frame."""
return self.left_hand is not None and self.right_hand is not None
def has_any_hand(self) -> bool:
"""Check if at least one hand is detected in this frame."""
return self.left_hand is not None or self.right_hand is not None
def get_hand_count(self) -> int:
"""Get the number of detected hands in this frame."""
return sum([self.left_hand is not None, self.right_hand is not None])
class PerformanceMonitor:
"""
Military-grade performance monitoring system for real-time tracking of system metrics,
processing times, hardware utilization, and comprehensive performance analysis.
"""
def __init__(self, window_size: int = 100, monitoring_interval: float = 1.0):
"""
Initialize performance monitor with comprehensive metric tracking.
Args:
window_size: Number of recent measurements for moving averages
monitoring_interval: Hardware monitoring update interval in seconds
"""
self.window_size = window_size
self.monitoring_interval = monitoring_interval
# Performance metrics with time-based sliding windows
self.frame_times = deque(maxlen=window_size)
self.processing_times = deque(maxlen=window_size)
self.gesture_times = deque(maxlen=window_size)
self.input_times = deque(maxlen=window_size)
self.detection_times = deque(maxlen=window_size)
self.classification_times = deque(maxlen=window_size)
# System metrics
self.total_frames = 0
self.total_gestures = 0
self.start_time = time.time()
self.last_fps_update = time.time()
self.current_fps = 0.0
self.peak_fps = 0.0
self.min_fps = float('inf')
# Hardware monitoring (updated in background thread)
self.cpu_percent = 0.0
self.memory_percent = 0.0
self.memory_used_gb = 0.0
self.gpu_utilization = 0.0
self.gpu_memory_percent = 0.0
self.gpu_temperature = 0.0
# Performance statistics
self.gesture_accuracy_history = deque(maxlen=1000)
self.latency_violations = 0 # Count of frames exceeding 50ms latency
self.error_count = 0
self.warning_count = 0
# Threading for non-blocking hardware monitoring
self.monitoring_active = True
self.monitor_thread = threading.Thread(target=self._monitor_hardware_loop, daemon=True)
self.monitor_thread.start()
# Performance thresholds for alerts
self.fps_threshold_low = 25.0
self.latency_threshold_ms = 50.0
self.cpu_threshold_high = 80.0
self.memory_threshold_high = 90.0
def record_frame_time(self, frame_time: float):
"""Record frame processing time and update FPS calculations."""
self.frame_times.append(frame_time)
self.total_frames += 1
# Update FPS calculation
current_time = time.time()
if current_time - self.last_fps_update >= 1.0:
if len(self.frame_times) > 0:
avg_frame_time = np.mean(list(self.frame_times)[-30:]) # Use last 30 frames
self.current_fps = 1.0 / avg_frame_time if avg_frame_time > 0 else 0.0
# Update peak and minimum FPS
if self.current_fps > self.peak_fps:
self.peak_fps = self.current_fps
if self.current_fps < self.min_fps and self.current_fps > 0:
self.min_fps = self.current_fps
self.last_fps_update = current_time
def record_processing_time(self, process_time: float):
"""Record gesture processing time."""
self.processing_times.append(process_time)
def record_gesture_time(self, gesture_time: float):
"""Record gesture classification time."""
self.gesture_times.append(gesture_time)
self.total_gestures += 1
def record_input_time(self, input_time: float):
"""Record game input simulation time."""
self.input_times.append(input_time)
def record_detection_time(self, detection_time: float):
"""Record hand detection time."""
self.detection_times.append(detection_time)
def record_classification_time(self, classification_time: float):
"""Record gesture classification time."""
self.classification_times.append(classification_time)
def record_gesture_accuracy(self, accuracy: float):
"""Record gesture recognition accuracy."""
self.gesture_accuracy_history.append(accuracy)
def record_latency_violation(self):
"""Record when system latency exceeds threshold."""
self.latency_violations += 1
def record_error(self):
"""Record system error occurrence."""
self.error_count += 1
def record_warning(self):
"""Record system warning occurrence."""
self.warning_count += 1
def _monitor_hardware_loop(self):
"""Background thread for continuous hardware monitoring."""
while self.monitoring_active:
try:
if PSUTIL_AVAILABLE:
# CPU and memory monitoring
self.cpu_percent = psutil.cpu_percent(interval=0.1)
memory_info = psutil.virtual_memory()
self.memory_percent = memory_info.percent
self.memory_used_gb = memory_info.used / (1024**3)
# GPU monitoring (if CUDA available)
if CUDA_AVAILABLE:
try:
# Get GPU utilization if available
if hasattr(torch.cuda, 'utilization'):
self.gpu_utilization = torch.cuda.utilization()
# Get GPU memory usage
memory_stats = torch.cuda.memory_stats()
if memory_stats:
allocated = memory_stats.get('allocated_bytes.all.current', 0)
reserved = memory_stats.get('reserved_bytes.all.current', 1)
self.gpu_memory_percent = (allocated / reserved) * 100 if reserved > 0 else 0
# Get GPU temperature if available via nvidia-ml-py
try:
import pynvml
pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
self.gpu_temperature = pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU)
except:
self.gpu_temperature = 0.0
except Exception:
self.gpu_utilization = 0.0
self.gpu_memory_percent = 0.0
self.gpu_temperature = 0.0
time.sleep(self.monitoring_interval)
except Exception:
time.sleep(self.monitoring_interval)
continue
def get_comprehensive_stats(self) -> Dict[str, Any]:
"""
Generate comprehensive performance statistics with detailed metrics.
Returns:
Dictionary containing all performance metrics and system information
"""
current_time = time.time()
uptime = current_time - self.start_time
# Calculate averages with error handling
def safe_mean(data_deque):
return np.mean(list(data_deque)) if len(data_deque) > 0 else 0.0
# Calculate total system latency
total_latency_ms = (safe_mean(self.processing_times) +
safe_mean(self.gesture_times) +
safe_mean(self.input_times)) * 1000
stats = {
# Performance Metrics
'fps': {
'current': self.current_fps,
'peak': self.peak_fps,
'minimum': self.min_fps if self.min_fps != float('inf') else 0.0,
'average': safe_mean(self.frame_times) and (1.0 / safe_mean(self.frame_times))
},
# Timing Metrics (all in milliseconds)
'timing': {
'frame_time_ms': safe_mean(self.frame_times) * 1000,
'processing_time_ms': safe_mean(self.processing_times) * 1000,
'detection_time_ms': safe_mean(self.detection_times) * 1000,
'classification_time_ms': safe_mean(self.classification_times) * 1000,
'input_time_ms': safe_mean(self.input_times) * 1000,
'total_latency_ms': total_latency_ms
},
# System Counters
'counters': {
'total_frames': self.total_frames,
'total_gestures': self.total_gestures,
'latency_violations': self.latency_violations,
'error_count': self.error_count,
'warning_count': self.warning_count,
'uptime_seconds': uptime,
'frames_per_minute': (self.total_frames / (uptime / 60)) if uptime > 0 else 0,
'gestures_per_minute': (self.total_gestures / (uptime / 60)) if uptime > 0 else 0
},
# Hardware Utilization
'hardware': {
'cpu_percent': self.cpu_percent,
'memory_percent': self.memory_percent,
'memory_used_gb': self.memory_used_gb,
'gpu_utilization': self.gpu_utilization,
'gpu_memory_percent': self.gpu_memory_percent,
'gpu_temperature': self.gpu_temperature
},
# Performance Quality Indicators
'quality': {
'average_accuracy': safe_mean(self.gesture_accuracy_history),
'latency_violation_rate': (self.latency_violations / max(self.total_frames, 1)) * 100,
'error_rate': (self.error_count / max(self.total_frames, 1)) * 100,
'system_health': self._calculate_system_health()
}
}
return stats
def _calculate_system_health(self) -> str:
"""
Calculate overall system health based on multiple performance indicators.
Returns:
System health status: "EXCELLENT", "GOOD", "FAIR", "POOR", or "CRITICAL"
"""
health_score = 100.0
# FPS performance impact
if self.current_fps < 20:
health_score -= 30
elif self.current_fps < 25:
health_score -= 15
elif self.current_fps < 30:
health_score -= 5
# Latency impact
total_latency = (np.mean(list(self.processing_times)) +
np.mean(list(self.gesture_times)) +
np.mean(list(self.input_times))) * 1000 if len(self.processing_times) > 0 else 0
if total_latency > 100:
health_score -= 40
elif total_latency > 75:
health_score -= 25
elif total_latency > 50:
health_score -= 15
# Hardware utilization impact
if self.cpu_percent > 90:
health_score -= 20
elif self.cpu_percent > 80:
health_score -= 10
if self.memory_percent > 95:
health_score -= 20
elif self.memory_percent > 85:
health_score -= 10
# Error rate impact
error_rate = (self.error_count / max(self.total_frames, 1)) * 100
if error_rate > 5:
health_score -= 30
elif error_rate > 2:
health_score -= 15
elif error_rate > 1:
health_score -= 5
# Determine health status
if health_score >= 90:
return "EXCELLENT"
elif health_score >= 75:
return "GOOD"
elif health_score >= 60:
return "FAIR"
elif health_score >= 40:
return "POOR"
else:
return "CRITICAL"
def get_performance_alerts(self) -> List[str]:
"""
Generate performance alerts based on current system metrics.
Returns:
List of performance alert messages
"""
alerts = []
if self.current_fps < self.fps_threshold_low:
alerts.append(f"LOW FPS: {self.current_fps:.1f} (target: >{self.fps_threshold_low})")
total_latency = (np.mean(list(self.processing_times)) +
np.mean(list(self.gesture_times)) +
np.mean(list(self.input_times))) * 1000 if len(self.processing_times) > 0 else 0
if total_latency > self.latency_threshold_ms:
alerts.append(f"HIGH LATENCY: {total_latency:.1f}ms (target: <{self.latency_threshold_ms}ms)")
if self.cpu_percent > self.cpu_threshold_high:
alerts.append(f"HIGH CPU: {self.cpu_percent:.1f}% (threshold: {self.cpu_threshold_high}%)")
if self.memory_percent > self.memory_threshold_high:
alerts.append(f"HIGH MEMORY: {self.memory_percent:.1f}% (threshold: {self.memory_threshold_high}%)")
return alerts
def cleanup(self):
"""Stop background monitoring threads and clean up resources."""
self.monitoring_active = False
if self.monitor_thread.is_alive():
self.monitor_thread.join(timeout=2.0)
class ConfigurationManager:
"""
Military-grade configuration management system for comprehensive gesture recognition settings,
game input mappings, performance parameters, and advanced system optimization options.
"""
def __init__(self, config_file: str = "gesture_config.json"):
"""
Initialize configuration manager with comprehensive default settings.
Args:
config_file: Path to JSON configuration file
"""
self.config_file = config_file
self.config = self._create_comprehensive_default_config()
self.load_configuration()
# Configuration validation and auto-correction
self._validate_and_correct_config()
def _create_comprehensive_default_config(self) -> Dict[str, Any]:
"""Create comprehensive default configuration with all system parameters."""
return {
# Camera and Video Processing Configuration
"camera": {
"device_id": 0,
"width": 1280,
"height": 720,
"fps": 30,
"buffer_size": 1,
"auto_exposure": True,
"brightness": 0.5,
"contrast": 0.5,
"saturation": 0.5,
"backend": "auto", # "auto", "dshow" (Windows), "v4l2" (Linux)
"fourcc": "MJPG", # Video codec for camera
"auto_focus": True
},
# MediaPipe Hand Detection Advanced Configuration
"mediapipe": {
"model_complexity": 1, # 0=lite, 1=full, 2=heavy
"min_detection_confidence": 0.7, # Hand detection threshold
"min_tracking_confidence": 0.5, # Hand tracking threshold
"max_num_hands": 2, # Maximum hands to detect
"static_image_mode": False, # For video vs static images
"refine_landmarks": True # Enhance landmark accuracy
},
# Advanced Gesture Recognition Parameters
"gestures": {
"confidence_threshold": 0.85, # Overall gesture confidence threshold
"stability_frames": 3, # Frames for gesture stability
"hand_alignment_tolerance": 0.12, # Horizontal alignment tolerance
"vertical_separation_threshold": 0.08, # Steering detection threshold
"fist_threshold": 0.8, # Fist detection confidence
"open_hand_threshold": 0.6, # Open hand detection confidence
"debounce_time_ms": 100, # Gesture change debounce
"gesture_timeout_ms": 5000, # Gesture loss timeout
"palm_center_smoothing": 0.7, # Palm center position smoothing
"landmark_smoothing": 0.8, # Landmark position smoothing
"angle_smoothing": 0.6 # Hand angle smoothing
},
# Comprehensive Game Control Mappings
"game_controls": {
# Primary Actions
"accelerate": "w",
"reverse": "s",
"steer_left": "a",
"steer_right": "d",
"brake": "space",
"engine_start": "e",
"handbrake": "space",
# Advanced Controls
"boost": "x",
"camera_change": "c",
"horn": "h",
"lights": "l",
"pause": "escape",
# Modifier Keys
"shift_modifier": False,
"ctrl_modifier": False,
"alt_modifier": False
},
# Performance Optimization Configuration
"performance": {
"enable_gpu_acceleration": True,
"max_fps": 60,
"target_latency_ms": 25, # Target system latency
"threading_enabled": True,
"thread_count": -1, # -1 for auto-detect
"frame_skip_threshold": 2,
"memory_optimization": True,
"cpu_cores": -1, # -1 for auto-detect
"priority_class": "high", # Process priority
"garbage_collection_interval": 100, # GC every N frames
"enable_profiling": False # Performance profiling
},
# Comprehensive Logging Configuration
"logging": {
"level": "INFO", # DEBUG, INFO, WARNING, ERROR, CRITICAL
"file_path": "gesture_control.log",
"max_file_size_mb": 50,
"backup_count": 5,
"console_output": True,
"performance_logging": True,
"gesture_logging": True,
"error_logging": True,
"debug_logging": False,
"log_format": "%(asctime)s | %(levelname)-8s | %(funcName)-20s | %(message)s"
},
# Display and User Interface Configuration
"display": {
"show_camera_feed": True,
"show_landmarks": True,
"show_gesture_info": True,
"show_performance_stats": True,
"show_debug_info": False,
"window_size": [800, 600],
"window_position": [100, 100],
"fullscreen": False,
"overlay_opacity": 0.8,
"text_size": 0.7,
"text_color": [0, 255, 0], # Green text
"background_color": [0, 0, 0], # Black background
"landmark_color": [255, 0, 0], # Red landmarks
"connection_color": [0, 255, 255] # Cyan connections
},
# Safety and Emergency Configuration
"safety": {
"enable_emergency_stop": True,
"emergency_key": "escape",
"auto_brake_on_no_hands": True,
"gesture_loss_timeout_ms": 1000,
"safe_mode_enabled": False,
"max_continuous_action_time": 30, # Seconds
"require_both_hands": True,
"hand_distance_max": 0.8, # Maximum hand separation
"hand_distance_min": 0.1 # Minimum hand separation
},
# Advanced AI and ML Configuration
"ai": {
"model_optimization": True,
"batch_processing": False,
"use_tensorrt": True, # Enable TensorRT optimization
"use_cuda": True, # Enable CUDA acceleration
"precision": "fp16", # Model precision: fp32, fp16, int8
"cache_models": True, # Cache loaded models
"warmup_iterations": 10 # Model warmup iterations
},
# System Monitoring Configuration
"monitoring": {
"enable_performance_monitoring": True,
"monitoring_interval": 1.0, # Hardware monitoring interval
"alert_thresholds": {
"fps_min": 25.0,
"latency_max_ms": 50.0,
"cpu_max_percent": 85.0,
"memory_max_percent": 90.0,
"gpu_temp_max_celsius": 85.0
},
"save_performance_logs": True,
"performance_log_interval": 60 # Save performance logs every N seconds
}
}
def load_configuration(self):
"""Load configuration from file with comprehensive error handling."""
try:
if os.path.exists(self.config_file):
with open(self.config_file, 'r', encoding='utf-8') as f:
file_config = json.load(f)
self._deep_merge_configs(self.config, file_config)
print(f"✅ Configuration loaded from {self.config_file}")
else:
self.save_configuration()
print(f"✅ Default configuration created: {self.config_file}")
except json.JSONDecodeError as e:
print(f"❌ Invalid JSON in config file: {e}")
print("🔧 Using default configuration")
except Exception as e:
print(f"❌ Error loading config: {e}")
print("🔧 Using default configuration")
def save_configuration(self):
"""Save current configuration to file with proper formatting."""
try:
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump(self.config, f, indent=4, sort_keys=True, ensure_ascii=False)
print(f"✅ Configuration saved to {self.config_file}")
except Exception as e:
print(f"❌ Error saving config: {e}")
def _deep_merge_configs(self, default: Dict, user: Dict):
"""Recursively merge user configuration with defaults."""
for key, value in user.items():
if key in default:
if isinstance(value, dict) and isinstance(default[key], dict):
self._deep_merge_configs(default[key], value)
else:
default[key] = value
else:
# Add new keys from user config
default[key] = value
def _validate_and_correct_config(self):
"""Validate configuration values and auto-correct invalid settings."""
corrections = []
# Validate camera settings
if not isinstance(self.config["camera"]["device_id"], int) or self.config["camera"]["device_id"] < 0:
self.config["camera"]["device_id"] = 0
corrections.append("camera.device_id corrected to 0")
# Validate MediaPipe settings
if not 0 <= self.config["mediapipe"]["model_complexity"] <= 2:
self.config["mediapipe"]["model_complexity"] = 1
corrections.append("mediapipe.model_complexity corrected to 1")
# Validate gesture thresholds
for threshold_key in ["confidence_threshold", "fist_threshold", "open_hand_threshold"]:
if not 0.0 <= self.config["gestures"][threshold_key] <= 1.0:
self.config["gestures"][threshold_key] = 0.8
corrections.append(f"gestures.{threshold_key} corrected to 0.8")
# Validate performance settings
if self.config["performance"]["max_fps"] <= 0:
self.config["performance"]["max_fps"] = 30
corrections.append("performance.max_fps corrected to 30")
if corrections:
print(f"🔧 Configuration corrections applied: {len(corrections)} items")
for correction in corrections:
print(f" • {correction}")
self.save_configuration()
def get(self, path: str, default=None):
"""
Get configuration value using dot notation path with comprehensive error handling.
Args:
path: Dot-separated path (e.g., "camera.width")
default: Default value if path not found
Returns:
Configuration value or default
"""
try:
keys = path.split('.')
value = self.config
for key in keys:
if isinstance(value, dict) and key in value:
value = value[key]
else:
return default
return value
except (KeyError, TypeError, AttributeError):
return default
def set(self, path: str, value: Any, save: bool = False):
"""
Set configuration value using dot notation path.
Args:
path: Dot-separated path (e.g., "camera.width")
value: Value to set
save: Whether to save configuration to file immediately
"""
try:
keys = path.split('.')
config_ref = self.config
for key in keys[:-1]:
if key not in config_ref:
config_ref[key] = {}
config_ref = config_ref[key]
config_ref[keys[-1]] = value
if save:
self.save_configuration()
except Exception as e:
print(f"❌ Error setting config path {path}: {e}")
def get_camera_config(self) -> Dict[str, Any]:
"""Get camera-specific configuration."""
return self.config.get("camera", {})
def get_mediapipe_config(self) -> Dict[str, Any]:
"""Get MediaPipe-specific configuration."""
return self.config.get("mediapipe", {})
def get_gesture_config(self) -> Dict[str, Any]:
"""Get gesture recognition configuration."""
return self.config.get("gestures", {})
def get_game_controls_config(self) -> Dict[str, Any]:
"""Get game controls configuration."""
return self.config.get("game_controls", {})
def get_performance_config(self) -> Dict[str, Any]:
"""Get performance optimization configuration."""
return self.config.get("performance", {})
class GameInputController:
"""
Military-grade game input simulation system with ultra-low latency key press/release handling,
simultaneous input support, advanced error recovery, and comprehensive input state management.
"""
def __init__(self, config: ConfigurationManager):
"""
Initialize game input controller with comprehensive configuration and safety systems.
Args:
config: Configuration manager instance
"""
self.config = config
self.is_available = PYNPUT_AVAILABLE
if not self.is_available:
print("❌ Input controller not available - pynput library missing")
return
# Initialize input controllers
self.keyboard_controller = keyboard.Controller()