Spaces:
Sleeping

File size: 2,454 Bytes
5a5e72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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