Spaces:
Runtime error
Runtime error
File size: 61,249 Bytes
8cbe6eb | 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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 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 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 | """
Audio processing and optimization for the voice control system.
This module provides audio format conversion, compression, noise reduction,
and provider-specific optimization for speech-to-text processing.
"""
import asyncio
import logging
import io
import struct
import wave
from typing import List, Optional, Dict, Any, Tuple
from dataclasses import dataclass
from .interfaces import AudioProcessorInterface
from .models import ProcessedAudio, AudioSegment, ProviderType
from .exceptions import AudioProcessingError, UnsupportedFormatError
from .utils import generate_fingerprint, clamp
from .config import get_config
logger = logging.getLogger(__name__)
@dataclass
class AudioFormat:
"""Audio format specification."""
format: str
sample_rate: int
channels: int
bit_depth: int
codec: Optional[str] = None
class AudioProcessor(AudioProcessorInterface):
"""
Audio processor for optimizing audio data for different STT providers.
Handles format conversion, compression, noise reduction, and provider-specific
audio optimization to improve transcription accuracy and reduce bandwidth usage.
"""
def __init__(self):
"""Initialize the audio processor."""
self.config = get_config()
self._provider_formats = self._load_provider_formats()
self._format_converters = self._initialize_converters()
def _load_provider_formats(self) -> Dict[str, AudioFormat]:
"""Load optimal audio formats for each provider type."""
return {
ProviderType.WEB_SPEECH_API.value: AudioFormat(
format="webm",
sample_rate=16000,
channels=1,
bit_depth=16,
codec="opus"
),
ProviderType.GOOGLE_SPEECH.value: AudioFormat(
format="wav",
sample_rate=16000,
channels=1,
bit_depth=16
),
ProviderType.AZURE_SPEECH.value: AudioFormat(
format="wav",
sample_rate=16000,
channels=1,
bit_depth=16
),
ProviderType.ASSEMBLY_AI.value: AudioFormat(
format="wav",
sample_rate=16000,
channels=1,
bit_depth=16
),
ProviderType.DEEPGRAM.value: AudioFormat(
format="webm",
sample_rate=16000,
channels=1,
bit_depth=16,
codec="opus"
)
}
def _initialize_converters(self) -> Dict[str, Any]:
"""Initialize format converters (placeholder for actual audio libraries)."""
# In a real implementation, this would initialize audio processing libraries
# like pydub, librosa, or ffmpeg-python
return {}
async def optimize_for_provider(
self,
audio_data: bytes,
provider: str,
target_format: Optional[str] = None
) -> ProcessedAudio:
"""
Optimize audio for a specific provider.
Args:
audio_data: Raw audio bytes
provider: Target provider name
target_format: Desired output format (optional)
Returns:
ProcessedAudio optimized for the provider
Raises:
AudioProcessingError: If optimization fails
UnsupportedFormatError: If format is not supported
"""
try:
logger.debug(f"Optimizing audio for provider: {provider}")
# Get provider's optimal format
provider_format = self._get_provider_format(provider)
if target_format:
provider_format.format = target_format
# Detect input audio format
input_format = await self._detect_audio_format(audio_data)
# Convert to optimal format if needed
if self._needs_conversion(input_format, provider_format):
audio_data = await self.convert_format(
audio_data,
input_format.format,
provider_format.format,
sample_rate=provider_format.sample_rate,
channels=provider_format.channels,
bit_depth=provider_format.bit_depth
)
# Apply noise reduction
if self.config.audio_processing.get("noise_reduction_enabled", True):
strength = self.config.audio_processing.get("noise_reduction_strength", 0.5)
audio_data = await self.apply_noise_reduction(audio_data, strength)
# Remove silence if enabled
silence_removed = False
if self.config.audio_processing.get("silence_removal_enabled", True):
segments = await self.detect_silence(audio_data)
if len(segments) > 1: # Only process if silence was detected
audio_data = await self._remove_silence_segments(audio_data, segments)
silence_removed = True
# Apply compression
compression_ratio = await self._apply_compression(
audio_data,
provider_format,
provider
)
# Calculate duration
duration = await self._calculate_duration(audio_data, provider_format)
return ProcessedAudio(
data=audio_data,
format=provider_format.format,
sample_rate=provider_format.sample_rate,
channels=provider_format.channels,
duration=duration,
provider=provider,
compression_ratio=compression_ratio,
noise_reduced=True,
silence_removed=silence_removed
)
except Exception as e:
logger.error(f"Audio optimization failed for provider {provider}: {e}")
raise AudioProcessingError("optimization", f"Failed to optimize audio: {e}")
def _get_provider_format(self, provider: str) -> AudioFormat:
"""Get the optimal audio format for a provider."""
# Try to match by provider type first
for provider_type in ProviderType:
if provider_type.value in provider.lower():
return self._provider_formats.get(provider_type.value, self._get_default_format())
# Fallback to default format
return self._get_default_format()
def _get_default_format(self) -> AudioFormat:
"""Get the default audio format."""
return AudioFormat(
format="wav",
sample_rate=16000,
channels=1,
bit_depth=16
)
async def _detect_audio_format(self, audio_data: bytes) -> AudioFormat:
"""
Detect the format of audio data.
This is a simplified implementation. In production, you would use
libraries like python-magic or analyze audio headers.
"""
# Check for WAV header
if audio_data.startswith(b'RIFF') and b'WAVE' in audio_data[:12]:
return await self._parse_wav_header(audio_data)
# Check for WebM header
if audio_data.startswith(b'\x1a\x45\xdf\xa3'):
return AudioFormat(format="webm", sample_rate=16000, channels=1, bit_depth=16, codec="opus")
# Check for MP3 header
if audio_data.startswith(b'ID3') or audio_data.startswith(b'\xff\xfb'):
return AudioFormat(format="mp3", sample_rate=44100, channels=2, bit_depth=16)
# Default assumption for unknown formats
logger.warning("Could not detect audio format, assuming WAV 16kHz mono")
return AudioFormat(format="wav", sample_rate=16000, channels=1, bit_depth=16)
async def _parse_wav_header(self, audio_data: bytes) -> AudioFormat:
"""Parse WAV file header to extract format information."""
try:
# WAV header parsing (simplified)
if len(audio_data) < 44:
raise AudioProcessingError("format_detection", "WAV file too small")
# Extract format information from WAV header
channels = struct.unpack('<H', audio_data[22:24])[0]
sample_rate = struct.unpack('<I', audio_data[24:28])[0]
bits_per_sample = struct.unpack('<H', audio_data[34:36])[0]
return AudioFormat(
format="wav",
sample_rate=sample_rate,
channels=channels,
bit_depth=bits_per_sample
)
except Exception as e:
logger.warning(f"Failed to parse WAV header: {e}")
return self._get_default_format()
def _needs_conversion(self, input_format: AudioFormat, target_format: AudioFormat) -> bool:
"""Check if audio format conversion is needed."""
return (
input_format.format != target_format.format or
input_format.sample_rate != target_format.sample_rate or
input_format.channels != target_format.channels or
input_format.bit_depth != target_format.bit_depth
)
async def convert_format(
self,
audio_data: bytes,
source_format: str,
target_format: str,
**kwargs
) -> bytes:
"""
Convert audio from one format to another.
Args:
audio_data: Raw audio bytes
source_format: Current audio format
target_format: Desired audio format
**kwargs: Format-specific options (sample_rate, channels, bit_depth)
Returns:
Converted audio bytes
Raises:
UnsupportedFormatError: If format conversion is not supported
AudioProcessingError: If conversion fails
"""
try:
logger.debug(f"Converting audio from {source_format} to {target_format}")
# Validate formats
if not self._is_format_supported(source_format):
raise UnsupportedFormatError("audio_processor", source_format, self.config.audio_processing.get("supported_formats", []))
if not self._is_format_supported(target_format):
raise UnsupportedFormatError("audio_processor", target_format, self.config.audio_processing.get("supported_formats", []))
# If formats are the same, just resample/rechannelize if needed
if source_format == target_format:
return await self._resample_audio(audio_data, **kwargs)
# Convert between different formats
if source_format == "webm" and target_format == "wav":
return await self._webm_to_wav(audio_data, **kwargs)
elif source_format == "wav" and target_format == "webm":
return await self._wav_to_webm(audio_data, **kwargs)
elif source_format == "mp3" and target_format == "wav":
return await self._mp3_to_wav(audio_data, **kwargs)
elif source_format == "wav" and target_format == "mp3":
return await self._wav_to_mp3(audio_data, **kwargs)
else:
# For unsupported conversions, use WAV as intermediate format
if source_format != "wav":
audio_data = await self.convert_format(audio_data, source_format, "wav", **kwargs)
if target_format != "wav":
audio_data = await self.convert_format(audio_data, "wav", target_format, **kwargs)
return audio_data
except UnsupportedFormatError:
# Re-raise UnsupportedFormatError without wrapping
raise
except Exception as e:
logger.error(f"Format conversion failed: {e}")
raise AudioProcessingError("format_conversion", f"Failed to convert {source_format} to {target_format}: {e}")
def _is_format_supported(self, format_str: str) -> bool:
"""Check if an audio format is supported."""
supported_formats = self.config.audio_processing.get("supported_formats", ["webm", "wav", "mp3", "ogg"])
return format_str.lower() in supported_formats
async def _resample_audio(self, audio_data: bytes, **kwargs) -> bytes:
"""
Resample audio to different sample rate/channels/bit depth.
This is a placeholder implementation. In production, you would use
libraries like librosa, scipy, or pydub for actual resampling.
"""
# Extract parameters
target_sample_rate = kwargs.get("sample_rate", 16000)
target_channels = kwargs.get("channels", 1)
target_bit_depth = kwargs.get("bit_depth", 16)
logger.debug(f"Resampling audio to {target_sample_rate}Hz, {target_channels} channels, {target_bit_depth}-bit")
# For now, return the original data
# In a real implementation, this would perform actual resampling
return audio_data
async def _webm_to_wav(self, audio_data: bytes, **kwargs) -> bytes:
"""Convert WebM audio to WAV format."""
# Placeholder implementation
# In production, use ffmpeg-python or similar library
logger.debug("Converting WebM to WAV (placeholder)")
# Create a simple WAV header for the converted audio
sample_rate = kwargs.get("sample_rate", 16000)
channels = kwargs.get("channels", 1)
bit_depth = kwargs.get("bit_depth", 16)
# This is a simplified conversion - in reality you'd decode WebM/Opus
return await self._create_wav_with_header(audio_data, sample_rate, channels, bit_depth)
async def _wav_to_webm(self, audio_data: bytes, **kwargs) -> bytes:
"""Convert WAV audio to WebM format."""
# Placeholder implementation
logger.debug("Converting WAV to WebM (placeholder)")
# In production, use ffmpeg-python to encode to WebM/Opus
return audio_data
async def _mp3_to_wav(self, audio_data: bytes, **kwargs) -> bytes:
"""Convert MP3 audio to WAV format."""
# Placeholder implementation
logger.debug("Converting MP3 to WAV (placeholder)")
# In production, use pydub or similar library
return audio_data
async def _wav_to_mp3(self, audio_data: bytes, **kwargs) -> bytes:
"""Convert WAV audio to MP3 format."""
# Placeholder implementation
logger.debug("Converting WAV to MP3 (placeholder)")
# In production, use pydub or similar library
return audio_data
async def _create_wav_with_header(
self,
audio_data: bytes,
sample_rate: int,
channels: int,
bit_depth: int
) -> bytes:
"""Create WAV file with proper header."""
# Calculate sizes
byte_rate = sample_rate * channels * bit_depth // 8
block_align = channels * bit_depth // 8
data_size = len(audio_data)
file_size = 36 + data_size
# Create WAV header
header = struct.pack('<4sI4s4sIHHIIHH4sI',
b'RIFF', # Chunk ID
file_size, # Chunk size
b'WAVE', # Format
b'fmt ', # Subchunk1 ID
16, # Subchunk1 size
1, # Audio format (PCM)
channels, # Number of channels
sample_rate, # Sample rate
byte_rate, # Byte rate
block_align, # Block align
bit_depth, # Bits per sample
b'data', # Subchunk2 ID
data_size # Subchunk2 size
)
return header + audio_data
async def detect_silence(
self,
audio_data: bytes,
threshold: float = None
) -> List[AudioSegment]:
"""
Detect silence in audio and return non-silent segments.
Enhanced implementation that:
- Uses configurable silence detection parameters
- Applies minimum segment duration filtering
- Handles edge cases and audio format variations
- Provides detailed segment timing information
Args:
audio_data: Raw audio bytes
threshold: Silence detection threshold (0.0 to 1.0), uses config default if None
Returns:
List of AudioSegment objects for non-silent parts
"""
try:
# Use configured threshold if not provided
if threshold is None:
threshold = self.config.audio_processing.get("silence_threshold", 0.01)
# Get additional silence detection parameters from config
min_silence_duration = self.config.audio_processing.get("min_silence_duration", 0.5) # seconds
min_speech_duration = self.config.audio_processing.get("min_speech_duration", 0.1) # seconds
window_size_ms = self.config.audio_processing.get("silence_window_size_ms", 50) # milliseconds
logger.debug(f"Detecting silence with threshold {threshold}, min_silence={min_silence_duration}s, min_speech={min_speech_duration}s")
# Parse audio format to get sample information
audio_format = await self._detect_audio_format(audio_data)
# Extract audio samples
samples = await self._extract_audio_samples(audio_data, audio_format)
if not samples or len(samples) == 0:
logger.warning("No audio samples found, returning empty segments")
return []
# Detect silence segments with enhanced algorithm
segments = await self._analyze_silence_enhanced(
samples,
audio_format,
threshold,
min_silence_duration,
min_speech_duration,
window_size_ms
)
# Filter out segments that are too short
filtered_segments = []
for segment in segments:
if segment.duration >= min_speech_duration:
filtered_segments.append(segment)
else:
logger.debug(f"Filtered out short segment: {segment.duration:.3f}s < {min_speech_duration}s")
logger.debug(f"Detected {len(filtered_segments)} non-silent segments (filtered from {len(segments)})")
# If no valid segments found, return entire audio as fallback
if not filtered_segments:
logger.info("No valid speech segments found, returning entire audio")
duration = len(samples) / audio_format.sample_rate
return [AudioSegment(
data=audio_data,
start_time=0.0,
end_time=duration,
sample_rate=audio_format.sample_rate,
channels=audio_format.channels,
format=audio_format.format
)]
return filtered_segments
except Exception as e:
logger.error(f"Silence detection failed: {e}")
# Return single segment containing all audio as fallback
duration = await self._estimate_audio_duration(audio_data)
return [AudioSegment(
data=audio_data,
start_time=0.0,
end_time=duration,
sample_rate=16000,
channels=1,
format="wav"
)]
async def _extract_audio_samples(self, audio_data: bytes, audio_format: AudioFormat) -> List[float]:
"""Extract normalized audio samples from raw audio data."""
# This is a simplified implementation for WAV files
if audio_format.format == "wav" and len(audio_data) > 44:
# Skip WAV header (44 bytes)
sample_data = audio_data[44:]
# Convert bytes to samples based on bit depth
if audio_format.bit_depth == 16:
# 16-bit signed integers
sample_count = len(sample_data) // 2
samples = struct.unpack(f'<{sample_count}h', sample_data[:sample_count * 2])
# Normalize to [-1.0, 1.0]
return [sample / 32768.0 for sample in samples]
elif audio_format.bit_depth == 8:
# 8-bit unsigned integers
samples = struct.unpack(f'{len(sample_data)}B', sample_data)
# Normalize to [-1.0, 1.0]
return [(sample - 128) / 128.0 for sample in samples]
# Fallback: return zeros
return [0.0] * 1000
async def _analyze_silence_enhanced(
self,
samples: List[float],
audio_format: AudioFormat,
threshold: float,
min_silence_duration: float,
min_speech_duration: float,
window_size_ms: float
) -> List[AudioSegment]:
"""
Enhanced silence analysis with configurable parameters.
Uses a more sophisticated algorithm that:
- Applies smoothing to reduce false positives
- Considers minimum durations for both silence and speech
- Uses energy-based detection with RMS calculation
- Handles edge cases at audio boundaries
"""
if not samples:
return []
# Calculate window parameters
window_size_samples = int(audio_format.sample_rate * window_size_ms / 1000)
window_size_samples = max(1, window_size_samples) # Ensure at least 1 sample
min_silence_samples = int(audio_format.sample_rate * min_silence_duration)
min_speech_samples = int(audio_format.sample_rate * min_speech_duration)
# Calculate energy for each window
energy_values = []
for i in range(0, len(samples), window_size_samples):
window = samples[i:i + window_size_samples]
if window:
# Calculate RMS energy
rms = (sum(sample ** 2 for sample in window) / len(window)) ** 0.5
energy_values.append(rms)
else:
energy_values.append(0.0)
# Apply smoothing to reduce noise in energy detection
smoothed_energy = await self._smooth_energy_values(energy_values)
# Classify windows as speech or silence
is_speech = [energy > threshold for energy in smoothed_energy]
# Find speech segments with minimum duration requirements
segments = []
current_segment_start = None
for i, speech_detected in enumerate(is_speech):
window_start_time = i * window_size_ms / 1000
if speech_detected and current_segment_start is None:
# Potential start of speech segment
current_segment_start = window_start_time
elif not speech_detected and current_segment_start is not None:
# Potential end of speech segment
segment_duration = window_start_time - current_segment_start
# Check if segment meets minimum duration
if segment_duration >= min_speech_duration:
# Extract actual audio data for this segment
start_sample = int(current_segment_start * audio_format.sample_rate)
end_sample = int(window_start_time * audio_format.sample_rate)
segment_data = await self._extract_segment_data(
samples[start_sample:end_sample],
audio_format
)
segments.append(AudioSegment(
data=segment_data,
start_time=current_segment_start,
end_time=window_start_time,
sample_rate=audio_format.sample_rate,
channels=audio_format.channels,
format=audio_format.format
))
current_segment_start = None
# Handle case where audio ends during speech
if current_segment_start is not None:
final_end_time = len(samples) / audio_format.sample_rate
segment_duration = final_end_time - current_segment_start
if segment_duration >= min_speech_duration:
start_sample = int(current_segment_start * audio_format.sample_rate)
segment_data = await self._extract_segment_data(
samples[start_sample:],
audio_format
)
segments.append(AudioSegment(
data=segment_data,
start_time=current_segment_start,
end_time=final_end_time,
sample_rate=audio_format.sample_rate,
channels=audio_format.channels,
format=audio_format.format
))
return segments
async def _smooth_energy_values(self, energy_values: List[float]) -> List[float]:
"""Apply smoothing to energy values to reduce false positives."""
if len(energy_values) < 3:
return energy_values
# Simple moving average smoothing
smoothed = []
window_size = 3
for i in range(len(energy_values)):
start_idx = max(0, i - window_size // 2)
end_idx = min(len(energy_values), i + window_size // 2 + 1)
window_values = energy_values[start_idx:end_idx]
smoothed.append(sum(window_values) / len(window_values))
return smoothed
async def _extract_segment_data(self, segment_samples: List[float], audio_format: AudioFormat) -> bytes:
"""Extract audio data for a specific segment."""
if not segment_samples:
return b''
# Convert samples back to bytes
segment_bytes = await self._samples_to_bytes(segment_samples, audio_format)
# Add WAV header if needed
if audio_format.format == "wav":
return await self._create_wav_with_header(
segment_bytes,
audio_format.sample_rate,
audio_format.channels,
audio_format.bit_depth
)
return segment_bytes
async def _estimate_audio_duration(self, audio_data: bytes) -> float:
"""Estimate audio duration for fallback cases."""
try:
audio_format = await self._detect_audio_format(audio_data)
return await self._calculate_duration(audio_data, audio_format)
except Exception:
# Very rough estimate: assume 16kHz, 16-bit, mono
return len(audio_data) / (16000 * 2)
async def _analyze_silence(
self,
samples: List[float],
audio_format: AudioFormat,
threshold: float
) -> List[AudioSegment]:
"""
Legacy silence analysis method (kept for backward compatibility).
This method is now deprecated in favor of _analyze_silence_enhanced.
"""
# Delegate to enhanced method with default parameters
return await self._analyze_silence_enhanced(
samples,
audio_format,
threshold,
min_silence_duration=0.5,
min_speech_duration=0.1,
window_size_ms=50
)
async def _remove_silence_segments(self, audio_data: bytes, segments: List[AudioSegment]) -> bytes:
"""Remove silence from audio data based on detected segments."""
# This is a placeholder implementation
# In production, you would extract and concatenate the non-silent segments
logger.debug(f"Removing silence from {len(segments)} segments")
return audio_data
async def apply_noise_reduction(
self,
audio_data: bytes,
strength: float = None
) -> bytes:
"""
Apply noise reduction to audio data.
Enhanced implementation that:
- Uses configurable noise reduction algorithms
- Supports multiple noise reduction techniques
- Adapts to different audio characteristics
- Preserves audio quality while reducing noise
Args:
audio_data: Raw audio bytes
strength: Noise reduction strength (0.0 to 1.0), uses config default if None
Returns:
Processed audio bytes with reduced noise
"""
try:
# Use configured strength if not provided
if strength is None:
strength = self.config.audio_processing.get("noise_reduction_strength", 0.5)
# Clamp strength to valid range
strength = clamp(strength, 0.0, 1.0)
# Get noise reduction configuration
algorithm = self.config.audio_processing.get("noise_reduction_algorithm", "spectral_subtraction")
adaptive = self.config.audio_processing.get("noise_reduction_adaptive", True)
preserve_speech = self.config.audio_processing.get("noise_reduction_preserve_speech", True)
logger.debug(f"Applying noise reduction: algorithm={algorithm}, strength={strength}, adaptive={adaptive}")
# Skip processing if strength is zero
if strength == 0.0:
logger.debug("Noise reduction strength is 0.0, skipping processing")
return audio_data
# Detect audio format and extract samples
audio_format = await self._detect_audio_format(audio_data)
samples = await self._extract_audio_samples(audio_data, audio_format)
if not samples:
logger.warning("No audio samples found for noise reduction")
return audio_data
# Apply noise reduction based on selected algorithm
if algorithm == "spectral_subtraction":
processed_samples = await self._apply_spectral_subtraction(
samples, audio_format, strength, adaptive
)
elif algorithm == "wiener_filter":
processed_samples = await self._apply_wiener_filter(
samples, audio_format, strength
)
elif algorithm == "adaptive_filter":
processed_samples = await self._apply_adaptive_filter(
samples, audio_format, strength
)
else:
logger.warning(f"Unknown noise reduction algorithm: {algorithm}, using spectral subtraction")
processed_samples = await self._apply_spectral_subtraction(
samples, audio_format, strength, adaptive
)
# Apply speech preservation if enabled
if preserve_speech:
processed_samples = await self._preserve_speech_characteristics(
samples, processed_samples, audio_format
)
# Convert back to bytes
processed_bytes = await self._samples_to_bytes(processed_samples, audio_format)
# Reconstruct audio with proper headers
if audio_format.format == "wav":
return await self._create_wav_with_header(
processed_bytes,
audio_format.sample_rate,
audio_format.channels,
audio_format.bit_depth
)
return processed_bytes
except Exception as e:
logger.error(f"Noise reduction failed: {e}")
# Return original audio on failure
return audio_data
async def _apply_spectral_subtraction(
self,
samples: List[float],
audio_format: AudioFormat,
strength: float,
adaptive: bool
) -> List[float]:
"""
Apply spectral subtraction noise reduction.
This is a simplified implementation. In production, you would use
libraries like librosa, scipy, or noisereduce for proper spectral analysis.
"""
# Estimate noise profile from the first 0.5 seconds (assumed to be mostly noise)
noise_samples = min(int(0.5 * audio_format.sample_rate), len(samples) // 4)
noise_profile = samples[:noise_samples] if noise_samples > 0 else samples[:100]
# Calculate noise energy
noise_energy = sum(sample ** 2 for sample in noise_profile) / len(noise_profile) if noise_profile else 0.01
# Apply spectral subtraction (simplified)
processed_samples = []
window_size = 512 # Small window for processing
for i in range(0, len(samples), window_size):
window = samples[i:i + window_size]
if not window:
break
# Calculate window energy
window_energy = sum(sample ** 2 for sample in window) / len(window)
# Determine noise reduction factor
if adaptive:
# Adaptive: reduce more noise in low-energy regions
snr_estimate = window_energy / (noise_energy + 1e-10)
reduction_factor = strength * (1.0 / (1.0 + snr_estimate))
else:
# Fixed reduction
reduction_factor = strength * 0.5
# Apply noise reduction
for sample in window:
# Simple noise gate with spectral subtraction approximation
if abs(sample) > noise_energy ** 0.5:
# Likely speech, apply minimal reduction
processed_sample = sample * (1.0 - reduction_factor * 0.3)
else:
# Likely noise, apply stronger reduction
processed_sample = sample * (1.0 - reduction_factor)
processed_samples.append(processed_sample)
return processed_samples
async def _apply_wiener_filter(
self,
samples: List[float],
audio_format: AudioFormat,
strength: float
) -> List[float]:
"""
Apply Wiener filter for noise reduction.
Simplified implementation of Wiener filtering.
"""
# Estimate signal and noise power
signal_power = sum(sample ** 2 for sample in samples) / len(samples)
# Estimate noise from quiet portions (simplified)
sorted_samples = sorted(abs(sample) for sample in samples)
noise_threshold_idx = int(len(sorted_samples) * 0.1) # Bottom 10% assumed to be noise
noise_power = sum(sorted_samples[:noise_threshold_idx]) / max(1, noise_threshold_idx)
noise_power = noise_power ** 2
# Calculate Wiener filter coefficient
wiener_coeff = signal_power / (signal_power + noise_power + 1e-10)
# Apply filter with strength adjustment
filter_strength = strength * wiener_coeff
processed_samples = [sample * (1.0 - filter_strength + filter_strength * wiener_coeff)
for sample in samples]
return processed_samples
async def _apply_adaptive_filter(
self,
samples: List[float],
audio_format: AudioFormat,
strength: float
) -> List[float]:
"""
Apply adaptive noise reduction filter.
Uses a simple adaptive algorithm that adjusts based on local signal characteristics.
"""
processed_samples = []
window_size = 256
for i in range(len(samples)):
# Define local window around current sample
start_idx = max(0, i - window_size // 2)
end_idx = min(len(samples), i + window_size // 2)
local_window = samples[start_idx:end_idx]
# Calculate local statistics
local_mean = sum(local_window) / len(local_window)
local_variance = sum((s - local_mean) ** 2 for s in local_window) / len(local_window)
local_std = local_variance ** 0.5
# Adaptive threshold based on local characteristics
adaptive_threshold = local_std * (1.0 + strength)
# Apply noise reduction
current_sample = samples[i]
if abs(current_sample - local_mean) > adaptive_threshold:
# Likely signal, preserve
processed_samples.append(current_sample)
else:
# Likely noise, reduce
reduction = strength * 0.7
processed_samples.append(current_sample * (1.0 - reduction))
return processed_samples
async def _preserve_speech_characteristics(
self,
original_samples: List[float],
processed_samples: List[float],
audio_format: AudioFormat
) -> List[float]:
"""
Preserve important speech characteristics after noise reduction.
This helps maintain speech intelligibility and naturalness.
"""
if len(original_samples) != len(processed_samples):
logger.warning("Sample length mismatch in speech preservation")
return processed_samples
# Calculate speech activity detection
speech_regions = await self._detect_speech_activity(original_samples, audio_format)
# Blend original and processed audio in speech regions
preserved_samples = []
for i, (original, processed) in enumerate(zip(original_samples, processed_samples)):
# Check if current sample is in a speech region
current_time = i / audio_format.sample_rate
is_speech_region = any(start <= current_time <= end for start, end in speech_regions)
if is_speech_region:
# In speech regions, blend more towards original
blend_factor = 0.7 # 70% original, 30% processed
final_sample = blend_factor * original + (1 - blend_factor) * processed
else:
# In non-speech regions, use more processed audio
blend_factor = 0.3 # 30% original, 70% processed
final_sample = blend_factor * original + (1 - blend_factor) * processed
preserved_samples.append(final_sample)
return preserved_samples
async def _detect_speech_activity(
self,
samples: List[float],
audio_format: AudioFormat
) -> List[tuple]:
"""
Detect regions of speech activity for preservation.
Returns list of (start_time, end_time) tuples for speech regions.
"""
speech_regions = []
window_size = audio_format.sample_rate // 20 # 50ms windows
speech_threshold = 0.02 # Energy threshold for speech detection
current_speech_start = None
for i in range(0, len(samples), window_size):
window = samples[i:i + window_size]
if not window:
break
# Calculate window energy
window_energy = sum(sample ** 2 for sample in window) / len(window)
window_time = i / audio_format.sample_rate
if window_energy > speech_threshold and current_speech_start is None:
# Start of speech region
current_speech_start = window_time
elif window_energy <= speech_threshold and current_speech_start is not None:
# End of speech region
speech_regions.append((current_speech_start, window_time))
current_speech_start = None
# Handle case where speech continues to end of audio
if current_speech_start is not None:
speech_regions.append((current_speech_start, len(samples) / audio_format.sample_rate))
return speech_regions
async def chunk_audio(
self,
audio_data: bytes,
chunk_duration: float = None,
overlap: float = None,
**kwargs
) -> List[AudioSegment]:
"""
Split audio into chunks of specified duration with configurable parameters.
Enhanced implementation that:
- Uses configurable chunk sizes based on provider requirements
- Supports intelligent chunking at silence boundaries
- Handles different overlap strategies
- Optimizes chunk sizes for different providers
Args:
audio_data: Raw audio bytes
chunk_duration: Duration of each chunk in seconds (uses config default if None)
overlap: Overlap between chunks in seconds (uses config default if None)
**kwargs: Additional chunking options:
- provider: Target provider for optimization
- boundary_detection: Whether to chunk at silence boundaries
- min_chunk_duration: Minimum chunk duration
- max_chunk_duration: Maximum chunk duration
Returns:
List of AudioSegment objects
"""
try:
# Use configured defaults if not provided
if chunk_duration is None:
chunk_duration = self.config.audio_processing.get("default_chunk_duration", 30.0)
if overlap is None:
overlap = self.config.audio_processing.get("default_chunk_overlap", 0.0)
# Get additional configuration
provider = kwargs.get("provider", None)
boundary_detection = kwargs.get("boundary_detection",
self.config.audio_processing.get("chunk_at_silence_boundaries", True))
min_chunk_duration = kwargs.get("min_chunk_duration",
self.config.audio_processing.get("min_chunk_duration", 1.0))
max_chunk_duration = kwargs.get("max_chunk_duration",
self.config.audio_processing.get("max_chunk_duration", 60.0))
# Optimize chunk parameters for specific provider
if provider:
chunk_duration, overlap = await self._optimize_chunking_for_provider(
provider, chunk_duration, overlap
)
# Validate parameters
chunk_duration = clamp(chunk_duration, min_chunk_duration, max_chunk_duration)
overlap = clamp(overlap, 0.0, chunk_duration * 0.8) # Max 80% overlap
logger.debug(f"Chunking audio: duration={chunk_duration}s, overlap={overlap}s, "
f"boundary_detection={boundary_detection}, provider={provider}")
# Detect audio format
audio_format = await self._detect_audio_format(audio_data)
# Calculate total audio duration
total_duration = await self._calculate_duration(audio_data, audio_format)
# If audio is shorter than chunk duration, return as single chunk
if total_duration <= chunk_duration:
logger.debug(f"Audio duration ({total_duration:.2f}s) <= chunk duration ({chunk_duration}s), returning single chunk")
return [AudioSegment(
data=audio_data,
start_time=0.0,
end_time=total_duration,
sample_rate=audio_format.sample_rate,
channels=audio_format.channels,
format=audio_format.format
)]
# Choose chunking strategy
if boundary_detection:
chunks = await self._chunk_at_boundaries(
audio_data, audio_format, chunk_duration, overlap,
min_chunk_duration, max_chunk_duration
)
else:
chunks = await self._chunk_fixed_duration(
audio_data, audio_format, chunk_duration, overlap
)
# Post-process chunks
chunks = await self._post_process_chunks(chunks, min_chunk_duration)
logger.debug(f"Created {len(chunks)} audio chunks")
return chunks
except Exception as e:
logger.error(f"Audio chunking failed: {e}")
raise AudioProcessingError("chunking", f"Failed to chunk audio: {e}")
async def _optimize_chunking_for_provider(
self,
provider: str,
default_duration: float,
default_overlap: float
) -> tuple:
"""
Optimize chunking parameters for specific provider requirements.
Different providers have different optimal chunk sizes and processing characteristics.
"""
provider_lower = provider.lower()
# Provider-specific optimizations
if "web_speech" in provider_lower:
# Web Speech API works well with shorter chunks for real-time processing
optimal_duration = min(default_duration, 10.0)
optimal_overlap = 0.5 # Small overlap for continuity
elif "google" in provider_lower:
# Google Speech-to-Text handles longer chunks well
optimal_duration = min(default_duration, 60.0)
optimal_overlap = default_overlap
elif "azure" in provider_lower:
# Azure Speech Services optimal chunk size
optimal_duration = min(default_duration, 30.0)
optimal_overlap = default_overlap
elif "assembly" in provider_lower:
# AssemblyAI works well with medium chunks
optimal_duration = min(default_duration, 45.0)
optimal_overlap = default_overlap
elif "deepgram" in provider_lower:
# Deepgram can handle longer chunks efficiently
optimal_duration = min(default_duration, 120.0)
optimal_overlap = default_overlap
else:
# Unknown provider, use defaults
optimal_duration = default_duration
optimal_overlap = default_overlap
logger.debug(f"Optimized chunking for {provider}: duration={optimal_duration}s, overlap={optimal_overlap}s")
return optimal_duration, optimal_overlap
async def _chunk_at_boundaries(
self,
audio_data: bytes,
audio_format: AudioFormat,
target_duration: float,
overlap: float,
min_duration: float,
max_duration: float
) -> List[AudioSegment]:
"""
Chunk audio at silence boundaries for more natural breaks.
This approach tries to split audio at natural pauses rather than
arbitrary time boundaries, which can improve transcription accuracy.
"""
# First, detect silence boundaries
silence_segments = await self.detect_silence(audio_data)
if not silence_segments:
# Fallback to fixed duration chunking
return await self._chunk_fixed_duration(audio_data, audio_format, target_duration, overlap)
# Extract silence boundary times
boundary_times = [0.0] # Start with beginning
for segment in silence_segments:
boundary_times.extend([segment.start_time, segment.end_time])
total_duration = await self._calculate_duration(audio_data, audio_format)
boundary_times.append(total_duration) # Add end
# Remove duplicates and sort
boundary_times = sorted(set(boundary_times))
# Create chunks based on boundaries
chunks = []
current_chunk_start = 0.0
for boundary_time in boundary_times[1:]: # Skip first boundary (0.0)
potential_chunk_duration = boundary_time - current_chunk_start
# Check if we should create a chunk
if potential_chunk_duration >= target_duration or boundary_time == total_duration:
# Create chunk
chunk_start = max(0.0, current_chunk_start - overlap)
chunk_end = boundary_time
# Ensure chunk doesn't exceed maximum duration
if chunk_end - chunk_start > max_duration:
# Split into multiple fixed-duration chunks
sub_chunks = await self._create_fixed_chunks_in_range(
audio_data, audio_format, chunk_start, chunk_end, target_duration, overlap
)
chunks.extend(sub_chunks)
else:
# Create single chunk
chunk_data = await self._extract_audio_range(
audio_data, audio_format, chunk_start, chunk_end
)
chunks.append(AudioSegment(
data=chunk_data,
start_time=chunk_start,
end_time=chunk_end,
sample_rate=audio_format.sample_rate,
channels=audio_format.channels,
format=audio_format.format
))
current_chunk_start = boundary_time - overlap
return chunks
async def _chunk_fixed_duration(
self,
audio_data: bytes,
audio_format: AudioFormat,
chunk_duration: float,
overlap: float
) -> List[AudioSegment]:
"""
Chunk audio into fixed-duration segments.
This is the traditional approach that splits audio at regular intervals.
"""
# Extract samples for processing
samples = await self._extract_audio_samples(audio_data, audio_format)
# Calculate chunk parameters
samples_per_chunk = int(chunk_duration * audio_format.sample_rate)
overlap_samples = int(overlap * audio_format.sample_rate)
step_size = samples_per_chunk - overlap_samples
chunks = []
for i in range(0, len(samples), step_size):
chunk_samples = samples[i:i + samples_per_chunk]
# Skip very short chunks at the end
if len(chunk_samples) < samples_per_chunk // 2:
break
start_time = i / audio_format.sample_rate
end_time = (i + len(chunk_samples)) / audio_format.sample_rate
# Convert samples back to bytes
chunk_data = await self._samples_to_bytes(chunk_samples, audio_format)
# Add proper audio headers
if audio_format.format == "wav":
chunk_data = await self._create_wav_with_header(
chunk_data,
audio_format.sample_rate,
audio_format.channels,
audio_format.bit_depth
)
chunks.append(AudioSegment(
data=chunk_data,
start_time=start_time,
end_time=end_time,
sample_rate=audio_format.sample_rate,
channels=audio_format.channels,
format=audio_format.format
))
return chunks
async def _create_fixed_chunks_in_range(
self,
audio_data: bytes,
audio_format: AudioFormat,
start_time: float,
end_time: float,
chunk_duration: float,
overlap: float
) -> List[AudioSegment]:
"""Create fixed-duration chunks within a specific time range."""
chunks = []
current_time = start_time
while current_time < end_time:
chunk_end = min(current_time + chunk_duration, end_time)
chunk_data = await self._extract_audio_range(
audio_data, audio_format, current_time, chunk_end
)
chunks.append(AudioSegment(
data=chunk_data,
start_time=current_time,
end_time=chunk_end,
sample_rate=audio_format.sample_rate,
channels=audio_format.channels,
format=audio_format.format
))
current_time += chunk_duration - overlap
return chunks
async def _extract_audio_range(
self,
audio_data: bytes,
audio_format: AudioFormat,
start_time: float,
end_time: float
) -> bytes:
"""Extract audio data for a specific time range."""
# Extract samples
samples = await self._extract_audio_samples(audio_data, audio_format)
# Calculate sample indices
start_sample = int(start_time * audio_format.sample_rate)
end_sample = int(end_time * audio_format.sample_rate)
# Extract range
range_samples = samples[start_sample:end_sample]
# Convert back to bytes
range_bytes = await self._samples_to_bytes(range_samples, audio_format)
# Add headers if needed
if audio_format.format == "wav":
return await self._create_wav_with_header(
range_bytes,
audio_format.sample_rate,
audio_format.channels,
audio_format.bit_depth
)
return range_bytes
async def _post_process_chunks(
self,
chunks: List[AudioSegment],
min_duration: float
) -> List[AudioSegment]:
"""
Post-process chunks to ensure quality and consistency.
- Filters out chunks that are too short
- Merges adjacent short chunks if beneficial
- Validates chunk integrity
"""
if not chunks:
return chunks
processed_chunks = []
for chunk in chunks:
# Filter out chunks that are too short
if chunk.duration >= min_duration:
processed_chunks.append(chunk)
else:
logger.debug(f"Filtered out short chunk: {chunk.duration:.3f}s < {min_duration}s")
# If we filtered out too many chunks, try to merge short chunks
if len(processed_chunks) < len(chunks) * 0.5 and len(chunks) > 1:
logger.debug("Too many chunks filtered, attempting to merge short chunks")
processed_chunks = await self._merge_short_chunks(chunks, min_duration)
return processed_chunks
async def _merge_short_chunks(
self,
chunks: List[AudioSegment],
min_duration: float
) -> List[AudioSegment]:
"""
Merge adjacent short chunks to meet minimum duration requirements.
"""
if not chunks:
return chunks
merged_chunks = []
current_merge_group = []
for chunk in chunks:
current_merge_group.append(chunk)
# Calculate total duration of current merge group
total_duration = sum(c.duration for c in current_merge_group)
if total_duration >= min_duration:
# Merge group meets minimum duration
if len(current_merge_group) == 1:
# Single chunk, add as-is
merged_chunks.append(current_merge_group[0])
else:
# Multiple chunks, merge them
merged_chunk = await self._merge_chunk_group(current_merge_group)
merged_chunks.append(merged_chunk)
current_merge_group = []
# Handle remaining chunks in merge group
if current_merge_group:
if len(current_merge_group) == 1:
merged_chunks.append(current_merge_group[0])
else:
merged_chunk = await self._merge_chunk_group(current_merge_group)
merged_chunks.append(merged_chunk)
return merged_chunks
async def _merge_chunk_group(self, chunk_group: List[AudioSegment]) -> AudioSegment:
"""
Merge a group of adjacent chunks into a single chunk.
"""
if not chunk_group:
raise ValueError("Cannot merge empty chunk group")
if len(chunk_group) == 1:
return chunk_group[0]
# Sort chunks by start time
sorted_chunks = sorted(chunk_group, key=lambda c: c.start_time)
# Combine audio data (simplified - assumes compatible formats)
combined_data = b''.join(chunk.data for chunk in sorted_chunks)
# Calculate merged chunk properties
start_time = sorted_chunks[0].start_time
end_time = sorted_chunks[-1].end_time
return AudioSegment(
data=combined_data,
start_time=start_time,
end_time=end_time,
sample_rate=sorted_chunks[0].sample_rate,
channels=sorted_chunks[0].channels,
format=sorted_chunks[0].format
)
async def _samples_to_bytes(self, samples: List[float], audio_format: AudioFormat) -> bytes:
"""Convert normalized samples back to bytes."""
if audio_format.bit_depth == 16:
# Convert to 16-bit signed integers
int_samples = [int(clamp(sample * 32767, -32768, 32767)) for sample in samples]
return struct.pack(f'<{len(int_samples)}h', *int_samples)
elif audio_format.bit_depth == 8:
# Convert to 8-bit unsigned integers
int_samples = [int(clamp((sample + 1.0) * 127.5, 0, 255)) for sample in samples]
return struct.pack(f'{len(int_samples)}B', *int_samples)
else:
# Fallback
return b'\x00' * len(samples) * 2
async def _apply_compression(
self,
audio_data: bytes,
audio_format: AudioFormat,
provider: str
) -> float:
"""
Apply audio compression optimized for the provider.
Returns:
Compression ratio achieved
"""
# This is a placeholder implementation
# In production, you would apply provider-specific compression
# For example:
# - WebM/Opus for Web Speech API and Deepgram
# - Compressed WAV for Google/Azure/AssemblyAI
original_size = len(audio_data)
# Simulate compression based on provider preferences
if "webm" in audio_format.format or "opus" in str(audio_format.codec):
# Opus compression typically achieves 8:1 ratio
compression_ratio = 0.125
elif audio_format.format == "mp3":
# MP3 compression typically achieves 10:1 ratio
compression_ratio = 0.1
else:
# Uncompressed formats
compression_ratio = 1.0
logger.debug(f"Applied compression for {provider}: {compression_ratio:.2f} ratio")
return compression_ratio
async def _calculate_duration(self, audio_data: bytes, audio_format: AudioFormat) -> float:
"""Calculate the duration of audio data."""
try:
if audio_format.format == "wav" and len(audio_data) > 44:
# For WAV files, calculate from data size
data_size = len(audio_data) - 44 # Subtract header size
bytes_per_sample = audio_format.bit_depth // 8
samples_per_second = audio_format.sample_rate * audio_format.channels
bytes_per_second = samples_per_second * bytes_per_sample
if bytes_per_second > 0:
return data_size / bytes_per_second
# Fallback estimation
# Assume 16kHz, 16-bit, mono for unknown formats
estimated_bytes_per_second = 16000 * 2 * 1 # 32KB/s
return len(audio_data) / estimated_bytes_per_second
except Exception as e:
logger.warning(f"Duration calculation failed: {e}")
return 1.0 # Default fallback |