Download utils/audio.py from devmm03/vs: direct link, hf CLI and curl.
- Browser
- Download file 4.73 kB
-
https://huggingface.co/spaces/devmm03/vs/resolve/main/utils/audio.py
- Command line
-
hf download hf://spaces/devmm03/vs/utils/audio.py
-
curl -L -o audio.py https://huggingface.co/spaces/devmm03/vs/resolve/main/utils/audio.py
4.73 kB
| """ | |
| Audio Utilities | |
| Common audio processing functions for loading, preprocessing, and segmentation. | |
| """ | |
| import io | |
| import base64 | |
| import numpy as np | |
| import librosa | |
| import soundfile as sf | |
| from pathlib import Path | |
| from typing import Union, Tuple, Optional | |
| import tempfile | |
| import os | |
| import sys | |
| sys.path.insert(0, str(Path(__file__).parent.parent)) | |
| from config import SAMPLE_RATE, DURATION, TEMP_DIR | |
| def load_audio( | |
| source: Union[str, Path, bytes], | |
| sr: int = SAMPLE_RATE, | |
| mono: bool = True | |
| ) -> Tuple[np.ndarray, int]: | |
| """ | |
| Load audio from file path, bytes, or base64 string. | |
| Args: | |
| source: File path, raw bytes, or base64-encoded audio | |
| sr: Target sample rate | |
| mono: Convert to mono if True | |
| Returns: | |
| Tuple of (audio_array, sample_rate) | |
| """ | |
| if isinstance(source, (str, Path)): | |
| # Load from file path | |
| audio, sample_rate = librosa.load(source, sr=sr, mono=mono) | |
| elif isinstance(source, bytes): | |
| # Load from bytes | |
| with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp: | |
| tmp.write(source) | |
| tmp_path = tmp.name | |
| try: | |
| audio, sample_rate = librosa.load(tmp_path, sr=sr, mono=mono) | |
| finally: | |
| os.unlink(tmp_path) | |
| else: | |
| raise ValueError(f"Unsupported source type: {type(source)}") | |
| return audio, sample_rate | |
| def decode_base64_audio( | |
| audio_base64: str, | |
| audio_format: str = "wav", | |
| sr: int = SAMPLE_RATE, | |
| mono: bool = True | |
| ) -> Tuple[np.ndarray, int]: | |
| """ | |
| Decode base64-encoded audio and load it. | |
| Args: | |
| audio_base64: Base64-encoded audio string | |
| audio_format: Audio format (wav, mp3, etc.) | |
| sr: Target sample rate | |
| mono: Convert to mono if True | |
| Returns: | |
| Tuple of (audio_array, sample_rate) | |
| """ | |
| audio_bytes = base64.b64decode(audio_base64) | |
| return load_audio(audio_bytes, sr=sr, mono=mono) | |
| def preprocess_audio( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| normalize: bool = True, | |
| trim_silence: bool = True, | |
| top_db: int = 20 | |
| ) -> np.ndarray: | |
| """ | |
| Preprocess audio: normalize amplitude and optionally trim silence. | |
| Args: | |
| audio: Audio array | |
| sr: Sample rate | |
| normalize: Normalize amplitude to [-1, 1] | |
| trim_silence: Remove leading/trailing silence | |
| top_db: Threshold for silence trimming | |
| Returns: | |
| Preprocessed audio array | |
| """ | |
| # Trim silence | |
| if trim_silence: | |
| audio, _ = librosa.effects.trim(audio, top_db=top_db) | |
| # Normalize | |
| if normalize: | |
| max_val = np.max(np.abs(audio)) | |
| if max_val > 0: | |
| audio = audio / max_val | |
| return audio | |
| def segment_audio( | |
| audio: np.ndarray, | |
| sr: int = SAMPLE_RATE, | |
| segment_duration: float = DURATION, | |
| overlap: float = 0.5 | |
| ) -> list: | |
| """ | |
| Segment audio into fixed-length chunks. | |
| Args: | |
| audio: Audio array | |
| sr: Sample rate | |
| segment_duration: Duration of each segment in seconds | |
| overlap: Overlap ratio between segments (0-1) | |
| Returns: | |
| List of audio segments | |
| """ | |
| segment_samples = int(segment_duration * sr) | |
| hop_samples = int(segment_samples * (1 - overlap)) | |
| segments = [] | |
| start = 0 | |
| while start + segment_samples <= len(audio): | |
| segment = audio[start:start + segment_samples] | |
| segments.append(segment) | |
| start += hop_samples | |
| # Handle last segment if there's remaining audio | |
| if start < len(audio): | |
| # Pad the last segment if needed | |
| last_segment = audio[start:] | |
| if len(last_segment) >= segment_samples // 2: # Only if at least half length | |
| padded = np.zeros(segment_samples) | |
| padded[:len(last_segment)] = last_segment | |
| segments.append(padded) | |
| return segments | |
| def ensure_length( | |
| audio: np.ndarray, | |
| target_length: int, | |
| pad_mode: str = "constant" | |
| ) -> np.ndarray: | |
| """ | |
| Ensure audio has exact target length by padding or truncating. | |
| Args: | |
| audio: Audio array | |
| target_length: Target number of samples | |
| pad_mode: Padding mode ('constant', 'reflect', etc.) | |
| Returns: | |
| Audio array with exact target length | |
| """ | |
| if len(audio) > target_length: | |
| return audio[:target_length] | |
| elif len(audio) < target_length: | |
| padding = target_length - len(audio) | |
| return np.pad(audio, (0, padding), mode=pad_mode) | |
| return audio | |
| def get_audio_duration(audio: np.ndarray, sr: int = SAMPLE_RATE) -> float: | |
| """Get duration of audio in seconds.""" | |
| return len(audio) / sr | |