duongve commited on
Commit
0eb9e91
·
verified ·
1 Parent(s): 531efa1

Update QA_result/check.txt.txt

Browse files
Files changed (1) hide show
  1. QA_result/check.txt.txt +682 -619
QA_result/check.txt.txt CHANGED
@@ -1,620 +1,683 @@
1
- """
2
- Emotion Detection Service Module
3
-
4
- Provides async emotion detection from audio with:
5
- - Concurrent request handling via semaphores
6
- - Audio chunking for multi-emotion detection
7
- - Temporary file management
8
- - Thread-safe model inference
9
- """
10
-
11
- import asyncio
12
- import os
13
- import uuid
14
- import threading
15
- import numpy as np
16
- import soundfile as sf
17
- from pathlib import Path
18
- from typing import Dict, List, Optional, Tuple, Any
19
- from datetime import datetime
20
- from collections import defaultdict
21
-
22
- from .config import EmotionConfig, get_emotion_config
23
- from .history import EmotionHistory, EmotionTurn, build_emotion_prompt_context
24
-
25
-
26
- def _ensure_mono_1d(audio: np.ndarray) -> np.ndarray:
27
- """
28
- Ensure audio is a 1D mono array.
29
-
30
- Handles various audio formats:
31
- - Already 1D: return as-is
32
- - (samples, channels): transpose and average channels
33
- - (channels, samples): average channels
34
- - (1, samples) or (samples, 1): squeeze to 1D
35
-
36
- Args:
37
- audio: Audio data as numpy array (1D or 2D)
38
-
39
- Returns:
40
- 1D mono audio array
41
- """
42
- if audio.ndim == 1:
43
- return audio
44
-
45
- if audio.ndim != 2:
46
- # For higher dimensional arrays, try to flatten
47
- print(f"[EMOTION] Warning: unexpected audio shape {audio.shape}, attempting to flatten")
48
- return audio.flatten()
49
-
50
- # 2D array - determine format and convert to mono
51
- rows, cols = audio.shape
52
-
53
- # Check if one dimension is small (likely channels: 1 or 2)
54
- if rows <= 2 and cols > 2:
55
- # Shape is (channels, samples) - average across axis 0
56
- if rows == 1:
57
- return audio.squeeze(axis=0)
58
- else:
59
- return np.mean(audio, axis=0)
60
-
61
- elif cols <= 2 and rows > 2:
62
- # Shape is (samples, channels) - average across axis 1
63
- if cols == 1:
64
- return audio.squeeze(axis=1)
65
- else:
66
- return np.mean(audio, axis=1)
67
-
68
- else:
69
- # Both dimensions are large or both are small
70
- # Heuristic: if rows > cols, assume (samples, channels)
71
- if rows > cols:
72
- if cols == 1:
73
- return audio.squeeze(axis=1)
74
- return np.mean(audio, axis=1)
75
- else:
76
- if rows == 1:
77
- return audio.squeeze(axis=0)
78
- return np.mean(audio, axis=0)
79
-
80
-
81
- class EmotionDetectionService:
82
- """
83
- Async-safe emotion detection service.
84
-
85
- Handles:
86
- - Audio preprocessing and chunking
87
- - Concurrent request management via semaphores
88
- - Temporary file lifecycle
89
- - Model inference with thread safety
90
- """
91
-
92
- def __init__(self, config: Optional[EmotionConfig] = None):
93
- """
94
- Initialize the emotion detection service.
95
-
96
- Args:
97
- config: Optional EmotionConfig. If not provided, loads from .env
98
- """
99
- self.config = config or get_emotion_config()
100
- self._model = None
101
- self._model_lock = threading.Lock()
102
- self._semaphore: Optional[asyncio.Semaphore] = None
103
- self._history = EmotionHistory()
104
- self._initialized = False
105
-
106
- # Track active requests for debugging
107
- self._active_requests: Dict[str, datetime] = {}
108
- self._request_lock = threading.Lock()
109
-
110
- if self.config.enabled:
111
- self._initialize()
112
-
113
- def _initialize(self):
114
- """Initialize the service (load model, create directories)."""
115
- if self._initialized:
116
- return
117
-
118
- try:
119
- # Create temp directory
120
- Path(self.config.temp_audio_dir).mkdir(parents=True, exist_ok=True)
121
- print(f"[EMOTION] Temp audio directory: {self.config.temp_audio_dir}")
122
-
123
- # Create semaphore for concurrent task limiting
124
- self._semaphore = asyncio.Semaphore(self.config.max_concurrent_tasks)
125
- print(f"[EMOTION] Max concurrent tasks: {self.config.max_concurrent_tasks}")
126
-
127
- # Lazy load model on first use
128
- self._initialized = True
129
- print(f"[EMOTION] Service initialized successfully")
130
-
131
- except Exception as e:
132
- print(f"[EMOTION] Failed to initialize service: {e}")
133
- self.config.enabled = False
134
-
135
- def _ensure_model(self):
136
- """Ensure model is loaded (lazy loading with thread safety)."""
137
- if self._model is not None:
138
- return
139
-
140
- with self._model_lock:
141
- if self._model is not None:
142
- return
143
-
144
- try:
145
- import onnxruntime as ort
146
-
147
- # Check available providers
148
- available = ort.get_available_providers()
149
- providers = []
150
- if "CUDAExecutionProvider" in available:
151
- providers.append("CUDAExecutionProvider")
152
- print(f"[EMOTION] CUDA available, using GPU acceleration")
153
- providers.append("CPUExecutionProvider")
154
-
155
- # Load model
156
- self._model = ort.InferenceSession(
157
- self.config.model_path,
158
- providers=providers
159
- )
160
-
161
- # Log model info
162
- actual_provider = self._model.get_providers()[0]
163
- print(f"[EMOTION] Model loaded from: {self.config.model_path}")
164
- print(f"[EMOTION] Running on: {actual_provider}")
165
-
166
- except Exception as e:
167
- print(f"[EMOTION] Failed to load model: {e}")
168
- self.config.enabled = False
169
- raise
170
-
171
- def _generate_request_id(self) -> str:
172
- """Generate unique request ID for tracking."""
173
- return f"emo_{uuid.uuid4().hex[:12]}_{int(datetime.now().timestamp() * 1000)}"
174
-
175
- def _get_temp_audio_path(self, request_id: str, chunk_idx: int = 0) -> str:
176
- """
177
- Generate temporary audio file path.
178
-
179
- Args:
180
- request_id: Unique request identifier
181
- chunk_idx: Index of audio chunk (for multi-emotion)
182
-
183
- Returns:
184
- Full path to temporary audio file
185
- """
186
- filename = f"{request_id}_chunk{chunk_idx}{self.config.audio_extension}"
187
- return os.path.join(self.config.temp_audio_dir, filename)
188
-
189
- def _split_audio_into_chunks(
190
- self,
191
- audio: np.ndarray,
192
- sample_rate: int,
193
- chunk_duration: int
194
- ) -> List[np.ndarray]:
195
- """
196
- Split audio into fixed-duration chunks.
197
-
198
- Args:
199
- audio: Audio data as numpy array (1D or 2D)
200
- sample_rate: Sample rate of audio
201
- chunk_duration: Duration of each chunk in seconds
202
-
203
- Returns:
204
- List of audio chunks as numpy arrays (1D mono)
205
- """
206
- # Ensure audio is 1D mono before processing
207
- audio = _ensure_mono_1d(audio)
208
-
209
- chunk_samples = chunk_duration * sample_rate
210
- total_samples = len(audio)
211
-
212
- if total_samples <= chunk_samples:
213
- # Single chunk, pad if needed
214
- if total_samples < chunk_samples:
215
- audio = np.pad(audio, (0, chunk_samples - total_samples), mode='constant')
216
- return [audio]
217
-
218
- # Split into multiple chunks
219
- chunks = []
220
- for start in range(0, total_samples, chunk_samples):
221
- end = start + chunk_samples
222
- chunk = audio[start:end]
223
-
224
- # Pad last chunk if needed
225
- if len(chunk) < chunk_samples:
226
- chunk = np.pad(chunk, (0, chunk_samples - len(chunk)), mode='constant')
227
-
228
- chunks.append(chunk)
229
-
230
- return chunks
231
-
232
- async def _save_audio_chunk(
233
- self,
234
- audio: np.ndarray,
235
- sample_rate: int,
236
- path: str
237
- ) -> bool:
238
- """
239
- Save audio chunk to file asynchronously.
240
-
241
- Args:
242
- audio: Audio data
243
- sample_rate: Sample rate
244
- path: Output file path
245
-
246
- Returns:
247
- True if successful
248
- """
249
- try:
250
- # Run file I/O in thread pool
251
- await asyncio.get_event_loop().run_in_executor(
252
- None,
253
- lambda: sf.write(path, audio.astype(np.float32), sample_rate)
254
- )
255
- return True
256
- except Exception as e:
257
- print(f"[EMOTION] Failed to save audio chunk: {e}")
258
- return False
259
-
260
- def _cleanup_temp_file(self, path: str):
261
- """Remove temporary audio file."""
262
- if self.config.cleanup_temp_files:
263
- try:
264
- if os.path.exists(path):
265
- os.remove(path)
266
- except Exception as e:
267
- print(f"[EMOTION] Failed to cleanup temp file {path}: {e}")
268
-
269
- def _run_inference(self, audio_path: str) -> Dict[str, float]:
270
- """
271
- Run emotion inference on audio file.
272
-
273
- Args:
274
- audio_path: Path to audio file
275
-
276
- Returns:
277
- Dict mapping emotion class to confidence score
278
- """
279
- self._ensure_model()
280
-
281
- try:
282
- import librosa
283
- from audio_emotion_detection.preprocessing import MelSTFT
284
-
285
- # Get model input/output info
286
- input_name = self._model.get_inputs()[0].name
287
- output_name = self._model.get_outputs()[0].name
288
-
289
- # Preprocess audio
290
- mel = MelSTFT(n_mels=128, sr=32000, win_length=800, hopsize=320)
291
- waveform, _ = librosa.core.load(audio_path, sr=32000, mono=True)
292
- waveform = np.stack([waveform])
293
- spec = mel(waveform)
294
-
295
- # Ensure correct temporal dimension (400 frames for ~4s audio)
296
- if spec.shape[-1] > 400:
297
- spec = spec[:, :, :400]
298
- else:
299
- spec = np.pad(spec, ((0, 0), (0, 0), (0, 400 - spec.shape[-1])), mode='constant')
300
-
301
- spec = np.expand_dims(spec, axis=0).astype(np.float32)
302
-
303
- # Run inference
304
- output = self._model.run([output_name], {input_name: spec})
305
-
306
- # Softmax
307
- logits = output[0][0]
308
- exp_logits = np.exp(logits - np.max(logits))
309
- probs = exp_logits / np.sum(exp_logits)
310
-
311
- # Map to emotion classes
312
- results = {}
313
- for i, class_name in enumerate(self.config.class_labels):
314
- results[class_name] = float(probs[i])
315
-
316
- return results
317
-
318
- except Exception as e:
319
- print(f"[EMOTION] Inference failed: {e}")
320
- import traceback
321
- traceback.print_exc()
322
- return {}
323
-
324
- async def detect_emotion(
325
- self,
326
- audio: np.ndarray,
327
- sample_rate: int,
328
- request_id: Optional[str] = None
329
- ) -> Dict[str, float]:
330
- """
331
- Detect emotion from single audio segment.
332
-
333
- Args:
334
- audio: Audio data as numpy array (1D or 2D)
335
- sample_rate: Sample rate of audio
336
- request_id: Optional request ID for tracking
337
-
338
- Returns:
339
- Dict mapping emotion class to confidence score
340
- """
341
- if not self.config.enabled:
342
- return {}
343
-
344
- request_id = request_id or self._generate_request_id()
345
-
346
- # Ensure audio is 1D mono before processing
347
- audio = _ensure_mono_1d(audio)
348
-
349
- # Track request
350
- with self._request_lock:
351
- self._active_requests[request_id] = datetime.now()
352
-
353
- try:
354
- # Acquire semaphore for concurrency control
355
- async with self._semaphore:
356
- # Resample if needed
357
- if sample_rate != self.config.sample_rate:
358
- try:
359
- import librosa
360
- audio = librosa.resample(
361
- audio.astype(np.float32),
362
- orig_sr=sample_rate,
363
- target_sr=self.config.sample_rate
364
- )
365
- sample_rate = self.config.sample_rate
366
- except Exception as e:
367
- print(f"[EMOTION] Resampling failed: {e}")
368
-
369
- # Ensure correct duration
370
- target_samples = self.config.audio_duration * sample_rate
371
- if len(audio) > target_samples:
372
- audio = audio[:target_samples]
373
- elif len(audio) < target_samples:
374
- audio = np.pad(audio, (0, target_samples - len(audio)), mode='constant')
375
-
376
- # Save to temp file
377
- temp_path = self._get_temp_audio_path(request_id)
378
- if not await self._save_audio_chunk(audio, sample_rate, temp_path):
379
- return {}
380
-
381
- try:
382
- # Run inference in thread pool
383
- result = await asyncio.wait_for(
384
- asyncio.get_event_loop().run_in_executor(
385
- None,
386
- self._run_inference,
387
- temp_path
388
- ),
389
- timeout=self.config.detection_timeout
390
- )
391
- return result
392
- finally:
393
- # Cleanup temp file
394
- self._cleanup_temp_file(temp_path)
395
-
396
- except asyncio.TimeoutError:
397
- print(f"[EMOTION] Detection timeout for request {request_id}")
398
- return {}
399
- except Exception as e:
400
- print(f"[EMOTION] Detection failed for request {request_id}: {e}")
401
- return {}
402
- finally:
403
- # Remove from active requests
404
- with self._request_lock:
405
- self._active_requests.pop(request_id, None)
406
-
407
- async def detect_emotions_multi(
408
- self,
409
- audio: np.ndarray,
410
- sample_rate: int,
411
- request_id: Optional[str] = None
412
- ) -> List[Dict[str, float]]:
413
- """
414
- Detect emotions from audio with multiple chunks.
415
-
416
- If multi_emotion_per_conversation is enabled, splits audio into
417
- chunks and detects emotion for each. Otherwise, uses first chunk only.
418
-
419
- Args:
420
- audio: Audio data as numpy array (1D or 2D)
421
- sample_rate: Sample rate of audio
422
- request_id: Optional request ID for tracking
423
-
424
- Returns:
425
- List of dicts, each mapping emotion class to confidence score
426
- """
427
- if not self.config.enabled:
428
- return []
429
-
430
- request_id = request_id or self._generate_request_id()
431
-
432
- # Ensure audio is 1D mono before processing
433
- audio = _ensure_mono_1d(audio)
434
-
435
- # Resample if needed
436
- if sample_rate != self.config.sample_rate:
437
- try:
438
- import librosa
439
- audio = librosa.resample(
440
- audio.astype(np.float32),
441
- orig_sr=sample_rate,
442
- target_sr=self.config.sample_rate
443
- )
444
- sample_rate = self.config.sample_rate
445
- except Exception as e:
446
- print(f"[EMOTION] Resampling failed: {e}")
447
- return []
448
-
449
- if not self.config.multi_emotion_per_conversation:
450
- # Single chunk mode
451
- result = await self.detect_emotion(audio, sample_rate, request_id)
452
- return [result] if result else []
453
-
454
- # Multi-chunk mode
455
- chunks = self._split_audio_into_chunks(
456
- audio, sample_rate, self.config.audio_duration
457
- )
458
-
459
- print(f"[EMOTION] Processing {len(chunks)} audio chunks for request {request_id}")
460
-
461
- # Process chunks concurrently
462
- tasks = []
463
- for i, chunk in enumerate(chunks):
464
- chunk_request_id = f"{request_id}_c{i}"
465
- tasks.append(self.detect_emotion(chunk, sample_rate, chunk_request_id))
466
-
467
- results = await asyncio.gather(*tasks, return_exceptions=True)
468
-
469
- # Filter out failures
470
- valid_results = []
471
- for result in results:
472
- if isinstance(result, dict) and result:
473
- valid_results.append(result)
474
- elif isinstance(result, Exception):
475
- print(f"[EMOTION] Chunk detection failed: {result}")
476
-
477
- return valid_results
478
-
479
- def aggregate_emotions(
480
- self,
481
- emotion_results: List[Dict[str, float]]
482
- ) -> Dict[str, float]:
483
- """
484
- Aggregate emotions from multiple chunks into single result.
485
-
486
- Uses average confidence across all chunks.
487
-
488
- Args:
489
- emotion_results: List of emotion dicts from each chunk
490
-
491
- Returns:
492
- Aggregated emotion dict with average confidences
493
- """
494
- if not emotion_results:
495
- return {}
496
-
497
- if len(emotion_results) == 1:
498
- return emotion_results[0]
499
-
500
- # Average across all results
501
- aggregated = defaultdict(float)
502
- for result in emotion_results:
503
- for emotion, confidence in result.items():
504
- aggregated[emotion] += confidence
505
-
506
- n = len(emotion_results)
507
- return {k: v / n for k, v in aggregated.items()}
508
-
509
- async def process_conversation_turn(
510
- self,
511
- user_id: str,
512
- text: str,
513
- audio: np.ndarray,
514
- sample_rate: int
515
- ) -> Tuple[EmotionTurn, bool, str]:
516
- """
517
- Process a full conversation turn with emotion tracking.
518
-
519
- This is the main entry point for integrating emotion detection
520
- into the conversation pipeline.
521
-
522
- Args:
523
- user_id: User identifier for tracking
524
- text: Transcribed text from STT
525
- audio: Audio data (1D or 2D)
526
- sample_rate: Sample rate
527
-
528
- Returns:
529
- Tuple of:
530
- - EmotionTurn object
531
- - bool: Whether empathy should be triggered
532
- - str: Emotion prompt context (empty if no empathy needed)
533
- """
534
- if not self.config.enabled or not text.strip():
535
- return None, False, ""
536
-
537
- request_id = self._generate_request_id()
538
-
539
- # Log audio shape for debugging
540
- print(f"[EMOTION] Processing turn for user {user_id}, request {request_id}, audio shape: {audio.shape}")
541
-
542
- # Detect emotions (multi-chunk if enabled)
543
- emotion_results = await self.detect_emotions_multi(audio, sample_rate, request_id)
544
-
545
- if not emotion_results:
546
- print(f"[EMOTION] No emotions detected for request {request_id}")
547
- return None, False, ""
548
-
549
- # Aggregate results
550
- aggregated = self.aggregate_emotions(emotion_results)
551
-
552
- print(f"[EMOTION] Detected emotions: {aggregated}")
553
-
554
- # Record in history
555
- turn = self._history.add_turn(
556
- user_id=user_id,
557
- text=text,
558
- emotions=aggregated,
559
- negative_classes=self.config.negative_classes,
560
- min_confidence_scores=self.config.min_confidence_scores
561
- )
562
-
563
- print(f"[EMOTION] Turn recorded - negative majority: {turn.is_negative_majority}")
564
-
565
- # Check if empathy should be triggered
566
- should_empathize, negative_turns = self._history.should_trigger_empathy(
567
- user_id=user_id,
568
- consecutive_threshold=self.config.consecutive_count
569
- )
570
-
571
- emotion_prompt = ""
572
- if should_empathize:
573
- print(f"[EMOTION] Triggering empathetic response for user {user_id}")
574
- emotion_prompt = build_emotion_prompt_context(negative_turns)
575
-
576
- return turn, should_empathize, emotion_prompt
577
-
578
- def get_user_emotion_summary(self, user_id: str) -> Dict:
579
- """Get emotion summary for a user."""
580
- return self._history.get_emotion_summary(user_id)
581
-
582
- def reset_user_emotions(self, user_id: str):
583
- """Reset emotion history for a user."""
584
- self._history.reset_user_history(user_id)
585
-
586
- def get_active_request_count(self) -> int:
587
- """Get count of currently active emotion detection requests."""
588
- with self._request_lock:
589
- return len(self._active_requests)
590
-
591
-
592
- # Global service instance (lazy loaded)
593
- _GLOBAL_SERVICE: Optional[EmotionDetectionService] = None
594
- _SERVICE_LOCK = threading.Lock()
595
-
596
-
597
- def get_emotion_service() -> EmotionDetectionService:
598
- """Get the global emotion detection service instance."""
599
- global _GLOBAL_SERVICE
600
- if _GLOBAL_SERVICE is None:
601
- with _SERVICE_LOCK:
602
- if _GLOBAL_SERVICE is None:
603
- _GLOBAL_SERVICE = EmotionDetectionService()
604
- return _GLOBAL_SERVICE
605
-
606
-
607
- def initialize_emotion_service(config: Optional[EmotionConfig] = None) -> EmotionDetectionService:
608
- """
609
- Initialize or reinitialize the global emotion service.
610
-
611
- Args:
612
- config: Optional config. If not provided, loads from .env
613
-
614
- Returns:
615
- The initialized service instance
616
- """
617
- global _GLOBAL_SERVICE
618
- with _SERVICE_LOCK:
619
- _GLOBAL_SERVICE = EmotionDetectionService(config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  return _GLOBAL_SERVICE
 
1
+ """
2
+ Emotion Detection Service Module
3
+
4
+ Provides async emotion detection from audio with:
5
+ - Concurrent request handling via semaphores
6
+ - Audio chunking for multi-emotion detection
7
+ - Temporary file management
8
+ - Thread-safe model inference
9
+ """
10
+
11
+ import asyncio
12
+ import os
13
+ import uuid
14
+ import threading
15
+ import numpy as np
16
+ import soundfile as sf
17
+ from pathlib import Path
18
+ from typing import Dict, List, Optional, Tuple, Any
19
+ from datetime import datetime
20
+ from collections import defaultdict
21
+
22
+ from .config import EmotionConfig, get_emotion_config
23
+ from .history import EmotionHistory, EmotionTurn, build_emotion_prompt_context
24
+
25
+
26
+ def _normalize_audio_to_float32(audio: np.ndarray) -> np.ndarray:
27
+ """
28
+ Normalize audio to float32 in range [-1, 1].
29
+
30
+ This is critical for soundfile.write which expects float32 audio
31
+ to be in the [-1, 1] range. Without normalization, audio gets
32
+ clipped and distorted.
33
+
34
+ Args:
35
+ audio: Audio data as numpy array (int16, int32, float32, float64)
36
+
37
+ Returns:
38
+ float32 audio normalized to [-1, 1] range
39
+ """
40
+ if audio.dtype == np.int16:
41
+ # int16 range: -32768 to 32767
42
+ return audio.astype(np.float32) / 32768.0
43
+ elif audio.dtype == np.int32:
44
+ # int32 range: -2147483648 to 2147483647
45
+ return audio.astype(np.float32) / 2147483648.0
46
+ elif audio.dtype in (np.float32, np.float64):
47
+ audio = audio.astype(np.float32)
48
+ # Check if already normalized (values in [-1, 1])
49
+ max_val = np.max(np.abs(audio))
50
+ if max_val > 1.0:
51
+ # Likely int16 values stored as float, normalize
52
+ if max_val > 32767:
53
+ # Likely int32 range
54
+ return audio / 2147483648.0
55
+ else:
56
+ # Likely int16 range
57
+ return audio / 32768.0
58
+ return audio
59
+ else:
60
+ # For other types, convert to float32 and check range
61
+ audio = audio.astype(np.float32)
62
+ max_val = np.max(np.abs(audio))
63
+ if max_val > 1.0:
64
+ # Normalize by max value to prevent clipping
65
+ return audio / max_val
66
+ return audio
67
+
68
+
69
+ def _ensure_mono_1d(audio: np.ndarray) -> np.ndarray:
70
+ """
71
+ Ensure audio is a 1D mono array, normalized to float32 [-1, 1].
72
+
73
+ Handles various audio formats:
74
+ - Already 1D: normalize and return
75
+ - (samples, channels): average channels and normalize
76
+ - (channels, samples): average channels and normalize
77
+ - (1, samples) or (samples, 1): squeeze to 1D and normalize
78
+
79
+ Args:
80
+ audio: Audio data as numpy array (1D or 2D, any dtype)
81
+
82
+ Returns:
83
+ 1D mono audio array as float32 in [-1, 1] range
84
+ """
85
+ # First normalize to float32 to avoid issues with integer overflow in np.mean
86
+ audio = _normalize_audio_to_float32(audio)
87
+
88
+ if audio.ndim == 1:
89
+ return audio
90
+
91
+ if audio.ndim != 2:
92
+ # For higher dimensional arrays, try to flatten
93
+ print(f"[EMOTION] Warning: unexpected audio shape {audio.shape}, attempting to flatten")
94
+ return audio.flatten()
95
+
96
+ # 2D array - determine format and convert to mono
97
+ rows, cols = audio.shape
98
+
99
+ # Check if one dimension is small (likely channels: 1 or 2)
100
+ if rows <= 2 and cols > 2:
101
+ # Shape is (channels, samples) - average across axis 0
102
+ if rows == 1:
103
+ return audio.squeeze(axis=0)
104
+ else:
105
+ return np.mean(audio, axis=0).astype(np.float32)
106
+
107
+ elif cols <= 2 and rows > 2:
108
+ # Shape is (samples, channels) - average across axis 1
109
+ if cols == 1:
110
+ return audio.squeeze(axis=1)
111
+ else:
112
+ return np.mean(audio, axis=1).astype(np.float32)
113
+
114
+ else:
115
+ # Both dimensions are large or both are small
116
+ # Heuristic: if rows > cols, assume (samples, channels)
117
+ if rows > cols:
118
+ if cols == 1:
119
+ return audio.squeeze(axis=1)
120
+ return np.mean(audio, axis=1).astype(np.float32)
121
+ else:
122
+ if rows == 1:
123
+ return audio.squeeze(axis=0)
124
+ return np.mean(audio, axis=0).astype(np.float32)
125
+
126
+
127
+ class EmotionDetectionService:
128
+ """
129
+ Async-safe emotion detection service.
130
+
131
+ Handles:
132
+ - Audio preprocessing and chunking
133
+ - Concurrent request management via semaphores
134
+ - Temporary file lifecycle
135
+ - Model inference with thread safety
136
+ """
137
+
138
+ def __init__(self, config: Optional[EmotionConfig] = None):
139
+ """
140
+ Initialize the emotion detection service.
141
+
142
+ Args:
143
+ config: Optional EmotionConfig. If not provided, loads from .env
144
+ """
145
+ self.config = config or get_emotion_config()
146
+ self._model = None
147
+ self._model_lock = threading.Lock()
148
+ self._semaphore: Optional[asyncio.Semaphore] = None
149
+ self._history = EmotionHistory()
150
+ self._initialized = False
151
+
152
+ # Track active requests for debugging
153
+ self._active_requests: Dict[str, datetime] = {}
154
+ self._request_lock = threading.Lock()
155
+
156
+ if self.config.enabled:
157
+ self._initialize()
158
+
159
+ def _initialize(self):
160
+ """Initialize the service (load model, create directories)."""
161
+ if self._initialized:
162
+ return
163
+
164
+ try:
165
+ # Create temp directory
166
+ Path(self.config.temp_audio_dir).mkdir(parents=True, exist_ok=True)
167
+ print(f"[EMOTION] Temp audio directory: {self.config.temp_audio_dir}")
168
+
169
+ # Create semaphore for concurrent task limiting
170
+ self._semaphore = asyncio.Semaphore(self.config.max_concurrent_tasks)
171
+ print(f"[EMOTION] Max concurrent tasks: {self.config.max_concurrent_tasks}")
172
+
173
+ # Lazy load model on first use
174
+ self._initialized = True
175
+ print(f"[EMOTION] Service initialized successfully")
176
+
177
+ except Exception as e:
178
+ print(f"[EMOTION] Failed to initialize service: {e}")
179
+ self.config.enabled = False
180
+
181
+ def _ensure_model(self):
182
+ """Ensure model is loaded (lazy loading with thread safety)."""
183
+ if self._model is not None:
184
+ return
185
+
186
+ with self._model_lock:
187
+ if self._model is not None:
188
+ return
189
+
190
+ try:
191
+ import onnxruntime as ort
192
+
193
+ # Check available providers
194
+ available = ort.get_available_providers()
195
+ providers = []
196
+ if "CUDAExecutionProvider" in available:
197
+ providers.append("CUDAExecutionProvider")
198
+ print(f"[EMOTION] CUDA available, using GPU acceleration")
199
+ providers.append("CPUExecutionProvider")
200
+
201
+ # Load model
202
+ self._model = ort.InferenceSession(
203
+ self.config.model_path,
204
+ providers=providers
205
+ )
206
+
207
+ # Log model info
208
+ actual_provider = self._model.get_providers()[0]
209
+ print(f"[EMOTION] Model loaded from: {self.config.model_path}")
210
+ print(f"[EMOTION] Running on: {actual_provider}")
211
+
212
+ except Exception as e:
213
+ print(f"[EMOTION] Failed to load model: {e}")
214
+ self.config.enabled = False
215
+ raise
216
+
217
+ def _generate_request_id(self) -> str:
218
+ """Generate unique request ID for tracking."""
219
+ return f"emo_{uuid.uuid4().hex[:12]}_{int(datetime.now().timestamp() * 1000)}"
220
+
221
+ def _get_temp_audio_path(self, request_id: str, chunk_idx: int = 0) -> str:
222
+ """
223
+ Generate temporary audio file path.
224
+
225
+ Args:
226
+ request_id: Unique request identifier
227
+ chunk_idx: Index of audio chunk (for multi-emotion)
228
+
229
+ Returns:
230
+ Full path to temporary audio file
231
+ """
232
+ filename = f"{request_id}_chunk{chunk_idx}{self.config.audio_extension}"
233
+ return os.path.join(self.config.temp_audio_dir, filename)
234
+
235
+ def _split_audio_into_chunks(
236
+ self,
237
+ audio: np.ndarray,
238
+ sample_rate: int,
239
+ chunk_duration: int
240
+ ) -> List[np.ndarray]:
241
+ """
242
+ Split audio into fixed-duration chunks.
243
+
244
+ Args:
245
+ audio: Audio data as numpy array (1D or 2D)
246
+ sample_rate: Sample rate of audio
247
+ chunk_duration: Duration of each chunk in seconds
248
+
249
+ Returns:
250
+ List of audio chunks as numpy arrays (1D mono)
251
+ """
252
+ # Ensure audio is 1D mono before processing
253
+ audio = _ensure_mono_1d(audio)
254
+
255
+ chunk_samples = chunk_duration * sample_rate
256
+ total_samples = len(audio)
257
+
258
+ if total_samples <= chunk_samples:
259
+ # Single chunk, pad if needed
260
+ if total_samples < chunk_samples:
261
+ audio = np.pad(audio, (0, chunk_samples - total_samples), mode='constant')
262
+ return [audio]
263
+
264
+ # Split into multiple chunks
265
+ chunks = []
266
+ for start in range(0, total_samples, chunk_samples):
267
+ end = start + chunk_samples
268
+ chunk = audio[start:end]
269
+
270
+ # Pad last chunk if needed
271
+ if len(chunk) < chunk_samples:
272
+ chunk = np.pad(chunk, (0, chunk_samples - len(chunk)), mode='constant')
273
+
274
+ chunks.append(chunk)
275
+
276
+ return chunks
277
+
278
+ async def _save_audio_chunk(
279
+ self,
280
+ audio: np.ndarray,
281
+ sample_rate: int,
282
+ path: str
283
+ ) -> bool:
284
+ """
285
+ Save audio chunk to file asynchronously.
286
+
287
+ Audio should already be normalized to float32 [-1, 1] by _ensure_mono_1d.
288
+ This method adds a safety check and clips to prevent distortion.
289
+
290
+ Args:
291
+ audio: Audio data (should be float32 in [-1, 1])
292
+ sample_rate: Sample rate
293
+ path: Output file path
294
+
295
+ Returns:
296
+ True if successful
297
+ """
298
+ try:
299
+ # Ensure audio is float32 and normalized
300
+ audio_to_save = _normalize_audio_to_float32(audio)
301
+
302
+ # Safety clip to prevent any distortion from edge cases
303
+ audio_to_save = np.clip(audio_to_save, -1.0, 1.0)
304
+
305
+ # Log audio stats for debugging
306
+ max_val = np.max(np.abs(audio_to_save))
307
+ print(f"[EMOTION] Saving audio: shape={audio_to_save.shape}, dtype={audio_to_save.dtype}, max_abs={max_val:.4f}")
308
+
309
+ # Run file I/O in thread pool
310
+ await asyncio.get_event_loop().run_in_executor(
311
+ None,
312
+ lambda: sf.write(path, audio_to_save, sample_rate)
313
+ )
314
+ return True
315
+ except Exception as e:
316
+ print(f"[EMOTION] Failed to save audio chunk: {e}")
317
+ import traceback
318
+ traceback.print_exc()
319
+ return False
320
+
321
+ def _cleanup_temp_file(self, path: str):
322
+ """Remove temporary audio file."""
323
+ if self.config.cleanup_temp_files:
324
+ try:
325
+ if os.path.exists(path):
326
+ os.remove(path)
327
+ except Exception as e:
328
+ print(f"[EMOTION] Failed to cleanup temp file {path}: {e}")
329
+
330
+ def _run_inference(self, audio_path: str) -> Dict[str, float]:
331
+ """
332
+ Run emotion inference on audio file.
333
+
334
+ Args:
335
+ audio_path: Path to audio file
336
+
337
+ Returns:
338
+ Dict mapping emotion class to confidence score
339
+ """
340
+ self._ensure_model()
341
+
342
+ try:
343
+ import librosa
344
+ from audio_emotion_detection.preprocessing import MelSTFT
345
+
346
+ # Get model input/output info
347
+ input_name = self._model.get_inputs()[0].name
348
+ output_name = self._model.get_outputs()[0].name
349
+
350
+ # Preprocess audio
351
+ mel = MelSTFT(n_mels=128, sr=32000, win_length=800, hopsize=320)
352
+ waveform, _ = librosa.core.load(audio_path, sr=32000, mono=True)
353
+ waveform = np.stack([waveform])
354
+ spec = mel(waveform)
355
+
356
+ # Ensure correct temporal dimension (400 frames for ~4s audio)
357
+ if spec.shape[-1] > 400:
358
+ spec = spec[:, :, :400]
359
+ else:
360
+ spec = np.pad(spec, ((0, 0), (0, 0), (0, 400 - spec.shape[-1])), mode='constant')
361
+
362
+ spec = np.expand_dims(spec, axis=0).astype(np.float32)
363
+
364
+ # Run inference
365
+ output = self._model.run([output_name], {input_name: spec})
366
+
367
+ # Softmax
368
+ logits = output[0][0]
369
+ exp_logits = np.exp(logits - np.max(logits))
370
+ probs = exp_logits / np.sum(exp_logits)
371
+
372
+ # Map to emotion classes
373
+ results = {}
374
+ for i, class_name in enumerate(self.config.class_labels):
375
+ results[class_name] = float(probs[i])
376
+
377
+ return results
378
+
379
+ except Exception as e:
380
+ print(f"[EMOTION] Inference failed: {e}")
381
+ import traceback
382
+ traceback.print_exc()
383
+ return {}
384
+
385
+ async def detect_emotion(
386
+ self,
387
+ audio: np.ndarray,
388
+ sample_rate: int,
389
+ request_id: Optional[str] = None
390
+ ) -> Dict[str, float]:
391
+ """
392
+ Detect emotion from single audio segment.
393
+
394
+ Args:
395
+ audio: Audio data as numpy array (1D or 2D)
396
+ sample_rate: Sample rate of audio
397
+ request_id: Optional request ID for tracking
398
+
399
+ Returns:
400
+ Dict mapping emotion class to confidence score
401
+ """
402
+ if not self.config.enabled:
403
+ return {}
404
+
405
+ request_id = request_id or self._generate_request_id()
406
+
407
+ # Ensure audio is 1D mono before processing
408
+ audio = _ensure_mono_1d(audio)
409
+
410
+ # Track request
411
+ with self._request_lock:
412
+ self._active_requests[request_id] = datetime.now()
413
+
414
+ try:
415
+ # Acquire semaphore for concurrency control
416
+ async with self._semaphore:
417
+ # Resample if needed
418
+ if sample_rate != self.config.sample_rate:
419
+ try:
420
+ import librosa
421
+ audio = librosa.resample(
422
+ audio.astype(np.float32),
423
+ orig_sr=sample_rate,
424
+ target_sr=self.config.sample_rate
425
+ )
426
+ sample_rate = self.config.sample_rate
427
+ except Exception as e:
428
+ print(f"[EMOTION] Resampling failed: {e}")
429
+
430
+ # Ensure correct duration
431
+ target_samples = self.config.audio_duration * sample_rate
432
+ if len(audio) > target_samples:
433
+ audio = audio[:target_samples]
434
+ elif len(audio) < target_samples:
435
+ audio = np.pad(audio, (0, target_samples - len(audio)), mode='constant')
436
+
437
+ # Save to temp file
438
+ temp_path = self._get_temp_audio_path(request_id)
439
+ if not await self._save_audio_chunk(audio, sample_rate, temp_path):
440
+ return {}
441
+
442
+ try:
443
+ # Run inference in thread pool
444
+ result = await asyncio.wait_for(
445
+ asyncio.get_event_loop().run_in_executor(
446
+ None,
447
+ self._run_inference,
448
+ temp_path
449
+ ),
450
+ timeout=self.config.detection_timeout
451
+ )
452
+ return result
453
+ finally:
454
+ # Cleanup temp file
455
+ self._cleanup_temp_file(temp_path)
456
+
457
+ except asyncio.TimeoutError:
458
+ print(f"[EMOTION] Detection timeout for request {request_id}")
459
+ return {}
460
+ except Exception as e:
461
+ print(f"[EMOTION] Detection failed for request {request_id}: {e}")
462
+ return {}
463
+ finally:
464
+ # Remove from active requests
465
+ with self._request_lock:
466
+ self._active_requests.pop(request_id, None)
467
+
468
+ async def detect_emotions_multi(
469
+ self,
470
+ audio: np.ndarray,
471
+ sample_rate: int,
472
+ request_id: Optional[str] = None
473
+ ) -> List[Dict[str, float]]:
474
+ """
475
+ Detect emotions from audio with multiple chunks.
476
+
477
+ If multi_emotion_per_conversation is enabled, splits audio into
478
+ chunks and detects emotion for each. Otherwise, uses first chunk only.
479
+
480
+ Args:
481
+ audio: Audio data as numpy array (1D or 2D)
482
+ sample_rate: Sample rate of audio
483
+ request_id: Optional request ID for tracking
484
+
485
+ Returns:
486
+ List of dicts, each mapping emotion class to confidence score
487
+ """
488
+ if not self.config.enabled:
489
+ return []
490
+
491
+ request_id = request_id or self._generate_request_id()
492
+
493
+ # Ensure audio is 1D mono before processing
494
+ audio = _ensure_mono_1d(audio)
495
+
496
+ # Resample if needed
497
+ if sample_rate != self.config.sample_rate:
498
+ try:
499
+ import librosa
500
+ audio = librosa.resample(
501
+ audio.astype(np.float32),
502
+ orig_sr=sample_rate,
503
+ target_sr=self.config.sample_rate
504
+ )
505
+ sample_rate = self.config.sample_rate
506
+ except Exception as e:
507
+ print(f"[EMOTION] Resampling failed: {e}")
508
+ return []
509
+
510
+ if not self.config.multi_emotion_per_conversation:
511
+ # Single chunk mode
512
+ result = await self.detect_emotion(audio, sample_rate, request_id)
513
+ return [result] if result else []
514
+
515
+ # Multi-chunk mode
516
+ chunks = self._split_audio_into_chunks(
517
+ audio, sample_rate, self.config.audio_duration
518
+ )
519
+
520
+ print(f"[EMOTION] Processing {len(chunks)} audio chunks for request {request_id}")
521
+
522
+ # Process chunks concurrently
523
+ tasks = []
524
+ for i, chunk in enumerate(chunks):
525
+ chunk_request_id = f"{request_id}_c{i}"
526
+ tasks.append(self.detect_emotion(chunk, sample_rate, chunk_request_id))
527
+
528
+ results = await asyncio.gather(*tasks, return_exceptions=True)
529
+
530
+ # Filter out failures
531
+ valid_results = []
532
+ for result in results:
533
+ if isinstance(result, dict) and result:
534
+ valid_results.append(result)
535
+ elif isinstance(result, Exception):
536
+ print(f"[EMOTION] Chunk detection failed: {result}")
537
+
538
+ return valid_results
539
+
540
+ def aggregate_emotions(
541
+ self,
542
+ emotion_results: List[Dict[str, float]]
543
+ ) -> Dict[str, float]:
544
+ """
545
+ Aggregate emotions from multiple chunks into single result.
546
+
547
+ Uses average confidence across all chunks.
548
+
549
+ Args:
550
+ emotion_results: List of emotion dicts from each chunk
551
+
552
+ Returns:
553
+ Aggregated emotion dict with average confidences
554
+ """
555
+ if not emotion_results:
556
+ return {}
557
+
558
+ if len(emotion_results) == 1:
559
+ return emotion_results[0]
560
+
561
+ # Average across all results
562
+ aggregated = defaultdict(float)
563
+ for result in emotion_results:
564
+ for emotion, confidence in result.items():
565
+ aggregated[emotion] += confidence
566
+
567
+ n = len(emotion_results)
568
+ return {k: v / n for k, v in aggregated.items()}
569
+
570
+ async def process_conversation_turn(
571
+ self,
572
+ user_id: str,
573
+ text: str,
574
+ audio: np.ndarray,
575
+ sample_rate: int
576
+ ) -> Tuple[EmotionTurn, bool, str]:
577
+ """
578
+ Process a full conversation turn with emotion tracking.
579
+
580
+ This is the main entry point for integrating emotion detection
581
+ into the conversation pipeline.
582
+
583
+ Args:
584
+ user_id: User identifier for tracking
585
+ text: Transcribed text from STT
586
+ audio: Audio data (1D or 2D)
587
+ sample_rate: Sample rate
588
+
589
+ Returns:
590
+ Tuple of:
591
+ - EmotionTurn object
592
+ - bool: Whether empathy should be triggered
593
+ - str: Emotion prompt context (empty if no empathy needed)
594
+ """
595
+ if not self.config.enabled or not text.strip():
596
+ return None, False, ""
597
+
598
+ request_id = self._generate_request_id()
599
+
600
+ # Log audio stats for debugging
601
+ max_abs = np.max(np.abs(audio)) if audio.size > 0 else 0
602
+ print(f"[EMOTION] Processing turn for user {user_id}, request {request_id}")
603
+ print(f"[EMOTION] Input audio: shape={audio.shape}, dtype={audio.dtype}, max_abs={max_abs:.4f}")
604
+
605
+ # Detect emotions (multi-chunk if enabled)
606
+ emotion_results = await self.detect_emotions_multi(audio, sample_rate, request_id)
607
+
608
+ if not emotion_results:
609
+ print(f"[EMOTION] No emotions detected for request {request_id}")
610
+ return None, False, ""
611
+
612
+ # Aggregate results
613
+ aggregated = self.aggregate_emotions(emotion_results)
614
+
615
+ print(f"[EMOTION] Detected emotions: {aggregated}")
616
+
617
+ # Record in history
618
+ turn = self._history.add_turn(
619
+ user_id=user_id,
620
+ text=text,
621
+ emotions=aggregated,
622
+ negative_classes=self.config.negative_classes,
623
+ min_confidence_scores=self.config.min_confidence_scores
624
+ )
625
+
626
+ print(f"[EMOTION] Turn recorded - negative majority: {turn.is_negative_majority}")
627
+
628
+ # Check if empathy should be triggered
629
+ should_empathize, negative_turns = self._history.should_trigger_empathy(
630
+ user_id=user_id,
631
+ consecutive_threshold=self.config.consecutive_count
632
+ )
633
+
634
+ emotion_prompt = ""
635
+ if should_empathize:
636
+ print(f"[EMOTION] Triggering empathetic response for user {user_id}")
637
+ emotion_prompt = build_emotion_prompt_context(negative_turns)
638
+
639
+ return turn, should_empathize, emotion_prompt
640
+
641
+ def get_user_emotion_summary(self, user_id: str) -> Dict:
642
+ """Get emotion summary for a user."""
643
+ return self._history.get_emotion_summary(user_id)
644
+
645
+ def reset_user_emotions(self, user_id: str):
646
+ """Reset emotion history for a user."""
647
+ self._history.reset_user_history(user_id)
648
+
649
+ def get_active_request_count(self) -> int:
650
+ """Get count of currently active emotion detection requests."""
651
+ with self._request_lock:
652
+ return len(self._active_requests)
653
+
654
+
655
+ # Global service instance (lazy loaded)
656
+ _GLOBAL_SERVICE: Optional[EmotionDetectionService] = None
657
+ _SERVICE_LOCK = threading.Lock()
658
+
659
+
660
+ def get_emotion_service() -> EmotionDetectionService:
661
+ """Get the global emotion detection service instance."""
662
+ global _GLOBAL_SERVICE
663
+ if _GLOBAL_SERVICE is None:
664
+ with _SERVICE_LOCK:
665
+ if _GLOBAL_SERVICE is None:
666
+ _GLOBAL_SERVICE = EmotionDetectionService()
667
+ return _GLOBAL_SERVICE
668
+
669
+
670
+ def initialize_emotion_service(config: Optional[EmotionConfig] = None) -> EmotionDetectionService:
671
+ """
672
+ Initialize or reinitialize the global emotion service.
673
+
674
+ Args:
675
+ config: Optional config. If not provided, loads from .env
676
+
677
+ Returns:
678
+ The initialized service instance
679
+ """
680
+ global _GLOBAL_SERVICE
681
+ with _SERVICE_LOCK:
682
+ _GLOBAL_SERVICE = EmotionDetectionService(config)
683
  return _GLOBAL_SERVICE