Spaces:
Paused
Paused
Download src/audio_processor/converter.py from Consulawtech/NarratifAI: direct link, hf CLI and curl.
- Browser
- Download file 5 kB
-
https://huggingface.co/spaces/Consulawtech/NarratifAI/resolve/main/src/audio_processor/converter.py
- Command line
-
hf download hf://spaces/Consulawtech/NarratifAI/src/audio_processor/converter.py
-
curl -L -o converter.py https://huggingface.co/spaces/Consulawtech/NarratifAI/resolve/main/src/audio_processor/converter.py
5 kB
| """ | |
| Audio conversion and normalization module - Simplified without noisereduce | |
| Author: Maaldeens | |
| License: MIT | |
| """ | |
| import os | |
| import numpy as np | |
| import librosa | |
| import soundfile as sf | |
| from pydub import AudioSegment | |
| from pathlib import Path | |
| import tempfile | |
| import logging | |
| from typing import Optional | |
| import uuid | |
| logger = logging.getLogger(__name__) | |
| class AudioConverter: | |
| """ | |
| Converts audio to standard format for ASR processing | |
| Target: 16kHz mono WAV with normalized volume | |
| """ | |
| def __init__(self, target_sr: int = 16000, target_channels: int = 1, | |
| target_dbfs: int = -20, apply_noise_reduction: bool = False): # Disabled by default | |
| self.target_sr = target_sr | |
| self.target_channels = target_channels | |
| self.target_dbfs = target_dbfs | |
| self.apply_noise_reduction = False # Force disable | |
| self.temp_dir = Path(tempfile.gettempdir()) / "asr_temp" | |
| self.temp_dir.mkdir(exist_ok=True) | |
| def convert_to_wav(self, input_path: str, output_path: Optional[str] = None) -> str: | |
| """Convert any audio format to WAV using pydub""" | |
| if not output_path: | |
| output_path = str(self.temp_dir / f"{uuid.uuid4()}.wav") | |
| try: | |
| audio = AudioSegment.from_file(input_path) | |
| audio.export(output_path, format="wav") | |
| logger.info(f"Converted {input_path} to WAV: {output_path}") | |
| return output_path | |
| except Exception as e: | |
| logger.error(f"Conversion failed for {input_path}: {e}") | |
| raise | |
| def resample(self, input_path: str, target_sr: int = None) -> np.ndarray: | |
| """Resample audio to target sample rate""" | |
| target_sr = target_sr or self.target_sr | |
| try: | |
| audio, sr = librosa.load(input_path, sr=None, mono=False) | |
| if sr != target_sr: | |
| audio = librosa.resample(audio, orig_sr=sr, target_sr=target_sr) | |
| logger.info(f"Resampled from {sr}Hz to {target_sr}Hz") | |
| return audio | |
| except Exception as e: | |
| logger.error(f"Resampling failed: {e}") | |
| raise | |
| def convert_to_mono(self, audio: np.ndarray) -> np.ndarray: | |
| """Convert stereo to mono by averaging channels""" | |
| if audio.ndim > 1 and audio.shape[0] == 2: | |
| mono = np.mean(audio, axis=0) | |
| logger.info("Converted stereo to mono") | |
| return mono | |
| return audio | |
| def normalize_volume(self, audio: np.ndarray, sr: int, target_dbfs: int = None) -> np.ndarray: | |
| """Normalize audio volume to target dBFS""" | |
| target_dbfs = target_dbfs or self.target_dbfs | |
| # Simple peak normalization | |
| max_val = np.max(np.abs(audio)) | |
| if max_val > 0: | |
| # Target max amplitude of 0.95 to avoid clipping | |
| target_amplitude = 0.95 | |
| audio = audio * (target_amplitude / max_val) | |
| logger.info(f"Normalized volume (peak: {max_val:.3f} -> {target_amplitude:.3f})") | |
| return audio | |
| def preprocess(self, input_path: str, output_path: Optional[str] = None) -> str: | |
| """Complete preprocessing pipeline without noise reduction""" | |
| if not output_path: | |
| output_path = str(self.temp_dir / f"processed_{uuid.uuid4()}.wav") | |
| # Step 1: Convert to WAV if needed | |
| wav_path = self.convert_to_wav(input_path) if not input_path.lower().endswith('.wav') else input_path | |
| # Step 2: Load and resample | |
| audio = self.resample(wav_path) | |
| # Step 3: Convert to mono | |
| audio = self.convert_to_mono(audio) | |
| # Step 4: Normalize volume | |
| audio = self.normalize_volume(audio, self.target_sr) | |
| # Step 5: Trim leading/trailing silence — prevents Whisper from | |
| # hallucinating at the end when it encounters long silence. | |
| # top_db=20 was too aggressive and cut quiet speech at the edges | |
| # of phone recordings; 35 dB only removes genuine dead air. | |
| audio, kept = librosa.effects.trim(audio, top_db=35) | |
| # Seconds cut from the start. Timestamps are measured on the trimmed | |
| # audio, so the engine adds this back to line them up with the | |
| # original recording the user replays. | |
| self.last_trim_offset = float(kept[0]) / self.target_sr if len(kept) else 0.0 | |
| # Step 6: Save processed audio | |
| sf.write(output_path, audio, self.target_sr) | |
| logger.info(f"Saved processed audio to {output_path}") | |
| # Cleanup temporary WAV if created | |
| if wav_path != input_path and Path(wav_path).exists(): | |
| Path(wav_path).unlink() | |
| return output_path | |
| def cleanup(self): | |
| """Clean up temporary files""" | |
| for file in self.temp_dir.glob("*.wav"): | |
| try: | |
| file.unlink() | |
| except Exception as e: | |
| logger.warning(f"Failed to delete {file}: {e}") |