Spaces:
Sleeping

Speech2Face / s2f /qualified_audio.py
ProgramComputer's picture
Super-squash branch 'main' using huggingface_hub
5a5e72e
Raw History Blame Contribute Delete
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