Download preprocessing/silence_removal.py from JsonDONSON/Machine-Sound-Anomaly-Detector: direct link, hf CLI and curl.
- Browser
- Download file 1.53 kB
-
https://huggingface.co/spaces/JsonDONSON/Machine-Sound-Anomaly-Detector/resolve/main/preprocessing/silence_removal.py
- Command line
-
hf download hf://spaces/JsonDONSON/Machine-Sound-Anomaly-Detector/preprocessing/silence_removal.py
-
curl -L -o silence_removal.py https://huggingface.co/spaces/JsonDONSON/Machine-Sound-Anomaly-Detector/resolve/main/preprocessing/silence_removal.py
1.53 kB
| """ | |
| =============================================================================== | |
| preprocessing/silence_removal.py — Energy-Based Silence Trimming | |
| =============================================================================== | |
| """ | |
| import numpy as np | |
| import librosa | |
| from config import SILENCE_TOP_DB | |
| def remove_silence(audio, sr): | |
| """ | |
| Remove leading and trailing silence from the audio signal. | |
| Uses energy-based detection to find where the "real" sound starts and ends, | |
| then trims everything outside that window. | |
| Parameters | |
| ---------- | |
| audio : np.ndarray | |
| 1D array of audio samples. | |
| sr : int | |
| Sampling rate of the audio. | |
| Returns | |
| ------- | |
| np.ndarray | |
| Trimmed audio signal. If the entire signal is below the threshold, | |
| returns the original audio unchanged (safety fallback). | |
| Notes | |
| ----- | |
| - top_db is imported from config.py (default: 20 dB). | |
| - A small margin (frame_length=2048, hop_length=512) is used for | |
| energy estimation. These are independent of the mel spectrogram | |
| parameters — they only control how finely we detect silence boundaries. | |
| """ | |
| # TODO (EL sir): Implement silence removal. | |
| trimmed_audio, index = librosa.effects.trim( | |
| audio, | |
| top_db=SILENCE_TOP_DB, | |
| frame_length = 2048, | |
| hop_length = 512 | |
| ) | |
| if len(trimmed_audio) < 1024: | |
| return audio | |
| return trimmed_audio | |