Spaces:
Sleeping
Sleeping
Download s2f/qualified_audio.py from ProgramComputer/Speech2Face: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/spaces/ProgramComputer/Speech2Face/resolve/main/s2f/qualified_audio.py
- Command line
-
hf download hf://spaces/ProgramComputer/Speech2Face/s2f/qualified_audio.py
-
curl -L -o qualified_audio.py https://huggingface.co/spaces/ProgramComputer/Speech2Face/resolve/main/s2f/qualified_audio.py
2.45 kB
| from __future__ import annotations | |
| import io | |
| from pathlib import Path | |
| from . import runtime as _runtime | |
| import numpy as np | |
| from .asset_contract import need | |
| from .audio_features import repeat_or_trim_waveform | |
| MAX_AUDIO_BYTES = 32 << 20 | |
| def decode_audio_file(audio_path: str | Path) -> np.ndarray: | |
| import av | |
| need(av.__version__ == "12.3.0" and np.__version__ == "2.2.6", "Audio runtime versions differ") | |
| path = Path(audio_path) | |
| need(path.is_file() and 0 < path.stat().st_size <= MAX_AUDIO_BYTES, "The recording is empty") | |
| raw = path.read_bytes() | |
| need(0 < len(raw) <= MAX_AUDIO_BYTES, "Audio bytes exceed per-row bound") | |
| seconds = 6 | |
| retained: list[np.ndarray] | |
| retained, kept, decoded_samples, errors = [], 0, 0, 0 | |
| target = seconds * 16000 | |
| with av.open(io.BytesIO(raw), mode="r") as container: | |
| need(container.streams.audio, "No audio stream") | |
| stream = container.streams.audio[0] | |
| stream.codec_context.thread_count = 1 | |
| resampler = av.AudioResampler(format="fltp", layout="mono", rate=16000) | |
| def keep(frames: list[av.AudioFrame]) -> None: | |
| nonlocal kept | |
| for frame in frames: | |
| wave = frame.to_ndarray().reshape(-1).astype(np.float32, copy=False) | |
| need(np.isfinite(wave).all(), "Non-finite resampled waveform") | |
| length = min(len(wave), target - kept) | |
| if length > 0: | |
| retained.append(wave[:length].copy()) | |
| kept += length | |
| for packet in container.demux(stream): | |
| try: | |
| frames = packet.decode() | |
| except av.error.FFmpegError: | |
| errors += 1 | |
| if errors > 64: | |
| break | |
| continue | |
| for frame in frames: | |
| decoded_samples += int(frame.samples) | |
| keep(resampler.resample(frame)) | |
| keep(resampler.resample(None)) | |
| context = stream.codec_context | |
| channels = getattr(context, "channels", None) or len(context.layout.channels) | |
| observed = { | |
| "audio_codec": str(context.name), | |
| "audio_sample_rate": int(context.sample_rate), | |
| "audio_channels": int(channels), | |
| "audio_decoded_samples": decoded_samples, | |
| } | |
| need(kept > 0, "No decodable waveform") | |
| waveform = repeat_or_trim_waveform(np.concatenate(retained), target) | |
| return waveform | |