Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Audio: keep PyAV decoding working on PyAV 19, and stop the tests needing an AMR encoder (#12295)
Daniel Han8c5e833f5a85
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.pyindex 614ae3c4bb6..d6a22889ccb 100644--- a/studio/backend/core/inference/stt_sidecar.py+++ b/studio/backend/core/inference/stt_sidecar.py@@ -1050,6 +1050,18 @@ def _close_engine(engine) -> bool:return not _engine_is_alive(engine)+def _av_open(av, source):+ """Open ``source`` for reading with undecodable metadata ignored. PyAV 19 removed ``metadata_errors`` from ``av.open``, so passing it there raises TypeError before anything is read; retry without it."""+ try:+ return av.open(source, mode = "r", metadata_errors = "ignore")+ except TypeError as exc:+ if "metadata_errors" not in str(exc):+ raise+ # format = None is PyAV's own default (probe the container); spelling it keeps this call+ # distinguishable from Path.open for the text-encoding lint.+ return av.open(source, mode = "r", format = None)++def _decode_audio_bounded(audio: bytes, cancel_event = None):"""Decode to 16 kHz mono PCM without buffering unbounded audio.@@ -1093,7 +1105,7 @@ def _decode_audio_bounded(audio: bytes, cancel_event = None):raw_buffer.write(array)try:- with av.open(io.BytesIO(audio), mode = "r", metadata_errors = "ignore") as container:+ with _av_open(av, io.BytesIO(audio)) as container:if not container.streams.audio:raise SttAudioDecodeError("Could not decode the audio.")frames = iter(container.decode(audio = 0))diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8c06305b070..af36406f0b1 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -22793,6 +22793,18 @@ def _av_expected_samples(container, sample_rate: int, ceiling: int) -> int:return min(int(seconds * sample_rate) + 1, ceiling)+def _av_open(av, source):+ """Open ``source`` for reading with undecodable metadata ignored. PyAV 19 removed ``metadata_errors`` from ``av.open``, so passing it there raises TypeError before anything is read; retry without it."""+ try:+ return av.open(source, mode = "r", metadata_errors = "ignore")+ except TypeError as exc:+ if "metadata_errors" not in str(exc):+ raise+ # format = None is PyAV's own default (probe the container); spelling it keeps this call+ # distinguishable from Path.open for the text-encoding lint.+ return av.open(source, mode = "r", format = None)++def _decode_audio_mono_with_av(raw: bytes) -> "tuple[np.ndarray, int]":"""Decode an audio container with PyAV's bundled FFmpeg libraries."""import io@@ -22832,7 +22844,7 @@ def _decode_audio_mono_with_av(raw: bytes) -> "tuple[np.ndarray, int]":joined = grownjoined[sample_count - len(block) : sample_count] = block- with av.open(io.BytesIO(raw), mode = "r", metadata_errors = "ignore") as container:+ with _av_open(av, io.BytesIO(raw)) as container:if not container.streams.audio:raise ValueError("audio container has no audio stream")for frame in container.decode(audio = 0):diff --git a/studio/backend/tests/test_llama_audio_attachment_container.py b/studio/backend/tests/test_llama_audio_attachment_container.pyindex a65a051f412..ee30843f84b 100644--- a/studio/backend/tests/test_llama_audio_attachment_container.py+++ b/studio/backend/tests/test_llama_audio_attachment_container.py@@ -81,26 +81,30 @@ def _encode_wma() -> bytes:return buffer.getvalue()+# 0.4 s of a 440 Hz tone as AMR-NB at 12.2 kbit/s, 678 bytes. Stored rather than encoded here:+# PyAV 19.0.0 wheels still decode AMR but no longer ship an AMR encoder, so building the fixture+# at test time failed every test below with UnknownCodecError while the decoder the product+# depends on was fine. Encoded with PyAV 18.1.0 from the same tone the old fixture generated.+_AMR_NB_440HZ = base64.b64decode(+ "IyFBTVIKPCQCB0gQS8fMygN69kBlccAAYacLDD94AAAacSQCayA8LXrmkAA3h2BeA1oHVr3p6Gb5"+ "Lu9EzyrIpP3Gaz70MDwkBuLoADWf4ZQDevbv9s/CmWXyFVr35EkEhUFlPm0gPC2A5YgAZ5/Q0AZq"+ "2LMr0PKTDEs69hdMV8GClhn9f6A8JAepSAA127CkAerVt0Ma+9xD//PQH+VOQ4f1rFMSsDwtgOKI"+ "AGf5kIYGWsKfc8PR+FdYj5XvaUwAUI/qupQwPCQG5UAAH5/BlAN6m1+Cre4KwEx2nrBnsj/KUsYg"+ "fSA8LA/D8ABhn2GOBhqqrkIj49cwP+muHBmtO7CcpNEXYDwkBuWQAB+f8IYB2swWDDr2GECheNQZ"+ "niOealsfXBlwPC2BqUgAddu5AgY604cpLMjWKUm7HSRoIOT+bbAenPA8JAbikAA1n2GUA1p3O9Q5"+ "xi7nPsbMZgk5OneAJFmZoDwtgOVIAGWf0JoGOtR9TA3yU1yG5bqrGEk0EO0y2mJAPCQHw/AANZ/w"+ "sAGa4b7SUcjWXF5Bn1ukotzoHLClaDA8LYDlkABzn5GMBlrxuRko45kdoUOX9fYutAMI68eFoDwk"+ "B6lIADXbIZ4BulEogbnQ9Om8lo1vgc+o/Aj/DZ/wPC2A4pAAcduwsgZa0r4Q9PEYTWPWv0geT797"+ "jSDebzA8JAblSAAfn+GOAbqKTR5t6+fpZ36WL2aL+IZnQtx6sDwsD8PwAGWfYbQEmmwOO5fFgwOR"+ "iREd2d6Bf80grdBwPCQG5ZAAH5/hjAHa6WHkK/LpjOQUvsF2UDIQMO+Sx7A8LYGpSAEj27GoBjrf"+ "i5eu5k4w8A7o6+wKxFpNnc+D0DweGClCCL+RGJl2ysLn6qow2oDGAWgiqhGHBRFfYB4Q"+)++def _encode_amr() -> bytes:- av = pytest.importorskip("av")- buffer = io.BytesIO()- with av.open(buffer, mode = "w", format = "amr") as output:- stream = output.add_stream("amr_nb", rate = 8_000)- stream.layout = "mono"- stream.bit_rate = 12_200- indexes = np.arange(3_200)- samples = (np.sin(indexes * 2 * np.pi * 440 / 8_000) * 16_000).astype(np.int16)- frame = av.AudioFrame.from_ndarray(- samples.reshape(1, -1),- format = "s16",- layout = "mono",- )- frame.sample_rate = 8_000- for packet in stream.encode(frame):- output.mux(packet)- for packet in stream.encode():- output.mux(packet)- return buffer.getvalue()+ # The decode under test still needs PyAV; only the encode step is gone.+ pytest.importorskip("av")+ return _AMR_NB_440HZdef test_wma_and_amr_decode_with_no_librosa(monkeypatch):@@ -1384,3 +1388,35 @@ def test_no_allocation_outgrows_the_limit_the_decode_enforces(monkeypatch):assert len(samples) > 0assert sizes, "the decoder allocated nothing"assert max(sizes) <= inference_route._decoded_sample_ceiling(rate)+++class _FakeAv:+ def __init__(self, error = None):+ self.error = error+ self.calls = []++ def open(self, source, **kwargs):+ self.calls.append(kwargs)+ if "metadata_errors" in kwargs and self.error is not None:+ raise self.error+ return source+++def test_av_open_drops_metadata_errors_where_pyav_removed_it():+ # PyAV 19 rejects the keyword; without the retry every PyAV-only upload (wma, amr, m4a) failed.+ av = _FakeAv(TypeError("open() got an unexpected keyword argument 'metadata_errors'"))+ assert inference_route._av_open(av, "source") == "source"+ assert av.calls == [{"mode": "r", "metadata_errors": "ignore"}, {"mode": "r", "format": None}]+++def test_av_open_keeps_metadata_errors_where_pyav_accepts_it():+ av = _FakeAv()+ assert inference_route._av_open(av, "source") == "source"+ assert av.calls == [{"mode": "r", "metadata_errors": "ignore"}]+++def test_av_open_does_not_swallow_an_unrelated_type_error():+ av = _FakeAv(TypeError("expected str, bytes or os.PathLike object"))+ with pytest.raises(TypeError, match = "PathLike"):+ inference_route._av_open(av, "source")+ assert len(av.calls) == 1diff --git a/studio/backend/tests/test_video_gallery.py b/studio/backend/tests/test_video_gallery.pyindex 7b29a02478c..fc3218667c3 100644--- a/studio/backend/tests/test_video_gallery.py+++ b/studio/backend/tests/test_video_gallery.py@@ -399,7 +399,11 @@ def test_webm_export_keeps_the_audio_track():av = pytest.importorskip("av")import io- record = gallery.save(_real_mp4_with_audio(), _meta())+ source = _real_mp4_with_audio()+ with av.open(io.BytesIO(source)) as container:+ stream = container.streams.audio[0]+ source_seconds = sum(frame.samples for frame in container.decode(stream)) / stream.rate+ record = gallery.save(source, _meta())webm = gallery.transcode(record["id"], "webm")assert webm is not None and webm[:4] == b"\x1a\x45\xdf\xa3"with av.open(io.BytesIO(webm)) as container:@@ -410,8 +414,11 @@ def test_webm_export_keeps_the_audio_track():with av.open(io.BytesIO(webm)) as container:for frame in container.decode(audio = 0):samples += frame.samples- # A full second of 48 kHz audio survived (Opus pads its last 20 ms frame).- assert samples >= 48000, samples+ # The whole source track survived, give or take one 20 ms Opus frame (960 samples at 48 kHz)+ # lost to resampling and framing at the edges. Measured against the decoded source, not a+ # flat 48000: PyAV 18 decoded the 1 s AAC fixture with its encoder padding (45056 samples at+ # 44.1 kHz), PyAV 19 trims it to the true 44100, and a flat floor only passed on the padding.+ assert samples >= source_seconds * 48000 - 960, (samples, source_seconds)def test_webm_export_still_works_without_an_audio_encoder(monkeypatch):diff --git a/studio/backend/utils/datasets/audio_decode.py b/studio/backend/utils/datasets/audio_decode.pyindex 4ab49197d63..8e929b2e7f2 100644--- a/studio/backend/utils/datasets/audio_decode.py+++ b/studio/backend/utils/datasets/audio_decode.py@@ -44,6 +44,18 @@ def _token_for_url(path: str, token_per_repo_id: Optional[dict]) -> Any:return token_per_repo_id.get(fields["repo_id"])+def _av_open(av, source):+ """Open ``source`` for reading with undecodable metadata ignored. PyAV 19 removed ``metadata_errors`` from ``av.open``, so passing it there raises TypeError before anything is read; retry without it."""+ try:+ return av.open(source, mode = "r", metadata_errors = "ignore")+ except TypeError as exc:+ if "metadata_errors" not in str(exc):+ raise+ # format = None is PyAV's own default (probe the container); spelling it keeps this call+ # distinguishable from Path.open for the text-encoding lint.+ return av.open(source, mode = "r", format = None)++def _decode_with_av(source: Any, stream_index: Optional[int] = None) -> "tuple[Any, int]":"""Mono float32 at the native rate through PyAV's bundled FFmpeg: every container torchcodec would have read (m4a, aac, webm, wma, amr) without a system FFmpeg. Same shape as routes/inference.py's upload decoder, minus its upload ceilings: a dataset row is not an upload."""import av@@ -52,7 +64,7 @@ def _decode_with_av(source: Any, stream_index: Optional[int] = None) -> "tuple[Achunks = []rate = 0resampler = None- with av.open(source, mode = "r", metadata_errors = "ignore") as container:+ with _av_open(av, source) as container:if not container.streams.audio:raise ValueError("audio container has no audio stream")# datasets.Audio(stream_index=...) is the container's absolute stream index, as torchcodec reads it; None is the best audio stream.diff --git a/tests/test_datasets_audio_fallback.py b/tests/test_datasets_audio_fallback.pyindex 10e6c85d30e..b444baa1577 100644--- a/tests/test_datasets_audio_fallback.py+++ b/tests/test_datasets_audio_fallback.py@@ -337,13 +337,17 @@ def _normalized(path: Path, name: str, rename: dict) -> str:@pytest.mark.parametrize(("library", "studio"),- [("_audio_decode_with_av", "_decode_with_av"), ("_audio_read_mono", "_read_mono")],+ [+ ("_audio_decode_with_av", "_decode_with_av"),+ ("_audio_read_mono", "_read_mono"),+ ("_audio_av_open", "_av_open"),+ ],)def test_the_library_and_studio_decoders_do_not_drift(library, studio):# Studio's API process never imports unsloth, so it carries its own copy of the decoder.if not _STUDIO_SHIM.exists():pytest.skip("no studio checkout")- rename = {"_audio_decode_with_av": "_decode_with_av"}+ rename = {"_audio_decode_with_av": "_decode_with_av", "_audio_av_open": "_av_open"}assert _normalized(_REPO / "unsloth" / "import_fixes.py", library, rename) == _normalized(_STUDIO_SHIM, studio, {})diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 0397189510f..d1c14fd95a9 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -6913,6 +6913,18 @@ def disable_torchcodec_if_broken():pass # a report must never abort the disable fallback above+def _audio_av_open(av, source):+ """Open ``source`` for reading with undecodable metadata ignored. PyAV 19 removed ``metadata_errors`` from ``av.open``, so passing it there raises TypeError before anything is read; retry without it."""+ try:+ return av.open(source, mode = "r", metadata_errors = "ignore")+ except TypeError as exc:+ if "metadata_errors" not in str(exc):+ raise+ # format = None is PyAV's own default (probe the container); spelling it keeps this call+ # distinguishable from Path.open for the text-encoding lint.+ return av.open(source, mode = "r", format = None)++def _audio_decode_with_av(source, stream_index = None):"""Mono float32 at the native rate through PyAV's bundled FFmpeg: every container torchcodec would have read (m4a, aac, webm, wma, amr) without a system FFmpeg. Kept identical to studio/backend/utils/datasets/audio_decode.py; a test holds the two together."""import av@@ -6921,7 +6933,7 @@ def _audio_decode_with_av(source, stream_index = None):chunks = []rate = 0resampler = None- with av.open(source, mode = "r", metadata_errors = "ignore") as container:+ with _audio_av_open(av, source) as container:if not container.streams.audio:raise ValueError("audio container has no audio stream")# datasets.Audio(stream_index=...) is the container's absolute stream index, as torchcodec reads it; None is the best audio stream.