import whisper import jiwer import threading import string import os from pydub import AudioSegment from config import TEMP_DIR from config import WHISPER_MODEL_SIZE, PHONETIC_GAP_THRESHOLD class SpeechEngine: _instance = None _lock = threading.Lock() def __new__(cls): with cls._lock: if cls._instance is None: cls._instance = super(SpeechEngine, cls).__new__(cls) cls._instance.model = whisper.load_model(WHISPER_MODEL_SIZE) return cls._instance def _extract_and_normalize_audio(self, video_path, audio_path): """Standardization for Whisper (16kHz Mono) [cite: 2026-02-08].""" audio = AudioSegment.from_file(video_path, format="webm") audio = audio.set_channels(1).set_frame_rate(16000) if audio.max_dBFS < 0: audio = audio.apply_gain(-audio.max_dBFS) audio.export(audio_path, format="wav") return audio_path def _generate_alignment_and_blocks(self, segments, silence_threshold=PHONETIC_GAP_THRESHOLD): """Temporal Mapping & Silence (Phonetic Block) Detection [cite: 2026-02-21].""" word_alignment, phonetic_blocks = [], [] last_word_end = 0.0 for segment in segments: for word in segment.get('words', []): start, end = round(word['start'], 3), round(word['end'], 3) if last_word_end > 0 and (start - last_word_end) > silence_threshold: phonetic_blocks.append({ "start": last_word_end, "end": start, "duration": round(start - last_word_end, 2) }) word_alignment.append({ "word": self._normalize(word['word']), "start": start, "end": end, "confidence": round(word['probability'], 2) }) last_word_end = end return word_alignment, phonetic_blocks def _calculate_accuracy_raw(self, reference_text, hypothesis_text): """Clinical Accuracy Scoring (Raw WER decimal) [cite: 2026-02-21].""" ref, hyp = self._normalize(reference_text), self._normalize(hypothesis_text) if not hyp: return 1.0 return round(float(jiwer.wer(ref, hyp)), 4) def identify_struggles(self, word_alignment, phonetic_blocks): """Tags problematic words based on confidence or gaps.""" struggle_words, gap_starts = [], [b['start'] for b in phonetic_blocks] for word in word_alignment: is_low_conf = word['confidence'] < 0.6 is_pre_gap = any(abs(word['end'] - gs) < 0.3 for gs in gap_starts) if is_low_conf or is_pre_gap: struggle_words.append({ "word": word['word'], "reason": "Phonetic Block" if is_pre_gap else "Low Confidence", "timestamp": word['start'] }) return struggle_words def _normalize(self, text): return text.lower().translate(str.maketrans('', '', string.punctuation)).strip() def analyze_with_timestamps(self, video_path, target_text, session_id="default"): audio_path = os.path.join(TEMP_DIR, f"audio_{session_id}.wav") try: self._extract_and_normalize_audio(video_path, audio_path) result = self.model.transcribe(audio_path, fp16=False, word_timestamps=True) word_alignment, blocks = self._generate_alignment_and_blocks(result.get('segments', [])) raw_wer = self._calculate_accuracy_raw(target_text, result["text"]) struggle_words = self.identify_struggles(word_alignment, blocks) if os.path.exists(audio_path): os.remove(audio_path) return { "accuracy": {"wer": raw_wer}, "transcribed_text": result["text"].strip(), "word_alignment": word_alignment, "phonetic_blocks": blocks, "block_count": len(blocks), "struggle_words": struggle_words, "meta": {"audio_start_offset": result['segments'][0]['start'] if result.get('segments') else 0.0} } except Exception as e: if os.path.exists(audio_path): os.remove(audio_path) return {"accuracy": {"wer": 1.0}, "error": str(e), "word_alignment": [], "phonetic_blocks": [], "struggle_words": []} speech_engine = SpeechEngine()