Update QA_result/check.txt.txt
Browse files- 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
|
| 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 |
-
if
|
| 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 |
-
self,
|
| 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 |
-
self
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
if
|
| 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 |
-
if
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
self
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
sample_rate
|
| 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 |
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
|