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
Studio: stop Whisper dropping sentences from clips longer than 30 seconds (#12481)
Nilayf7349b6b2590
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.pyindex a2b9cfe4d47..7b0e4c9893e 100644--- a/studio/backend/core/inference/stt_sidecar.py+++ b/studio/backend/core/inference/stt_sidecar.py@@ -55,6 +55,11 @@ _HF_COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")# Bound decoded PCM length so a crafted upload cannot exhaust memory (callers also cap the encoded bytes)._MAX_AUDIO_SECONDS = 30 * 60_TARGET_SAMPLE_RATE = 16000+_STT_WINDOW_SECONDS = 30+_STT_WINDOW_SILENCE_LOOKBACK_SECONDS = 3+_STT_ENERGY_FRAME_SECONDS = 0.02+_STT_MIN_SILENCE_SECONDS = 0.1+_STT_SILENCE_ENERGY_RATIO = 0.01# Non-weight files WhisperProcessor/WhisperForConditionalGeneration may load. Weight selection is built from pinned Hub# metadata. A custom repo id is attacker-controllable, so only safetensors weights are accepted: a pytorch_model.bin is@@ -261,6 +266,34 @@ def normalize_whisper_language(language: Optional[str]) -> Optional[str]:return _WHISPER_LANGUAGE_ALIASES.get(primary, primary)+def _stt_quiet_window_end(decoded_audio, start: int, window: int) -> Optional[int]:+ """Return a nearby quiet window boundary, or None when speech fills it."""+ import numpy as np++ hard_end = min(start + window, len(decoded_audio))+ if hard_end == len(decoded_audio):+ return None++ lookback = _STT_WINDOW_SILENCE_LOOKBACK_SECONDS * _TARGET_SAMPLE_RATE+ search_start = hard_end - lookback+ candidate = decoded_audio[search_start:hard_end]+ frame = round(_STT_ENERGY_FRAME_SECONDS * _TARGET_SAMPLE_RATE)+ frame_count = len(candidate) // frame+ framed = candidate[: frame_count * frame].reshape(frame_count, frame).astype(np.float64)+ framed -= np.mean(framed, axis = 1, keepdims = True)+ energy = np.mean(np.square(np.diff(framed, axis = 1)), axis = 1)+ silence_frames = round(_STT_MIN_SILENCE_SECONDS / _STT_ENERGY_FRAME_SECONDS)+ smoothed = np.convolve(+ energy, np.ones(silence_frames, dtype = np.float64) / silence_frames, mode = "valid"+ )+ quietest = int(np.argmin(smoothed))+ active_reference = float(np.mean(np.partition(energy, -silence_frames)[-silence_frames:]))+ if active_reference <= 0 or smoothed[quietest] > active_reference * _STT_SILENCE_ENERGY_RATIO:+ return None+ silence_midpoint = round(_STT_MIN_SILENCE_SECONDS * _TARGET_SAMPLE_RATE / 2)+ return search_start + quietest * frame + silence_midpoint++def _known_whisper_languages() -> Optional[frozenset[str]]:"""Return Whisper's language codes without constructing/loading a model."""try:@@ -1646,22 +1679,32 @@ class WhisperSttSidecar:# passing them here.effective_generate_kwargs.pop("task", None)effective_generate_kwargs.pop("language", None)- window = 30 * _TARGET_SAMPLE_RATE+ window = _STT_WINDOW_SECONDS * _TARGET_SAMPLE_RATEparts: list[str] = []- for start in range(0, max(len(decoded_audio), 1), window):+ supports_timestamps = getattr(generation_config, "supports_timestamps", True) is not False+ start = 0+ while start < len(decoded_audio):if cancel_event is not None and cancel_event.is_set():raise SttTranscriptionCancelledError("Transcription cancelled.")- segment = decoded_audio[start : start + window]- if segment.size == 0:- continue+ end = min(start + window, len(decoded_audio))+ window_generate_kwargs = dict(effective_generate_kwargs)+ if end < len(decoded_audio):+ quiet_end = _stt_quiet_window_end(decoded_audio, start, window)+ if quiet_end is not None:+ end = quiet_end+ elif supports_timestamps:+ # Whisper's long-form seek: keep only finished segments and resume where the last one ended.+ window_generate_kwargs["return_timestamps"] = True+ segment = decoded_audio[start:end]pcm = np.ascontiguousarray(segment, dtype = np.float32).tobytes()- parts.append(engine.transcribe_window(pcm, effective_generate_kwargs, cancel_event))+ text, consumed = engine.transcribe_window(pcm, window_generate_kwargs, cancel_event)+ parts.append(text)+ start += consumedif on_progress is not None:on_progress({"text": " ".join(part.strip() for part in parts if part.strip()),- "processed_seconds": min(start + window, len(decoded_audio))- / _TARGET_SAMPLE_RATE,+ "processed_seconds": min(start, len(decoded_audio)) / _TARGET_SAMPLE_RATE,"duration": len(decoded_audio) / _TARGET_SAMPLE_RATE,})diff --git a/studio/backend/core/inference/stt_transformers_worker.py b/studio/backend/core/inference/stt_transformers_worker.pyindex 61f15662dec..07129f8d4f9 100644--- a/studio/backend/core/inference/stt_transformers_worker.py+++ b/studio/backend/core/inference/stt_transformers_worker.py@@ -45,6 +45,7 @@ _TRANSCRIBE_TIMEOUT_SECONDS = 600.0_CANCEL_GRACE_SECONDS = 10.0_SHUTDOWN_TIMEOUT_SECONDS = 10.0_POLL_SECONDS = 0.1+_TIMESTAMPS_PER_SECOND = 50# Errors the child may report that the parent must re-raise as themselves; any other failure crosses as a RuntimeError# carrying the child's message.@@ -136,20 +137,62 @@ def transcribe_window(segment = np.frombuffer(pcm, dtype = np.float32)kwargs = dict(generate_kwargs)+ return_timestamps = bool(kwargs.get("return_timestamps"))+ if return_timestamps:+ kwargs["force_unique_generate_call"] = Trueif cancel_event is not None:from transformers import StoppingCriteriaListkwargs["stopping_criteria"] = StoppingCriteriaList([_CancelCriteria(cancel_event)])from core.inference.stt_sidecar import _TARGET_SAMPLE_RATE- inputs = processor(segment, sampling_rate = _TARGET_SAMPLE_RATE, return_tensors = "pt")+ inputs = processor(+ segment,+ sampling_rate = _TARGET_SAMPLE_RATE,+ return_tensors = "pt",+ return_attention_mask = return_timestamps,+ )features = inputs.input_features.to(model.device)target_dtype = getattr(model, "dtype", None)if target_dtype is not None:features = features.to(target_dtype)+ if return_timestamps:+ kwargs["attention_mask"] = inputs.attention_mask.to(model.device)with torch.no_grad():generated = model.generate(features, **kwargs)+ consumed = len(segment)+ if return_timestamps:+ raw_tokens = [int(token) for token in generated[0]]+ indices, end = _complete_segment_indices(raw_tokens, model.generation_config)+ if end:+ consumed = end * _TARGET_SAMPLE_RATE // _TIMESTAMPS_PER_SECOND+ generated = [[raw_tokens[index] for index in indices]]text = processor.batch_decode(generated, skip_special_tokens = True)- return text[0] if text else ""+ return (text[0] if text else ""), consumed+++def _complete_segment_indices(tokens: list, generation_config) -> tuple:+ # whisper's long-form seek decodes a segment cut off by the window again from the next window+ timestamp_begin = generation_config.no_timestamps_token_id + 1+ indexed_tokens = [+ (index, token)+ for index, token in enumerate(tokens)+ if token < generation_config.eos_token_id or token >= timestamp_begin+ ]+ is_timestamp = [token >= timestamp_begin for _, token in indexed_tokens]+ pairs = [i for i in range(1, len(indexed_tokens)) if is_timestamp[i - 1] and is_timestamp[i]]+ if not pairs or is_timestamp[-2:] == [False, True]:+ return [index for index, _ in indexed_tokens], 0+ return (+ [index for index, _ in indexed_tokens[: pairs[-1]]],+ indexed_tokens[pairs[-1] - 1][1] - timestamp_begin,+ )+++def _supports_segment_timestamps(generation_config) -> bool:+ return all(+ isinstance(getattr(generation_config, field, None), int)+ for field in ("no_timestamps_token_id", "eos_token_id")+ )def _error_response(exc: BaseException) -> dict:@@ -238,6 +281,7 @@ def run_stt_worker(engine = (model, processor)generation_config = getattr(model, "generation_config", None)is_multilingual = getattr(generation_config, "is_multilingual", None)+ supports_timestamps = _supports_segment_timestamps(generation_config)_send(resp_queue,{@@ -246,13 +290,14 @@ def run_stt_worker("is_multilingual": (is_multilingual if isinstance(is_multilingual, bool) else None),+ "supports_timestamps": supports_timestamps,},)elif kind == "transcribe":if engine is None:raise SttWorkerError("The dictation worker has no model loaded.")cancellable = bool(command.get("cancellable"))- text = transcribe_window(+ text, consumed = transcribe_window(engine[0],engine[1],command["audio"],@@ -262,7 +307,7 @@ def run_stt_worker(if cancellable and cancel_event.is_set():from core.inference.stt_sidecar import SttTranscriptionCancelledErrorraise SttTranscriptionCancelledError("Transcription cancelled.")- _send(resp_queue, {"type": "text", "text": text})+ _send(resp_queue, {"type": "text", "text": text, "consumed": consumed})elif kind == "shutdown":_send(resp_queue, {"type": "shutdown_ack"})return@@ -418,14 +463,17 @@ class WhisperWorker:) from excraiseself.device = response.get("device") or device- self.generation_config = SimpleNamespace(is_multilingual = response.get("is_multilingual"))+ self.generation_config = SimpleNamespace(+ is_multilingual = response.get("is_multilingual"),+ supports_timestamps = response.get("supports_timestamps") is True,+ )def transcribe_window(self,pcm: bytes,generate_kwargs: dict,cancel_event: Optional[threading.Event] = None,- ) -> str:+ ) -> tuple[str, int]:if self._cancel_event is not None:self._cancel_event.clear()self._send(@@ -438,7 +486,7 @@ class WhisperWorker:)response = self._await("text", _TRANSCRIBE_TIMEOUT_SECONDS, cancel_event, "transcribe")text = response.get("text")- return text if isinstance(text, str) else ""+ return (text if isinstance(text, str) else ""), response["consumed"]def is_alive(self) -> bool:process = self._process@@ -657,7 +705,8 @@ class InProcessWhisperEngine:generation_config = getattr(model, "generation_config", None)is_multilingual = getattr(generation_config, "is_multilingual", None)self.generation_config = SimpleNamespace(- is_multilingual = is_multilingual if isinstance(is_multilingual, bool) else None+ is_multilingual = is_multilingual if isinstance(is_multilingual, bool) else None,+ supports_timestamps = _supports_segment_timestamps(generation_config),)logger.info("STT model loaded in process on the CPU from %s", snapshot_path)@@ -666,16 +715,16 @@ class InProcessWhisperEngine:pcm: bytes,generate_kwargs: dict,cancel_event: Optional[threading.Event] = None,- ) -> str:+ ) -> tuple[str, int]:if self._model is None:raise SttWorkerError("The dictation worker has no model loaded.")- text = transcribe_window(+ result = transcribe_window(self._model, self._processor, pcm, dict(generate_kwargs), cancel_event)if cancel_event is not None and cancel_event.is_set():from core.inference.stt_sidecar import SttTranscriptionCancelledErrorraise SttTranscriptionCancelledError("Transcription cancelled.")- return text+ return resultdef is_alive(self) -> bool:return self._model is not Nonediff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.pyindex 9f1098722a9..fb574a66d9a 100644--- a/studio/backend/tests/test_stt_sidecar.py+++ b/studio/backend/tests/test_stt_sidecar.py@@ -381,7 +381,7 @@ def test_english_only_model_omits_forbidden_generation_controls(monkeypatch):_cancel_event = None,):calls.append(generate_kwargs)- return "hello"+ return "hello", 160sidecar = WhisperSttSidecar()monkeypatch.setattr(sidecar, "load", lambda _model: FakeWorker())@@ -401,6 +401,141 @@ def test_english_only_model_omits_forbidden_generation_controls(monkeypatch):assert calls == [{"condition_on_prev_tokens": False, "num_beams": 1}]+def test_long_audio_uses_a_quiet_boundary_without_merging_repeated_text(monkeypatch):+ lengths = []+ calls = []++ class FakeWorker:+ generation_config = SimpleNamespace(is_multilingual = True)++ def transcribe_window(+ self,+ pcm,+ generate_kwargs,+ _cancel_event = None,+ ):+ window = np.frombuffer(pcm, dtype = np.float32)+ lengths.append(len(window))+ calls.append(generate_kwargs)+ text = (+ "turn left right now" if len(calls) == 1 else "turn left right now after the pause"+ )+ return text, len(window)++ sidecar = WhisperSttSidecar()+ monkeypatch.setattr(sidecar, "load", lambda _model: FakeWorker())+ audio = np.ones(50 * 16000, dtype = np.float32)+ audio[1::2] = -1+ audio += 0.04+ hum = 0.04 * np.sin(2 * np.pi * 60 * np.arange(len(audio)) / 16000)+ audio += hum+ audio[28 * 16000 : 28 * 16000 + 3200] = 0.04 + hum[28 * 16000 : 28 * 16000 + 3200]++ text = sidecar._transcribe_decoded("small", audio, {"num_beams": 5})++ assert text == "turn left right now turn left right now after the pause"+ assert lengths == [448800, 351200]+ assert calls == [{"num_beams": 5}, {"num_beams": 5}]+++def test_quiet_boundary_handles_a_long_pause_before_resumed_speech():+ audio = np.ones(50 * 16000, dtype = np.float32)+ audio[1::2] = -1+ audio[27 * 16000 : 29 * 16000] = 0++ assert stt_sidecar_module._stt_quiet_window_end(audio, 0, 30 * 16000) == 432800+++def test_quiet_boundary_rejects_lower_energy_speech():+ audio = np.ones(50 * 16000, dtype = np.float32)+ audio[1::2] = -1+ audio[28 * 16000 : 28 * 16000 + 3200] *= 0.4++ assert stt_sidecar_module._stt_quiet_window_end(audio, 0, 30 * 16000) is None+++def test_long_audio_without_a_quiet_boundary_uses_timestamp_seek(monkeypatch):+ starts = []+ calls = []++ class FakeWorker:+ generation_config = SimpleNamespace(is_multilingual = True)++ def transcribe_window(+ self,+ pcm,+ generate_kwargs,+ _cancel_event = None,+ ):+ window = np.frombuffer(pcm, dtype = np.float32)+ starts.append(int(window[0]))+ calls.append(generate_kwargs)+ consumed = 454400 if len(calls) == 1 else len(window)+ return f"part {len(calls)}", consumed++ sidecar = WhisperSttSidecar()+ monkeypatch.setattr(sidecar, "load", lambda _model: FakeWorker())++ text = sidecar._transcribe_decoded(+ "small", np.arange(50 * 16000, dtype = np.float32), {"num_beams": 5}+ )++ assert text == "part 1 part 2"+ assert starts == [0, 454400]+ assert calls == [{"num_beams": 5, "return_timestamps": True}, {"num_beams": 5}]+++def test_short_timestamp_seek_resumes_at_the_last_finished_segment(monkeypatch):+ starts = []++ class FakeWorker:+ generation_config = SimpleNamespace(is_multilingual = True)++ def transcribe_window(+ self,+ pcm,+ _generate_kwargs,+ _cancel_event = None,+ ):+ window = np.frombuffer(pcm, dtype = np.float32)+ starts.append(int(window[0]))+ return "part", 8000 if len(starts) == 1 else len(window)++ sidecar = WhisperSttSidecar()+ monkeypatch.setattr(sidecar, "load", lambda _model: FakeWorker())++ sidecar._transcribe_decoded("small", np.arange(round(30.5 * 16000), dtype = np.float32), {})++ assert starts == [0, 8000]+++def test_long_audio_without_timestamp_metadata_keeps_fixed_windows(monkeypatch):+ lengths = []+ calls = []++ class FakeWorker:+ generation_config = SimpleNamespace(is_multilingual = True, supports_timestamps = False)++ def transcribe_window(+ self,+ pcm,+ generate_kwargs,+ _cancel_event = None,+ ):+ window = np.frombuffer(pcm, dtype = np.float32)+ lengths.append(len(window))+ calls.append(generate_kwargs)+ return "part", len(window)++ sidecar = WhisperSttSidecar()+ monkeypatch.setattr(sidecar, "load", lambda _model: FakeWorker())++ sidecar._transcribe_decoded("owner/custom-whisper", np.ones(50 * 16000, dtype = np.float32), {})++ assert lengths == [30 * 16000, 20 * 16000]+ assert calls == [{}, {}]++def test_unknown_language_is_rejected_before_decode_or_model_load(monkeypatch):sidecar = WhisperSttSidecar()diff --git a/studio/backend/tests/test_stt_transformers_worker.py b/studio/backend/tests/test_stt_transformers_worker.pyindex f404403e3e7..4a5efd6ddae 100644--- a/studio/backend/tests/test_stt_transformers_worker.py+++ b/studio/backend/tests/test_stt_transformers_worker.py@@ -53,16 +53,21 @@ class _FakeProcessor:self.seen_audio = Noneself.seen_rate = Noneself.features = _FakeTensor()+ self.attention_mask = _FakeTensor()def __call__(self,audio,sampling_rate = None,return_tensors = None,+ return_attention_mask = False,):self.seen_audio = audioself.seen_rate = sampling_rate- return SimpleNamespace(input_features = self.features)+ result = SimpleNamespace(input_features = self.features)+ if return_attention_mask:+ result.attention_mask = self.attention_mask+ return resultdef batch_decode(self, _generated, **_kwargs):return ["hello"]@@ -235,11 +240,11 @@ def test_child_feeds_decoded_pcm_and_matches_the_model_dtype(monkeypatch):_calls, model, processor = _install_fake_transformers(monkeypatch)pcm = np.arange(4, dtype = np.float32).tobytes()- text = worker_module.transcribe_window(+ result = worker_module.transcribe_window(model, processor, pcm, {"task": "transcribe", "num_beams": 5})- assert text == "hello"+ assert result == ("hello", 4)assert processor.seen_rate == 16000assert np.array_equal(processor.seen_audio, np.arange(4, dtype = np.float32))# to(device) then to(dtype): features must match the weights they meet.@@ -263,6 +268,60 @@ def test_child_only_installs_stopping_criteria_for_a_cancellable_request(monkeypassert "stopping_criteria" not in model.generate_kwargs+_TIMESTAMP_BEGIN = 50364+_EOS = 50257+++class _TimestampedModel(_FakeModel):+ def __init__(self, tokens) -> None:+ super().__init__()+ self.generation_config = SimpleNamespace(+ is_multilingual = True, no_timestamps_token_id = _TIMESTAMP_BEGIN - 1, eos_token_id = _EOS+ )+ self.tokens = tokens++ def generate(self, _features, **kwargs):+ self.generate_kwargs = kwargs+ return [self.tokens]+++class _RecordingProcessor(_FakeProcessor):+ def batch_decode(self, generated, **_kwargs):+ self.decoded = [list(row) for row in generated]+ return ["decoded"]+++def _at(seconds):+ return _TIMESTAMP_BEGIN + round(seconds * 50)+++ "tail, kept, consumed",+ [+ pytest.param([_at(28.4), _at(28.4), 33], [_at(28.4)], 454400, id = "cut-mid-sentence"),+ pytest.param([33, _at(29.0)], [33, _at(29.0)], 480000, id = "last-segment-closed"),+ ],+)+def test_child_resumes_a_long_clip_after_its_last_complete_segment(+ monkeypatch, tail, kept, consumed+):+ head = [_at(0), 11, _at(5.0), _at(5.0), 22]+ model = _TimestampedModel([50258, 50259, 50359] + head + tail + [_EOS])+ processor = _RecordingProcessor()+ _install_fake_transformers(monkeypatch, model = model, processor = processor)+ pcm = np.zeros(480000, dtype = np.float32).tobytes()++ result = worker_module.transcribe_window(+ model, processor, pcm, {"num_beams": 5, "return_timestamps": True}+ )++ assert result == ("decoded", consumed)+ assert processor.decoded == [head + kept]+ assert model.generate_kwargs["force_unique_generate_call"] is True+ assert model.generate_kwargs["attention_mask"] is processor.attention_mask+ assert processor.attention_mask.moved_to == ["cuda"]++# ---------------------------------------------------------------------------# Child: command loop# ---------------------------------------------------------------------------@@ -327,12 +386,17 @@ def test_child_reports_the_loaded_model_then_transcribes_then_exits(monkeypatch){"type": "shutdown"},],load = lambda *_args, **_kwargs: (model, _FakeProcessor()),- transcribe = lambda *_args, **_kwargs: "hello",+ transcribe = lambda *_args, **_kwargs: ("hello", 16000),)assert responses == [- {"type": "loaded", "device": "cuda", "is_multilingual": False},- {"type": "text", "text": "hello"},+ {+ "type": "loaded",+ "device": "cuda",+ "is_multilingual": False,+ "supports_timestamps": False,+ },+ {"type": "text", "text": "hello", "consumed": 16000},{"type": "shutdown_ack"},]@@ -387,7 +451,7 @@ def test_child_reports_a_cancelled_generation_rather_than_partial_text(monkeypatcancel_event = None,):cancel_event.set() # what StoppingCriteria does to a running generate- return "half a sen"+ return "half a sen", 0responses, _cancel = _run_child(monkeypatch,@@ -455,11 +519,11 @@ def test_an_unknown_failure_arrives_as_a_worker_error_carrying_its_message():def test_handle_sends_one_window_and_returns_its_text():handle = _wired_worker()- handle._resp_queue.put({"type": "text", "text": "hello"})+ handle._resp_queue.put({"type": "text", "text": "hello", "consumed": 1})- text = handle.transcribe_window(b"\x00\x00\x00\x00", {"num_beams": 1})+ result = handle.transcribe_window(b"\x00\x00\x00\x00", {"num_beams": 1})- assert text == "hello"+ assert result == ("hello", 1)command = handle._cmd_queue.get_nowait()assert command["type"] == "transcribe"assert command["generate_kwargs"] == {"num_beams": 1}@@ -753,7 +817,7 @@ def test_dictation_still_loads_and_transcribes_when_no_child_can_be_started(monkassert isinstance(engine, worker_module.InProcessWhisperEngine)assert engine.device == "cpu"assert engine.is_alive() is True- assert engine.transcribe_window(np.zeros(4, dtype = np.float32).tobytes(), {}) == "hello"+ assert engine.transcribe_window(np.zeros(4, dtype = np.float32).tobytes(), {}) == ("hello", 4)def test_a_spawn_failure_on_an_accelerator_leaves_the_cpu_retry_to_the_sidecar(monkeypatch):@@ -1001,6 +1065,7 @@ def test_the_in_process_fallback_reports_the_checkpoint_language_support(monkeyp# The sidecar reads this to drop the kwargs an English-only model rejects.assert engine.generation_config.is_multilingual is False+ assert engine.generation_config.supports_timestamps is Falseengine.close()assert engine.is_alive() is Falsediff --git a/studio/backend/tests/test_transcript_stream.py b/studio/backend/tests/test_transcript_stream.pyindex 9675ccbdf97..f87dddd724f 100644--- a/studio/backend/tests/test_transcript_stream.py+++ b/studio/backend/tests/test_transcript_stream.py@@ -85,7 +85,9 @@ def test_transformers_progress_uses_existing_audio_windows(monkeypatch):def transcribe_window(self, pcm, kwargs, cancel):self.calls += 1- return f"part {self.calls}"+ previous = kwargs.get("_stt_previous_text")+ text = f"{previous} part {self.calls}" if previous else f"part {self.calls}"+ return text, len(pcm) // 4worker = Worker()sidecar = WhisperSttSidecar()