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
| import numpy as np from dataclasses import dataclass from typing import List, Tuple from enum import Enum
class ImpairmentLevel(Enum): """损伤等级""" NORMAL = "正常" MILD = "轻度影响" MODERATE = "中度影响" SEVERE = "重度影响"
@dataclass class EyeFeatures: """眼部特征""" blink_rate: float blink_duration_mean: float blink_duration_std: float saccade_velocity: float saccade_latency: float pupil_size: float gaze_entropy: float eyelid_closure_rate: float
class AlcoholImpairmentDetector: """酒精损伤检测器 - 基于眼动特征""" def __init__(self, bac_threshold: float = 0.05): """ Args: bac_threshold: 血液酒精浓度阈值 (g/dL) 0.05 = Euro NCAP标准 0.08 = 美国多数州标准 """ self.bac_threshold = bac_threshold self.feature_weights = { 'blink_rate': 0.15, 'blink_duration_mean': 0.12, 'blink_duration_std': 0.18, 'saccade_velocity': 0.20, 'saccade_latency': 0.15, 'gaze_entropy': 0.12, 'eyelid_closure_rate': 0.08 } self.baselines = { 'blink_rate': (15, 20), 'blink_duration_mean': (100, 150), 'saccade_velocity': (200, 400), 'saccade_latency': (150, 250) } def extract_features(self, eye_data: List[dict], time_window: float = 60.0) -> EyeFeatures: """ 从眼动数据提取特征 Args: eye_data: 眼动数据序列 time_window: 时间窗口(秒) Returns: 提取的眼部特征 """ blinks = [d for d in eye_data if d.get('event') == 'blink'] blink_durations = [b['duration'] for b in blinks] blink_rate = len(blinks) / (time_window / 60) blink_mean = np.mean(blink_durations) if blink_durations else 0 blink_std = np.std(blink_durations) if blink_durations else 0 saccades = [d for d in eye_data if d.get('event') == 'saccade'] saccade_velocities = [s['velocity'] for s in saccades] saccade_latencies = [s['latency'] for s in saccades] saccade_velocity = np.mean(saccade_velocities) if saccade_velocities else 0 saccade_latency = np.mean(saccade_latencies) if saccade_latencies else 0 gaze_points = [(d['gaze_x'], d['gaze_y']) for d in eye_data if 'gaze_x' in d] gaze_entropy = self._calculate_entropy(gaze_points) closures = [d for d in eye_data if d.get('eyelid_closure', 0) > 0.8] eyelid_closure_rate = len(closures) / len(eye_data) if eye_data else 0 pupil_sizes = [d.get('pupil_diameter', 0) for d in eye_data if 'pupil_diameter' in d] pupil_size = np.mean(pupil_sizes) if pupil_sizes else 0 return EyeFeatures( blink_rate=blink_rate, blink_duration_mean=blink_mean, blink_duration_std=blink_std, saccade_velocity=saccade_velocity, saccade_latency=saccade_latency, pupil_size=pupil_size, gaze_entropy=gaze_entropy, eyelid_closure_rate=eyelid_closure_rate ) def _calculate_entropy(self, points: List[Tuple[float, float]]) -> float: """计算注视熵值""" if len(points) < 10: return 0.0 points_array = np.array(points) grid_size = 20 x_bins = np.linspace(points_array[:, 0].min(), points_array[:, 0].max(), grid_size) y_bins = np.linspace(points_array[:, 1].min(), points_array[:, 1].max(), grid_size) hist, _, _ = np.histogram2d(points_array[:, 0], points_array[:, 1], bins=[x_bins, y_bins]) prob = hist.flatten() / hist.sum() prob = prob[prob > 0] entropy = -np.sum(prob * np.log2(prob)) return entropy def detect_impairment(self, features: EyeFeatures) -> Tuple[ImpairmentLevel, float]: """ 检测酒精损伤等级 Args: features: 眼部特征 Returns: (损伤等级, 估计BAC值) """ score = 0.0 if features.blink_rate > self.baselines['blink_rate'][1] * 1.3: score += self.feature_weights['blink_rate'] * 0.8 elif features.blink_rate < self.baselines['blink_rate'][0] * 0.7: score += self.feature_weights['blink_rate'] * 0.5 if features.blink_duration_std > 50: score += self.feature_weights['blink_duration_std'] * min( features.blink_duration_std / 100, 1.0) if features.saccade_velocity < self.baselines['saccade_velocity'][0] * 0.8: velocity_ratio = (self.baselines['saccade_velocity'][0] * 0.8 - features.saccade_velocity) / self.baselines['saccade_velocity'][0] score += self.feature_weights['saccade_velocity'] * velocity_ratio if features.saccade_latency > self.baselines['saccade_latency'][1] * 1.2: latency_ratio = (features.saccade_latency - self.baselines['saccade_latency'][1] * 1.2) / 100 score += self.feature_weights['saccade_latency'] * latency_ratio if features.gaze_entropy < 2.0: score += self.feature_weights['gaze_entropy'] * (1 - features.gaze_entropy / 3) estimated_bac = score * 0.15 if estimated_bac < 0.02: level = ImpairmentLevel.NORMAL elif estimated_bac < 0.05: level = ImpairmentLevel.MILD elif estimated_bac < 0.08: level = ImpairmentLevel.MODERATE else: level = ImpairmentLevel.SEVERE return level, estimated_bac def get_intervention(self, level: ImpairmentLevel, estimated_bac: float) -> dict: """ 获取干预策略 Args: level: 损伤等级 estimated_bac: 估计BAC值 Returns: 干预建议 """ interventions = { ImpairmentLevel.NORMAL: { "action": "none", "message": None, "adas_adjustment": None }, ImpairmentLevel.MILD: { "action": "warn", "message": "检测到轻微疲劳迹象,建议休息", "adas_adjustment": { "warning_sensitivity": +0.1, "fcw_threshold": -0.5 } }, ImpairmentLevel.MODERATE: { "action": "alert", "message": "检测到驾驶能力下降,强烈建议停车休息", "adas_adjustment": { "warning_sensitivity": +0.2, "fcw_threshold": -1.0, "aeb_sensitivity": +0.1 } }, ImpairmentLevel.SEVERE: { "action": "intervene", "message": "检测到严重损伤,建议靠边停车", "adas_adjustment": { "warning_sensitivity": +0.3, "fcw_threshold": -1.5, "aeb_sensitivity": +0.2, "speed_limit": 80 }, "emergency_contact": True } } return interventions.get(level, interventions[ImpairmentLevel.NORMAL])
if __name__ == "__main__": detector = AlcoholImpairmentDetector(bac_threshold=0.05) np.random.seed(42) test_data = [] for i in range(1000): event = 'gaze' if np.random.random() > 0.1 else 'blink' data_point = { 'event': event, 'gaze_x': np.random.normal(0, 50), 'gaze_y': np.random.normal(0, 30), 'pupil_diameter': np.random.normal(4, 0.5) } if event == 'blink': data_point['duration'] = np.random.normal(180, 60) elif np.random.random() > 0.7: data_point['event'] = 'saccade' data_point['velocity'] = np.random.normal(150, 30) data_point['latency'] = np.random.normal(350, 50) test_data.append(data_point) features = detector.extract_features(test_data, time_window=60) print(f"眨眼频率: {features.blink_rate:.1f} 次/分钟") print(f"眼跳速度: {features.saccade_velocity:.1f} °/s") print(f"注视熵值: {features.gaze_entropy:.2f}") level, estimated_bac = detector.detect_impairment(features) print(f"\n损伤等级: {level.value}") print(f"估计BAC: {estimated_bac:.3f} g/dL") intervention = detector.get_intervention(level, estimated_bac) print(f"干预动作: {intervention['action']}") if intervention['message']: print(f"提示信息: {intervention['message']}")
|