""" Alert Management Module Handles generation and playback of alert sounds and voice warnings. Generates alert audio files at startup for use during detection. Uses gTTS for voice synthesis and generates alarm tones programmatically. """ import os import numpy as np import wave import struct import tempfile from pathlib import Path from typing import Optional class AlertManager: """ Manages alert audio generation for drowsiness warnings. Generates two types of alerts: 1. Alarm beep sound (attention-getting tone) 2. Voice alert ("Wake up! You are getting sleepy.") Audio files are generated once at initialization and cached. """ ASSETS_DIR = Path("assets") ALARM_FILENAME = "alarm.wav" VOICE_FILENAME = "voice_alert.wav" COMBINED_FILENAME = "combined_alert.wav" def __init__(self): """Initialize the alert manager and generate audio files.""" self.ASSETS_DIR.mkdir(exist_ok=True) self.alarm_path = self.ASSETS_DIR / self.ALARM_FILENAME self.voice_path = self.ASSETS_DIR / self.VOICE_FILENAME self.combined_path = self.ASSETS_DIR / self.COMBINED_FILENAME # Generate audio files if they don't exist self._generate_alarm_sound() self._generate_voice_alert() self._generate_combined_alert() def _generate_alarm_sound(self): """ Generate an alarm beep sound programmatically. Creates a series of beeps with increasing urgency. """ if self.alarm_path.exists(): return sample_rate = 44100 duration_per_beep = 0.15 # seconds pause_duration = 0.08 # seconds between beeps num_beeps = 6 frequencies = [880, 1100, 880, 1100, 880, 1100] # Alternating A5 and C#6 samples = [] for i in range(num_beeps): freq = frequencies[i] t = np.linspace( 0, duration_per_beep, int(sample_rate * duration_per_beep), endpoint=False, ) # Generate sine wave with envelope (fade in/out to avoid clicks) envelope = np.ones_like(t) fade_samples = int(0.01 * sample_rate) # 10ms fade envelope[:fade_samples] = np.linspace(0, 1, fade_samples) envelope[-fade_samples:] = np.linspace(1, 0, fade_samples) beep = 0.8 * np.sin(2 * np.pi * freq * t) * envelope # Add harmonics for a more attention-getting sound beep += 0.3 * np.sin(2 * np.pi * freq * 2 * t) * envelope beep += 0.1 * np.sin(2 * np.pi * freq * 3 * t) * envelope # Normalize beep = beep / np.max(np.abs(beep)) * 0.9 samples.extend(beep) # Add pause between beeps if i < num_beeps - 1: pause_samples = int(sample_rate * pause_duration) samples.extend([0.0] * pause_samples) self._write_wav(self.alarm_path, np.array(samples), sample_rate) def _generate_voice_alert(self): """ Generate voice alert using gTTS (Google Text-to-Speech). Falls back to a simple tone if gTTS is unavailable. """ if self.voice_path.exists(): return try: from gtts import gTTS from pydub import AudioSegment import io # Generate speech tts = gTTS( text="Wake up! You are getting sleepy. Please take a break.", lang="en", slow=False, ) # Save to temporary MP3 file, then convert to WAV with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp: tts.save(tmp.name) tmp_path = tmp.name # Convert MP3 to WAV using pydub audio = AudioSegment.from_mp3(tmp_path) audio = audio.set_frame_rate(44100).set_channels(1).set_sample_width(2) audio.export(str(self.voice_path), format="wav") # Clean up temp file os.unlink(tmp_path) except Exception as e: print(f"gTTS unavailable ({e}), generating fallback voice alert tone") self._generate_fallback_voice_alert() def _generate_fallback_voice_alert(self): """Generate a series of distinctive tones as fallback for voice alert.""" sample_rate = 44100 # Create a distinctive pattern: three descending tones samples = [] for freq in [660, 550, 440]: t = np.linspace(0, 0.4, int(sample_rate * 0.4), endpoint=False) envelope = np.ones_like(t) fade = int(0.02 * sample_rate) envelope[:fade] = np.linspace(0, 1, fade) envelope[-fade:] = np.linspace(1, 0, fade) tone = 0.7 * np.sin(2 * np.pi * freq * t) * envelope samples.extend(tone) samples.extend([0.0] * int(sample_rate * 0.1)) # Short pause self._write_wav(self.voice_path, np.array(samples), sample_rate) def _generate_combined_alert(self): """Combine alarm and voice into a single alert file.""" if self.combined_path.exists(): return try: from pydub import AudioSegment alarm = AudioSegment.from_wav(str(self.alarm_path)) voice = AudioSegment.from_wav(str(self.voice_path)) # Combine: alarm beeps followed by voice message combined = alarm + AudioSegment.silent(duration=300) + voice combined.export(str(self.combined_path), format="wav") except Exception as e: print(f"Could not combine alerts ({e}), using alarm only") # Copy alarm as combined import shutil shutil.copy2(str(self.alarm_path), str(self.combined_path)) @staticmethod def _write_wav(filepath: Path, samples: np.ndarray, sample_rate: int): """ Write audio samples to a WAV file. Args: filepath: Output file path samples: Audio samples (float64, range -1 to 1) sample_rate: Sample rate in Hz """ # Convert float samples to 16-bit integers int_samples = np.int16(samples * 32767) with wave.open(str(filepath), "w") as wav_file: wav_file.setnchannels(1) # Mono wav_file.setsampwidth(2) # 16-bit wav_file.setframerate(sample_rate) wav_file.writeframes(int_samples.tobytes()) def get_alert_audio_path(self) -> str: """ Get the path to the combined alert audio file. Returns: String path to the combined alert WAV file """ if self.combined_path.exists(): return str(self.combined_path) elif self.alarm_path.exists(): return str(self.alarm_path) return "" def get_alarm_path(self) -> str: """Get path to alarm-only audio.""" return str(self.alarm_path) if self.alarm_path.exists() else "" def get_voice_path(self) -> str: """Get path to voice-only alert.""" return str(self.voice_path) if self.voice_path.exists() else ""