Skip to content

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.

Studio: add timestamps, speakers and exports to the Transcribe page (#12607)

Etherl9d76f7557373
diff --git a/studio/backend/core/inference/audio_cpp_models.py b/studio/backend/core/inference/audio_cpp_models.py
index de5b28e36d5..5547499ca49 100644
--- a/studio/backend/core/inference/audio_cpp_models.py
+++ b/studio/backend/core/inference/audio_cpp_models.py
@@ -541,10 +541,20 @@ _FAMILY_LIST: tuple[AudioCppFamily, ...] = (
)
for name in names
),
+ # Its spec says ASR, but it answers with a description of the audio, not what was said.
+ AudioCppFamily(
+ "samsone",
+ "",
+ unsupported = "SAMSONE describes audio rather than transcribing speech, so Studio does not "
+ "offer it for transcription.",
+ ),
)
FAMILIES: dict[str, AudioCppFamily] = {f.family: f for f in _FAMILY_LIST}
+# Sessions refuse any backend but CPU ("Niagara ASR CPU variants require --backend cpu").
+CPU_ONLY_FAMILIES: frozenset[str] = frozenset({"niagara_asr"})
+
# Spec task names that are not runtime task tokens.
_SPEC_TO_SERVER_TASK = {
"music": "gen",
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 5ec55b8e033..c81d3a4c4e1 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -2519,11 +2519,12 @@ class InferenceOrchestrator:
engine: str,
request_cancel_event: Optional[threading.Event] = None,
device: Optional[str] = None,
+ **options,
) -> None:
"""Make a dictation model resident on its sidecar. ``device`` is the user's audio device
preference (``auto``/``cpu``/``gpu``)."""
from core.inference import stt_registry
- stt_registry.load(model, engine, request_cancel_event, device = device)
+ stt_registry.load(model, engine, request_cancel_event, device = device, **options)
def unload_stt_model(
self,
diff --git a/studio/backend/core/inference/stt_audiocpp_sidecar.py b/studio/backend/core/inference/stt_audiocpp_sidecar.py
index ce28b377f7b..17c5f207596 100644
--- a/studio/backend/core/inference/stt_audiocpp_sidecar.py
+++ b/studio/backend/core/inference/stt_audiocpp_sidecar.py
@@ -7,28 +7,36 @@ Serves any audio.cpp ASR GGUF (Qwen3-ASR, Parakeet, Canary, Moonshine, Nemotron
whatever else audio.cpp transcribes) through one ``audiocpp_server`` child, with the same lifecycle as the
whisper.cpp sidecar: loads on demand, stays warm for the keep-alive window, yields
to training, and is paused while the managed runtime is being replaced. Audio is
-decoded with PyAV like every other engine and sent as 16 kHz mono WAV, since the
-default server build reads WAV only.
+decoded with PyAV like every other engine and handed to the server as a 16 kHz mono
+WAV file it reads by path (``/v1/audio/transcriptions/details``), which also returns
+the timestamps and speakers a model produces.
"""
from __future__ import annotations
import json
import subprocess
+import tempfile
import threading
+import wave
from contextlib import contextmanager
+from dataclasses import replace
from pathlib import Path
-from typing import Iterator, Optional
+from typing import Callable, Iterator, Optional
-from core.inference import audio_cpp_files, audio_cpp_server
+from core.inference import audio_cpp_files, audio_cpp_server, stt_details
from core.inference.audio_cpp_models import (
+ AUDIO_CPP_REPO,
+ CPU_ONLY_FAMILIES,
DEFAULT_AUDIO_CPP_STT_MODEL,
is_legacy_key,
legacy_keys,
RECOMMENDED_STT_MODELS,
AudioCppModel,
AudioCppModelError,
+ CompanionModel,
downloaded_models,
+ forget,
parse_identifier,
require_runnable,
resolve,
@@ -57,7 +65,6 @@ from core.inference.stt_sidecar import (
_downloaded_file_bytes,
_HF_COMMIT_SHA,
_prepare_stt_cache_for_http,
- _TARGET_SAMPLE_RATE,
_training_active,
normalize_whisper_language,
)
@@ -68,12 +75,77 @@ from loggers import get_logger
logger = get_logger(__name__)
_TRANSCRIBE_TIMEOUT_SECONDS = 600.0
+_DETAILS_PATH = "/v1/audio/transcriptions/details"
+
+# Fixed chunking keeps the runtime off its Silero VAD, which Studio does not ship.
+QWEN3_ALIGNER = CompanionModel(
+ f"{AUDIO_CPP_REPO}/Qwen3-ForcedAligner-0.6B-GGUF",
+ "Q8_0",
+ "qwen3_asr.forced_aligner_model_path",
+)
+_ALIGNED_FAMILIES = frozenset({"qwen3_asr"})
+# Without preserve_punctuation the runtime rebuilds text from aligned words, losing punctuation.
+_TIMESTAMP_OPTIONS = {
+ "return_timestamps": "true",
+ "audio_chunk_mode": "fixed",
+ "qwen3_asr.preserve_punctuation": "true",
+}
class SttEngineUnavailableError(SttUnavailableError):
"""audiocpp_server is not installed or stopped serving; the audio.cpp dictation engine is off."""
+def _stt_tmp_dir() -> Path:
+ """Where the WAVs the server reads by path are written: ``<studio_root>/cache/audiocpp-stt``."""
+ from utils.paths.storage_roots import ensure_dir, studio_root, tmp_root
+ try:
+ return ensure_dir(studio_root() / "cache" / "audiocpp-stt")
+ except Exception: # noqa: BLE001 - an unusable studio root falls back to the temp dir
+ directory = tmp_root()
+ directory.mkdir(parents = True, exist_ok = True)
+ return directory
+
+
+@contextmanager
+def _temp_wav(wav_bytes: bytes) -> Iterator[Path]:
+ """``wav_bytes`` in a private file for the server to read, removed however the request ends."""
+ handle = tempfile.NamedTemporaryFile(
+ dir = _stt_tmp_dir(), prefix = "stt-", suffix = ".wav", delete = False
+ )
+ path = Path(handle.name)
+ try:
+ with handle:
+ handle.write(wav_bytes)
+ yield path
+ finally:
+ try:
+ path.unlink(missing_ok = True)
+ except OSError:
+ # Windows refuses while the server still holds the file open.
+ logger.debug("audio.cpp: could not remove a transcription temp file")
+
+
+def _wav_rate_and_duration(path: Path) -> tuple[int, Optional[float]]:
+ try:
+ with wave.open(str(path), "rb") as w:
+ rate, frames = w.getframerate(), w.getnframes()
+ except (OSError, EOFError, wave.Error) as exc:
+ raise SttAudioDecodeError("Could not read the audio.") from exc
+ if rate <= 0:
+ raise SttAudioDecodeError("Could not read the audio.")
+ return rate, (round(frames / rate, 3) if frames else None)
+
+
+def _notify(on_phase: Optional[Callable[[str], None]], phase: str) -> None:
+ if on_phase is None:
+ return
+ try:
+ on_phase(phase)
+ except Exception: # noqa: BLE001 - progress reporting never fails a transcription
+ logger.debug("audio.cpp: phase callback failed", exc_info = True)
+
+
# Rows the dictation picker recommends, in order; any other audio.cpp ASR GGUF works too.
AUDIO_CPP_STT_MODELS: tuple[str, ...] = RECOMMENDED_STT_MODELS
@@ -429,6 +501,10 @@ def cancel_model_download() -> bool:
return _download_state.cancel()
+def _launches_on_cpu(entry: AudioCppModel, force_cpu: bool) -> bool:
+ return force_cpu or _training_active() or entry.family in CPU_ONLY_FAMILIES
+
+
class AudioCppSttSidecar:
"""Owns one audiocpp_server serving an ASR model and proxies dictation to it."""
@@ -444,6 +520,8 @@ class AudioCppSttSidecar:
self._forced_cpu = False
# Where the server actually runs: training also puts it on the CPU, without the user asking.
self._launched_cpu = False
+ # Tracked separately: ``model_options`` is not part of AudioCppModel equality.
+ self._aligned = False
self._idle_timer: Optional[threading.Timer] = None
self._idle_generation = 0
self._keep_alive_seconds = keep_alive_seconds
@@ -548,6 +626,7 @@ class AudioCppSttSidecar:
self._loaded_as = None
self._forced_cpu = False
self._launched_cpu = False
+ self._aligned = False
if server is not None:
server.stop()
@@ -644,19 +723,67 @@ class AudioCppSttSidecar:
# A path the runtime cannot open (Windows MAX_PATH) is a runtime limit, not a missing download.
raise SttEngineUnavailableError(str(exc)) from exc
+ def _ensure_aligner_downloaded(
+ self,
+ entry: AudioCppModel,
+ on_phase: Optional[Callable[[str], None]] = None,
+ ) -> None:
+ from core.inference import audio_cpp_backend
+
+ try:
+ aligner = audio_cpp_backend._resolve_companion(entry, QWEN3_ALIGNER, network = False)
+ if audio_cpp_files.is_downloaded(aligner):
+ return
+ except RuntimeError:
+ pass
+ _notify(on_phase, "downloading_aligner")
+ try:
+ aligner = audio_cpp_backend._resolve_companion(entry, QWEN3_ALIGNER, network = True)
+ audio_cpp_backend.AudioCppBackend._download_missing(aligner, None)
+ except Exception as exc: # noqa: BLE001 - every failure reads the same to the user
+ reason = sanitize_runtime_detail(str(exc)) or type(exc).__name__
+ logger.warning("audio.cpp: timestamp aligner download failed: %s", reason)
+ raise SttModelNotDownloadedError(
+ f"Could not download the timestamp aligner ({reason}). "
+ "Turn off Timestamps to transcribe without them."
+ ) from exc
+ forget(QWEN3_ALIGNER.id)
+
+ def _with_aligner(self, entry: AudioCppModel) -> AudioCppModel:
+ from core.inference import audio_cpp_backend
+
+ try:
+ aligner = audio_cpp_backend._resolve_companion(entry, QWEN3_ALIGNER, network = False)
+ aligner_path = audio_cpp_files.materialize(aligner)
+ except AudioCppUnavailableError as exc:
+ raise SttEngineUnavailableError(str(exc)) from exc
+ except (FileNotFoundError, RuntimeError):
+ raise SttModelNotDownloadedError(
+ "The timestamp aligner is not downloaded. Turn off Timestamps to transcribe "
+ "without them."
+ ) from None
+ options = dict(entry.model_options or {})
+ session = dict(options.get("session_options") or {})
+ session[QWEN3_ALIGNER.session_option] = aligner_path
+ return replace(entry, model_options = {**options, "session_options": session})
+
def load(
self,
model: Optional[str] = None,
request_cancel_event: Optional[threading.Event] = None,
device: Optional[str] = None,
+ *,
+ timestamps: bool = False,
+ on_phase: Optional[Callable[[str], None]] = None,
) -> None:
- """Start (or switch) audiocpp_server for the requested audio.cpp ASR model."""
+ """A server already holding the aligner keeps it for untimestamped requests (no restart)."""
from core.inference.audio_device import audio_device_forces_cpu
if request_cancel_event is not None and request_cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
entry = resolve_audio_cpp_stt_model(self.keep_loaded_variant(model))
+ aligned = bool(timestamps) and entry.family in _ALIGNED_FAMILIES
with self._lock:
if request_cancel_event is not None and request_cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
@@ -672,12 +799,17 @@ class AudioCppSttSidecar:
and self._model == entry
and self._forced_cpu == force_cpu
# A server training moved to the CPU goes back to the GPU once training ends.
- and self._launched_cpu == (force_cpu or _training_active())
+ and self._launched_cpu == _launches_on_cpu(entry, force_cpu)
+ and (self._aligned or not aligned)
):
self._loaded_as = _reported_name(model, entry)
self._schedule_idle_unload_locked()
return
model_path = self._ensure_model_downloaded(entry)
+ served = entry
+ if aligned:
+ self._ensure_aligner_downloaded(entry, on_phase)
+ served = self._with_aligner(entry)
cancel_event = (
request_cancel_event if request_cancel_event is not None else threading.Event()
)
@@ -691,8 +823,9 @@ class AudioCppSttSidecar:
raise SttLoadCancelledError("Dictation model loading was cancelled.")
# Decided under the loading flag: training admission reads is_loading() without the lock. During training
# the model goes to CPU so a dictation cannot reclaim the VRAM training just freed.
- run_on_cpu = force_cpu or _training_active()
+ run_on_cpu = _launches_on_cpu(entry, force_cpu)
self._release_locked()
+ _notify(on_phase, "loading")
def _track(process: subprocess.Popen) -> None:
with self._load_state_lock:
@@ -700,7 +833,7 @@ class AudioCppSttSidecar:
try:
server = AudioCppServer.start(
- entry,
+ served,
model_path,
force_cpu = run_on_cpu,
cancel_event = cancel_event,
@@ -716,6 +849,7 @@ class AudioCppSttSidecar:
self._loaded_as = _reported_name(model, entry)
self._forced_cpu = force_cpu
self._launched_cpu = run_on_cpu
+ self._aligned = aligned
self._schedule_idle_unload_locked()
finally:
with self._load_state_lock:
@@ -733,13 +867,10 @@ class AudioCppSttSidecar:
fast: bool = False,
cancel_event: Optional[threading.Event] = None,
) -> dict:
- """Transcribe encoded audio bytes via audiocpp_server. Returns {text, language, duration, model}."""
del fast # audio.cpp ASR families decode greedily; there is no beam knob to trade.
self._raise_if_update_in_progress()
ensure_engine_available()
- target = self.keep_loaded_variant(model)
- entry = resolve_audio_cpp_stt_model(target)
- lang = normalize_whisper_language(language)
+ entry = resolve_audio_cpp_stt_model(self.keep_loaded_variant(model))
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
# A missing model fails before decoding so a long clip does not burn CPU only to 409. The
@@ -749,15 +880,54 @@ class AudioCppSttSidecar:
decoded_audio = _decode_audio_bounded(audio, cancel_event)
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
- wav_bytes = _pcm_to_wav_bytes(decoded_audio)
+ with _temp_wav(_pcm_to_wav_bytes(decoded_audio)) as path:
+ return self.transcribe_path(path, model, language, cancel_event = cancel_event)
+
+ def ensure_aligner(
+ self,
+ model: Optional[str],
+ on_phase: Optional[Callable[[str], None]] = None,
+ ) -> None:
+ """Runs before the load so a 1.1 GB download holds neither the load lock nor dictation."""
+ entry = resolve_audio_cpp_stt_model(self.keep_loaded_variant(model))
+ if entry.family in _ALIGNED_FAMILIES:
+ self._ensure_aligner_downloaded(entry, on_phase)
+
+ def transcribe_path(
+ self,
+ path: Path,
+ model: Optional[str],
+ language: Optional[str],
+ *,
+ timestamps: bool = False,
+ cancel_event: Optional[threading.Event] = None,
+ on_phase: Optional[Callable[[str], None]] = None,
+ ) -> dict:
+ """Transcribe a server-local 16/24 kHz mono WAV in place."""
+ self._raise_if_update_in_progress()
+ ensure_engine_available()
+ target = self.keep_loaded_variant(model)
+ entry = resolve_audio_cpp_stt_model(target)
+ lang = normalize_whisper_language(language)
+ if not audio_cpp_files.is_downloaded(entry):
+ self._ensure_model_downloaded(entry)
+ rate, duration = _wav_rate_and_duration(Path(path))
+ aligned = bool(timestamps) and entry.family in _ALIGNED_FAMILIES
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
with self._lock:
try:
# The caller's own name, so a legacy key stays the name status reports.
- if cancel_event is None:
- self.load(target)
- else:
- self.load(target, request_cancel_event = cancel_event)
- text = self._post_transcription(wav_bytes, lang, cancel_event)
+ self.load(
+ target,
+ request_cancel_event = cancel_event,
+ timestamps = aligned,
+ on_phase = on_phase,
+ )
+ _notify(on_phase, "transcribing")
+ payload = self._post_details(
+ path, lang, cancel_event, dict(_TIMESTAMP_OPTIONS) if aligned else {}
+ )
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
except Exception:
@@ -766,55 +936,64 @@ class AudioCppSttSidecar:
raise
finally:
self._schedule_idle_unload_locked()
- duration = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
- return {
- "text": text,
- "language": lang,
+ details = stt_details.normalize(payload, entry.family, rate)
+ result = {
+ "text": details["text"],
+ "language": lang or details["language"],
"duration": duration,
"model": _reported_name(model, entry),
}
+ for key in ("segments", "words"):
+ if details.get(key):
+ result[key] = details[key]
+ if details.get("speaker_ids"):
+ result["speakers"] = list(details["speaker_ids"])
+ return result
def cancel_transcription(self, cancel_event: threading.Event) -> bool:
already_cancelled = cancel_event.is_set()
cancel_event.set()
return self._cancel_owned_load(cancel_event) or not already_cancelled
- def _post_transcription(
- self, wav_bytes: bytes, lang: Optional[str], cancel_event: Optional[threading.Event]
- ) -> str:
+ def _post_details(
+ self,
+ path: Path,
+ lang: Optional[str],
+ cancel_event: Optional[threading.Event],
+ options: dict,
+ ) -> dict:
server = self._server
if server is None:
raise SttEngineUnavailableError("The audio runtime is not running.")
- fields = {"model": server.model_id}
+ body: dict = {"model": server.model_id, "audio": str(path)}
if lang:
- fields["language"] = lang
-
- def post(form: dict[str, str]) -> bytes:
- return server.post_multipart(
- "/v1/audio/transcriptions",
- form,
- "dictation.wav",
- wav_bytes,
- "audio/wav",
+ body["language"] = lang
+ if options:
+ body["options"] = dict(options)
+
+ def post(request: dict) -> bytes:
+ return server.post_json(
+ _DETAILS_PATH,
+ request,
timeout = _TRANSCRIBE_TIMEOUT_SECONDS,
cancel_event = cancel_event,
)[1]
try:
try:
- data = post(fields)
+ data = post(body)
except AudioCppRequestError as exc:
- if "language" not in fields or not 400 <= exc.status < 500:
+ if "language" not in body or not 400 <= exc.status < 500:
raise
# English-only families (Moonshine, Nemotron, Parakeet) reject a language option; a
# dictation language preference is a hint, so transcribe without it rather than fail.
logger.info(
"audio.cpp: %s rejected language %r (%s); retrying without it",
server.model.family,
- fields["language"],
+ body["language"],
exc.detail,
)
- data = post({k: v for k, v in fields.items() if k != "language"})
+ data = post({k: v for k, v in body.items() if k != "language"})
payload = json.loads(data.decode("utf-8"))
except AudioCppRequestCancelledError as exc:
# The server keeps decoding the abandoned clip and would queue the next request behind it;
@@ -835,11 +1014,10 @@ class AudioCppSttSidecar:
raise SttEngineUnavailableError(
"The audio runtime did not answer the request."
) from exc
- text = payload.get("text") if isinstance(payload, dict) else None
- if not isinstance(text, str):
+ if not isinstance(payload, dict) or not isinstance(payload.get("text"), str):
raise SttAudioDecodeError("Could not decode the audio.")
clear_runtime_inference_failure()
- return " ".join(part.strip() for part in text.splitlines() if part.strip()).strip()
+ return payload
_sidecar: Optional[AudioCppSttSidecar] = None
diff --git a/studio/backend/core/inference/stt_capabilities.py b/studio/backend/core/inference/stt_capabilities.py
new file mode 100644
index 00000000000..240d56ad9a2
--- /dev/null
+++ b/studio/backend/core/inference/stt_capabilities.py
@@ -0,0 +1,133 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""STT model capabilities, answered offline (cache, else name); never raises."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from core.inference.stt_details import ALWAYS_TIMESTAMPED, ON_REQUEST_TIMESTAMPS
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+_SPEAKER_FAMILIES = frozenset({"moss_transcribe_diarize", "vibevoice_asr"})
+_ALIGNER_SIZE_BYTES = 1_129_966_496
+
+_ENGINE_ALIASES = {
+ "": "transformers",
+ "transformers": "transformers",
+ "whisper": "transformers",
+ "gguf": "gguf",
+ "ggml": "gguf",
+ "whisper_cpp": "gguf",
+ "whisper.cpp": "gguf",
+ "mtmd": "mtmd",
+ "llama_cpp": "mtmd",
+ "llama.cpp": "mtmd",
+ "audiocpp": "audiocpp",
+ "audio_cpp": "audiocpp",
+ "audio.cpp": "audiocpp",
+}
+
+
+def label_speakers(ids) -> list[dict]:
+ """``[{id, label}]`` with labels "Speaker 1", "Speaker 2"… in the order the ids first speak."""
+ unique = list(dict.fromkeys(str(i) for i in ids or () if str(i).strip()))
+ return [{"id": sid, "label": f"Speaker {n}"} for n, sid in enumerate(unique, start = 1)]
+
+
+def _is_mtmd(model: str) -> bool:
+ from core.inference.stt_mtmd_sidecar import MTMD_STT_MODELS
+ low = model.lower()
+ return model in MTMD_STT_MODELS or any(m.repo.lower() == low for m in MTMD_STT_MODELS.values())
+
+
+def _engine_for(model: str, engine: Optional[str]) -> Optional[str]:
+ """The engine that would serve ``model``: the one asked for, else the one its id requires."""
+ # The llama.cpp Qwen3-ASR repos are not audio.cpp models, whatever engine was named.
+ if model and _is_mtmd(model):
+ return "mtmd"
+ if engine is not None and str(engine).strip():
+ return _ENGINE_ALIASES.get(str(engine).strip().lower())
+ if not model:
+ return "transformers"
+ from core.inference.audio_cpp_models import looks_like_audio_cpp, resolve
+
+ if looks_like_audio_cpp(model):
+ return "audiocpp"
+ try:
+ found = resolve(model, network = False)
+ except Exception: # noqa: BLE001 - unreadable from the cache: the default engine
+ found = None
+ return "audiocpp" if found is not None and found.task == "asr" else "transformers"
+
+
+def _audio_cpp_family(model: str) -> Optional[str]:
+ """The family of a downloaded audio.cpp ASR model, else the one its name suggests."""
+ from core.inference.audio_cpp_models import (
+ family_from_names,
+ family_policy,
+ parse_identifier,
+ resolve,
+ split_variant_ref,
+ )
+
+ ref = parse_identifier(split_variant_ref(model)[0])
+ if ref is None:
+ return None
+ try:
+ found = resolve(model, network = False)
+ except Exception: # noqa: BLE001 - the name still says something
+ found = None
+ if found is None:
+ family = family_from_names((ref.id, ref.folder or ""))
+ found = family_policy(family) if family else None
+ return found.family if found and found.task == "asr" and not found.unsupported else None
+
+
+def capabilities_for(model: Optional[str], engine: Optional[str]) -> dict:
+ """``timestamps``: "on_request" | "always" | "unsupported"; ``aligner`` only for "on_request"."""
+ model = str(model or "").strip()
+ result = {
+ "engine": None,
+ "family": None,
+ "timestamps": "unsupported",
+ "speakers": False,
+ "aligner": None,
+ "cpu_only": False,
+ }
+ try:
+ resolved_engine = _engine_for(model, engine)
+ result["engine"] = resolved_engine
+ if resolved_engine != "audiocpp" or not model:
+ return result
+ family = _audio_cpp_family(model)
+ if family is None:
+ return result
+ from core.inference.audio_cpp_models import CPU_ONLY_FAMILIES
+
+ result["family"] = family
+ result["cpu_only"] = family in CPU_ONLY_FAMILIES
+ result["speakers"] = family in _SPEAKER_FAMILIES
+ if family in ALWAYS_TIMESTAMPED:
+ result["timestamps"] = "always"
+ elif family in ON_REQUEST_TIMESTAMPS:
+ result["timestamps"] = "on_request"
+ from core.inference import audio_cpp_files
+ from core.inference.audio_cpp_models import resolve
+ from core.inference.stt_audiocpp_sidecar import QWEN3_ALIGNER
+
+ try:
+ aligner = resolve(QWEN3_ALIGNER.id, QWEN3_ALIGNER.variant, network = False)
+ except Exception: # noqa: BLE001 - not in the cache
+ aligner = None
+ result["aligner"] = {
+ "downloaded": aligner is not None and audio_cpp_files.is_downloaded(aligner),
+ "size_bytes": (aligner and aligner.size_bytes) or _ALIGNER_SIZE_BYTES,
+ }
+ except Exception as exc: # noqa: BLE001 - a capability probe never fails the page
+ logger.info("STT capabilities for %r unavailable (%s)", model, type(exc).__name__)
+ result.update(timestamps = "unsupported", speakers = False, aligner = None)
+ return result
diff --git a/studio/backend/core/inference/stt_details.py b/studio/backend/core/inference/stt_details.py
new file mode 100644
index 00000000000..8c044892152
--- /dev/null
+++ b/studio/backend/core/inference/stt_details.py
@@ -0,0 +1,263 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""audio.cpp ``/details`` answers (sample offsets, markers) -> seconds, speakers, clean text."""
+
+from __future__ import annotations
+
+import difflib
+import math
+import re
+from typing import Any, Optional
+
+# Nemotron's spans are sub-word pieces ("f ever ed"), so it is not listed: its text stays whole.
+ALWAYS_TIMESTAMPED = frozenset(
+ {"moss_transcribe_diarize", "vibevoice_asr", "parakeet_tdt", "kroko_asr"}
+)
+ON_REQUEST_TIMESTAMPS = frozenset({"qwen3_asr"})
+_SPAN_KEYS = ("words", "segments", "speaker_turns")
+# VibeVoice-ASR counts its spans at 24 kHz whatever rate it was fed (and reports the input's rate).
+FIXED_SPAN_RATES = {"vibevoice_asr": 24000, "vibevoice_asr_streaming": 24000}
+# MOSS-Transcribe-Diarize embeds "[0.12][S01]" markers in its text; its segments carry the prose.
+_MARKED_TEXT_FAMILIES = frozenset({"moss_transcribe_diarize"})
+_MARKER_RE = re.compile(r"\[\d+(?:\.\d+)?\]|\[S\d+\]")
+
+_SEGMENT_GAP_SECONDS = 0.6
+_SEGMENT_MAX_SECONDS = 10.0
+_SENTENCE_END = tuple(".?!。?!")
+_CLAUSE_END = tuple(",;:,;:")
+
+
+def _number(value: Any) -> Optional[float]:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ value = float(value)
+ return value if math.isfinite(value) else None
+
+
+def _span(item: dict, rate: int) -> Optional[tuple[float, float]]:
+ start, end = _number(item.get("start_sample")), _number(item.get("end_sample"))
+ if start is not None and end is not None:
+ start, end = start / rate, end / rate
+ else:
+ start, end = _number(item.get("start")), _number(item.get("end"))
+ if start is None or end is None:
+ return None
+ if start < 0 or end < start:
+ return None
+ return round(start, 3), round(end, 3)
+
+
+def _clean_lines(text: str) -> str:
+ return " ".join(part.strip() for part in text.splitlines() if part.strip()).strip()
+
+
+def _is_cjk(char: str) -> bool:
+ # Han and kana run together; Hangul is left out because Korean puts spaces between words.
+ code = ord(char)
+ return (
+ 0x3000 <= code <= 0x30FF
+ or 0x3400 <= code <= 0x4DBF
+ or 0x4E00 <= code <= 0x9FFF
+ or 0xF900 <= code <= 0xFAFF
+ or 0xFF00 <= code <= 0xFFEF
+ )
+
+
+def _join_words(words: list[str]) -> str:
+ out = ""
+ for word in words:
+ if out and not (_is_cjk(out[-1]) and _is_cjk(word[0])):
+ out += " "
+ out += word
+ return out
+
+
+def _spanned(raw: Any, rate: int):
+ for item in raw if isinstance(raw, list) else ():
+ span = _span(item, rate) if isinstance(item, dict) else None
+ if span is not None:
+ yield item, span
+
+
+def _words(raw: Any, rate: int) -> list[dict]:
+ return [
+ {"start": start, "end": end, "word": word.strip()}
+ for item, (start, end) in _spanned(raw, rate)
+ if isinstance(word := item.get("word", item.get("text")), str) and word.strip()
+ ]
+
+
+def _segments(raw: Any, rate: int) -> list[dict]:
+ return [
+ {"start": start, "end": end, "text": _clean_lines(text)}
+ for item, (start, end) in _spanned(raw, rate)
+ if isinstance(text := item.get("text"), str)
+ ]
+
+
+def _turns(raw: Any, rate: int) -> list[tuple[float, float, str]]:
+ turns = []
+ for item, (start, end) in _spanned(raw, rate):
+ speaker = item.get("speaker_id", item.get("speaker"))
+ if (
+ isinstance(speaker, (str, int))
+ and not isinstance(speaker, bool)
+ and str(speaker).strip()
+ ):
+ turns.append((start, end, str(speaker).strip()))
+ return turns
+
+
+def _assign_speakers(segments: list[dict], turns: list[tuple[float, float, str]]) -> None:
+ for segment in segments:
+ overlap: dict[str, float] = {}
+ for start, end, speaker in turns:
+ shared = min(segment["end"], end) - max(segment["start"], start)
+ if shared > 0 or (shared == 0 and start <= segment["start"] <= end):
+ overlap[speaker] = overlap.get(speaker, 0.0) + shared
+ if overlap:
+ segment["speaker"] = max(overlap, key = lambda s: overlap[s])
+
+
+def _letters(text: str) -> str:
+ return "".join(ch.lower() for ch in text if ch.isalnum())
+
+
+def _respell(token: str, word: str) -> str:
+ """Keeps ``word``'s case: a chunk can restart mid-sentence with a capital ("Work")."""
+ letters = iter(ch for ch in word if ch.isalnum())
+ return "".join(next(letters, ch) if ch.isalnum() else ch for ch in token)
+
+
+def _split_cjk(token: str) -> list[str]:
+ """``token`` with each CJK character on its own: CJK text has no spaces to split words on."""
+ units, run = [], ""
+ for ch in token:
+ if ch.isalnum() and _is_cjk(ch):
+ if run:
+ units.append(run)
+ run = ""
+ units.append(ch)
+ else:
+ run += ch
+ return units + [run] if run else units
+
+
+def punctuate_words(words: list[dict], text: str) -> list[dict]:
+ """Aligned on letters, matches only: the text repeats chunk overlaps. A word takes the text's
+ spelling only when every one of its pieces matched."""
+ tokens = [unit for token in text.split() for unit in _split_cjk(token)]
+ if not words or not tokens:
+ return words
+ pieces = [(i, unit) for i, word in enumerate(words) for unit in _split_cjk(word["word"])]
+ letters = [_letters(token) for token in tokens]
+ matcher = difflib.SequenceMatcher(
+ None, [_letters(unit) for _, unit in pieces], letters, autojunk = False
+ )
+ shown: dict[int, str] = {}
+ for block in matcher.get_matching_blocks():
+ for offset in range(block.size):
+ index = block.b + offset
+ piece = _respell(tokens[index], pieces[block.a + offset][1])
+ following = index + 1
+ while following < len(tokens) and not letters[following]:
+ piece += tokens[following]
+ following += 1
+ shown[block.a + offset] = piece
+ spelled = [dict(word) for word in words]
+ by_word: dict[int, list[int]] = {}
+ for n, (i, _) in enumerate(pieces):
+ by_word.setdefault(i, []).append(n)
+ for i, ns in by_word.items():
+ if all(n in shown for n in ns):
+ spelled[i]["word"] = "".join(shown[n] for n in ns)
+ return spelled
+
+
+def group_words(words: list[dict]) -> list[dict]:
+ segments: list[dict] = []
+ current: list[dict] = []
+
+ def flush() -> None:
+ if current:
+ segments.append(
+ {
+ "start": current[0]["start"],
+ "end": max(w["end"] for w in current),
+ "text": _join_words([w["word"] for w in current]),
+ }
+ )
+ current.clear()
+
+ for word in words:
+ if current and word["start"] - current[-1]["end"] >= _SEGMENT_GAP_SECONDS:
+ flush()
+ elif current and word["end"] - current[0]["start"] >= _SEGMENT_MAX_SECONDS:
+ cut = next(
+ (
+ i
+ for i in range(len(current) - 1, 0, -1)
+ if current[i - 1]["word"].endswith(_CLAUSE_END)
+ ),
+ len(current),
+ )
+ tail = current[cut:]
+ del current[cut:]
+ flush()
+ current.extend(tail)
+ current.append(word)
+ if word["word"].endswith(_SENTENCE_END):
+ flush()
+ flush()
+ return segments
+
+
+def normalize(payload: dict, family: str, sent_rate: int) -> dict:
+ """``sent_rate`` (the WAV's rate) applies only when the answer names none."""
+ payload = payload if isinstance(payload, dict) else {}
+ if family not in ALWAYS_TIMESTAMPED | ON_REQUEST_TIMESTAMPS:
+ payload = {k: v for k, v in payload.items() if k not in _SPAN_KEYS}
+ rate = FIXED_SPAN_RATES.get(family)
+ if rate is None:
+ reported = payload.get("sample_rate")
+ rate = (
+ int(reported)
+ if isinstance(reported, int) and not isinstance(reported, bool) and reported > 0
+ else int(sent_rate)
+ )
+ words = _words(payload.get("words"), rate)
+ segments = _segments(payload.get("segments"), rate)
+ turns = _turns(payload.get("speaker_turns"), rate)
+ if not segments and turns:
+ segments = _segments(payload.get("speaker_turns"), rate)
+ native_segments = bool(segments)
+ if turns:
+ _assign_speakers(segments, turns)
+ raw_text = payload.get("text")
+ text = raw_text if isinstance(raw_text, str) else ""
+ if not segments and words:
+ # Text rebuilt from words: the runtime's punctuated text repeats each chunk's overlap.
+ words = punctuate_words(words, _clean_lines(text))
+ segments = group_words(words)
+ text = _join_words([w["word"] for w in words])
+
+ if native_segments and (family in _MARKED_TEXT_FAMILIES or _MARKER_RE.search(text)):
+ text = " ".join(s["text"] for s in segments if s["text"])
+ elif _MARKER_RE.search(text):
+ text = " ".join(_MARKER_RE.sub(" ", text).split())
+ text = _clean_lines(text)
+
+ language = payload.get("language")
+ result: dict = {
+ "text": text,
+ "language": language.strip() if isinstance(language, str) and language.strip() else None,
+ }
+ if segments:
+ result["segments"] = segments
+ if words:
+ result["words"] = words
+ speaker_ids = list(dict.fromkeys(s["speaker"] for s in segments if "speaker" in s))
+ if speaker_ids:
+ result["speaker_ids"] = speaker_ids
+ return result
diff --git a/studio/backend/core/inference/stt_registry.py b/studio/backend/core/inference/stt_registry.py
index 467bd3d5088..37932dedd8f 100644
--- a/studio/backend/core/inference/stt_registry.py
+++ b/studio/backend/core/inference/stt_registry.py
@@ -50,6 +50,7 @@ def load(
engine: str,
request_cancel_event: Optional[threading.Event] = None,
device: Optional[str] = None,
+ **options,
) -> None:
"""Make ``model`` resident on ``engine``, then release every idle other engine.
@@ -72,11 +73,11 @@ def load(
if _model_is_downloaded(engine, model):
unload(others, wait = False)
sidecar_for(engine).load(
- model, request_cancel_event = request_cancel_event, device = device
+ model, request_cancel_event = request_cancel_event, device = device, **options
)
else:
sidecar_for(engine).load(
- model, request_cancel_event = request_cancel_event, device = device
+ model, request_cancel_event = request_cancel_event, device = device, **options
)
unload(others, wait = False)
diff --git a/studio/backend/core/inference/transcript_gallery.py b/studio/backend/core/inference/transcript_gallery.py
index 45ba16ee792..761aecd1ca0 100644
--- a/studio/backend/core/inference/transcript_gallery.py
+++ b/studio/backend/core/inference/transcript_gallery.py
@@ -1,11 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Account-scoped transcript history, stored independently of model residency."""
+"""Account-scoped transcript history; optional keys are validated on every read."""
from __future__ import annotations
import json
+import math
import os
import re
import uuid
@@ -18,6 +19,17 @@ from utils.paths import ensure_account_dir, ensure_dir, studio_root
from utils.paths.storage_roots import account_path
_ID_RE = re.compile(r"^[a-f0-9]{32}$")
+_BASE_KEYS = ("id", "title", "text", "model", "duration", "language", "created_at", "archived")
+_MAX_SEGMENTS = 20_000
+_MAX_WORDS = 100_000
+_MAX_SPEAKERS = 64
+SPEAKER_NAME_MAX = 40
+_SOURCE_KINDS = ("input", "clip", "voice")
+_SOURCE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
+
+
+class TranscriptPatchError(ValueError):
+ """A speaker rename the record cannot take (an unknown id, a name too long)."""
def gallery_dir() -> Path:
@@ -26,6 +38,101 @@ def gallery_dir() -> Path:
return ensure_account_dir(account_path("transcripts"))
+def _seconds(value) -> float | None:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ value = float(value)
+ return value if math.isfinite(value) and value >= 0 else None
+
+
+def _spans(items, limit: int, text_key: str, speakers: bool) -> list[dict] | None:
+ if not isinstance(items, list) or len(items) > limit:
+ return None
+ out = []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ start, end = _seconds(item.get("start")), _seconds(item.get("end"))
+ text = item.get(text_key)
+ if start is None or end is None or start > end or not isinstance(text, str):
+ continue
+ span = {"start": start, "end": end, text_key: text}
+ speaker = item.get("speaker")
+ if speakers and isinstance(speaker, str) and 0 < len(speaker) <= 64:
+ span["speaker"] = speaker
+ out.append(span)
+ return out
+
+
+def _sanitize_details(record: dict) -> dict:
+ """``record`` with each optional key kept only when well formed; base keys untouched."""
+ clean = {key: value for key, value in record.items() if key in _BASE_KEYS}
+ segments = _spans(record.get("segments"), _MAX_SEGMENTS, "text", speakers = True)
+ if segments:
+ clean["segments"] = segments
+ words = _spans(record.get("words"), _MAX_WORDS, "word", speakers = False)
+ if words:
+ clean["words"] = words
+ speakers = record.get("speakers")
+ if isinstance(speakers, list) and len(speakers) <= _MAX_SPEAKERS:
+ kept = [
+ {"id": s["id"], "label": s["label"]}
+ for s in speakers
+ if isinstance(s, dict)
+ and isinstance(s.get("id"), str)
+ and 0 < len(s["id"]) <= 64
+ and isinstance(s.get("label"), str)
+ and len(s["label"]) <= 64
+ ]
+ if kept:
+ clean["speakers"] = list({s["id"]: s for s in kept}.values())
+ known = {s["id"] for s in clean.get("speakers", ())}
+ names = record.get("speaker_names")
+ if isinstance(names, dict):
+ kept_names = {
+ sid: name.strip()
+ for sid, name in names.items()
+ if sid in known
+ and isinstance(name, str)
+ and name.strip()
+ and len(name.strip()) <= SPEAKER_NAME_MAX
+ }
+ if kept_names:
+ clean["speaker_names"] = kept_names
+ source = record.get("source")
+ if (
+ isinstance(source, dict)
+ and source.get("kind") in _SOURCE_KINDS
+ and isinstance(source.get("id"), str)
+ and _SOURCE_ID_RE.fullmatch(source["id"])
+ and isinstance(source.get("name"), str)
+ ):
+ clean["source"] = {"kind": source["kind"], "id": source["id"], "name": source["name"][:255]}
+ if record.get("timestamps") is True and "segments" in clean:
+ clean["timestamps"] = True
+ return clean
+
+
+def summary(record: dict) -> dict:
+ row = {key: record.get(key) for key in _BASE_KEYS}
+ row["segment_count"] = len(record.get("segments") or ())
+ row["has_words"] = bool(record.get("words"))
+ for key in ("speakers", "speaker_names", "source"):
+ if key in record:
+ row[key] = record[key]
+ return row
+
+
+def _write(directory: Path, record: dict) -> None:
+ transcript_id = record["id"]
+ staged = directory / f".{transcript_id}.tmp"
+ try:
+ staged.write_text(json.dumps(record, ensure_ascii = False), encoding = "utf-8")
+ os.replace(staged, directory / f"{transcript_id}.json")
+ finally:
+ staged.unlink(missing_ok = True)
+
+
def save(result: dict, title: str) -> dict:
transcript_id = uuid.uuid4().hex
record = {
@@ -38,13 +145,14 @@ def save(result: dict, title: str) -> dict:
"created_at": datetime.now(timezone.utc).isoformat(),
"archived": False,
}
- directory = gallery_dir()
- staged = directory / f".{transcript_id}.tmp"
- try:
- staged.write_text(json.dumps(record, ensure_ascii = False), encoding = "utf-8")
- os.replace(staged, directory / f"{transcript_id}.json")
- finally:
- staged.unlink(missing_ok = True)
+ details = {
+ key: result[key]
+ for key in ("segments", "words", "speakers", "speaker_names", "source", "timestamps")
+ if key in result
+ }
+ if details:
+ record = _sanitize_details({**record, **details})
+ _write(gallery_dir(), record)
return record
@@ -62,6 +170,8 @@ def _read(directory: Path, transcript_id: str) -> dict | None:
isinstance(record.get(key), str) for key in ("text", "model", "title", "created_at")
):
return None
+ if any(key not in _BASE_KEYS for key in record):
+ return _sanitize_details(record)
return record
except (OSError, ValueError):
return None
@@ -91,7 +201,7 @@ def list_transcripts(
if before is not None and cursor >= before:
continue
record["archived"] = archived
- records.append(record)
+ records.append(summary(record))
records.sort(key = lambda record: (record["created_at"], record["id"]), reverse = True)
visible = records[:limit]
return {
@@ -115,6 +225,38 @@ def set_archived(transcript_id: str, archived: bool) -> dict | None:
return record
+def set_speaker_names(transcript_id: str, names: dict) -> dict | None:
+ """None or "" unnames; raises ``TranscriptPatchError`` on unknown ids or overlong names."""
+ directory = gallery_dir()
+ with gallery_flags.exclusive(directory):
+ record = _read(directory, transcript_id)
+ if record is None:
+ return None
+ known = {s["id"] for s in record.get("speakers", ())}
+ merged = dict(record.get("speaker_names") or {})
+ for speaker_id, name in names.items():
+ if speaker_id not in known:
+ raise TranscriptPatchError(f"This transcript has no speaker '{speaker_id}'.")
+ name = (name or "").strip()
+ if len(name) > SPEAKER_NAME_MAX:
+ raise TranscriptPatchError(
+ f"Speaker names can be at most {SPEAKER_NAME_MAX} characters."
+ )
+ if name:
+ merged[speaker_id] = name
+ else:
+ merged.pop(speaker_id, None)
+ if merged:
+ record["speaker_names"] = merged
+ else:
+ record.pop("speaker_names", None)
+ stored = {key: value for key, value in record.items() if key != "archived"}
+ stored["archived"] = False
+ _write(directory, stored)
+ record["archived"] = gallery_flags.is_archived(gallery_flags.read(directory), transcript_id)
+ return record
+
+
def delete(transcript_id: str) -> bool:
directory = gallery_dir()
with gallery_flags.exclusive(directory):
diff --git a/studio/backend/core/inference/transcript_stream.py b/studio/backend/core/inference/transcript_stream.py
index 15928dab231..9435dc5c6f6 100644
--- a/studio/backend/core/inference/transcript_stream.py
+++ b/studio/backend/core/inference/transcript_stream.py
@@ -34,7 +34,8 @@ async def stream_transcript(transcribe, title: str):
if closed:
return
now = time.monotonic()
- if now - last_update >= 0.25:
+ # A phase change ("loading", "downloading_aligner", "transcribing") is never throttled away.
+ if update.get("phase") or now - last_update >= 0.25:
last_update = now
loop.call_soon_threadsafe(publish, update)
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 6c2f46436a5..ea3c0d0f548 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -5276,6 +5276,48 @@ class AudioInputTranscript(BaseModel):
model: str
+class TranscribeSourceRef(BaseModel):
+ """The audio to transcribe, by id: an upload, a history clip or a saved voice. Exactly one."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ input_id: Optional[str] = Field(None, pattern = _AUDIO_ID_PATTERN)
+ clip_id: Optional[str] = Field(None, pattern = _AUDIO_ID_PATTERN)
+ voice_id: Optional[str] = Field(None, pattern = _AUDIO_ID_PATTERN)
+
+ @model_validator(mode = "after")
+ def _exactly_one(self):
+ named = [v for v in (self.input_id, self.clip_id, self.voice_id) if v]
+ if len(named) != 1:
+ raise ValueError("Name exactly one of input_id, clip_id or voice_id.")
+ return self
+
+
+class TranscribeSourceRequest(BaseModel):
+ """``POST /audio/transcribe/source``: Audio page audio named by id, transcribed and saved."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ source: TranscribeSourceRef
+ model: str = Field(..., min_length = 1, max_length = 512)
+ engine: Optional[str] = Field(None, max_length = 64)
+ device: Optional[Literal["auto", "cpu", "gpu"]] = None
+ language: Optional[str] = Field(None, max_length = 64)
+ timestamps: bool = Field(False, description = "Ask for segment and word timestamps")
+ speakers: bool = Field(False, description = "Keep who spoke each segment, when the model tells")
+ title: Optional[str] = Field(None, max_length = 255, description = "Defaults to the source's name")
+
+
+class TranscriptPatch(BaseModel):
+ """``PATCH /audio/transcripts/{id}``: archive or restore, and name speakers (None clears)."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ archived: Optional[bool] = None
+ # transcript_gallery.set_speaker_names validates ids and lengths against the record.
+ speaker_names: Optional[Dict[str, Optional[str]]] = None
+
+
class AudioVoice(BaseModel):
id: str
name: str
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a827ef50653..6aa9d2b53a8 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3706,6 +3706,8 @@ from models.inference import (
AudioVoiceCreate,
AudioVoiceListResponse,
AudioVoicePatch,
+ TranscribeSourceRequest,
+ TranscriptPatch,
LoadResponse,
LoadProgressResponse,
UnloadResponse,
@@ -23613,9 +23615,15 @@ async def _transcribe_audio_result(
request: Optional[Request] = None,
device: Optional[str] = None,
on_progress = None,
+ *,
+ source_path: Optional[Path] = None,
+ timestamps: bool = False,
) -> dict:
"""STT for already-decoded bytes, sidecar errors mapped to HTTP statuses.
- Returns the sidecar's result dict so callers own the response shape."""
+ Returns the sidecar's result dict so callers own the response shape.
+
+ ``source_path`` (a prepared WAV inside the account) replaces ``raw``: audio.cpp reads it in
+ place, with ``timestamps`` when asked; every other engine gets its bytes."""
if account_access.managed_account():
await asyncio.to_thread(
account_access.require_model_access, _stt_repo_reference(model, engine)
@@ -23633,12 +23641,19 @@ async def _transcribe_audio_result(
SttTranscriptionCancelledError,
)
- if not raw:
- raise HTTPException(status_code = 400, detail = "Audio is empty.")
- if len(raw) > _MAX_AUDIO_RAW_BYTES:
- raise HTTPException(status_code = 413, detail = "Audio is too large.")
+ if source_path is None:
+ if not raw:
+ raise HTTPException(status_code = 400, detail = "Audio is empty.")
+ if len(raw) > _MAX_AUDIO_RAW_BYTES:
+ raise HTTPException(status_code = 413, detail = "Audio is too large.")
serving_engine = _resolve_serving_stt_engine(engine)
+ if source_path is not None and serving_engine != "audiocpp":
+ # Prepared WAVs are capped at 30 min; the encoded-upload cap would refuse past ~13 min.
+ raw = await asyncio.to_thread(source_path.read_bytes)
+ source_path = None
+ if not raw:
+ raise HTTPException(status_code = 400, detail = "Audio is empty.")
await asyncio.to_thread(
_prepare_runtime_fallback_checkpoint,
engine,
@@ -23660,13 +23675,37 @@ async def _transcribe_audio_result(
# timers fired, which is what OOMs a device that fits either alone. A no-op once
# the model is resident, so the steady state costs a residency check.
load_stt, _ = _stt_lifecycle()
+ on_phase = (
+ (lambda phase: on_progress({"text": "", "phase": phase}))
+ if on_progress is not None and source_path is not None
+ else None
+ )
+ load_options = {"on_phase": on_phase} if on_phase is not None else {}
+ if source_path is not None and timestamps:
+ await asyncio.to_thread(sidecar.ensure_aligner, model, on_phase)
+ # Started with its aligner now, or transcribe_path would restart it.
+ load_options["timestamps"] = True
await asyncio.to_thread(
- functools.partial(load_stt, model, serving_engine, cancel_event, device = device)
+ functools.partial(
+ load_stt, model, serving_engine, cancel_event, device = device, **load_options
+ )
)
loaded = getattr(sidecar, "loaded_model", None)
if loaded is not None and loaded == _stt_resolved_model_id(model, serving_engine):
account_access.note_resident_account(f"stt:{serving_engine}", loaded)
- if on_progress is not None and serving_engine in ("transformers", "mtmd"):
+ if source_path is not None:
+ result = await asyncio.to_thread(
+ functools.partial(
+ sidecar.transcribe_path,
+ source_path,
+ model,
+ language,
+ timestamps = timestamps,
+ cancel_event = cancel_event,
+ on_phase = on_phase,
+ )
+ )
+ elif on_progress is not None and serving_engine in ("transformers", "mtmd"):
result = await asyncio.to_thread(
sidecar.transcribe,
raw,
@@ -23724,6 +23763,10 @@ async def _transcribe_audio_result(
finally:
if disconnect_watcher is not None:
await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
+ speakers = result.get("speakers") if isinstance(result, dict) else None
+ if isinstance(speakers, list) and all(isinstance(s, str) for s in speakers):
+ from core.inference.stt_capabilities import label_speakers
+ result = {**result, "speakers": label_speakers(speakers)}
return result
@@ -23802,6 +23845,86 @@ async def transcribe_audio_raw(
)
+def _source_transcript(result: dict, source, speakers: bool) -> dict:
+ out = dict(result)
+ if not (speakers and out.get("speakers")):
+ out.pop("speakers", None)
+ if out.get("segments"):
+ out["segments"] = [
+ {k: v for k, v in s.items() if k != "speaker"} for s in out["segments"]
+ ]
+ out["source"] = {"kind": source.kind, "id": source.id, "name": source.name}
+ out["timestamps"] = bool(out.get("segments"))
+ return out
+
+
+@studio_router.post("/audio/transcribe/source")
+async def transcribe_audio_source(
+ body: TranscribeSourceRequest, current_subject: str = Depends(get_current_subject)
+):
+ """Transcribe Audio page audio named by id, streamed as NDJSON and saved to history."""
+ from core.inference import audio_inputs, stt_capabilities, stt_details
+ from core.inference.transcript_stream import stream_transcript
+
+ engine = body.engine or await asyncio.to_thread(_stt_engine_for_model, body.model)
+ serving_engine = _resolve_serving_stt_engine(engine)
+ caps = await asyncio.to_thread(stt_capabilities.capabilities_for, body.model, serving_engine)
+ if body.timestamps and caps["timestamps"] == "unsupported":
+ raise HTTPException(
+ status_code = 422,
+ detail = "This model cannot add timestamps. Pick Qwen3-ASR (audio.cpp), Parakeet-TDT, "
+ "MOSS-Transcribe-Diarize or VibeVoice-ASR.",
+ )
+ if body.speakers and not caps["speakers"]:
+ raise HTTPException(
+ status_code = 422,
+ detail = "This model cannot tell speakers apart. Pick MOSS-Transcribe-Diarize or "
+ "VibeVoice-ASR.",
+ )
+ rate = stt_details.FIXED_SPAN_RATES.get(caps["family"], 16000)
+
+ def _prepare():
+ source = audio_inputs.resolve_source(body.source.model_dump(exclude_none = True))
+ return source, audio_inputs.prepared_path(source, rate)
+
+ try:
+ source, path = await asyncio.to_thread(_prepare)
+ except audio_inputs.AudioInputError as exc:
+ raise _audio_source_error(exc) from None
+
+ async def _run(on_progress):
+ result = await _transcribe_audio_result(
+ b"",
+ body.model,
+ body.language,
+ False,
+ engine,
+ None,
+ body.device,
+ on_progress,
+ source_path = path,
+ timestamps = body.timestamps,
+ )
+ return _source_transcript(result, source, body.speakers)
+
+ return StreamingResponse(
+ stream_transcript(_run, body.title or source.name),
+ media_type = "application/x-ndjson",
+ headers = {"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
+ )
+
+
+@studio_router.get("/audio/stt/capabilities")
+async def stt_model_capabilities(
+ model: Optional[str] = Query(None, max_length = 512),
+ engine: Optional[str] = Query(None, max_length = 64),
+ current_subject: str = Depends(get_current_subject),
+):
+ """What ``model`` can add to a transcript (timestamps, speakers) and where it runs. Offline."""
+ from core.inference import stt_capabilities
+ return await asyncio.to_thread(stt_capabilities.capabilities_for, model, engine)
+
+
# =====================================================================
# OpenAI-Compatible Chat Completions (/chat/completions)
@@ -44881,20 +45004,48 @@ async def list_gallery_transcripts(
return await asyncio.to_thread(transcript_gallery.list_transcripts, limit, before, archived)
+@studio_router.get("/audio/transcripts/{transcript_id}")
+async def get_gallery_transcript(
+ transcript_id: str, current_subject: str = Depends(get_current_subject)
+):
+ """One transcript in full: its segments, words and speakers included."""
+ from core.inference import transcript_gallery
+
+ record = await asyncio.to_thread(transcript_gallery.get, transcript_id)
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Transcript not found.")
+ return record
+
+
@studio_router.patch("/audio/transcripts/{transcript_id}")
async def archive_gallery_transcript(
transcript_id: str,
- patch: AudioGalleryFlagsPatch,
+ patch: TranscriptPatch,
current_subject: str = Depends(get_current_subject),
):
+ """Archive or restore a transcript, and name its speakers; returns its list row."""
from core.inference import transcript_gallery
- if patch.archived is None:
+ if patch.archived is None and patch.speaker_names is None:
raise HTTPException(status_code = 422, detail = "Specify whether to archive this transcript.")
- record = await asyncio.to_thread(transcript_gallery.set_archived, transcript_id, patch.archived)
- if record is None:
- raise HTTPException(status_code = 404, detail = "Transcript not found.")
- return record
+ record = None
+ if patch.speaker_names is not None:
+ try:
+ record = await asyncio.to_thread(
+ transcript_gallery.set_speaker_names, transcript_id, patch.speaker_names
+ )
+ except transcript_gallery.TranscriptPatchError as exc:
+ raise HTTPException(status_code = 422, detail = str(exc)) from None
+ if record is None:
+ raise HTTPException(status_code = 404, detail = "Transcript not found.")
+ if patch.archived is not None:
+ archived = await asyncio.to_thread(
+ transcript_gallery.set_archived, transcript_id, patch.archived
+ )
+ if archived is None:
+ raise HTTPException(status_code = 404, detail = "Transcript not found.")
+ record = archived
+ return transcript_gallery.summary(record)
@studio_router.delete("/audio/transcripts/{transcript_id}")
diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.py
index a7acb16fb48..9f6bc8e441d 100644
--- a/studio/backend/tests/multi_account/factories_media.py
+++ b/studio/backend/tests/multi_account/factories_media.py
@@ -356,6 +356,9 @@ FACTORIES = {
),
"routes.inference:DELETE:/audio/voices/{voice_id}": Factory("media-audio-voice"),
"routes.inference:GET:/audio/voices/{voice_id}/file": Factory("media-audio-voice"),
+ "routes.inference:GET:/audio/transcripts/{transcript_id}": Factory(
+ "media-transcript", fragment = SENTINEL
+ ),
"routes.inference:PATCH:/audio/transcripts/{transcript_id}": Factory(
"media-transcript", {"archived": True}, fragment = SENTINEL
),
diff --git a/studio/backend/tests/test_account_media_isolation.py b/studio/backend/tests/test_account_media_isolation.py
index 441c8abb061..bbc24c00bfb 100644
--- a/studio/backend/tests/test_account_media_isolation.py
+++ b/studio/backend/tests/test_account_media_isolation.py
@@ -304,3 +304,21 @@ def test_inputs_and_voices_live_in_the_accounts_audio_folder(tmp_path):
assert run_as(BOB, audio_inputs.inputs_dir) == bob / "inputs"
assert run_as(BOB, audio_voices.voices_dir) == bob / "voices"
assert run_as(OWNER, audio_inputs.inputs_dir) == tmp_path / "audio" / "inputs"
+
+
[email protected]("account,other", [(ALICE, BOB), (BOB, ALICE)])
+def test_transcribe_sources_and_transcripts_do_not_resolve_another_accounts_ids(account, other):
+ from core.inference import transcript_gallery
+
+ clip_id = run_as(account, _save, "audio")["id"]
+ transcript = run_as(account, transcript_gallery.save, {"text": "t", "model": "m"}, "t")
+ with _client(other) as client:
+ for source in ({"input_id": _save_input(account)["id"]}, {"clip_id": clip_id}):
+ body = {"source": source, "model": "small"}
+ response = client.post("/api/inference/audio/transcribe/source", json = body)
+ assert response.status_code == 404, response.text
+ url = f"/api/inference/audio/transcripts/{transcript['id']}"
+ assert client.get(url).status_code == 404
+ assert client.patch(url, json = {"speaker_names": {"S01": "Mallory"}}).status_code == 404
+ assert client.patch(url, json = {"archived": True}).status_code == 404
+ assert transcript["id"] not in client.get("/api/inference/audio/transcripts").text
diff --git a/studio/backend/tests/test_audio_cpp_models.py b/studio/backend/tests/test_audio_cpp_models.py
index 64753081e6e..7c9366af912 100644
--- a/studio/backend/tests/test_audio_cpp_models.py
+++ b/studio/backend/tests/test_audio_cpp_models.py
@@ -418,7 +418,7 @@ def test_a_spec_fallback_family_the_runtime_lacks_is_refused(hub, monkeypatch, t
monkeypatch.setattr(acm, "runtime_knows_family", _REAL_RUNTIME_KNOWS_FAMILY)
_fake_runtime(monkeypatch, tmp_path, tag = AUDIO_CPP_SPEC_FAMILIES_TAG)
for family, folder, tasks in (
- ("samsone", "Samsone-GGUF", ["asr"]),
+ ("gigaam_asr", "GigaAM-v3-GGUF", ["asr"]),
("crisperwhisper", "CrisperWhisper2.0-GGUF", ["asr"]),
("kugelaudio", "KugelAudio-0-Open-GGUF", ["tts"]),
):
@@ -427,8 +427,8 @@ def test_a_spec_fallback_family_the_runtime_lacks_is_refused(hub, monkeypatch, t
f"{folder}/m-q8_0.gguf",
_gguf_bytes(family = family, spec = {"tasks": tasks}),
)
- samsone = acm.resolve(f"{AUDIO_CPP_REPO}/Samsone-GGUF", network = False)
- assert (samsone.task, samsone.unsupported) == ("asr", None)
+ gigaam = acm.resolve(f"{AUDIO_CPP_REPO}/GigaAM-v3-GGUF", network = False)
+ assert (gigaam.task, gigaam.unsupported) == ("asr", None)
crisper = acm.resolve(f"{AUDIO_CPP_REPO}/CrisperWhisper2.0-GGUF", network = False)
assert crisper.task == "" and crisper.workflows == {}
assert crisper.unsupported == (
@@ -2073,3 +2073,14 @@ def test_required_inputs_come_from_the_raw_spec(hub):
design_spec = {**maya_spec, "family": "qwen3_tts"}
_put(snap, f"{folder}/m-q8_0.gguf", _gguf_bytes(family = "qwen3_tts", spec = design_spec))
assert acm.resolve(f"{AUDIO_CPP_REPO}/{folder}", network = False).required_inputs == ()
+
+
+def test_samsone_is_refused_for_transcription(hub):
+ from core.inference import stt_audiocpp_sidecar as s
+ from core.inference.stt_sidecar import SttModelIdError
+
+ spec = {"category": "asr", "tasks": ["asr"]}
+ _put(_snapshot(hub), "Samsone-GGUF/s-q8_0.gguf", _gguf_bytes(family = "samsone", spec = spec))
+ with pytest.raises(SttModelIdError, match = "describes audio"):
+ s.resolve_audio_cpp_stt_model(f"{AUDIO_CPP_REPO}/Samsone-GGUF")
+ assert f"{AUDIO_CPP_REPO}/Samsone-GGUF" not in s.downloaded_model_ids()
diff --git a/studio/backend/tests/test_audio_cpp_server_http.py b/studio/backend/tests/test_audio_cpp_server_http.py
index cd48be382b2..f84d1336343 100644
--- a/studio/backend/tests/test_audio_cpp_server_http.py
+++ b/studio/backend/tests/test_audio_cpp_server_http.py
@@ -79,6 +79,11 @@ FAKE_SERVER = textwrap.dedent(
if fields.get("language") == "slow":
time.sleep(30)
return self.reply(200, json.dumps({"text": json.dumps(fields, sort_keys=True)}).encode())
+ if self.path == "/v1/audio/transcriptions/details":
+ req = json.loads(body)
+ if req.get("language") == "slow":
+ time.sleep(30)
+ return self.reply(200, json.dumps({"text": json.dumps(req, sort_keys=True)}).encode())
self.reply(404, b"{}")
ThreadingHTTPServer(("127.0.0.1", cfg["port"]), H).serve_forever()
@@ -160,16 +165,20 @@ def test_cancel_closes_the_socket_mid_request(fake_binary, tmp_path):
server.stop()
-def test_transcription_multipart_carries_model_language_and_file(fake_binary, tmp_path):
+def test_transcription_details_carries_model_audio_language_and_options(fake_binary, tmp_path):
from core.inference.stt_audiocpp_sidecar import AudioCppSttSidecar
-
- model = CANARY
- server = srv.AudioCppServer.start(model, str(tmp_path / "m.gguf"))
+ server = srv.AudioCppServer.start(CANARY, str(tmp_path / "m.gguf"))
try:
side = AudioCppSttSidecar()
side._server = server
- fields = json.loads(side._post_transcription(b"RIFF....WAVE", "en", None))
- assert fields == {"file": "dictation.wav", "language": "en", "model": server.model_id}
+ audio = tmp_path / "a.wav"
+ payload = side._post_details(audio, "en", None, {"timestamps": True})
+ assert json.loads(payload["text"]) == {
+ "audio": str(audio),
+ "language": "en",
+ "model": server.model_id,
+ "options": {"timestamps": True},
+ }
finally:
server.stop()
@@ -186,7 +195,7 @@ def test_cancelled_transcription_stops_the_busy_server(fake_binary, tmp_path):
cancel = threading.Event()
threading.Timer(0.3, cancel.set).start()
with side._lock, pytest.raises(SttTranscriptionCancelledError):
- side._post_transcription(b"RIFF....WAVE", "slow", cancel)
+ side._post_details(tmp_path / "a.wav", "slow", cancel, {})
# The child still decoding the abandoned clip is gone, so the next load starts a fresh one.
assert side._server is None and not server.alive()
finally:
diff --git a/studio/backend/tests/test_audio_runtime_errors.py b/studio/backend/tests/test_audio_runtime_errors.py
index bc943d09fcc..102807e0da0 100644
--- a/studio/backend/tests/test_audio_runtime_errors.py
+++ b/studio/backend/tests/test_audio_runtime_errors.py
@@ -246,19 +246,19 @@ def test_a_transcription_error_is_sanitized_before_it_reaches_the_client():
def __init__(self, status):
self.status = status
- def post_multipart(self, *_args, **_kwargs):
+ def post_json(self, *_args, **_kwargs):
raise AudioCppRequestError(self.status, _LEAKY)
sidecar = stt.AudioCppSttSidecar.__new__(stt.AudioCppSttSidecar)
sidecar._server = _Server(500)
with pytest.raises(stt.SttEngineUnavailableError) as failed:
- sidecar._post_transcription(b"RIFF", None, None)
+ sidecar._post_details("a.wav", None, None, {})
message = str(failed.value)
assert message.startswith("The audio runtime failed: The audio runtime could not generate")
assert "/home/alice" not in message and "hf_AbCdEf" not in message and "\n" not in message
sidecar._server = _Server(400)
with pytest.raises(SttAudioDecodeError) as refused:
- sidecar._post_transcription(b"RIFF", None, None)
+ sidecar._post_details("a.wav", None, None, {})
assert "/home/alice" not in str(refused.value)
stt.clear_runtime_inference_failure()
diff --git a/studio/backend/tests/test_stt_audiocpp_details.py b/studio/backend/tests/test_stt_audiocpp_details.py
new file mode 100644
index 00000000000..99875f379a6
--- /dev/null
+++ b/studio/backend/tests/test_stt_audiocpp_details.py
@@ -0,0 +1,264 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The audio.cpp STT sidecar against a fake ``audiocpp_server`` that records requests."""
+
+import json
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+from core.inference import audio_cpp_backend
+from core.inference import audio_cpp_models as acm
+from core.inference import audio_cpp_server as srv
+from core.inference import stt_audiocpp_sidecar as stt
+from core.inference.audio_cpp_models import AUDIO_CPP_REPO
+from core.inference.stt_sidecar import SttAudioDecodeError
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_audio_cpp_models import _gguf_bytes, _put, _snapshot, hub # noqa: E402, F401
+from test_audio_inputs import wav_bytes # noqa: E402
+
+QWEN3 = f"{AUDIO_CPP_REPO}/Qwen3-ASR-0.6B-GGUF"
+MOSS = f"{AUDIO_CPP_REPO}/MOSS-Transcribe-Diarize-GGUF"
+NIAGARA = f"{AUDIO_CPP_REPO}/Niagara-ASR-GGUF"
+ALIGNER_FILE = "Qwen3-ForcedAligner-0.6B-GGUF/qwen3-forced-aligner-0.6b-q8_0.gguf"
+ALIGNER_KEY = "qwen3_asr.forced_aligner_model_path"
+
+FAKE_SERVER = textwrap.dedent(
+ r"""
+ import json, os, sys, time
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ here = os.path.dirname(os.path.abspath(__file__))
+ cfg = json.load(open(sys.argv[sys.argv.index("--config") + 1], encoding="utf-8"))
+ entry = cfg["models"][0]
+ with open(os.path.join(here, "starts.jsonl"), "a", encoding="utf-8") as log:
+ log.write(json.dumps({"backend": cfg["backend"], "entry": entry}) + "\n")
+
+ SPANS = [(1920, 16000, "Hello there.", "S01"), (17600, 32000, "General Kenobi.", "S02")]
+ MOSS = {
+ "text": "[0.12][S01] Hello there.[1.00][1.10][S02] General Kenobi.[2.00]",
+ "segments": [{"start_sample": a, "end_sample": b, "text": t} for a, b, t, _ in SPANS],
+ "speaker_turns": [{"start_sample": a, "end_sample": b, "speaker_id": s} for a, b, _, s in SPANS],
+ "sample_rate": 16000,
+ }
+
+ class H(BaseHTTPRequestHandler):
+ def log_message(self, *a): pass
+ def reply(self, code, payload):
+ body = json.dumps(payload).encode()
+ self.send_response(code); self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
+ def do_GET(self):
+ if self.path == "/health":
+ return self.reply(200, {"status": "ok"})
+ if self.path == "/v1/models":
+ return self.reply(200, {"data": [{"id": entry["id"]}]})
+ self.reply(404, {})
+ def do_POST(self):
+ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
+ audio = req.get("audio")
+ record = {"path": self.path, "json": req, "audio_existed": bool(audio) and os.path.isfile(audio)}
+ with open(os.path.join(here, "requests.jsonl"), "a", encoding="utf-8") as log:
+ log.write(json.dumps(record) + "\n")
+ language = req.get("language")
+ if language == "xx":
+ return self.reply(400, {"error": {"message": "unsupported language"}})
+ if language == "boom":
+ return self.reply(500, {"error": {"message": "decoder exploded"}})
+ if entry["family"] == "moss_transcribe_diarize":
+ return self.reply(200, MOSS)
+ payload = {"text": "Concord returned.", "language": "English"}
+ if (req.get("options") or {}).get("return_timestamps") == "true":
+ payload["words"] = [
+ {"word": "Concord", "start_sample": 9088, "end_sample": 19328},
+ {"word": "returned.", "start_sample": 19328, "end_sample": 25728},
+ ]
+ self.reply(200, payload)
+
+ ThreadingHTTPServer(("127.0.0.1", cfg["port"]), H).serve_forever()
+ """
+)
+
+
+def _add(hub, rel, family):
+ path = _put(_snapshot(hub), rel, _gguf_bytes(family = family))
+ acm.forget()
+ with acm._resolve_lock:
+ acm._downloaded_cache.clear()
+ return path
+
+
+class Fake:
+ def __init__(self, root: Path):
+ self.root = root
+
+ def log(self, name):
+ return [json.loads(line) for line in (self.root / name).read_text("utf-8").splitlines()]
+
+ bodies = property(lambda self: [r["json"] for r in self.log("requests.jsonl")])
+ starts = property(lambda self: self.log("starts.jsonl"))
+
+
+def fake(tmp_path, monkeypatch, hub):
+ _add(hub, "Qwen3-ASR-0.6B-GGUF/qwen3-asr-0.6b-q8_0.gguf", "qwen3_asr")
+ _add(hub, "MOSS-Transcribe-Diarize-GGUF/moss-q8_0.gguf", "moss_transcribe_diarize")
+ _add(hub, "Niagara-ASR-GGUF/niagara-19m-batch.en-f32.gguf", "niagara_asr")
+ root = tmp_path / "fake"
+ root.mkdir()
+ for log in ("starts.jsonl", "requests.jsonl"):
+ (root / log).touch()
+ script = root / "fake_server.py"
+ script.write_text(FAKE_SERVER, encoding = "utf-8")
+ binary = tmp_path / srv.BINARY_NAME
+ binary.write_bytes(b"")
+ real_popen = srv.subprocess.Popen
+
+ def launch(command, *args, **kwargs):
+ if command and command[0] == str(binary):
+ command = [sys.executable, str(script), *command[1:]]
+ return real_popen(command, *args, **kwargs)
+
+ monkeypatch.setattr(srv.subprocess, "Popen", launch)
+ monkeypatch.setattr(srv, "ensure_binary", lambda: str(binary))
+ monkeypatch.setattr(srv, "model_runtime_problem", lambda model, binary = None: None)
+ monkeypatch.setattr(
+ srv, "select_backend", lambda binary, force_cpu: "cpu" if force_cpu else "cuda"
+ )
+ monkeypatch.setattr(stt, "_training_active", lambda: False)
+ monkeypatch.setenv("UNSLOTH_AUDIO_DEVICE", "auto")
+ return Fake(root)
+
+
+def side():
+ sidecar = stt.AudioCppSttSidecar()
+ yield sidecar
+ sidecar.unload()
+
+
+def source(tmp_path):
+ path = tmp_path / "source.wav"
+ path.write_bytes(wav_bytes(2.0))
+ return path
+
+
+def test_bytes_go_as_json_naming_a_temp_file_removed_after_success_or_error(fake, side):
+ result = side.transcribe(wav_bytes(2.0), QWEN3, "en")
+ assert result["text"] == "Concord returned." and result["language"] == "en"
+ assert result["duration"] == pytest.approx(2.0)
+ assert not {"segments", "words", "speakers"} & set(result)
+ (record,) = fake.log("requests.jsonl")
+ body, audio = record["json"], Path(record["json"]["audio"])
+ assert record["path"] == "/v1/audio/transcriptions/details"
+ assert audio.is_absolute() and audio.parent == stt._stt_tmp_dir() and audio.suffix == ".wav"
+ assert record["audio_existed"] and not list(audio.parent.glob("*.wav"))
+ assert (body["language"], body["model"]) == ("en", fake.starts[0]["entry"]["id"])
+ assert "options" not in body
+ with pytest.raises(stt.SttEngineUnavailableError):
+ side.transcribe(wav_bytes(), QWEN3, "boom")
+ assert not list(audio.parent.glob("*.wav"))
+ # A family that rejects the language is asked again without it.
+ assert side.transcribe(wav_bytes(), QWEN3, "xx")["text"] == "Concord returned."
+ assert fake.bodies[-2]["language"] == "xx" and "language" not in fake.bodies[-1]
+
+
+def test_moss_reads_the_source_in_place_with_speakers_and_no_options(fake, side, source):
+ result = side.transcribe_path(source, MOSS, None, timestamps = True)
+ (body,) = fake.bodies
+ assert body["audio"] == str(source) and "options" not in body
+ assert source.exists() # the caller's file is not ours to remove
+ assert result["text"] == "Hello there. General Kenobi." and result["duration"] == 2.0
+ assert result["speakers"] == ["S01", "S02"]
+ assert [(s["start"], s["end"], s["speaker"]) for s in result["segments"]] == [
+ (0.12, 1.0, "S01"),
+ (1.1, 2.0, "S02"),
+ ]
+ # MOSS loads without the aligner whatever the request asked.
+ assert ALIGNER_KEY not in json.dumps(fake.starts[0]["entry"])
+ assert side.transcribe(wav_bytes(), MOSS, None)["text"] == "Hello there. General Kenobi."
+
+
+def test_qwen3_aligner_is_downloaded_loaded_once_and_kept(fake, side, source, hub, monkeypatch):
+ real_resolve = audio_cpp_backend._resolve_companion
+ downloads, phases = [], []
+
+ def resolve(
+ model,
+ companion,
+ hf_token = None,
+ *,
+ network = True,
+ ):
+ if network:
+ # Stands in for the Hub listing: the files arrive with the download below.
+ _add(hub, ALIGNER_FILE, "qwen3_forced_aligner")
+ return real_resolve(model, companion, hf_token, network = False)
+
+ monkeypatch.setattr(audio_cpp_backend, "_resolve_companion", resolve)
+ download = staticmethod(lambda model, token: downloads.append(model.id) or True)
+ monkeypatch.setattr(audio_cpp_backend.AudioCppBackend, "_download_missing", download)
+
+ def run(**kwargs):
+ phases.clear()
+ return side.transcribe_path(source, QWEN3, None, on_phase = phases.append, **kwargs)
+
+ assert run() == {
+ "text": "Concord returned.",
+ "language": "English",
+ "duration": 2.0,
+ "model": QWEN3,
+ }
+ assert "options" not in fake.bodies[-1] and "session_options" not in fake.starts[0]["entry"]
+ result = run(timestamps = True)
+ assert phases == ["downloading_aligner", "loading", "transcribing"]
+ assert downloads == [stt.QWEN3_ALIGNER.id] and len(fake.starts) == 2
+ assert Path(fake.starts[1]["entry"]["session_options"][ALIGNER_KEY]).suffix == ".gguf"
+ assert fake.bodies[-1]["options"] == {
+ "return_timestamps": "true",
+ "audio_chunk_mode": "fixed",
+ "qwen3_asr.preserve_punctuation": "true",
+ }
+ assert result["words"] == [
+ {"start": 0.568, "end": 1.208, "word": "Concord"},
+ {"start": 1.208, "end": 1.608, "word": "returned."},
+ ]
+ assert result["segments"] == [{"start": 0.568, "end": 1.608, "text": "Concord returned."}]
+ run(timestamps = True)
+ assert phases == ["transcribing"] and len(downloads) == 1
+ run()
+ side.transcribe(wav_bytes(), QWEN3, None)
+ assert len(fake.starts) == 2 and all("options" not in b for b in fake.bodies[-2:])
+
+
+def test_an_aligner_download_failure_says_how_to_go_on(fake, side, source, monkeypatch):
+ def offline(*_args, **_kwargs):
+ raise RuntimeError(
+ "Qwen3-ASR needs Qwen3-ForcedAligner-0.6B-GGUF, which Studio could not find."
+ )
+
+ monkeypatch.setattr(audio_cpp_backend, "_resolve_companion", offline)
+ with pytest.raises(stt.SttModelNotDownloadedError, match = "Turn off Timestamps"):
+ side.transcribe_path(source, QWEN3, None, timestamps = True)
+ assert fake.starts == []
+
+
+def test_niagara_runs_on_the_cpu_even_when_the_gpu_is_asked_for(fake, side):
+ side.load(NIAGARA, device = "gpu")
+ side.load(NIAGARA, device = "gpu")
+ side.transcribe(wav_bytes(), NIAGARA, None)
+ assert [s["backend"] for s in fake.starts] == ["cpu"]
+ assert side.device == "cpu" and side._gpu_disabled is True
+
+
+def test_an_unreadable_source_is_a_decode_error(fake, side, tmp_path):
+ bad = tmp_path / "bad.wav"
+ bad.write_bytes(b"not a wav")
+ with pytest.raises(SttAudioDecodeError):
+ side.transcribe_path(bad, QWEN3, None)
+ assert fake.starts == []
diff --git a/studio/backend/tests/test_stt_capabilities.py b/studio/backend/tests/test_stt_capabilities.py
new file mode 100644
index 00000000000..1dafd4467f5
--- /dev/null
+++ b/studio/backend/tests/test_stt_capabilities.py
@@ -0,0 +1,105 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""stt_capabilities: what each speech-to-text model adds to a transcript, answered offline."""
+
+import sys
+from pathlib import Path
+
+import pytest
+
+from core.inference import audio_cpp_models as acm
+from core.inference import stt_capabilities as caps
+from core.inference.audio_cpp_models import AUDIO_CPP_REPO as REPO
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_audio_cpp_models import _gguf_bytes, _put, _snapshot, hub # noqa: E402, F401
+
+
+def _add(hub, folder, family):
+ _put(_snapshot(hub), f"{folder}/{folder.lower()}-q8_0.gguf", _gguf_bytes(family = family))
+ acm.forget()
+
+
+ "folder,family,timestamps,speakers,cpu_only",
+ [
+ ("Qwen3-ASR-0.6B-GGUF", "qwen3_asr", "on_request", False, False),
+ ("MOSS-Transcribe-Diarize-GGUF", "moss_transcribe_diarize", "always", True, False),
+ ("VibeVoice-ASR-GGUF", "vibevoice_asr", "always", True, False),
+ ("VibeVoice-ASR-Streaming-GGUF", "vibevoice_asr_streaming", "unsupported", False, False),
+ ("Parakeet-TDT-0.6B-v3-GGUF", "parakeet_tdt", "always", False, False),
+ ("Kroko-ASR-GGUF", "kroko_asr", "always", False, False),
+ # Its spans are sub-word pieces, so Studio treats it as plain text.
+ ("Nemotron-3.5-ASR-Streaming-0.6B-GGUF", "nemotron_asr", "unsupported", False, False),
+ ("Canary-180M-Flash-GGUF", "canary_asr", "unsupported", False, False),
+ ("Niagara-ASR-GGUF", "niagara_asr", "unsupported", False, True),
+ ],
+)
[email protected]("downloaded", [True, False])
+def test_audio_cpp_table(hub, folder, family, timestamps, speakers, cpu_only, downloaded):
+ if downloaded:
+ _add(hub, folder, family)
+ for engine in ("audiocpp", None):
+ result = caps.capabilities_for(f"{REPO}/{folder}", engine)
+ assert (result["engine"], result["family"]) == ("audiocpp", family)
+ assert (result["timestamps"], result["speakers"]) == (timestamps, speakers)
+ assert result["cpu_only"] is cpu_only
+ assert (result["aligner"] is not None) == (timestamps == "on_request")
+
+
+def test_qwen3_reports_whether_its_aligner_is_downloaded(hub):
+ def aligner():
+ return caps.capabilities_for(f"{REPO}/Qwen3-ASR-1.7B-GGUF", "audiocpp")["aligner"]
+
+ assert aligner() == {"downloaded": False, "size_bytes": 1_129_966_496}
+ _add(hub, "Qwen3-ForcedAligner-0.6B-GGUF", "qwen3_forced_aligner")
+ assert aligner()["downloaded"] is True and aligner()["size_bytes"] > 0
+
+
+ "model,engine,expected_engine",
+ [
+ ("qwen3-asr-0.6b", "mtmd", "mtmd"),
+ ("qwen3-asr-0.6b", None, "mtmd"),
+ ("unslothai/Qwen3-ASR-0.6B-GGUF", "audiocpp", "mtmd"),
+ ("small", "transformers", "transformers"),
+ ("small", "gguf", "gguf"),
+ ("small", None, "transformers"),
+ (None, None, "transformers"),
+ ("", "audiocpp", "audiocpp"),
+ ("nobody/Nothing-Here", None, "transformers"),
+ ("nobody/Nothing-Here", "audiocpp", "audiocpp"),
+ (f"{REPO}/Samsone-GGUF", "audiocpp", "audiocpp"),
+ (f"{REPO}/Qwen3-ASR-0.6B-GGUF", "no-such-engine", None),
+ ],
+)
+def test_other_engines_and_unknown_models_are_plain_text(hub, model, engine, expected_engine):
+ result = caps.capabilities_for(model, engine)
+ assert result == {
+ "engine": expected_engine,
+ "family": None,
+ "timestamps": "unsupported",
+ "speakers": False,
+ "aligner": None,
+ "cpu_only": False,
+ }
+
+
+def test_a_failing_lookup_still_answers(hub, monkeypatch):
+ def broken(*_args, **_kwargs):
+ raise OSError("cache unreadable")
+
+ monkeypatch.setattr(acm, "resolve", broken)
+ monkeypatch.setattr(acm, "family_from_names", broken)
+ result = caps.capabilities_for(f"{REPO}/MOSS-Transcribe-Diarize-GGUF", "audiocpp")
+ assert result["timestamps"] == "unsupported" and result["speakers"] is False
+
+
+def test_speakers_are_labelled_in_the_order_they_first_speak():
+ assert caps.label_speakers(["S03", "S01", "S03", "0"]) == [
+ {"id": "S03", "label": "Speaker 1"},
+ {"id": "S01", "label": "Speaker 2"},
+ {"id": "0", "label": "Speaker 3"},
+ ]
+ assert caps.label_speakers(None) == []
diff --git a/studio/backend/tests/test_stt_details.py b/studio/backend/tests/test_stt_details.py
new file mode 100644
index 00000000000..a4f25759b42
--- /dev/null
+++ b/studio/backend/tests/test_stt_details.py
@@ -0,0 +1,184 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""stt_details.normalize: audio.cpp ``/details`` answers (as the S4 spike recorded them) in seconds."""
+
+import pytest
+
+from core.inference import stt_details
+
+_MOSS_TEXTS = (
+ ("S01", 2880, 75360, "Welcome back to the studio."),
+ ("S01", 77040, 187680, "Check the solar forecast."),
+ ("S02", 201840, 244320, "I reviewed the forecast this morning."),
+ ("S03", 387600, 511920, "The radios are charged and paired."),
+ ("S04", 533280, 671040, "Good. I will send everyone the final plan before dinner."),
+)
+
+
+def _moss(rate = 24000):
+ scale = rate / 24000
+ segments, turns, marked = [], [], []
+ for speaker, start, end, text in _MOSS_TEXTS:
+ start, end = int(start * scale), int(end * scale)
+ segments.append({"start_sample": start, "end_sample": end, "confidence": 0, "text": text})
+ turns.append({**segments[-1], "speaker_id": speaker})
+ marked.append(f"[{start / rate:.2f}][{speaker}] {text}[{end / rate:.2f}]")
+ return {
+ "text": "".join(marked),
+ "segments": segments,
+ "speaker_turns": turns,
+ "sample_rate": rate,
+ }
+
+
+def _seq(words, step = 0.5):
+ """``words`` back to back, ``step`` seconds each."""
+ return [{"start": i * step, "end": i * step + step, "word": w} for i, w in enumerate(words)]
+
+
+def _payload(words, text):
+ spans = [
+ {"word": w["word"], "start_sample": w["start"] * 16000, "end_sample": w["end"] * 16000}
+ for w in words
+ ]
+ return {"text": text, "words": spans, "sample_rate": 16000}
+
+
[email protected]("rate", [24000, 16000])
+def test_moss_markers_are_stripped_and_segments_carry_speakers(rate):
+ result = stt_details.normalize(_moss(rate), "moss_transcribe_diarize", rate)
+ assert result["text"] == " ".join(text for *_, text in _MOSS_TEXTS)
+ segments = result["segments"]
+ assert [s["speaker"] for s in segments] == ["S01", "S01", "S02", "S03", "S04"]
+ assert result["speaker_ids"] == ["S01", "S02", "S03", "S04"]
+ assert (segments[0]["start"], segments[0]["end"], segments[-1]["end"]) == (0.12, 3.14, 27.96)
+ assert "words" not in result
+
+
+def test_vibevoice_spans_are_always_24k_and_a_segment_without_a_turn_has_no_speaker():
+ payload = {
+ "text": "Concord returned. Later.",
+ "segments": [
+ {"start_sample": 0, "end_sample": 84000, "text": "Concord returned."},
+ {"start_sample": 96000, "end_sample": 120000, "text": "Later."},
+ ],
+ "speaker_turns": [{"start_sample": 0, "end_sample": 90000, "speaker_id": "0"}],
+ "sample_rate": 16000,
+ "language": "en",
+ }
+ assert stt_details.normalize(payload, "vibevoice_asr", 16000) == {
+ "text": "Concord returned. Later.",
+ "language": "en",
+ "segments": [
+ {"start": 0.0, "end": 3.5, "text": "Concord returned.", "speaker": "0"},
+ {"start": 4.0, "end": 5.0, "text": "Later."},
+ ],
+ "speaker_ids": ["0"],
+ }
+
+
+def test_qwen3_words_become_seconds_and_take_the_texts_punctuation():
+ payload = _payload(_seq(["Concord", "returned", "home"]), "Concord returned home.")
+ result = stt_details.normalize({**payload, "language": "English"}, "qwen3_asr", 16000)
+ assert result["text"] == "Concord returned home." and result["language"] == "English"
+ assert result["words"][-1] == {"start": 1.0, "end": 1.5, "word": "home."}
+ assert result["segments"] == [{"start": 0.0, "end": 1.5, "text": "Concord returned home."}]
+
+
+def test_word_grouping_splits_on_a_pause_a_long_run_and_a_sentence_end():
+ words = _seq(["One", "two.", "Three", "four"])
+ words[3].update(start = 2.5, end = 3.0)
+ assert [(g["text"], g["start"], g["end"]) for g in stt_details.group_words(words)] == [
+ ("One two.", 0.0, 1.0),
+ ("Three", 1.0, 1.5),
+ ("four", 2.5, 3.0),
+ ]
+ runs = stt_details.group_words(_seq([f"w{i}" for i in range(30)]))
+ assert len(runs) == 2 and all(r["end"] - r["start"] <= 10.0 for r in runs)
+ text = "the great work is still done by patience, courage, memory and care."
+ assert [s["text"] for s in stt_details.group_words(_seq(text.split(), 0.9))] == [
+ "the great work is still done by patience, courage,",
+ "memory and care.",
+ ]
+ # CJK words run together; a CJK word next to a Latin one keeps its space. Korean keeps spaces.
+ assert (
+ stt_details.group_words(_seq(["你好", "世界", "AI", "。"]))[0]["text"] == "你好世界 AI 。"
+ )
+ assert (
+ stt_details.group_words(_seq(["안녕하세요", "반갑습니다"]))[0]["text"]
+ == "안녕하세요 반갑습니다"
+ )
+
+
+def test_malformed_spans_are_dropped():
+ payload = _moss()
+ payload["segments"][1]["start_sample"] = "soon"
+ payload["segments"][2]["end_sample"] = 1 # ends before it starts
+ payload["segments"] += ["not a segment", {"start_sample": 0, "end_sample": 10}]
+ payload["speaker_turns"].append({"start_sample": True, "end_sample": 4, "speaker_id": "S09"})
+ payload["words"] = [
+ {"word": "ok", "start_sample": 0, "end_sample": 16000},
+ {"word": "", "start_sample": 0, "end_sample": 1},
+ {"word": "bad", "start_sample": float("nan"), "end_sample": 1},
+ {"word": "neg", "start_sample": -5, "end_sample": 1},
+ ]
+ result = stt_details.normalize(payload, "moss_transcribe_diarize", 24000)
+ assert len(result["segments"]) == 3 and "S09" not in result["speaker_ids"]
+ assert result["words"] == [{"start": 0.0, "end": 0.667, "word": "ok"}]
+ assert stt_details.normalize("not a dict", "qwen3_asr", 16000) == {"text": "", "language": None}
+
+
+ "words,text,expected",
+ [
+ (
+ ["Friends", "neighbors", "lifewe", "meet", "Again"],
+ "Friends, neighbors, life—we meet. Again!",
+ ["Friends,", "neighbors,", "life—we", "meet.", "Again!"],
+ ),
+ (["Friends", "neighbors"], "Friends — neighbors", ["Friends—", "neighbors"]),
+ (["hello", "world"], "helloworld", ["hello", "world"]),
+ (["hello", "world"], "", ["hello", "world"]),
+ (["hello", "world"], "Goodbye, world!", ["hello", "world!"]),
+ (
+ "the great work of a people is done by patience courage and care".split(),
+ "the great work of a people is done by patience. "
+ "Work of a people is done by patience, courage, and care.",
+ "the great work of a people is done by patience, courage, and care.".split(),
+ ),
+ ],
+)
+def test_aligned_words_take_the_punctuation_of_the_text(words, text, expected):
+ bare = _seq(words)
+ spelled = stt_details.punctuate_words(bare, text)
+ assert [w["word"] for w in spelled] == expected
+ assert [(w["start"], w["end"]) for w in spelled] == [(w["start"], w["end"]) for w in bare]
+ assert [w["word"] for w in bare] == words # the input is never changed
+
+
+ "payload,family,text",
+ [
+ # Shape audiocpp_server returned on a T4: text whole, words split mid-word.
+ (
+ _payload(
+ _seq(["He", "was", "in", "a", "f", "ever", "ed", "sta", "te"]),
+ "He was in a fevered state",
+ ),
+ "nemotron_asr",
+ "He was in a fevered state",
+ ),
+ ({"text": " hello\n world "}, "parakeet_tdt", "hello world"),
+ ({"text": "[0.12][S01] hi there[1.5]"}, "other_asr", "hi there"),
+ ],
+)
+def test_plain_text_and_nemotron_sub_word_spans_never_replace_text(payload, family, text):
+ assert stt_details.normalize(payload, family, 16000) == {"text": text, "language": None}
+
+
[email protected]("split", [["你好", "世界"], ["你", "好", "世", "界"]])
+def test_cjk_text_keeps_its_punctuation_through_alignment(split):
+ # Qwen3-ASR's punctuated Chinese has no spaces; the aligner splits it into words.
+ result = stt_details.normalize(_payload(_seq(split, 0.3), "你好,世界。"), "qwen3_asr", 16000)
+ assert result["text"] == "你好,世界。" and result["segments"][0]["text"] == "你好,世界。"
diff --git a/studio/backend/tests/test_transcribe_source_route.py b/studio/backend/tests/test_transcribe_source_route.py
new file mode 100644
index 00000000000..579f9b13dfe
--- /dev/null
+++ b/studio/backend/tests/test_transcribe_source_route.py
@@ -0,0 +1,219 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""POST /audio/transcribe/source with stub engines; the account boundary is real."""
+
+from __future__ import annotations
+
+import asyncio
+import io
+import json
+import sys
+import wave
+from pathlib import Path
+
+import pytest
+
+from core.inference import audio_gallery, audio_inputs, transcript_gallery
+from core.inference.audio_cpp_models import AUDIO_CPP_REPO as REPO
+from routes import inference
+from utils.account_context import run_as
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_account_media_isolation import ALICE, _client, isolated # noqa: E402, F401
+from test_audio_cpp_models import hub # noqa: E402, F401
+from test_audio_inputs import _chunks, encode, wav_bytes # noqa: E402
+
+MOSS = f"{REPO}/MOSS-Transcribe-Diarize-GGUF"
+QWEN3 = f"{REPO}/Qwen3-ASR-0.6B-GGUF"
+SEGMENTS = [
+ {"start": 0.12, "end": 1.0, "text": "Hello there.", "speaker": "S01"},
+ {"start": 1.1, "end": 2.0, "text": "General Kenobi.", "speaker": "S02"},
+]
+
+
+class _Sidecar:
+ loaded_model = None
+
+ def __init__(self):
+ self.result = {"text": "Hello there. General Kenobi.", "language": None, "duration": 2.0}
+ self.result.update(segments = SEGMENTS, speakers = ["S01", "S02"])
+ self.paths, self.bytes, self.events, self.loads = [], [], [], []
+
+ def ensure_aligner(self, model, on_phase):
+ self.events.append(("aligner", model))
+
+ def transcribe_path(self, path, model, language, *, timestamps, cancel_event, on_phase):
+ on_phase("transcribing")
+ with wave.open(str(path)) as w:
+ self.paths.append((Path(path), w.getframerate(), timestamps, language))
+ return {**self.result, "model": model}
+
+ def transcribe(self, raw, model, language, *_args, **_kwargs):
+ self.bytes.append(raw)
+ return {"text": "plain words", "language": language, "duration": 1.0, "model": model}
+
+ def cancel_transcription(self, cancel_event):
+ cancel_event.set()
+ return True
+
+
+def stub(monkeypatch, hub):
+ sidecar = _Sidecar()
+
+ def load(
+ model,
+ engine,
+ *_args,
+ timestamps = False,
+ on_phase = None,
+ **_kwargs,
+ ):
+ sidecar.loads.append((model, engine))
+ sidecar.events.append(("load", timestamps))
+ if on_phase is not None:
+ on_phase("loading")
+
+ monkeypatch.setattr(inference, "_stt_lifecycle", lambda: (load, lambda *a, **k: []))
+ monkeypatch.setattr(inference, "_stt_sidecar_for", lambda engine: sidecar)
+ monkeypatch.setattr(inference.account_access, "require_model_access", lambda *a, **k: None)
+ return sidecar
+
+
+def _input(account) -> str:
+ data = encode("webm", "libopus", 48000, "stereo", 1.0)
+ save = audio_inputs.save_stream(_chunks([data]), "meeting.webm")
+ return run_as(account, lambda: asyncio.run(save)[0]["id"])
+
+
+def _post(client, **body):
+ body = {"model": MOSS, "engine": "audiocpp", **body}
+ response = client.post("/api/inference/audio/transcribe/source", json = body)
+ return response, [json.loads(line) for line in response.text.splitlines() if line.strip()]
+
+
+ "body",
+ [
+ {"source": {"input_id": "a" * 32}, "path": "/etc/passwd"},
+ {"source": {"path": "/etc/passwd"}},
+ {"source": {"input_id": "a" * 32, "clip_id": "b" * 32}},
+ {"source": {}},
+ {"source": {"input_id": "../../etc/passwd"}},
+ {"source": {"input_id": "a" * 32}, "title": "x" * 256},
+ {"source": {"input_id": "a" * 32}, "device": "tpu"},
+ ],
+)
+def test_client_paths_and_unknown_fields_are_422(stub, body):
+ with _client(ALICE) as client:
+ assert _post(client, **body)[0].status_code == 422
+ assert not stub.paths and not stub.bytes
+
+
+def test_audio_cpp_reads_a_16k_copy_in_the_account_and_the_record_names_the_source(stub, tmp_path):
+ input_id = _input(ALICE)
+ with _client(ALICE) as client:
+ response, events = _post(
+ client, source = {"input_id": input_id}, speakers = True, language = "en"
+ )
+ ((path, rate, timestamps, language),) = stub.paths
+ assert path.parent == tmp_path / "accounts" / ALICE.account_id / "audio" / "inputs"
+ assert path.name.startswith(f"{input_id}.16000.mono") and rate == 16000
+ assert (timestamps, language) == (False, "en") and not stub.bytes
+ assert [e["phase"] for e in events if "phase" in e] == ["loading", "transcribing"]
+ complete = events[-1]
+ labels = [{"id": "S01", "label": "Speaker 1"}, {"id": "S02", "label": "Speaker 2"}]
+ assert (complete["speakers"], complete["segments"]) == (labels, SEGMENTS)
+ assert complete["source"] == {"kind": "input", "id": input_id, "name": "meeting.webm"}
+ assert complete["timestamps"] is True
+ record = complete["record"]
+ assert record["title"] == "meeting.webm" and record["source"] == complete["source"]
+ saved = client.get(f"/api/inference/audio/transcripts/{record['id']}").json()
+ assert (saved["segments"], saved["speakers"]) == (SEGMENTS, labels)
+ stored = run_as(
+ ALICE, lambda: (transcript_gallery.gallery_dir() / f"{record['id']}.json").read_text()
+ )
+ for text in (response.text, stored):
+ assert str(tmp_path) not in text and "/inputs/" not in text
+
+
+def test_vibevoice_sources_are_prepared_at_24k_and_speakers_off_strips_them(stub):
+ meta = {"prompt": "p", "model": "m", "audio_type": "audiocpp_tts", "sample_rate": 24000}
+ meta.update(duration_s = 1.0, created_at = "2026-10-02T00:00:00Z")
+ clip_id = run_as(ALICE, audio_gallery.save, wav_bytes(1.0, 24000), meta)["id"]
+ with _client(ALICE) as client:
+ _, events = _post(client, model = f"{REPO}/VibeVoice-ASR-GGUF", source = {"clip_id": clip_id})
+ ((path, rate, _, _),) = stub.paths
+ assert rate == 24000 and path.name.startswith(f"c-{clip_id}.24000.mono")
+ complete = events[-1]
+ assert "speakers" not in complete and "speakers" not in complete["record"]
+ assert all("speaker" not in s for s in complete["segments"])
+
+
+def test_qwen3_timestamps_are_asked_of_the_sidecar(stub):
+ stub.result = {"text": "Concord returned.", "language": "English", "duration": 3.5}
+ source = {"input_id": _input(ALICE)}
+ with _client(ALICE) as client:
+ complete = _post(client, model = QWEN3, source = source, timestamps = True)[1][-1]
+ assert stub.paths[0][2] is True
+ # The aligner is fetched first and the server starts with it: one load, not two.
+ assert stub.events == [("aligner", QWEN3), ("load", True)]
+ assert complete["timestamps"] is False and "segments" not in complete
+
+
+def test_another_engine_gets_the_prepared_bytes_past_the_encoded_upload_cap(stub, monkeypatch):
+ # 30 minutes of 16 kHz PCM is ~58 MB, past the 25 MB cap for encoded uploads.
+ monkeypatch.setattr(inference, "_MAX_AUDIO_RAW_BYTES", 1024)
+ source = {"input_id": _input(ALICE)}
+ with _client(ALICE) as client:
+ response, events = _post(client, model = "small", engine = "transformers", source = source)
+ assert response.status_code == 200, response.text
+ (raw,) = stub.bytes
+ assert len(raw) > 1024 and not stub.paths and stub.loads == [("small", "transformers")]
+ with wave.open(io.BytesIO(raw)) as w:
+ assert (w.getframerate(), w.getnchannels()) == (16000, 1)
+ assert (events[-1]["text"], events[-1]["timestamps"]) == ("plain words", False)
+
+
+ "model,engine,flag",
+ [
+ ("small", "transformers", "timestamps"),
+ ("qwen3-asr-0.6b", "mtmd", "timestamps"),
+ (f"{REPO}/Nemotron-3.5-ASR-Streaming-0.6B-GGUF", "audiocpp", "timestamps"),
+ (QWEN3, "audiocpp", "speakers"),
+ ("small", "transformers", "speakers"),
+ ],
+)
+def test_asking_an_unsupported_model_for_timestamps_or_speakers_is_422(stub, model, engine, flag):
+ body = {"model": model, "engine": engine, "source": {"input_id": _input(ALICE)}, flag: True}
+ with _client(ALICE) as client:
+ response, _ = _post(client, **body)
+ assert response.status_code == 422 and not stub.paths and not stub.bytes
+ expected = "cannot add timestamps" if flag == "timestamps" else "cannot tell speakers apart"
+ assert expected in response.json()["detail"]
+
+
+def test_capabilities_route_answers_for_any_model(stub):
+ url = "/api/inference/audio/stt/capabilities"
+ with _client(ALICE) as client:
+ assert client.get(url, params = {"model": MOSS}).json()["speakers"] is True
+ unknown = client.get(url, params = {"model": "who/knows", "engine": "bogus"})
+ assert unknown.status_code == 200 and unknown.json()["timestamps"] == "unsupported"
+
+
+def test_transcript_routes_get_rename_and_archive(stub):
+ with _client(ALICE) as client:
+ record = _post(client, source = {"input_id": _input(ALICE)}, speakers = True)[1][-1]["record"]
+ url = f"/api/inference/audio/transcripts/{record['id']}"
+ renamed = client.patch(url, json = {"speaker_names": {"S01": "Alice"}}).json()
+ assert renamed["speaker_names"] == {"S01": "Alice"} and "segments" not in renamed
+ assert client.get(url).json()["speaker_names"] == {"S01": "Alice"}
+ for bad in ({"S09": "Ghost"}, {"S01": "x" * 41}):
+ assert client.patch(url, json = {"speaker_names": bad}).status_code == 422
+ for bad in ({"pinned": True}, {}):
+ assert client.patch(url, json = bad).status_code == 422
+ cleared = client.patch(url, json = {"speaker_names": {"S01": None}, "archived": True}).json()
+ assert "speaker_names" not in cleared and cleared["archived"] is True
+ assert client.get("/api/inference/audio/transcripts/" + "e" * 32).status_code == 404
diff --git a/studio/backend/tests/test_transcript_gallery.py b/studio/backend/tests/test_transcript_gallery.py
index 2d9e9114546..a0a39074a0b 100644
--- a/studio/backend/tests/test_transcript_gallery.py
+++ b/studio/backend/tests/test_transcript_gallery.py
@@ -21,16 +21,18 @@ def test_round_trip_preserves_text_and_origin():
record = save("some/folder/speech.wav")
assert record["title"] == "speech.wav"
assert gallery.get(record["id"]) == record
- assert gallery.list_transcripts()["transcripts"] == [record]
+ assert gallery.list_transcripts()["transcripts"] == [gallery.summary(record)]
def test_cursor_survives_new_records_and_deletion():
first, second = save(), save()
page = gallery.list_transcripts(limit = 1)
- assert page["transcripts"] == [second]
+ assert page["transcripts"] == [gallery.summary(second)]
gallery.delete(second["id"])
save()
- assert gallery.list_transcripts(before = page["next_cursor"])["transcripts"] == [first]
+ assert gallery.list_transcripts(before = page["next_cursor"])["transcripts"] == [
+ gallery.summary(first)
+ ]
def test_clear_keeps_archived_transcripts():
@@ -60,7 +62,7 @@ def test_clear_does_not_guess_when_archive_flags_are_corrupt():
def test_listing_recovers_when_archive_flags_are_unavailable(contents):
record = save()
gallery_flags._store_path(gallery.gallery_dir()).write_text(contents)
- assert gallery.list_transcripts()["transcripts"] == [record]
+ assert gallery.list_transcripts()["transcripts"] == [gallery.summary(record)]
with pytest.raises(gallery_flags.FlagsUnavailable):
gallery.clear()
assert gallery.get(record["id"])["text"] == record["text"]
@@ -121,3 +123,98 @@ def test_archive_and_delete_survive_a_filesystem_without_flock(monkeypatch):
assert gallery.delete(record["id"]) is True
with pytest.raises(gallery_flags.FlagsUnavailable):
gallery.clear()
+
+
+DETAILS = {
+ "segments": [
+ {"start": 0.12, "end": 3.14, "text": "Welcome back.", "speaker": "S01"},
+ {"start": 3.21, "end": 7.82, "text": "Check the forecast.", "speaker": "S02"},
+ ],
+ "words": [{"start": 0.12, "end": 0.5, "word": "Welcome"}],
+ "speakers": [{"id": "S01", "label": "Speaker 1"}, {"id": "S02", "label": "Speaker 2"}],
+ "source": {"kind": "input", "id": "c" * 32, "name": "meeting.webm"},
+ "timestamps": True,
+}
+
+
+def save_details(**overrides):
+ result = {"text": "Welcome back. Check the forecast.", "model": "moss", "duration": 7.9}
+ return gallery.save({**result, **DETAILS, **overrides}, "meeting.webm")
+
+
+def test_an_old_record_reads_exactly_as_before():
+ record = {
+ "id": "d" * 32,
+ "title": "old.wav",
+ "text": "old words",
+ "model": "tiny",
+ "duration": 1.0,
+ "language": None,
+ "created_at": "2026-01-01T00:00:00+00:00",
+ "archived": False,
+ }
+ (gallery.gallery_dir() / f"{record['id']}.json").write_text(json.dumps(record))
+ assert gallery.get(record["id"]) == record
+ assert gallery.list_transcripts()["transcripts"] == [
+ {**record, "segment_count": 0, "has_words": False}
+ ]
+
+
+def test_details_round_trip_and_the_list_carries_counts_only():
+ record = save_details()
+ assert {key: record[key] for key in DETAILS} == DETAILS
+ assert gallery.get(record["id"]) == record
+ (row,) = gallery.list_transcripts()["transcripts"]
+ assert "segments" not in row and "words" not in row
+ assert (row["segment_count"], row["has_words"]) == (2, True)
+ assert (row["speakers"], row["source"]) == (DETAILS["speakers"], DETAILS["source"])
+
+
+def test_malformed_details_are_dropped_and_the_record_survives():
+ record = save_details(
+ segments = [
+ {"start": "soon", "end": 1, "text": "bad time"},
+ {"start": 5, "end": 1, "text": "backwards"},
+ {"start": 0, "end": 1, "text": "kept"},
+ "not a segment",
+ ],
+ words = [{"start": 0, "end": 1, "word": "ok"}] * 100_001,
+ speakers = [{"id": "S01", "label": "Speaker 1"}, {"id": 3}],
+ speaker_names = {"S01": "x" * 41, "S99": "ghost"},
+ source = {"kind": "path", "id": "/etc/passwd", "name": "x"},
+ )
+ assert record["segments"] == [{"start": 0.0, "end": 1.0, "text": "kept"}]
+ assert record["speakers"] == [{"id": "S01", "label": "Speaker 1"}]
+ assert not {"words", "speaker_names", "source"} & set(record)
+ path = gallery.gallery_dir() / f"{record['id']}.json"
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ data.update(segments = {"not": "a list"}, speaker_names = {"S01": 7})
+ path.write_text(json.dumps(data))
+ read = gallery.get(record["id"])
+ assert read["text"] == record["text"]
+ assert not {"segments", "speaker_names", "timestamps"} & set(read)
+
+
+def test_speaker_names_are_validated_cleared_and_written_atomically(monkeypatch):
+ record_id = save_details()["id"]
+ named = gallery.set_speaker_names(record_id, {"S01": " Alice ", "S02": "Bob"})
+ assert named["speaker_names"] == {"S01": "Alice", "S02": "Bob"}
+ assert gallery.set_speaker_names(record_id, {"S02": None})["speaker_names"] == {"S01": "Alice"}
+ for names, error in (({"S09": "Ghost"}, "no speaker"), ({"S01": "x" * 41}, "40")):
+ with pytest.raises(gallery.TranscriptPatchError, match = error):
+ gallery.set_speaker_names(record_id, names)
+ assert gallery.get(record_id)["speaker_names"] == {"S01": "Alice"}
+ assert "speaker_names" not in gallery.set_speaker_names(record_id, {"S01": ""})
+ gallery.set_archived(record_id, True)
+ assert gallery.set_speaker_names(record_id, {"S01": "Al"})["archived"] is True
+ monkeypatch.setattr(gallery.os, "replace", lambda *a: (_ for _ in ()).throw(OSError("full")))
+ with pytest.raises(OSError):
+ gallery.set_speaker_names(record_id, {"S01": "Never"})
+ assert gallery.get(record_id)["speaker_names"] == {"S01": "Al"}
+ assert not list(gallery.gallery_dir().glob(".*.tmp"))
+
+
+def test_unknown_and_unsafe_ids_have_no_speakers_to_name():
+ (gallery.gallery_dir() / ("f" * 32 + ".json")).write_text(json.dumps({"text": "foreign"}))
+ for transcript_id in ("../private", "e" * 32, "f" * 32):
+ assert gallery.set_speaker_names(transcript_id, {"S01": "x"}) is None
diff --git a/studio/backend/tests/test_transcript_stream.py b/studio/backend/tests/test_transcript_stream.py
index f87dddd724f..1f3c012da5c 100644
--- a/studio/backend/tests/test_transcript_stream.py
+++ b/studio/backend/tests/test_transcript_stream.py
@@ -30,6 +30,23 @@ def test_progress_and_saved_result(monkeypatch):
asyncio.run(scenario())
+def test_phases_are_never_throttled(monkeypatch):
+ monkeypatch.setattr(transcript_stream.transcript_gallery, "save", lambda result, title: {})
+
+ async def transcribe(progress):
+ # 50 ms apart: a text update this close to the last one would be throttled away.
+ for phase in ("loading", "transcribing"):
+ progress({"text": "", "phase": phase})
+ await asyncio.sleep(0.05)
+ return {"text": "done", "model": "moss"}
+
+ async def collect(stream):
+ return [json.loads(line) async for line in stream]
+
+ events = asyncio.run(collect(transcript_stream.stream_transcript(transcribe, "clip")))
+ assert [e["phase"] for e in events if "phase" in e] == ["loading", "transcribing"]
+
+
def test_save_failure_returns_complete_text(monkeypatch):
async def transcribe(progress):
return {"text": "keep this", "model": "tiny"}
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index a5f9d79b635..55a1a71d64c 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -235,42 +235,6 @@ export async function fetchClipObjectUrl(
return { url: URL.createObjectURL(blob), bytes: blob.size, blob };
}
-export async function transcribeWithProgress(
- blob: Blob,
- title: string,
- options: {
- model: string;
- engine: string;
- device: string;
- signal: AbortSignal;
- },
- onProgress: (
- progress: import("./transcript-stream").TranscriptProgress,
- ) => void,
-): Promise<import("./transcript-stream").TranscriptResult> {
- const { readTranscriptStream } = await import("./transcript-stream");
- const params = new URLSearchParams({
- model: options.model,
- engine: options.engine,
- device: options.device,
- fast: "true",
- stream: "true",
- title: title.slice(0, 255),
- });
- const response = await authFetch(
- `/api/inference/audio/transcribe/raw?${params}`,
- {
- method: "POST",
- headers: { "Content-Type": blob.type || "application/octet-stream" },
- body: blob,
- signal: options.signal,
- },
- );
- if (!response.ok) throw new Error(await readFastApiError(response));
- if (!response.body) throw new Error("The transcription response was empty.");
- return readTranscriptStream(response.body, onProgress);
-}
-
export async function listTranscripts(
archived = false,
before?: string | null,
diff --git a/studio/frontend/src/features/audio/audio-cpp-catalog.ts b/studio/frontend/src/features/audio/audio-cpp-catalog.ts
index 9f76b469b40..0b6dafa0aff 100644
--- a/studio/frontend/src/features/audio/audio-cpp-catalog.ts
+++ b/studio/frontend/src/features/audio/audio-cpp-catalog.ts
@@ -68,6 +68,8 @@ export const AUDIO_CPP_MODELS: readonly AudioCppModel[] = [
{ id: folder("Canary-180M-Flash-GGUF"), task: "asr", languages: ["en", "de", "es", "fr"] },
{ id: folder("Moonshine-Streaming-GGUF"), task: "asr", languages: ENGLISH },
{ id: folder("Nemotron-3.5-ASR-Streaming-0.6B-GGUF"), task: "asr", languages: ENGLISH },
+ // Diarizes; Transcribe offers it for the Speakers switch.
+ { id: folder("MOSS-Transcribe-Diarize-GGUF"), task: "asr" },
];
// Families the backend marks speaks=False (audio_cpp_models.FAMILIES), by repo name: Hub rows
diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.ts
index 1160cc59673..72d2d2bd308 100644
--- a/studio/frontend/src/features/audio/audio-page-policy.ts
+++ b/studio/frontend/src/features/audio/audio-page-policy.ts
@@ -642,16 +642,6 @@ export function reconcileSttSelection({
return preservePending ? selectedRepo : null;
}
-/** Permission prompts cannot be aborted, so freshness is checked immediately after
- * getUserMedia resolves and stale streams are stopped before recording. */
-export function micStreamRequestIsCurrent(
- requestGeneration: number,
- currentGeneration: number,
- active: boolean,
-): boolean {
- return active && requestGeneration === currentGeneration;
-}
-
/**
* The line said above Generate when the run will load or switch the model first, so the wait is
* expected: "Loads Kokoro for Speak, about 5 s". Null when nothing will load.
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 8987bb98d4d..9118e80b8c1 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -29,8 +29,9 @@ import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { useIsMobileShell } from "@/hooks/use-mobile";
+import { useShallow } from "zustand/react/shallow";
-import { type AudioGalleryClip, fetchClipBlob } from "./api";
+import type { AudioGalleryClip } from "./api";
import {
type AudioBusy,
type AudioGenerationPhase,
@@ -63,7 +64,18 @@ import {
import { MusicOutput, MusicRail, musicPageModels } from "./pages/music-page";
import { SpeakOutput, SpeakRail, speakPageModels } from "./pages/speak-page";
import { type GenerateBlocker, TtsFooter } from "./pages/tts-workspace";
-import { TranscribeOutput, TranscribeRail } from "./pages/transcribe-page";
+import { TranscribeFooter, TranscribeOutput, TranscribeRail } from "./pages/transcribe-page";
+import { AUDIO_CPP_REPO, audioCppModelFor } from "./audio-cpp-catalog";
+import { selectionExpired } from "./audio-run-request";
+import type { AudioSourceInputHandle } from "./components/audio-source-input";
+import type { AudioSourceStatus } from "./hooks/audio-source-state";
+import { useTranscribeCapabilities } from "./hooks/use-transcribe-capabilities";
+import { useAudioTranscribeStore } from "./stores/audio-transcribe-store";
+import { SPEAKERS_MODEL_NAME, transcribeSwitches } from "./transcribe-capabilities";
+import {
+ transcribeLanguageFor,
+ transcribeLanguagesFor,
+} from "./transcribe-languages";
import { type AudioPickerRow, audioRowMatchesWorkflow } from "./picker-filter";
import { useAudioCloneStore } from "./stores/audio-clone-store";
import { useAudioWorkspaceStore } from "./stores/audio-workspace-store";
@@ -74,9 +86,10 @@ import {
clipWorkflow,
loadedModelRunsWorkflow,
slotForWorkflow,
- workflowForLoadedModel,
} from "./workflows";
+const SPEAKERS_MODEL_REPO = `${AUDIO_CPP_REPO}/MOSS-Transcribe-Diarize-GGUF`;
+
const MODELS_BY_MODE: Record<CreateMode, ModelOption[]> = {
speak: audioModelsForTask("tts"),
transcribe: audioModelsForTask("stt"),
@@ -204,37 +217,27 @@ export function AudioPage({
const {
transcript,
- setTranscript,
transcribedName,
- setTranscribedName,
transcriptModel,
- setTranscriptModel,
transcriptRecord,
- setTranscriptRecord,
transcriptExported,
- setTranscriptExported,
- transcriptVersion,
transcriptionStartedAt,
- setTranscriptionStartedAt,
transcriptionFinishedAt,
transcriptionStopping,
setTranscriptionStopping,
transcriptionProgress,
transcriptError,
- setTranscriptError,
- isRecording,
- micRequestPending,
- recordingSupported,
+ transcriptDetails,
+ speakerNames,
transcriptionAbort,
- stopAndDiscardRecording,
clearTranscript,
confirmTranscriptReplacement,
- handleRecordToggle,
- handleTranscribeFile,
+ runTranscription,
+ selectRecord,
+ renameSpeaker,
handleCopyTranscript,
handleDownloadTranscript,
} = useTranscription({
- active,
activeRef,
busyRef,
setBusy,
@@ -344,8 +347,6 @@ export function AudioPage({
audioDevice,
isMac,
status,
- isRecording,
- stopAndDiscardRecording,
releaseTranscribeSelection,
ensureSttLoaded,
sttGgufVariants,
@@ -500,15 +501,9 @@ export function AudioPage({
useEffect(() => {
if (adoptedLoadedModel.current || status === null) return;
adoptedLoadedModel.current = true;
- if (modeRef.current !== "speak" || !ttsLoaded) return;
- // A model already resident on mount (reload, another client) opens the page it runs on.
- const store = useAudioWorkspaceStore.getState();
- const next = workflowForLoadedModel({
- current: store.workflow,
- audioWorkflows: status.audio_workflows,
- music: musicGeneration,
- });
- if (next !== "speak" && next !== store.workflow) store.adoptWorkflow(next);
+ if (modeRef.current === "speak" && ttsLoaded && musicGeneration) {
+ useAudioWorkspaceStore.getState().adoptWorkflow("music");
+ }
}, [status, ttsLoaded, musicGeneration]);
const {
@@ -533,42 +528,32 @@ export function AudioPage({
() => handleClearGallery(ttsWorkflow),
[handleClearGallery, ttsWorkflow],
);
- // Send to: only pages that can take a finished clip today. Bytes first, so a failed fetch leaves the page.
const sendHandlersFor = useCallback(
(clip: AudioGalleryClip): ClipSendHandlers => ({
clone: () => {
if (transitionWorkflow("clone")) adoptReference(clipReference(clip));
},
transcribe: () => {
- // Switching mid-run stops the run, and the stopped run still holds the page busy, so the
- // transcription would be refused and the clip silently dropped.
- const busyNow = () => {
- if (busyRef.current === null) return false;
+ // Switching mid-run would stop the run in progress; wait for it instead.
+ if (busyRef.current !== null) {
toast.info("Wait for the current audio task to finish, then send the clip.");
- return true;
- };
- if (busyNow()) return;
- void (async () => {
- try {
- const blob = await fetchClipBlob(clip.url);
- // Checked again: a run started while the clip downloaded would be stopped the same way.
- if (busyNow()) return;
- if (!transitionWorkflow("transcribe")) return;
- const name = `${clip.prompt.trim().slice(0, 40) || "Audio clip"}.wav`;
- handleTranscribeFile(
- new File([blob], name, { type: blob.type || "audio/wav" }),
- );
- } catch (error) {
- toast.error(
- error instanceof Error
- ? error.message
- : "Could not load this clip for transcription.",
- );
- }
- })();
+ return;
+ }
+ if (!transitionWorkflow("transcribe")) return;
+ // The clip goes in by id, as "From history" does; the run keeps the page's own settings.
+ useAudioTranscribeStore.setState({
+ source: {
+ kind: "clip",
+ id: clip.id,
+ name: clip.prompt || "Generated clip",
+ durationS: clip.duration_s,
+ transcript: clip.prompt || null,
+ language: null,
+ },
+ });
},
}),
- [transitionWorkflow, handleTranscribeFile, busyRef],
+ [transitionWorkflow, busyRef],
);
const handleUseTextAgain = useCallback(
(clip: AudioGalleryClip) => {
@@ -711,6 +696,152 @@ export function AudioPage({
);
return () => window.clearInterval(timer);
}, [busy]);
+ const transcribeSource = useAudioTranscribeStore((state) => state.source);
+ const transcribePrefs = useAudioTranscribeStore(
+ useShallow((state) => ({
+ language: state.language,
+ timestamps: state.timestamps,
+ speakers: state.speakers,
+ })),
+ );
+ const transcribeSourceHandle = useRef<AudioSourceInputHandle | null>(null);
+ const [transcribeSourceStatus, setTranscribeSourceStatus] =
+ useState<AudioSourceStatus>({ phase: "idle" });
+ const [expiredTranscribeSourceId, setExpiredTranscribeSourceId] = useState<
+ string | null
+ >(null);
+ const transcribeRepo = (selectedSttRepo ?? lastSttRepo) || null;
+ const transcribeCaps = useTranscribeCapabilities(transcribeRepo);
+ const transcribeOptions = transcribeSwitches(
+ transcribeCaps.caps,
+ transcribePrefs,
+ { loading: transcribeCaps.loading, hasModel: transcribeRepo !== null },
+ );
+ const transcribeModelName = transcribeRepo?.split("/").pop() ?? "";
+ const transcribeLoadsFirst = Boolean(
+ transcribeRepo && !(sttSelected && sttReady),
+ );
+ const transcribeNotice = !transcribeLoadsFirst
+ ? transcribeOptions.notice
+ : transcribeOptions.request.timestamps &&
+ transcribeCaps.caps?.aligner?.downloaded
+ ? `Loads ${transcribeModelName} with its timing aligner first.`
+ : [`Loads ${transcribeModelName} first.`, transcribeOptions.notice]
+ .filter(Boolean)
+ .join(" ");
+ const transcribeLanguages = transcribeLanguagesFor(
+ audioCppModelFor(transcribeRepo)?.languages,
+ );
+ const transcribeLanguage = transcribeLanguageFor(
+ transcribePrefs.language,
+ transcribeLanguages,
+ );
+ const transcribeSourceExpired =
+ transcribeSourceStatus.phase === "expired" ||
+ selectionExpired(transcribeSource, Date.now()) ||
+ (transcribeSource !== null &&
+ transcribeSource.id === expiredTranscribeSourceId);
+ const addAudioActions = [
+ {
+ label: "Add audio",
+ onClick: () => transcribeSourceHandle.current?.focus(),
+ },
+ ];
+ const recommendedSttActions = [
+ { id: `${AUDIO_CPP_REPO}/Qwen3-ASR-0.6B-GGUF`, name: "Qwen3-ASR 0.6B" },
+ { id: SPEAKERS_MODEL_REPO, name: SPEAKERS_MODEL_NAME },
+ ].map((model) => ({
+ label: `use ${model.name}`,
+ onClick: () => void pickRecommendedModel(model.id),
+ }));
+ const transcribeBlocker: GenerateBlocker | null =
+ busy === "loading"
+ ? { reason: "Waiting for the model to finish loading." }
+ : busy !== null
+ ? null
+ : !transcribeRepo
+ ? {
+ reason: "Pick a speech-to-text model to transcribe.",
+ actions: [chooseModelAction, ...recommendedSttActions],
+ }
+ : !transcribeSource
+ ? transcribeSourceStatus.phase === "recording"
+ ? { reason: "Stop recording to transcribe it." }
+ : transcribeSourceStatus.phase === "uploading"
+ ? { reason: "Wait for the upload to finish." }
+ : transcribeSourceStatus.phase === "error"
+ ? {
+ reason: transcribeSourceStatus.message,
+ actions: addAudioActions,
+ }
+ : {
+ reason: "Add audio to transcribe.",
+ actions: addAudioActions,
+ }
+ : transcribeSourceExpired
+ ? {
+ reason: "This upload expired.",
+ actions: [
+ {
+ label: "Add it again",
+ onClick: () => {
+ useAudioTranscribeStore.setState({ source: null });
+ transcribeSourceHandle.current?.browse();
+ },
+ },
+ ],
+ }
+ : transcribeSourceStatus.phase === "uploading" ||
+ transcribeSourceStatus.phase === "loading"
+ ? { reason: "Wait for the upload to finish." }
+ : null;
+ const canTranscribe =
+ mode === "transcribe" && busy === null && transcribeBlocker === null;
+ const handleTranscribe = () => {
+ const source = useAudioTranscribeStore.getState().source;
+ if (!source) return;
+ const { request } = transcribeOptions;
+ void runTranscription(
+ source,
+ { language: transcribeLanguage, ...request },
+ () => {
+ setExpiredTranscribeSourceId(source.id);
+ transcribeSourceHandle.current?.markExpired();
+ },
+ ).then(() => {
+ // A timestamped run may have downloaded the aligner.
+ if (request.timestamps) transcribeCaps.refresh();
+ });
+ };
+ const [transcribeAnnouncement, setTranscribeAnnouncement] = useState("");
+ const lastTranscribeFinish = useRef<number | null>(transcriptionFinishedAt);
+ useEffect(() => {
+ if (
+ transcriptionFinishedAt === null ||
+ transcriptionFinishedAt === lastTranscribeFinish.current
+ )
+ return;
+ lastTranscribeFinish.current = transcriptionFinishedAt;
+ const failed = transcriptError || transcribeSourceExpired;
+ setTranscribeAnnouncement(
+ transcriptError
+ ? `Transcription failed. ${transcriptError}`
+ : transcribeSourceExpired
+ ? "This upload expired. Add it again."
+ : transcript
+ ? "Transcript ready."
+ : "No speech was heard in that audio.",
+ );
+ if (transcript && !failed && activeRef.current)
+ document.getElementById("transcribe-result")?.focus();
+ }, [
+ transcriptionFinishedAt,
+ transcriptError,
+ transcript,
+ activeRef,
+ transcribeSourceExpired,
+ ]);
+
const canGenerate =
mode === "speak" &&
busy === null &&
@@ -723,7 +854,8 @@ export function AudioPage({
const handlePageGenerate =
ttsWorkflow === "clone" ? clone.handleGenerate : handleGenerate;
generateShortcut.current = () => {
- if (canGenerate) void handlePageGenerate();
+ if (canTranscribe) handleTranscribe();
+ else if (canGenerate) void handlePageGenerate();
};
useEffect(() => {
if (!active) return;
@@ -788,7 +920,7 @@ export function AudioPage({
? showLastPageModel
? lastPageModel
: (status?.active_model ?? undefined)
- : (selectedSttRepo ?? undefined);
+ : (transcribeRepo ?? undefined);
const capabilityLine =
mode === "speak"
@@ -816,7 +948,9 @@ export function AudioPage({
: "No TTS model loaded."
: sttSelected
? audioCapabilityLine("stt", sttReady ? "ready" : "loading")
- : "No transcription model selected.";
+ : transcribeRepo
+ ? `${transcribeModelName} is not loaded. It loads when you transcribe.`
+ : "No transcription model selected.";
return (
<div
@@ -933,14 +1067,12 @@ export function AudioPage({
/>
) : null}
</div>
- {/* Its own container: at a large UI size the column is too narrow for the label, which then
- truncated to "Li…". The arrow drops first, then the label, leaving the named icon. */}
- <div className="@container pointer-events-none col-start-3 flex min-w-0 items-start justify-end pr-2 pt-[var(--studio-chat-header-padding-top,11px)]">
+ <div className="pointer-events-none col-start-3 flex min-w-0 items-start justify-end pr-2 pt-[var(--studio-chat-header-padding-top,11px)]">
<div className="pointer-events-auto flex min-w-0 items-center gap-2">
<LibraryPageLink
tab="audio"
- labelClassName="hidden @[8.5rem]:inline"
- arrowClassName="hidden @[10rem]:block"
+ labelClassName="hidden @[50rem]:inline"
+ arrowClassName="hidden @[50rem]:block"
/>
</div>
</div>
@@ -999,7 +1131,6 @@ export function AudioPage({
),
audioDevice,
busy,
- isRecording,
status,
setAudioDeviceState,
ttsLoaded,
@@ -1040,16 +1171,19 @@ export function AudioPage({
);
})()
) : (
- <TranscribeRail
- recordingSupported={recordingSupported}
- isRecording={isRecording}
- sttSelected={sttSelected}
- lastSttRepo={lastSttRepo}
- busy={busy}
- micRequestPending={micRequestPending}
- handleRecordToggle={handleRecordToggle}
- handleTranscribeFile={handleTranscribeFile}
- />
+ <AudioActiveProvider value={active}>
+ <TranscribeRail
+ historyClips={clips}
+ disabled={busy === "transcribing"}
+ sourceHandle={transcribeSourceHandle}
+ onSourceStatusChange={setTranscribeSourceStatus}
+ switches={transcribeOptions}
+ languages={transcribeLanguages}
+ onUseSpeakersModel={() =>
+ void pickRecommendedModel(SPEAKERS_MODEL_REPO)
+ }
+ />
+ </AudioActiveProvider>
)}
</div>
</div>
@@ -1086,7 +1220,24 @@ export function AudioPage({
/>
)}
</div>
- ) : null}
+ ) : (
+ <div className="relative z-10 flex shrink-0 justify-center px-10 pt-0.5 pb-4">
+ <TranscribeFooter
+ busy={busy}
+ blocker={transcribeBlocker}
+ notice={transcribeNotice}
+ modelName={transcribeModelName}
+ progress={transcriptionProgress}
+ shortcutLabel={shortcutLabel}
+ stopping={transcriptionStopping}
+ onTranscribe={handleTranscribe}
+ onStop={() => {
+ setTranscriptionStopping(true);
+ transcriptionAbort.current?.abort();
+ }}
+ />
+ </div>
+ )}
</div>
<div
@@ -1119,16 +1270,15 @@ export function AudioPage({
active={active}
mode={mode}
confirmTranscriptReplacement={confirmTranscriptReplacement}
- transcriptVersion={transcriptVersion}
- setTranscript={setTranscript}
- setTranscribedName={setTranscribedName}
- setTranscriptModel={setTranscriptModel}
- setTranscriptRecord={setTranscriptRecord}
- setTranscriptError={setTranscriptError}
- setTranscriptExported={setTranscriptExported}
- setTranscriptionStartedAt={setTranscriptionStartedAt}
clearTranscript={clearTranscript}
+ transcriptDetails={transcriptDetails}
+ speakerNames={speakerNames}
+ renameSpeaker={renameSpeaker}
+ selectRecord={selectRecord}
/>
+ <output aria-live="polite" aria-atomic="true" className="sr-only">
+ {transcribeAnnouncement}
+ </output>
</div>
) : (
<div className="flex min-h-0 flex-1 flex-col gap-4 p-6 px-10 @[50rem]:pt-[calc(60px*var(--ui-space-scale,1))]">
diff --git a/studio/frontend/src/features/audio/audio-workspace-constants.ts b/studio/frontend/src/features/audio/audio-workspace-constants.ts
index 5f473dd50cf..75e73b983aa 100644
--- a/studio/frontend/src/features/audio/audio-workspace-constants.ts
+++ b/studio/frontend/src/features/audio/audio-workspace-constants.ts
@@ -4,11 +4,8 @@
export const PAGE_SIZE = 50;
// The list route clamps a page to 200, so asking for more silently gets 200 back.
export const MAX_PAGE_SIZE = 200;
-// Mirrors the STT sidecar's _MAX_AUDIO_SECONDS and STT_AUDIO_B64_MAX_CHARS.
+// MAX_SECONDS in core/inference/audio_inputs.py: stop at the boundary rather than upload and be refused.
export const RECORDING_MAX_SECONDS = 30 * 60;
-// STT_AUDIO_RAW_MAX_BYTES in utils/upload_limits.py. A larger client cap let a dense codec build
-export const RECORDING_MAX_BYTES = 25 * 1024 * 1024;
-export const RECORDING_CHUNK_MS = 1000;
export const TTS_MAX_TOKENS = 8192;
// Max tokens caps output only and the prompt shares the context, so TTS_MAX_TOKENS itself is unreachable.
export const TTS_PROMPT_CONTEXT_RESERVE = 2048;
diff --git a/studio/frontend/src/features/audio/components/transcript-view.tsx b/studio/frontend/src/features/audio/components/transcript-view.tsx
new file mode 100644
index 00000000000..d96154e1cbb
--- /dev/null
+++ b/studio/frontend/src/features/audio/components/transcript-view.tsx
@@ -0,0 +1,346 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { PillTabs } from "@/features/model-picker/components/model-selector/pill-tabs";
+import { prefersReducedMotion } from "@/features/settings";
+import { cn } from "@/lib/utils";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+} from "react";
+import { fetchAudioBlob } from "../api";
+import { sourceFileUrl } from "../audio-run-request";
+import {
+ type TranscriptView as TranscriptViewMode,
+ useAudioTranscribeStore,
+} from "../stores/audio-transcribe-store";
+import {
+ SPEAKER_NAME_MAX_LENGTH,
+ type TranscriptDetails,
+ type TranscriptSource,
+ activeSegmentIndex,
+ formatTimestamp,
+ hasSpeakers,
+ paragraphs,
+ sanitizeSpeakerName,
+ speakerLabel,
+} from "../transcript-model";
+import { Waveform, type WaveformControl } from "./waveform";
+import { decodePeaks } from "./waveform-decode";
+
+const VIEW_TABS = [
+ { value: "text", label: "Text" },
+ { value: "segments", label: "Segments" },
+];
+
+const SPEAKER_COLORS = 5;
+
+type SourceAudio =
+ | { status: "idle" | "loading" | "missing" }
+ | {
+ status: "ready";
+ url: string;
+ peaks: number[] | null;
+ durationS: number | null;
+ };
+
+function useSourceAudio(source: TranscriptSource | null): SourceAudio {
+ const [state, setState] = useState<SourceAudio>({ status: "idle" });
+ const kind = source?.kind ?? null;
+ const id = source?.id ?? null;
+ useEffect(() => {
+ if (!(kind && id)) {
+ setState({ status: "idle" });
+ return;
+ }
+ const controller = new AbortController();
+ let url: string | null = null;
+ setState({ status: "loading" });
+ fetchAudioBlob(
+ sourceFileUrl({ kind, id, name: "", durationS: null }),
+ controller.signal,
+ )
+ .then(async (blob) => {
+ const decoded = await decodePeaks(blob);
+ if (controller.signal.aborted) return;
+ url = URL.createObjectURL(blob);
+ setState({ status: "ready", url, ...decoded });
+ })
+ .catch(() => {
+ if (!controller.signal.aborted) setState({ status: "missing" });
+ });
+ return () => {
+ controller.abort();
+ if (url) URL.revokeObjectURL(url);
+ };
+ }, [kind, id]);
+ return state;
+}
+
+function SpeakerChip({
+ id,
+ speakers,
+ names,
+ onRename,
+}: Pick<TranscriptDetails, "speakers"> & {
+ id: string;
+ names: Readonly<Record<string, string>>;
+ onRename: (id: string, name: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState("");
+ const inputId = useId();
+ const label = speakerLabel(id, speakers, names);
+ const index = speakers.findIndex((speaker) => speaker.id === id);
+ const color = (Math.max(0, index) % SPEAKER_COLORS) + 1;
+ const save = () => {
+ onRename(id, sanitizeSpeakerName(draft));
+ setOpen(false);
+ };
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ if (next) setDraft(names[id] ?? "");
+ setOpen(next);
+ }}
+ >
+ <PopoverTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={`Rename ${label}`}
+ className="inline-flex max-w-full shrink-0 items-center gap-1.5 rounded-full bg-muted px-2 py-0.5 text-ui-11p5 font-medium text-foreground transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <span
+ aria-hidden="true"
+ className="size-[calc(8px*var(--ui-space-scale,1))] shrink-0 rounded-full"
+ style={{ backgroundColor: `var(--chart-${color})` }}
+ />
+ <span className="min-w-0 truncate">{label}</span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-64 gap-2 p-3">
+ <label htmlFor={inputId} className="text-ui-13 font-medium">
+ Name
+ </label>
+ <Input
+ id={inputId}
+ value={draft}
+ placeholder={speakers[index]?.label ?? id}
+ maxLength={SPEAKER_NAME_MAX_LENGTH}
+ autoFocus={true}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ save();
+ }
+ }}
+ />
+ <p className="text-ui-11p5 leading-snug text-muted-foreground">
+ Renames every line by this speaker.
+ </p>
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="button" variant="secondary" size="sm" onClick={save}>
+ Save
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+export function TranscriptView({
+ text,
+ details,
+ names,
+ onRename,
+ durationS,
+ children,
+}: {
+ text: string;
+ details: TranscriptDetails;
+ names: Readonly<Record<string, string>>;
+ onRename: (id: string, name: string) => void;
+ durationS: number | null;
+ children: ReactNode;
+}) {
+ const { segments, speakers, source } = details;
+ const view = useAudioTranscribeStore((state) => state.view);
+ const audio = useSourceAudio(source);
+ const ready = audio.status === "ready" ? audio : null;
+ const control = useRef<WaveformControl | null>(null);
+ const player = ready ? control : null;
+ const [position, setPosition] = useState(0);
+ const [playing, setPlaying] = useState(false);
+ const handlePosition = useCallback((seconds: number, isPlaying: boolean) => {
+ setPosition(seconds);
+ setPlaying(isPlaying);
+ }, []);
+ const hasSegments = segments.length > 0;
+ const speakersOn = hasSpeakers(details);
+ const shown = hasSegments ? view : "text";
+ const active =
+ playing || position > 0 ? activeSegmentIndex(position, segments) : -1;
+ // A fixed width in ch keeps rows aligned at any UI size; h:mm:ss needs 7.
+ const stampWidth =
+ hasSegments && segments[segments.length - 1].start >= 3600
+ ? "min-w-[7ch]"
+ : "min-w-[5ch]";
+ const stampClass = cn(
+ "shrink-0 px-1 font-mono text-ui-11p5 tabular-nums text-muted-foreground",
+ stampWidth,
+ );
+ const tabsHint = !hasSegments
+ ? "No timestamps in this transcript. Turn on Timestamps with a model that supports them and transcribe again."
+ : shown === "segments" && player
+ ? "Select a time to play from there."
+ : null;
+ const activeRow = useRef<HTMLLIElement | null>(null);
+
+ // Only while playing, so reading ahead while paused is never yanked back.
+ useEffect(() => {
+ if (!playing || active < 0 || shown !== "segments") return;
+ activeRow.current?.scrollIntoView({
+ block: "nearest",
+ behavior: prefersReducedMotion() ? "auto" : "smooth",
+ });
+ }, [active, playing, shown]);
+
+ const chip = (id: string) => (
+ <SpeakerChip
+ id={id}
+ speakers={speakers}
+ names={names}
+ onRename={onRename}
+ />
+ );
+
+ return (
+ <>
+ {!source ? null : audio.status === "missing" ? (
+ <p className="text-ui-11p5 leading-snug text-muted-foreground">
+ The audio for this transcript is no longer available. Timestamps still
+ export.
+ </p>
+ ) : (
+ <Waveform
+ peaks={ready?.peaks ?? null}
+ durationS={ready?.durationS ?? durationS}
+ src={ready?.url ?? null}
+ label={source.name || "Transcript audio"}
+ controlRef={control}
+ onPositionChange={handlePosition}
+ />
+ )}
+ {children}
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1.5">
+ <PillTabs
+ ariaLabel="Transcript view"
+ tabs={VIEW_TABS}
+ value={shown}
+ onValueChange={(next) =>
+ useAudioTranscribeStore.setState({
+ view: next as TranscriptViewMode,
+ })
+ }
+ disabled={!hasSegments}
+ compact={true}
+ fit={true}
+ className="[&>button]:px-3"
+ />
+ {tabsHint ? (
+ <p className="text-ui-11p5 leading-snug text-muted-foreground">
+ {tabsHint}
+ </p>
+ ) : null}
+ </div>
+ {shown === "segments" ? (
+ <ol className="flex flex-col gap-0.5">
+ {segments.map((segment, index) => {
+ const current = index === active;
+ const stamp = formatTimestamp(segment.start);
+ return (
+ <li
+ // biome-ignore lint/suspicious/noArrayIndexKey: segments are positional and never reorder.
+ key={index}
+ ref={current ? activeRow : undefined}
+ aria-current={current ? "true" : undefined}
+ className={cn(
+ "flex items-start gap-2 rounded-md border-l-2 py-1 pr-2 pl-1.5 transition-colors duration-150 motion-reduce:transition-none",
+ current
+ ? "border-foreground bg-muted"
+ : "border-transparent",
+ )}
+ >
+ {player ? (
+ <button
+ type="button"
+ aria-label={`Play from ${stamp}`}
+ onClick={() => player.current?.seek(segment.start, true)}
+ className={cn(
+ stampClass,
+ "rounded-sm text-left underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",
+ )}
+ >
+ {stamp}
+ </button>
+ ) : (
+ <span className={stampClass}>{stamp}</span>
+ )}
+ <div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-1">
+ {speakersOn && segment.speaker
+ ? chip(segment.speaker)
+ : null}
+ <p className="min-w-0 flex-1 basis-[calc(160px*var(--ui-space-scale,1))] text-sm leading-relaxed text-foreground">
+ {segment.text}
+ </p>
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+ ) : speakersOn ? (
+ <div className="flex flex-col gap-3">
+ {paragraphs(segments).map((paragraph, index) => (
+ <div
+ // biome-ignore lint/suspicious/noArrayIndexKey: paragraphs are positional and never reorder.
+ key={index}
+ className="flex flex-col items-start gap-1"
+ >
+ {paragraph.speaker ? chip(paragraph.speaker) : null}
+ <p className="text-sm leading-relaxed text-foreground">
+ {paragraph.text}
+ </p>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground">
+ {text}
+ </p>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/audio/components/waveform.tsx b/studio/frontend/src/features/audio/components/waveform.tsx
index 82b82c6d872..e4b89847c4c 100644
--- a/studio/frontend/src/features/audio/components/waveform.tsx
+++ b/studio/frontend/src/features/audio/components/waveform.tsx
@@ -5,11 +5,23 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { PauseIcon, PlayIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ type Ref,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from "react";
import { WAVEFORM_BARS, formatSeconds } from "./waveform-peaks";
const SEEK_STEP_SECONDS = 5;
+export interface WaveformControl {
+ seek: (seconds: number, play?: boolean) => void;
+ toggle: () => void;
+}
+
/** The position is also spoken, so colour never carries it alone. */
export function Waveform({
peaks,
@@ -17,6 +29,8 @@ export function Waveform({
src,
label,
className,
+ controlRef,
+ onPositionChange,
}: {
/** 0..1; null draws a flat placeholder while decoding. */
peaks: readonly number[] | null;
@@ -24,6 +38,8 @@ export function Waveform({
src: string | null;
label: string;
className?: string;
+ controlRef?: Ref<WaveformControl>;
+ onPositionChange?: (seconds: number, playing: boolean) => void;
}) {
const audioRef = useRef<HTMLAudioElement | null>(null);
const [playing, setPlaying] = useState(false);
@@ -63,6 +79,27 @@ export function Waveform({
[src, duration],
);
+ useImperativeHandle(
+ controlRef,
+ () => ({
+ seek: (seconds: number, play = false) => {
+ const audio = audioRef.current;
+ if (!(audio && src)) return;
+ const limit = duration > 0 ? duration : Number.POSITIVE_INFINITY;
+ const next = Math.min(limit, Math.max(0, seconds));
+ audio.currentTime = next;
+ setPosition(next);
+ if (play && audio.paused) audio.play().catch(() => setPlaying(false));
+ },
+ toggle,
+ }),
+ [src, duration, toggle],
+ );
+
+ useEffect(() => {
+ onPositionChange?.(position, playing);
+ }, [onPositionChange, position, playing]);
+
return (
<div className={cn("flex items-center gap-2", className)}>
<Button
diff --git a/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts
index 78a790f695f..744b5ebb541 100644
--- a/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts
+++ b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts
@@ -70,7 +70,6 @@ import {
} from "../workflows";
import type { AudioHostState } from "./audio-host-state";
import type { SttSidecar } from "./use-stt-sidecar";
-import type { Transcription } from "./use-transcription";
export function useAudioModelSlot({
active,
@@ -87,8 +86,6 @@ export function useAudioModelSlot({
audioDevice,
isMac,
status,
- isRecording,
- stopAndDiscardRecording,
releaseTranscribeSelection,
ensureSttLoaded,
sttGgufVariants,
@@ -119,7 +116,6 @@ export function useAudioModelSlot({
| "isMac"
| "status"
> &
- Pick<Transcription, "isRecording" | "stopAndDiscardRecording"> &
Pick<
SttSidecar,
| "releaseTranscribeSelection"
@@ -406,7 +402,6 @@ export function useAudioModelSlot({
if (nextMode === "transcribe") invalidatePendingTtsSelection();
if (busyRef.current === "generating") handleStopGeneration();
- stopAndDiscardRecording();
setMode(nextMode);
if (mode === "transcribe") {
// Resolves to whether the sidecar is gone: a swallowed failed unload let the speech load OOM.
@@ -436,7 +431,6 @@ export function useAudioModelSlot({
handleStopGeneration,
mode,
releaseTranscribeSelection,
- stopAndDiscardRecording,
],
);
const transitionWorkflow = useCallback(
@@ -783,7 +777,6 @@ export function useAudioModelSlot({
return;
}
}
- stopAndDiscardRecording();
deferredSttLoad.current = null;
if (task === "stt") {
if (!transitionMode("transcribe")) return;
@@ -892,19 +885,16 @@ export function useAudioModelSlot({
ensureSttLoaded,
isMac,
loadOrStageTtsModel,
- stopAndDiscardRecording,
transitionMode,
],
);
const handleEject = useCallback(() => {
- if (busy !== null || isRecording) {
+ if (busy !== null) {
toast.info("Stop the active audio task before ejecting its model.");
return;
}
- stopAndDiscardRecording();
-
if (mode === "transcribe") {
if (!selectedSttRepo) return;
if (!sttReady) {
@@ -987,7 +977,6 @@ export function useAudioModelSlot({
})();
}, [
busy,
- isRecording,
mode,
refreshStatus,
releaseTranscribeSelection,
@@ -996,7 +985,6 @@ export function useAudioModelSlot({
stageTtsDownload,
status?.active_model,
sttReady,
- stopAndDiscardRecording,
]);
// Scan rows carry no modality until the backend tags them; without this trained checkpoints are unreachable.
diff --git a/studio/frontend/src/features/audio/hooks/use-transcribe-capabilities.ts b/studio/frontend/src/features/audio/hooks/use-transcribe-capabilities.ts
new file mode 100644
index 00000000000..ccbe5ac6a8f
--- /dev/null
+++ b/studio/frontend/src/features/audio/hooks/use-transcribe-capabilities.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useCallback, useEffect, useState } from "react";
+import { sttEngineForRepoId, sttSidecarKeyFor } from "../catalog";
+import { fetchSttCapabilities } from "../transcribe-api";
+import type { SttCapabilities } from "../transcribe-capabilities";
+
+// Answers change only after an aligner download, so one fetch per model per visit.
+const cache = new Map<string, SttCapabilities>();
+
+export function useTranscribeCapabilities(repo: string | null) {
+ const model = repo ? sttSidecarKeyFor(repo) : null;
+ const engine = repo ? sttEngineForRepoId(repo) : null;
+ const key = model ? `${engine ?? ""}:${model}` : null;
+ const [caps, setCaps] = useState<SttCapabilities | null>(
+ key ? (cache.get(key) ?? null) : null,
+ );
+ const [loading, setLoading] = useState(false);
+ const [generation, setGeneration] = useState(0);
+
+ useEffect(() => {
+ if (!(key && model)) {
+ setCaps(null);
+ setLoading(false);
+ return;
+ }
+ const cached = cache.get(key);
+ setCaps(cached ?? null);
+ if (cached && generation === 0) return;
+ const controller = new AbortController();
+ setLoading(true);
+ fetchSttCapabilities(model, engine, controller.signal)
+ .then((next) => {
+ cache.set(key, next);
+ if (!controller.signal.aborted) setCaps(next);
+ })
+ .catch(() => {
+ if (!controller.signal.aborted && !cached) setCaps(null);
+ })
+ .finally(() => {
+ if (!controller.signal.aborted) setLoading(false);
+ });
+ return () => controller.abort();
+ }, [key, model, engine, generation]);
+
+ const refresh = useCallback(() => setGeneration((value) => value + 1), []);
+
+ return { caps, loading, refresh };
+}
diff --git a/studio/frontend/src/features/audio/hooks/use-transcription.ts b/studio/frontend/src/features/audio/hooks/use-transcription.ts
index 5d8d1e05270..21b42f87c20 100644
--- a/studio/frontend/src/features/audio/hooks/use-transcription.ts
+++ b/studio/frontend/src/features/audio/hooks/use-transcription.ts
@@ -1,34 +1,32 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { AUTH_SESSION_ENDING_EVENT } from "@/features/auth";
-import {
- createAudioRecorder,
- PcmRecorder,
- type SegmentRecorder,
-} from "@/features/chat/adapters/pcm-recorder";
-import {
- StudioModelDictationAdapter,
-} from "@/features/chat/adapters/studio-model-dictation-adapter";
import { useVoiceSettingsStore } from "@/features/settings";
import { isTauri } from "@/lib/api-base";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { toast } from "@/lib/toast";
-import { transcribeWithProgress } from "../api";
-import { micStreamRequestIsCurrent } from "../audio-page-policy";
-import {
- RECORDING_CHUNK_MS,
- RECORDING_MAX_BYTES,
- RECORDING_MAX_SECONDS,
-} from "../audio-workspace-constants";
+import { AudioApiError } from "../api";
+import { type AudioSourceSelection, sourceRefOf } from "../audio-run-request";
import { sttEngineForRepoId, sttSidecarKeyFor } from "../catalog";
+import {
+ getTranscript,
+ renameTranscriptSpeakers,
+ transcribeSourceWithProgress,
+} from "../transcribe-api";
import { downloadTranscript } from "../transcript-download";
+import type { TranscriptExportFormat } from "../transcript-export";
import {
readTranscriptDraft,
transcriptDraftKey,
writeTranscriptDraft,
} from "../transcript-draft";
+import {
+ EMPTY_TRANSCRIPT_DETAILS,
+ type TranscriptDetails,
+ detailsFrom,
+} from "../transcript-model";
import type {
TranscriptProgress,
TranscriptRecord,
@@ -36,8 +34,26 @@ import type {
import type { AudioHostState } from "./audio-host-state";
import type { SttSidecar } from "./use-stt-sidecar";
+function withName(
+ names: Record<string, string>,
+ id: string,
+ name: string | undefined,
+): Record<string, string> {
+ const next = { ...names };
+ if (name) next[id] = name;
+ else delete next[id];
+ return next;
+}
+
+function toastFailure(what: string, error: unknown) {
+ toast.error(
+ error instanceof Error && error.message
+ ? `${what}: ${error.message}`
+ : `${what}.`,
+ );
+}
+
export function useTranscription({
- active,
activeRef,
busyRef,
setBusy,
@@ -49,7 +65,7 @@ export function useTranscription({
ensureSttLoaded,
setLastSttRepo,
refreshSttStatus,
-}: Pick<AudioHostState, "active" | "activeRef" | "busyRef" | "setBusy"> &
+}: Pick<AudioHostState, "activeRef" | "busyRef" | "setBusy"> &
Pick<
SttSidecar,
| "lastSttRepo"
@@ -66,6 +82,12 @@ export function useTranscription({
const [transcript, setTranscript] = useState(recoveredTranscript?.text ?? "");
const [transcribedName, setTranscribedName] = useState<string | null>(recoveredTranscript?.title ?? null);
const [transcriptModel, setTranscriptModel] = useState(recoveredTranscript?.model ?? "");
+ const [transcriptDetails, setTranscriptDetails] = useState<TranscriptDetails>(
+ () => recoveredTranscript?.details ?? EMPTY_TRANSCRIPT_DETAILS,
+ );
+ const [speakerNames, setSpeakerNames] = useState<Record<string, string>>(
+ () => recoveredTranscript?.speakerNames ?? {},
+ );
const [transcriptRecord, setTranscriptRecord] = useState<TranscriptRecord | null>(null);
const [transcriptExported, setTranscriptExported] = useState(false);
const transcriptVersion = useRef(0);
@@ -74,39 +96,8 @@ export function useTranscription({
const [transcriptionStopping, setTranscriptionStopping] = useState(false);
const [transcriptionProgress, setTranscriptionProgress] = useState<TranscriptProgress | null>(null);
const [transcriptError, setTranscriptError] = useState<string | null>(null);
- const [isRecording, setIsRecording] = useState(false);
- const [micRequestPending, setMicRequestPending] = useState(false);
- /** WebKit lacks MediaRecorder, and http LAN origins have no navigator.mediaDevices. */
- const recordingSupported = useMemo(
- () => StudioModelDictationAdapter.isSupported(),
- [],
- );
- const recorderRef = useRef<SegmentRecorder | null>(null);
- const recordStreamRef = useRef<MediaStream | null>(null);
- const discardRecordingRef = useRef(false);
- const micRequestGeneration = useRef(0);
- const micPendingGeneration = useRef<number | null>(null);
const transcriptionAbort = useRef<AbortController | null>(null);
- const stopRecordStream = useCallback(() => {
- for (const track of recordStreamRef.current?.getTracks() ?? [])
- track.stop();
- recordStreamRef.current = null;
- }, []);
- const stopAndDiscardRecording = useCallback(() => {
- micRequestGeneration.current += 1;
- micPendingGeneration.current = null;
- setMicRequestPending(false);
- const recorder = recorderRef.current;
- if (recorder) {
- discardRecordingRef.current = true;
- if (recorder.state !== "inactive") recorder.stop();
- recorderRef.current = null;
- setIsRecording(false);
- }
- stopRecordStream();
- }, [stopRecordStream]);
-
const clearTranscript = useCallback(() => {
transcriptVersion.current += 1;
setTranscript("");
@@ -115,6 +106,8 @@ export function useTranscription({
setTranscriptModel("");
setTranscriptRecord(null);
setTranscriptExported(false);
+ setTranscriptDetails(EMPTY_TRANSCRIPT_DETAILS);
+ setSpeakerNames({});
}, []);
const confirmTranscriptReplacement = useCallback(() => {
@@ -139,6 +132,8 @@ export function useTranscription({
text: transcript,
title: transcribedName ?? "Transcript",
model: transcriptModel,
+ details: transcriptDetails,
+ speakerNames,
} : null,
)) {
toast.error("Could not update transcript recovery. Download unsaved text before leaving.");
@@ -178,7 +173,7 @@ export function useTranscription({
window.removeEventListener("beforeunload", warn);
window.removeEventListener(AUTH_SESSION_ENDING_EVENT, confirmLogout);
};
- }, [draftKey, transcript, transcribedName, transcriptModel, transcriptRecord, transcriptExported]);
+ }, [draftKey, transcript, transcribedName, transcriptModel, transcriptRecord, transcriptExported, transcriptDetails, speakerNames]);
const prepareTranscriptionModel = useCallback(async () => {
const repo = selectedSttRepoRef.current ?? lastSttRepo;
@@ -204,7 +199,12 @@ export function useTranscription({
]);
const runTranscription = useCallback(
- async (blob: Blob, name: string, confirmedVersion?: number) => {
+ async (
+ source: AudioSourceSelection,
+ options: { language: string; timestamps: boolean; speakers: boolean },
+ onSourceExpired?: () => void,
+ confirmedVersion?: number,
+ ) => {
if (
transcriptionAbort.current ||
busyRef.current !== null ||
@@ -219,19 +219,20 @@ export function useTranscription({
if (!target || controller.signal.aborted || !activeRef.current) return;
setBusy("transcribing");
clearTranscript();
- setTranscribedName(name);
+ setTranscribedName(source.name);
setTranscriptModel(target.model);
started = true;
setTranscriptionStartedAt(Date.now());
setTranscriptionFinishedAt(null);
setTranscriptionStopping(false);
setTranscriptionProgress(null);
- const result = await transcribeWithProgress(
- blob,
- name,
+ const result = await transcribeSourceWithProgress(
+ sourceRefOf(source),
+ source.name,
{
...target,
device: useVoiceSettingsStore.getState().sttDevice,
+ ...options,
signal: controller.signal,
},
(progress) => {
@@ -242,6 +243,7 @@ export function useTranscription({
setTranscript(result.text);
setTranscriptModel(result.model);
setTranscriptRecord(result.record);
+ setTranscriptDetails(detailsFrom(result));
if (!result.text)
toast.info("The model heard no speech in that audio.");
else if (!result.record)
@@ -253,6 +255,14 @@ export function useTranscription({
setTranscriptError("Transcription cancelled.");
return;
}
+ if (
+ error instanceof AudioApiError &&
+ error.status === 404 &&
+ source.kind === "input"
+ ) {
+ onSourceExpired?.();
+ return;
+ }
const message =
error instanceof Error ? error.message : "Transcription failed.";
setTranscriptError(message);
@@ -274,137 +284,50 @@ export function useTranscription({
],
);
- const handleRecordToggle = useCallback(async () => {
- if (isRecording) {
- const recorder = recorderRef.current;
- if (recorder && recorder.state !== "inactive") recorder.stop();
- return;
- }
- if (micPendingGeneration.current !== null || busyRef.current !== null) return;
- if (!confirmTranscriptReplacement()) return;
- const confirmedVersion = transcriptVersion.current;
- const requestGeneration = ++micRequestGeneration.current;
- micPendingGeneration.current = requestGeneration;
- setMicRequestPending(true);
- try {
- if (
- !(await prepareTranscriptionModel()) ||
- !activeRef.current ||
- micRequestGeneration.current !== requestGeneration
- ) return;
- const stream = await navigator.mediaDevices.getUserMedia({
- audio: { echoCancellation: true, noiseSuppression: true },
+ useEffect(() => () => transcriptionAbort.current?.abort(), []);
+
+ const selectRecord = useCallback((record: TranscriptRecord) => {
+ const version = ++transcriptVersion.current;
+ setTranscript(record.text);
+ setTranscribedName(record.title);
+ setTranscriptModel(record.model);
+ setTranscriptRecord(record);
+ setTranscriptError(null);
+ setTranscriptExported(false);
+ setTranscriptionStartedAt(null);
+ setTranscriptDetails(detailsFrom(record));
+ setSpeakerNames(record.speaker_names ?? {});
+ if (!(record.segment_count || record.has_words)) return;
+ getTranscript(record.id)
+ .then((full) => {
+ if (transcriptVersion.current !== version) return;
+ setTranscriptDetails(detailsFrom(full));
+ setSpeakerNames(full.speaker_names ?? {});
+ })
+ .catch((error: unknown) => {
+ if (transcriptVersion.current === version)
+ toastFailure("Could not load this transcript's timing", error);
});
- if (
- !micStreamRequestIsCurrent(
- requestGeneration,
- micRequestGeneration.current,
- activeRef.current,
- )
- ) {
- for (const track of stream.getTracks()) track.stop();
- return;
- }
- recordStreamRef.current = stream;
- const recorder = createAudioRecorder(stream);
- const maxSeconds =
- recorder instanceof PcmRecorder
- ? Math.min(
- RECORDING_MAX_SECONDS,
- recorder.secondsWithin(RECORDING_MAX_BYTES),
- )
- : RECORDING_MAX_SECONDS;
- const chunks: Blob[] = [];
- let recordedBytes = 0;
- let limitHit: "duration" | "size" | null = null;
- const stopAtLimit = (reason: "duration" | "size") => {
- if (limitHit) return;
- limitHit = reason;
- toast.warning(
- reason === "duration"
- ? `Recording stopped at the ${Math.floor(maxSeconds / 60)} minute limit.`
- : "Recording stopped: it reached the maximum upload size.",
+ }, []);
+
+ const renameSpeaker = useCallback(
+ (id: string, name: string) => {
+ const previous = speakerNames[id];
+ setSpeakerNames((current) => withName(current, id, name));
+ if (!transcriptRecord) return;
+ const version = transcriptVersion.current;
+ renameTranscriptSpeakers(transcriptRecord.id, {
+ [id]: name || null,
+ }).catch((error: unknown) => {
+ // Only this speaker, unless renamed since: a whole-map rollback erased saved renames.
+ if (transcriptVersion.current !== version) return;
+ setSpeakerNames((current) =>
+ (current[id] ?? "") === name ? withName(current, id, previous) : current,
);
- try {
- recorder.stop();
- } catch {
- }
- };
- const durationTimer = window.setTimeout(
- () => stopAtLimit("duration"),
- maxSeconds * 1000,
- );
- recorder.addEventListener("dataavailable", (event) => {
- if (event.data.size > 0) {
- if (recordedBytes + event.data.size > RECORDING_MAX_BYTES) {
- stopAtLimit("size");
- return;
- }
- chunks.push(event.data);
- recordedBytes += event.data.size;
- }
- });
- recorder.addEventListener("stop", () => {
- window.clearTimeout(durationTimer);
- const discard = discardRecordingRef.current;
- discardRecordingRef.current = false;
- setIsRecording(false);
- stopRecordStream();
- recorderRef.current = null;
- const blob = new Blob(chunks, {
- type: recorder.mimeType || "audio/webm",
- });
- if (!discard && blob.size > 0)
- void runTranscription(blob, "Recording", confirmedVersion);
+ toastFailure("Could not rename the speaker", error);
});
- recorderRef.current = recorder;
- // A timeslice makes the byte cap observable; without one some browsers emit only on stop.
- recorder.start(RECORDING_CHUNK_MS);
- setIsRecording(true);
- } catch {
- // Release the stream if MediaRecorder construction failed, or the mic stays live.
- recorderRef.current = null;
- setIsRecording(false);
- stopRecordStream();
- if (
- micStreamRequestIsCurrent(
- requestGeneration,
- micRequestGeneration.current,
- activeRef.current,
- )
- )
- toast.error("Could not access the microphone.");
- } finally {
- if (micPendingGeneration.current === requestGeneration) {
- micPendingGeneration.current = null;
- setMicRequestPending(false);
- }
- }
- }, [
- isRecording,
- runTranscription,
- stopRecordStream,
- prepareTranscriptionModel,
- confirmTranscriptReplacement,
- ]);
-
- // Release the microphone on unmount AND whenever the page goes inactive: the page stays mounted
- // across tab switches, so unmount alone left a hidden recorder capturing.
- useEffect(() => {
- if (!active) {
- stopAndDiscardRecording();
- }
- return stopAndDiscardRecording;
- }, [active, stopAndDiscardRecording]);
-
- useEffect(() => () => transcriptionAbort.current?.abort(), []);
-
- const handleTranscribeFile = useCallback(
- (file: File | undefined) => {
- if (!file) return;
- void runTranscription(file, file.name);
},
- [runTranscription],
+ [speakerNames, transcriptRecord],
);
const handleCopyTranscript = useCallback(() => {
@@ -415,14 +338,23 @@ export function useTranscription({
);
}, [transcript]);
- const handleDownloadTranscript = useCallback(async () => {
- const version = transcriptVersion.current;
- if (
- (await downloadTranscript(transcript, transcribedName ?? "transcript")) &&
- transcriptVersion.current === version
- )
- setTranscriptExported(true);
- }, [transcript, transcribedName]);
+ const handleDownloadTranscript = useCallback(
+ async (format: TranscriptExportFormat) => {
+ const version = transcriptVersion.current;
+ if (
+ (await downloadTranscript(format, {
+ title: transcribedName ?? "transcript",
+ text: transcript,
+ model: transcriptModel,
+ details: transcriptDetails,
+ names: speakerNames,
+ })) &&
+ transcriptVersion.current === version
+ )
+ setTranscriptExported(true);
+ },
+ [transcript, transcribedName, transcriptModel, transcriptDetails, speakerNames],
+ );
return {
transcript,
@@ -444,15 +376,14 @@ export function useTranscription({
transcriptionProgress,
transcriptError,
setTranscriptError,
- isRecording,
- micRequestPending,
- recordingSupported,
+ transcriptDetails,
+ speakerNames,
transcriptionAbort,
- stopAndDiscardRecording,
clearTranscript,
confirmTranscriptReplacement,
- handleRecordToggle,
- handleTranscribeFile,
+ runTranscription,
+ selectRecord,
+ renameSpeaker,
handleCopyTranscript,
handleDownloadTranscript,
};
diff --git a/studio/frontend/src/features/audio/pages/transcribe-page.tsx b/studio/frontend/src/features/audio/pages/transcribe-page.tsx
index db6ce1acd74..ef826a71b8e 100644
--- a/studio/frontend/src/features/audio/pages/transcribe-page.tsx
+++ b/studio/frontend/src/features/audio/pages/transcribe-page.tsx
@@ -3,102 +3,216 @@
import { Button } from "@/components/ui/button";
import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Progress } from "@/components/ui/progress";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { cn } from "@/lib/utils";
+import {
+ Copy01Icon,
Download01Icon,
- Mic01Icon,
StopIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { type Ref, useEffect, useState } from "react";
+import type { AudioGalleryClip } from "../api";
+import { RECORDING_MAX_SECONDS } from "../audio-workspace-constants";
+import { formatClipDuration } from "../audio-workspace-utils";
+import {
+ AudioHistoryProvider,
+ AudioSourceInput,
+ type AudioSourceInputHandle,
+} from "../components/audio-source-input";
import { Field } from "../components/field";
-import { TranscriptGallery } from "../transcript-gallery";
+import { TranscriptView } from "../components/transcript-view";
+import { TranscriptExportItems, TranscriptGallery } from "../transcript-gallery";
import { TranscriptionProgress } from "../transcription-progress";
import type { AudioHostState } from "../hooks/audio-host-state";
-import type { SttSidecar } from "../hooks/use-stt-sidecar";
+import type { AudioSourceStatus } from "../hooks/audio-source-state";
import type { Transcription } from "../hooks/use-transcription";
+import { useAudioTranscribeStore } from "../stores/audio-transcribe-store";
+import {
+ SPEAKERS_MODEL_NAME,
+ type TranscribeSwitch,
+ type TranscribeSwitches,
+} from "../transcribe-capabilities";
+import { transcribeLanguageFor } from "../transcribe-languages";
+import type { TranscriptExportFormat } from "../transcript-export";
+import { formatTimestamp } from "../transcript-model";
+import type { TranscriptProgress } from "../transcript-stream";
+import { GenerateActions, type GenerateBlocker } from "./tts-workspace";
-export function TranscribeRail({
- recordingSupported,
- isRecording,
- sttSelected,
- lastSttRepo,
- busy,
- micRequestPending,
- handleRecordToggle,
- handleTranscribeFile,
-}: Pick<
- Transcription,
- | "recordingSupported"
- | "isRecording"
- | "micRequestPending"
- | "handleRecordToggle"
- | "handleTranscribeFile"
-> &
- Pick<SttSidecar, "sttSelected" | "lastSttRepo"> &
- Pick<AudioHostState, "busy">) {
+// Radix Select cannot hold an empty value, so "detect" travels as this.
+const AUTO = "__auto__";
+
+function SwitchRow({
+ name,
+ label,
+ value,
+ disabled,
+ onUseSpeakersModel,
+}: {
+ name: "timestamps" | "speakers";
+ label: string;
+ value: TranscribeSwitch;
+ disabled: boolean;
+ onUseSpeakersModel?: () => void;
+}) {
+ const id = `transcribe-${name}`;
return (
- <>
- <Field
- label="Microphone"
- htmlFor="audio-record"
- hint={
- recordingSupported
- ? "Record a clip and it is transcribed when you stop."
- : "This browser cannot record. Open Unsloth over https or on localhost, or upload a file below."
- }
+ <div className="grid gap-1.5">
+ <label
+ htmlFor={id}
+ className="flex items-center justify-between gap-3 text-ui-13 font-medium text-foreground"
>
- <Button
- data-tour="audio-record"
- id="audio-record"
- variant={isRecording ? "destructive" : "secondary"}
- disabled={
- !recordingSupported ||
- (!isRecording && (!(sttSelected || lastSttRepo) || busy !== null)) ||
- micRequestPending
- }
- onClick={handleRecordToggle}
- >
- <HugeiconsIcon
- icon={isRecording ? StopIcon : Mic01Icon}
- className="mr-2 size-4"
+ {label}
+ {value.always ? (
+ <span
+ id={id}
+ className="text-ui-11p5 font-normal text-muted-foreground"
+ >
+ Always on
+ </span>
+ ) : (
+ <Switch
+ id={id}
+ checked={value.checked}
+ disabled={disabled || value.disabled}
+ onCheckedChange={(checked) =>
+ useAudioTranscribeStore.setState({ [name]: checked })
+ }
+ aria-describedby={`${id}-hint`}
/>
- {isRecording
- ? "Stop recording"
- : micRequestPending
- ? busy === "loading" ? "Loading model…" : "Waiting for microphone…"
- : "Record"}
- </Button>
- </Field>
- <Field
- label="Audio file"
- htmlFor="audio-file"
- hint="Or transcribe an existing recording (wav, mp3, m4a, webm…)."
+ )}
+ </label>
+ <p
+ id={`${id}-hint`}
+ className="text-ui-11p5 leading-snug text-muted-foreground"
>
- <input
- id="audio-file"
- type="file"
- accept="audio/*"
- disabled={
- !(sttSelected || lastSttRepo) ||
- busy !== null ||
- isRecording ||
- micRequestPending
+ {value.hint}
+ {value.suggestSpeakersModel && onUseSpeakersModel ? (
+ <GenerateActions
+ actions={[
+ {
+ label: `Use ${SPEAKERS_MODEL_NAME}`,
+ onClick: onUseSpeakersModel,
+ },
+ ]}
+ />
+ ) : null}
+ </p>
+ </div>
+ );
+}
+
+export function TranscribeRail({
+ historyClips,
+ disabled,
+ sourceHandle,
+ onSourceStatusChange,
+ switches,
+ languages,
+ onUseSpeakersModel,
+}: {
+ historyClips: readonly AudioGalleryClip[];
+ disabled: boolean;
+ sourceHandle: Ref<AudioSourceInputHandle>;
+ onSourceStatusChange: (status: AudioSourceStatus) => void;
+ switches: TranscribeSwitches;
+ languages: readonly { code: string; name: string }[];
+ onUseSpeakersModel?: () => void;
+}) {
+ const source = useAudioTranscribeStore((state) => state.source);
+ const language = useAudioTranscribeStore((state) => state.language);
+ // A saved language the model no longer lists falls back to Auto rather than vanishing.
+ const languageValue = transcribeLanguageFor(language, languages) || AUTO;
+ return (
+ <AudioHistoryProvider value={historyClips}>
+ <div data-tour="audio-record">
+ <AudioSourceInput
+ id="transcribe-source"
+ label="Audio"
+ hint="Up to 30 minutes. Drop a file, record, or reuse a clip."
+ value={source}
+ onChange={(next) => useAudioTranscribeStore.setState({ source: next })}
+ disabled={disabled}
+ handleRef={sourceHandle}
+ onStatusChange={onSourceStatusChange}
+ maxRecordSeconds={RECORDING_MAX_SECONDS}
+ expiredMessage="This upload expired. Add it again."
+ usesFirstSeconds={null}
+ recordHint="Record up to 30 minutes, then transcribe it."
+ />
+ </div>
+
+ {languages.length > 1 ? (
+ <Field
+ label="Language"
+ htmlFor="transcribe-language"
+ hint="Picking the spoken language helps with short or noisy clips."
+ >
+ <Select
+ value={languageValue}
+ onValueChange={(next) =>
+ useAudioTranscribeStore.setState({
+ language: next === AUTO ? "" : next,
+ })
+ }
+ disabled={disabled}
+ >
+ <SelectTrigger
+ id="transcribe-language"
+ size="sm"
+ className="w-full"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {languages.map((entry) => (
+ <SelectItem key={entry.code || AUTO} value={entry.code || AUTO}>
+ {entry.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ ) : null}
+
+ {(["timestamps", "speakers"] as const).map((name) => (
+ <SwitchRow
+ key={name}
+ name={name}
+ label={name === "timestamps" ? "Timestamps" : "Speakers"}
+ value={switches[name]}
+ disabled={disabled}
+ // One "Use" link when both switches would offer the same model.
+ onUseSpeakersModel={
+ name === "speakers" && switches.timestamps.suggestSpeakersModel
+ ? undefined
+ : onUseSpeakersModel
}
- onChange={(event) => {
- handleTranscribeFile(event.target.files?.[0]);
- event.target.value = "";
- }}
- className="text-ui-13 file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-ui-13 file:font-medium"
/>
- </Field>
- {sttSelected || lastSttRepo ? null : (
- <p className="text-ui-11p5 leading-snug text-muted-foreground">
- Pick a speech-to-text model (Whisper or Qwen3-ASR) from the
- selector above to transcribe.
- </p>
- )}
- </>
+ ))}
+ </AudioHistoryProvider>
);
}
+const FORMAT_LABELS: Record<TranscriptExportFormat, string> = {
+ txt: "Text (.txt)",
+ srt: "Subtitles (.srt)",
+ vtt: "Web subtitles (.vtt)",
+ json: "JSON with timings (.json)",
+};
+
export function TranscribeOutput({
transcriptionStartedAt,
transcriptionFinishedAt,
@@ -118,15 +232,11 @@ export function TranscribeOutput({
active,
mode,
confirmTranscriptReplacement,
- transcriptVersion,
- setTranscript,
- setTranscribedName,
- setTranscriptModel,
- setTranscriptRecord,
- setTranscriptError,
- setTranscriptExported,
- setTranscriptionStartedAt,
clearTranscript,
+ transcriptDetails,
+ speakerNames,
+ renameSpeaker,
+ selectRecord,
}: Pick<
Transcription,
| "transcriptionStartedAt"
@@ -144,17 +254,15 @@ export function TranscribeOutput({
| "transcriptExported"
| "transcriptError"
| "confirmTranscriptReplacement"
- | "transcriptVersion"
- | "setTranscript"
- | "setTranscribedName"
- | "setTranscriptModel"
- | "setTranscriptRecord"
- | "setTranscriptError"
- | "setTranscriptExported"
- | "setTranscriptionStartedAt"
| "clearTranscript"
+ | "transcriptDetails"
+ | "speakerNames"
+ | "renameSpeaker"
+ | "selectRecord"
> &
Pick<AudioHostState, "busy" | "active" | "mode">) {
+ const language = transcriptDetails.language ?? transcriptRecord?.language;
+ const duration = transcriptDetails.duration ?? transcriptRecord?.duration;
return (
<>
<div className="hover-scrollbar flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">
@@ -171,36 +279,75 @@ export function TranscribeOutput({
/>
)}
{transcript ? (
- <>
- <div className="flex items-center gap-2">
- <Button
- variant="secondary"
- size="sm"
- onClick={handleCopyTranscript}
- >
- Copy
- </Button>
- <Button
- variant="secondary"
- size="sm"
- onClick={handleDownloadTranscript}
- >
- <HugeiconsIcon icon={Download01Icon} className="mr-2 size-3.5" />
- Download .txt
- </Button>
- </div>
- <div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">
- <span className="truncate">{transcribedName}</span>
- <span>·</span>
- <span className="truncate">{transcriptModel}</span>
- {!transcriptRecord && !transcriptExported && (
- <span>· Not saved</span>
- )}
- </div>
- <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground">
- {transcript}
- </p>
- </>
+ // Focused and announced by the host after a run.
+ <section
+ id="transcribe-result"
+ tabIndex={-1}
+ aria-label="Transcript"
+ aria-busy={busy === "loading" ? true : undefined}
+ className={cn(
+ "flex flex-col gap-3 transition-opacity duration-150 focus-visible:outline-none motion-reduce:transition-none",
+ busy === "loading" && "opacity-50",
+ )}
+ >
+ <TranscriptView
+ text={transcript}
+ details={transcriptDetails}
+ names={speakerNames}
+ onRename={renameSpeaker}
+ durationS={duration ?? null}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={handleCopyTranscript}
+ >
+ <HugeiconsIcon icon={Copy01Icon} className="mr-2 size-3.5" />
+ Copy
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button variant="secondary" size="sm">
+ <HugeiconsIcon
+ icon={Download01Icon}
+ className="mr-2 size-3.5"
+ />
+ Download
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <TranscriptExportItems
+ timed={transcriptDetails.segments.length > 0}
+ label={(format) => <span>{FORMAT_LABELS[format]}</span>}
+ onExport={(format) =>
+ void handleDownloadTranscript(format)
+ }
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 text-ui-11p5 text-muted-foreground">
+ <span className="min-w-0 truncate">{transcribedName}</span>
+ <span>·</span>
+ <span className="min-w-0 truncate" title={transcriptModel}>
+ {transcriptModel.split("/").pop() || transcriptModel}
+ </span>
+ {language ? <span>· {language}</span> : null}
+ {duration ? (
+ <span>
+ ·{" "}
+ <span className="font-mono tabular-nums">
+ {formatTimestamp(duration)}
+ </span>
+ </span>
+ ) : null}
+ {!transcriptRecord && !transcriptExported && (
+ <span>· Not saved</span>
+ )}
+ </div>
+ </TranscriptView>
+ </section>
) : transcriptError ? (
<div className="flex flex-col gap-1" role="alert">
<p className="text-ui-13 font-medium text-destructive">
@@ -222,16 +369,7 @@ export function TranscribeOutput({
currentId={transcriptRecord?.id ?? null}
latest={transcriptRecord}
canSelect={confirmTranscriptReplacement}
- onSelect={(record) => {
- transcriptVersion.current += 1;
- setTranscript(record.text);
- setTranscribedName(record.title);
- setTranscriptModel(record.model);
- setTranscriptRecord(record);
- setTranscriptError(null);
- setTranscriptExported(false);
- setTranscriptionStartedAt(null);
- }}
+ onSelect={selectRecord}
onDelete={(ids) => {
if (
transcriptRecord &&
@@ -246,3 +384,108 @@ export function TranscribeOutput({
</>
);
}
+
+export function TranscribeFooter({
+ busy,
+ blocker,
+ notice,
+ shortcutLabel,
+ stopping,
+ onTranscribe,
+ onStop,
+ modelName,
+ progress,
+}: Pick<AudioHostState, "busy"> & {
+ blocker: GenerateBlocker | null;
+ notice: string | null;
+ shortcutLabel: string;
+ stopping: boolean;
+ onTranscribe: () => void;
+ onStop: () => void;
+ modelName: string;
+ progress: TranscriptProgress | null;
+}) {
+ const running = busy === "transcribing";
+ const working = running || busy === "loading";
+ const [startedAt, setStartedAt] = useState<number | null>(null);
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!working) {
+ setStartedAt(null);
+ return;
+ }
+ setStartedAt((value) => value ?? Date.now());
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [working]);
+ const elapsed =
+ startedAt === null ? 0 : Math.max(0, Math.floor((now - startedAt) / 1000));
+ const status =
+ busy === "loading" || progress?.phase === "loading"
+ ? `Loading ${modelName || "the model"}…`
+ : progress?.phase === "downloading_aligner"
+ ? "Downloading the timing aligner…"
+ : stopping
+ ? "Stopping…"
+ : "Transcribing…";
+ return (
+ <div className="flex w-full max-w-sm flex-col gap-2">
+ {working ? (
+ <>
+ <output
+ aria-live="polite"
+ aria-atomic="true"
+ className="text-center text-ui-12 text-muted-foreground"
+ >
+ {status}
+ <span className="ml-1.5 font-mono tabular-nums">
+ {formatClipDuration(elapsed)}
+ </span>
+ </output>
+ <Progress
+ indeterminate
+ aria-label="Transcription in progress"
+ className="h-1.5"
+ />
+ </>
+ ) : null}
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ <Button
+ className="relative z-10 mx-auto h-11 px-8 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"
+ onClick={running ? onStop : onTranscribe}
+ disabled={running ? stopping : busy !== null || blocker !== null}
+ variant={running ? "destructive" : "default"}
+ aria-describedby={
+ blocker
+ ? "transcribe-blocker"
+ : notice
+ ? "transcribe-notice"
+ : undefined
+ }
+ aria-keyshortcuts="Control+Enter Meta+Enter"
+ title={running ? undefined : `Transcribe (${shortcutLabel})`}
+ >
+ {running ? (
+ <>
+ <HugeiconsIcon icon={StopIcon} className="mr-2 size-4" />
+ {stopping ? "Stopping…" : "Stop"}
+ </>
+ ) : busy === "loading" ? (
+ "Loading model…"
+ ) : (
+ "Transcribe"
+ )}
+ </Button>
+ </div>
+ {(blocker || notice) && !running ? (
+ <p
+ id={blocker ? "transcribe-blocker" : "transcribe-notice"}
+ className="text-center text-ui-11p5 leading-snug text-muted-foreground"
+ >
+ {blocker ? blocker.reason : notice}
+ <GenerateActions actions={blocker?.actions} />
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/audio/pages/tts-workspace.tsx b/studio/frontend/src/features/audio/pages/tts-workspace.tsx
index 3a2970cf5ba..7134ae4e10a 100644
--- a/studio/frontend/src/features/audio/pages/tts-workspace.tsx
+++ b/studio/frontend/src/features/audio/pages/tts-workspace.tsx
@@ -59,7 +59,7 @@ export interface GenerateBlocker {
actions?: GenerateAction[];
}
-function GenerateActions({ actions }: { actions?: GenerateAction[] }) {
+export function GenerateActions({ actions }: { actions?: GenerateAction[] }) {
if (!actions?.length) return null;
return (
<>
@@ -87,7 +87,6 @@ export function TtsRailFields({
toolPanels,
audioDevice,
busy,
- isRecording,
status,
setAudioDeviceState,
ttsLoaded,
@@ -140,7 +139,6 @@ export function TtsRailFields({
Pick<AudioModelSlot, "handleEject"> & {
musicGeneration: boolean;
toolPanels: ReactNode;
- isRecording: boolean;
setAudioDeviceState: (next: string) => void;
advancedOpen: boolean;
inputs?: ReactNode;
@@ -160,7 +158,7 @@ export function TtsRailFields({
<PillTabs
ariaLabel="Load model into"
value={audioDevice === "cpu" ? "cpu" : "auto"}
- disabled={busy !== null || isRecording}
+ disabled={busy !== null}
onValueChange={(value) => {
const next = value === "cpu" ? "cpu" : "auto";
if (next === audioDevice) return;
diff --git a/studio/frontend/src/features/audio/stores/audio-transcribe-store.ts b/studio/frontend/src/features/audio/stores/audio-transcribe-store.ts
new file mode 100644
index 00000000000..d6241d34e55
--- /dev/null
+++ b/studio/frontend/src/features/audio/stores/audio-transcribe-store.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { create } from "zustand";
+import { persist } from "zustand/middleware";
+import type { AudioSourceSelection } from "../audio-run-request";
+
+export const AUDIO_TRANSCRIBE_STORAGE_KEY = "unsloth_audio_transcribe_v1";
+
+export type TranscriptView = "text" | "segments";
+
+interface AudioTranscribeState {
+ source: AudioSourceSelection | null;
+ /** Empty means Auto. */
+ language: string;
+ timestamps: boolean;
+ speakers: boolean;
+ view: TranscriptView;
+}
+
+export const useAudioTranscribeStore = create<AudioTranscribeState>()(
+ persist(
+ (): AudioTranscribeState => ({
+ source: null,
+ language: "",
+ timestamps: false,
+ speakers: true,
+ view: "text",
+ }),
+ { name: AUDIO_TRANSCRIBE_STORAGE_KEY, version: 1 },
+ ),
+);
diff --git a/studio/frontend/src/features/audio/transcribe-api.ts b/studio/frontend/src/features/audio/transcribe-api.ts
new file mode 100644
index 00000000000..8fe0c8a8d79
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcribe-api.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+import { AudioApiError } from "./api";
+import type { AudioSourceRef } from "./audio-run-request";
+import type { SttCapabilities } from "./transcribe-capabilities";
+import {
+ type TranscriptProgress,
+ type TranscriptRecord,
+ type TranscriptResult,
+ readTranscriptStream,
+} from "./transcript-stream";
+
+const JSON_HEADERS = { "Content-Type": "application/json" };
+
+async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
+ const response = await authFetch(url, init);
+ if (!response.ok) throw new Error(await readFastApiError(response));
+ return (await response.json()) as T;
+}
+
+const transcriptUrl = (id: string) =>
+ `/api/inference/audio/transcripts/${encodeURIComponent(id)}`;
+
+export async function transcribeSourceWithProgress(
+ ref: AudioSourceRef,
+ title: string,
+ options: {
+ model: string;
+ engine: string;
+ device: string;
+ language: string;
+ timestamps: boolean;
+ speakers: boolean;
+ signal: AbortSignal;
+ },
+ onProgress: (progress: TranscriptProgress) => void,
+): Promise<TranscriptResult> {
+ const response = await authFetch("/api/inference/audio/transcribe/source", {
+ method: "POST",
+ headers: JSON_HEADERS,
+ body: JSON.stringify({
+ source: ref,
+ model: options.model,
+ engine: options.engine || null,
+ device: options.device || null,
+ language: options.language || null,
+ timestamps: options.timestamps,
+ speakers: options.speakers,
+ title: title.slice(0, 255),
+ }),
+ signal: options.signal,
+ });
+ // The status matters: a 404 means the upload expired, and the card says so.
+ if (!response.ok)
+ throw new AudioApiError(await readFastApiError(response), response.status);
+ if (!response.body) throw new Error("The transcription response was empty.");
+ return readTranscriptStream(response.body, onProgress);
+}
+
+export function fetchSttCapabilities(
+ model: string,
+ engine: string | null,
+ signal?: AbortSignal,
+): Promise<SttCapabilities> {
+ const params = new URLSearchParams({ model });
+ if (engine) params.set("engine", engine);
+ return fetchJson(`/api/inference/audio/stt/capabilities?${params}`, {
+ signal,
+ });
+}
+
+export function getTranscript(
+ id: string,
+ signal?: AbortSignal,
+): Promise<TranscriptRecord> {
+ return fetchJson(transcriptUrl(id), { signal });
+}
+
+/** null clears a name back to "Speaker N". */
+export function renameTranscriptSpeakers(
+ id: string,
+ names: Record<string, string | null>,
+): Promise<TranscriptRecord> {
+ return fetchJson(transcriptUrl(id), {
+ method: "PATCH",
+ headers: JSON_HEADERS,
+ body: JSON.stringify({ speaker_names: names }),
+ });
+}
diff --git a/studio/frontend/src/features/audio/transcribe-capabilities.ts b/studio/frontend/src/features/audio/transcribe-capabilities.ts
new file mode 100644
index 00000000000..e7c24a19b5b
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcribe-capabilities.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Import-free so node tests can load it.
+
+export interface SttCapabilities {
+ engine: string | null;
+ family: string | null;
+ /** on_request: only when asked (Qwen3-ASR with its aligner); always: every run has them. */
+ timestamps: "on_request" | "always" | "unsupported";
+ speakers: boolean;
+ aligner: { downloaded: boolean; size_bytes: number } | null;
+ cpu_only: boolean;
+}
+
+export interface TranscribeSwitch {
+ checked: boolean;
+ disabled: boolean;
+ hint: string;
+ suggestSpeakersModel?: boolean;
+ always?: boolean;
+}
+
+export interface TranscribeSwitches {
+ timestamps: TranscribeSwitch;
+ speakers: TranscribeSwitch;
+ notice: string | null;
+ request: { timestamps: boolean; speakers: boolean };
+}
+
+export const SPEAKERS_MODEL_NAME = "MOSS-Transcribe-Diarize";
+
+function formatSize(bytes: number): string {
+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
+ return `${Math.max(1, Math.round(bytes / 1e6))} MB`;
+}
+
+export function transcribeSwitches(
+ caps: SttCapabilities | null,
+ prefs: { timestamps: boolean; speakers: boolean },
+ state: { loading: boolean; hasModel: boolean },
+): TranscribeSwitches {
+ if (!caps) {
+ const hint = state.loading
+ ? "Checking what this model supports…"
+ : state.hasModel
+ ? "Could not check what this model supports. Transcribing still works."
+ : "Pick a speech-to-text model to see what it can add.";
+ const off = { checked: false, disabled: true, hint };
+ return {
+ timestamps: off,
+ speakers: off,
+ notice: null,
+ request: { timestamps: false, speakers: false },
+ };
+ }
+
+ const onRequest = caps.timestamps === "on_request";
+ const size =
+ onRequest && caps.aligner && !caps.aligner.downloaded
+ ? formatSize(caps.aligner.size_bytes)
+ : null;
+ const timestamps: TranscribeSwitch =
+ caps.timestamps === "always"
+ ? {
+ checked: true,
+ disabled: true,
+ always: true,
+ hint: "This model always adds timestamps.",
+ }
+ : onRequest
+ ? {
+ checked: prefs.timestamps,
+ disabled: false,
+ hint: `Adds the time of each line, using a separate timing aligner.${size ? ` The first run downloads it (${size}).` : ""}`,
+ }
+ : {
+ checked: false,
+ disabled: true,
+ hint: `This model returns plain text. Timestamps need Qwen3-ASR (audio.cpp), Parakeet-TDT, ${SPEAKERS_MODEL_NAME} or VibeVoice-ASR.`,
+ suggestSpeakersModel: true,
+ };
+ const speakers: TranscribeSwitch = caps.speakers
+ ? {
+ checked: prefs.speakers,
+ disabled: false,
+ hint: "Labels who is speaking. You can rename speakers afterwards.",
+ }
+ : {
+ checked: false,
+ disabled: true,
+ hint: `Only ${SPEAKERS_MODEL_NAME} and VibeVoice-ASR can tell speakers apart.`,
+ suggestSpeakersModel: true,
+ };
+ const request = {
+ timestamps: onRequest && prefs.timestamps,
+ speakers: speakers.checked,
+ };
+ const aligner = !request.timestamps
+ ? null
+ : size
+ ? `Downloads the timing aligner (${size}) and reloads the model.`
+ : "Reloads the model with its timing aligner if it is not loaded yet.";
+ const notice = !caps.cpu_only
+ ? aligner
+ : aligner
+ ? `${aligner} Runs on the CPU.`
+ : "This model runs on the CPU.";
+ return { timestamps, speakers, notice, request };
+}
diff --git a/studio/frontend/src/features/audio/transcribe-languages.ts b/studio/frontend/src/features/audio/transcribe-languages.ts
new file mode 100644
index 00000000000..18eef1e4bda
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcribe-languages.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// ISO codes, unlike the name-keyed TTS LanguageSelect; "" means the model detects it.
+
+const NAMES = new Intl.DisplayNames(["en"], { type: "language" });
+
+export const TRANSCRIBE_LANGUAGES: readonly { code: string; name: string }[] = [
+ { code: "", name: "Detect automatically" },
+ ...(
+ "en zh es fr de it pt ru ja ko ar hi nl pl tr uk vi id th sv da fi no cs " +
+ "el he hu ro ms yue"
+ )
+ .split(" ")
+ .map((code) => ({ code, name: NAMES.of(code) ?? code })),
+];
+
+/** The saved language if the model lists it, else "" (detect), never one hidden behind Auto. */
+export function transcribeLanguageFor(
+ saved: string,
+ languages: readonly { code: string }[],
+): string {
+ return saved && languages.some((entry) => entry.code === saved) ? saved : "";
+}
+
+export function transcribeLanguagesFor(
+ modelLanguages: readonly string[] | null | undefined,
+): readonly { code: string; name: string }[] {
+ if (!modelLanguages || modelLanguages.length === 0)
+ return TRANSCRIBE_LANGUAGES;
+ return TRANSCRIBE_LANGUAGES.filter(
+ (language) =>
+ language.code === "" || modelLanguages.includes(language.code),
+ );
+}
diff --git a/studio/frontend/src/features/audio/transcript-download.ts b/studio/frontend/src/features/audio/transcript-download.ts
index 0672fca8f89..e98794f32a0 100644
--- a/studio/frontend/src/features/audio/transcript-download.ts
+++ b/studio/frontend/src/features/audio/transcript-download.ts
@@ -3,22 +3,20 @@
import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
+import {
+ type TranscriptExport,
+ type TranscriptExportFormat,
+ exportFileName,
+ exportTranscript,
+} from "./transcript-export";
export async function downloadTranscript(
- text: string,
- title: string,
+ format: TranscriptExportFormat,
+ input: TranscriptExport,
): Promise<boolean> {
+ const { content: text, mime } = exportTranscript(format, input);
try {
- await downloadFile(
- text,
- `${
- title
- .replace(/\.[^.]+$/, "")
- .replace(/[<>:"/\\|?*]/g, "_")
- .replace(/\p{Cc}/gu, "_") || "transcript"
- }.txt`,
- "text/plain;charset=utf-8",
- );
+ await downloadFile(text, exportFileName(input.title, format), mime);
return true;
} catch (error) {
if (!isDownloadCancelled(error))
diff --git a/studio/frontend/src/features/audio/transcript-draft.ts b/studio/frontend/src/features/audio/transcript-draft.ts
index 3bbd43408b3..64858585628 100644
--- a/studio/frontend/src/features/audio/transcript-draft.ts
+++ b/studio/frontend/src/features/audio/transcript-draft.ts
@@ -2,11 +2,34 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { accountDatabaseName } from "../../lib/account-transition.ts";
+import {
+ type TranscriptDetails,
+ detailsFrom,
+ sanitizeSpeakerName,
+} from "./transcript-model.ts";
export interface TranscriptDraft {
text: string;
title: string;
model: string;
+ /** Absent on drafts written before timestamps existed. */
+ details?: TranscriptDetails;
+ speakerNames?: Record<string, string>;
+}
+
+function speakerNamesFrom(
+ value: unknown,
+ details: TranscriptDetails,
+): Record<string, string> {
+ const names: Record<string, string> = {};
+ if (!value || typeof value !== "object" || Array.isArray(value)) return names;
+ for (const [id, name] of Object.entries(value)) {
+ if (typeof name !== "string") continue;
+ if (!details.speakers.some((speaker) => speaker.id === id)) continue;
+ const clean = sanitizeSpeakerName(name);
+ if (clean) names[id] = clean;
+ }
+ return names;
}
export function transcriptDraftKey(): string {
@@ -25,7 +48,17 @@ export function readTranscriptDraft(key: string): TranscriptDraft | null {
) {
return null;
}
- return { text: draft.text, title: draft.title, model: draft.model };
+ const restored: TranscriptDraft = {
+ text: draft.text,
+ title: draft.title,
+ model: draft.model,
+ };
+ if (draft.details && typeof draft.details === "object") {
+ const details = detailsFrom(draft.details);
+ restored.details = details;
+ restored.speakerNames = speakerNamesFrom(draft.speakerNames, details);
+ }
+ return restored;
} catch {
return null;
}
diff --git a/studio/frontend/src/features/audio/transcript-export.ts b/studio/frontend/src/features/audio/transcript-export.ts
new file mode 100644
index 00000000000..452ed67c65e
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcript-export.ts
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ type TranscriptDetails,
+ type TranscriptSegment,
+ hasSpeakers,
+ paragraphs,
+ speakerLabel,
+} from "./transcript-model.ts";
+
+export type TranscriptExportFormat = "txt" | "srt" | "vtt" | "json";
+
+export interface TranscriptExport {
+ title: string;
+ text: string;
+ model: string;
+ details: TranscriptDetails;
+ names: Readonly<Record<string, string>>;
+}
+
+function nameOf(input: TranscriptExport, id: string): string {
+ return speakerLabel(id, input.details.speakers, input.names);
+}
+
+// A blank line would end the cue early.
+function cueText(text: string): string {
+ return text
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .join("\n");
+}
+
+function clock(seconds: number, separator: "," | "."): string {
+ const total = Math.max(
+ 0,
+ Math.round((Number.isFinite(seconds) ? seconds : 0) * 1000),
+ );
+ const millis = total % 1000;
+ const whole = Math.floor(total / 1000);
+ const pad = (value: number, width = 2) => String(value).padStart(width, "0");
+ return `${pad(Math.floor(whole / 3600))}:${pad(Math.floor((whole % 3600) / 60))}:${pad(whole % 60)}${separator}${pad(millis, 3)}`;
+}
+
+function cues(input: TranscriptExport) {
+ const { segments, duration } = input.details;
+ const timed: TranscriptSegment[] =
+ segments.length > 0
+ ? segments
+ : input.text.trim()
+ ? [{ start: 0, end: duration ?? 0, text: input.text }]
+ : [];
+ const on = hasSpeakers(input.details);
+ return timed
+ .map((segment) => ({
+ segment,
+ text: cueText(segment.text),
+ name: on && segment.speaker ? nameOf(input, segment.speaker) : null,
+ }))
+ .filter(({ text }) => text);
+}
+
+export function toTxt(input: TranscriptExport): string {
+ if (!hasSpeakers(input.details)) return input.text;
+ const blocks = paragraphs(input.details.segments).map(({ speaker, text }) =>
+ speaker ? `${nameOf(input, speaker)}: ${text}` : text,
+ );
+ return `${blocks.join("\n\n")}\n`;
+}
+
+export function toSrt(input: TranscriptExport): string {
+ const blocks = cues(input).map(
+ ({ segment, text, name }, index) =>
+ `${index + 1}\n${clock(segment.start, ",")} --> ${clock(segment.end, ",")}\n${name === null ? "" : `${name}: `}${text}`,
+ );
+ return blocks.length > 0 ? `${blocks.join("\n\n")}\n` : "";
+}
+
+function escapeVtt(text: string): string {
+ return text
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;");
+}
+
+export function toVtt(input: TranscriptExport): string {
+ const blocks = cues(input).map(
+ ({ segment, text, name }) =>
+ `${clock(segment.start, ".")} --> ${clock(segment.end, ".")}\n${name === null ? "" : `<v ${escapeVtt(name)}>`}${escapeVtt(text)}`,
+ );
+ return `${["WEBVTT", ...blocks].join("\n\n")}\n`;
+}
+
+export function toJson(input: TranscriptExport): string {
+ const { details } = input;
+ return `${JSON.stringify(
+ {
+ title: input.title,
+ model: input.model,
+ language: details.language,
+ duration: details.duration,
+ text: input.text,
+ segments: details.segments,
+ ...(details.words.length > 0 ? { words: details.words } : {}),
+ speakers: details.speakers.map((speaker) => ({
+ id: speaker.id,
+ label: speaker.label,
+ name: input.names[speaker.id]?.trim() || null,
+ })),
+ },
+ null,
+ 2,
+ )}\n`;
+}
+
+export function exportFileName(title: string, ext: string): string {
+ const base =
+ title
+ .replace(/\.[^.]+$/, "")
+ .replace(/[<>:"/\\|?*]/g, "_")
+ .replace(/\p{Cc}/gu, "_") || "transcript";
+ return `${base}.${ext}`;
+}
+
+const FORMATS: Record<
+ TranscriptExportFormat,
+ { mime: string; write: (input: TranscriptExport) => string }
+> = {
+ txt: { mime: "text/plain;charset=utf-8", write: toTxt },
+ srt: { mime: "application/x-subrip;charset=utf-8", write: toSrt },
+ vtt: { mime: "text/vtt;charset=utf-8", write: toVtt },
+ json: { mime: "application/json;charset=utf-8", write: toJson },
+};
+
+export const TRANSCRIPT_EXPORT_FORMATS = Object.keys(
+ FORMATS,
+) as TranscriptExportFormat[];
+
+export function exportTranscript(
+ format: TranscriptExportFormat,
+ input: TranscriptExport,
+): { content: string; mime: string } {
+ return { content: FORMATS[format].write(input), mime: FORMATS[format].mime };
+}
diff --git a/studio/frontend/src/features/audio/transcript-gallery.tsx b/studio/frontend/src/features/audio/transcript-gallery.tsx
index 4706d6cf292..c69c5e30fcf 100644
--- a/studio/frontend/src/features/audio/transcript-gallery.tsx
+++ b/studio/frontend/src/features/audio/transcript-gallery.tsx
@@ -7,6 +7,7 @@ import {
useLayoutEffect,
useRef,
useState,
+ type ReactNode,
} from "react";
import { HugeiconsIcon } from "@hugeicons/react";
import {
@@ -29,8 +30,74 @@ import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { archiveTranscript, deleteTranscript, listTranscripts } from "./api";
+import { getTranscript } from "./transcribe-api";
+import {
+ TRANSCRIPT_EXPORT_FORMATS,
+ type TranscriptExportFormat,
+} from "./transcript-export";
+import { detailsFrom, formatTimestamp } from "./transcript-model";
import type { TranscriptRecord } from "./transcript-stream";
+export function TranscriptExportItems({
+ timed,
+ label,
+ onExport,
+}: {
+ timed: boolean;
+ label: (format: TranscriptExportFormat) => ReactNode;
+ onExport: (format: TranscriptExportFormat) => void;
+}) {
+ return TRANSCRIPT_EXPORT_FORMATS.map((format) => {
+ const blocked = !timed && (format === "srt" || format === "vtt");
+ return (
+ <DropdownMenuItem
+ key={format}
+ disabled={blocked}
+ onClick={() => onExport(format)}
+ >
+ {label(format)}
+ {blocked ? (
+ <span className="ml-auto pl-3 text-ui-11p5 text-muted-foreground">
+ Needs timestamps
+ </span>
+ ) : null}
+ </DropdownMenuItem>
+ );
+ });
+}
+
+// The list carries counts only, so timed formats fetch the full record.
+async function downloadRecord(
+ record: TranscriptRecord,
+ format: TranscriptExportFormat,
+): Promise<void> {
+ let full = record;
+ if ((record.segment_count ?? 0) > 0) {
+ try {
+ full = await getTranscript(record.id);
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Could not load transcript.",
+ );
+ return;
+ }
+ }
+ await downloadTranscript(format, {
+ title: full.title,
+ text: full.text,
+ model: full.model,
+ details: detailsFrom(full),
+ names: full.speaker_names ?? {},
+ });
+}
+
+function recordBadge(record: TranscriptRecord): string | null {
+ const speakers = record.speakers?.length ?? 0;
+ if (speakers > 0)
+ return speakers === 1 ? "1 speaker" : `${speakers} speakers`;
+ return (record.segment_count ?? 0) > 0 ? "Timestamps" : null;
+}
+
export function TranscriptGallery({
active,
currentId,
@@ -97,6 +164,7 @@ export function TranscriptGallery({
useLayoutEffect(() => {
refreshRef.current = refresh;
}, [refresh]);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `latest` is the trigger; a newly saved transcript refetches the list.
useEffect(() => {
if (active) void refresh();
return () => {
@@ -212,6 +280,16 @@ export function TranscriptGallery({
}}
>
<span className="min-w-0 flex-1 truncate">{record.title}</span>
+ {recordBadge(record) ? (
+ <span className="shrink-0 rounded-4xl bg-muted px-1.5 text-ui-11 text-muted-foreground">
+ {recordBadge(record)}
+ </span>
+ ) : null}
+ {record.duration ? (
+ <span className="shrink-0 font-mono text-ui-11p5 tabular-nums text-muted-foreground">
+ {formatTimestamp(record.duration)}
+ </span>
+ ) : null}
<span className="shrink-0 text-ui-11p5 text-muted-foreground">
{new Date(record.created_at).toLocaleDateString()}
</span>
@@ -228,14 +306,16 @@ export function TranscriptGallery({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() =>
- void downloadTranscript(record.text, record.title)
- }
- >
- <HugeiconsIcon icon={Download01Icon} />
- Download .txt
- </DropdownMenuItem>
+ <TranscriptExportItems
+ timed={(record.segment_count ?? 0) > 0}
+ label={(format) => (
+ <>
+ <HugeiconsIcon icon={Download01Icon} />
+ Download .{format}
+ </>
+ )}
+ onExport={(format) => void downloadRecord(record, format)}
+ />
<DropdownMenuItem
onClick={() =>
void copyToClipboard(record.text).then((ok) =>
diff --git a/studio/frontend/src/features/audio/transcript-model.ts b/studio/frontend/src/features/audio/transcript-model.ts
new file mode 100644
index 00000000000..ff026ef0580
--- /dev/null
+++ b/studio/frontend/src/features/audio/transcript-model.ts
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// No imports, so node tests can load this file directly.
+
+export interface TranscriptSegment {
+ start: number;
+ end: number;
+ text: string;
+ speaker?: string;
+}
+
+export interface TranscriptWord {
+ start: number;
+ end: number;
+ word: string;
+}
+
+export interface TranscriptSpeaker {
+ id: string;
+ label: string;
+}
+
+export interface TranscriptSource {
+ kind: "input" | "clip" | "voice";
+ id: string;
+ name: string;
+}
+
+export interface TranscriptDetails {
+ segments: TranscriptSegment[];
+ words: TranscriptWord[];
+ speakers: TranscriptSpeaker[];
+ source: TranscriptSource | null;
+ language: string | null;
+ duration: number | null;
+}
+
+export const EMPTY_TRANSCRIPT_DETAILS = detailsFrom({});
+
+export const SPEAKER_NAME_MAX_LENGTH = 40;
+
+/** In a gap the previous segment stays current. */
+export function activeSegmentIndex(
+ seconds: number,
+ segments: readonly TranscriptSegment[],
+): number {
+ if (segments.length === 0 || !(seconds >= segments[0].start)) return -1;
+ let low = 0;
+ let high = segments.length - 1;
+ while (low < high) {
+ const middle = (low + high + 1) >> 1;
+ if (segments[middle].start <= seconds) low = middle;
+ else high = middle - 1;
+ }
+ return low;
+}
+
+export function speakerLabel(
+ id: string,
+ speakers: readonly TranscriptSpeaker[],
+ names: Readonly<Record<string, string>>,
+): string {
+ const named = names[id]?.trim();
+ if (named) return named;
+ return speakers.find((speaker) => speaker.id === id)?.label ?? id;
+}
+
+export function hasSpeakers({
+ speakers,
+ segments,
+}: TranscriptDetails): boolean {
+ return (
+ speakers.length > 0 && segments.some((segment) => Boolean(segment.speaker))
+ );
+}
+
+export function paragraphs(
+ segments: readonly TranscriptSegment[],
+): { speaker?: string; text: string }[] {
+ const result: { speaker?: string; text: string }[] = [];
+ for (const { speaker, text: raw } of segments) {
+ const text = raw.trim();
+ if (!text) continue;
+ const last = result[result.length - 1];
+ if (last && last.speaker === speaker) last.text += ` ${text}`;
+ else result.push({ speaker, text });
+ }
+ return result;
+}
+
+export function formatTimestamp(seconds: number): string {
+ const total = Math.max(0, Math.floor(Number.isFinite(seconds) ? seconds : 0));
+ const hours = Math.floor(total / 3600);
+ const minutes = Math.floor((total % 3600) / 60);
+ const secs = String(total % 60).padStart(2, "0");
+ return hours > 0
+ ? `${hours}:${String(minutes).padStart(2, "0")}:${secs}`
+ : `${minutes}:${secs}`;
+}
+
+export function sanitizeSpeakerName(name: string): string {
+ return name.replace(/\s+/g, " ").trim().slice(0, SPEAKER_NAME_MAX_LENGTH);
+}
+
+function finiteSeconds(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
+ ? value
+ : null;
+}
+
+export function detailsFrom(
+ value: Partial<Record<keyof TranscriptDetails, unknown>>,
+): TranscriptDetails {
+ const segments: TranscriptSegment[] = [];
+ const words: TranscriptWord[] = [];
+ for (const [list, key] of [
+ [value.segments, "text"],
+ [value.words, "word"],
+ ] as const) {
+ if (!Array.isArray(list)) continue;
+ for (const item of list) {
+ if (!item || typeof item !== "object") continue;
+ const start = finiteSeconds(item.start);
+ const end = finiteSeconds(item.end);
+ if (start === null || end === null || end < start) continue;
+ if (typeof item[key] !== "string") continue;
+ if (key === "word") words.push({ start, end, word: item.word });
+ else if (typeof item.speaker === "string" && item.speaker)
+ segments.push({ start, end, text: item.text, speaker: item.speaker });
+ else segments.push({ start, end, text: item.text });
+ }
+ }
+ const speakers: TranscriptSpeaker[] = (
+ Array.isArray(value.speakers) ? value.speakers : []
+ )
+ .filter(
+ (item) => typeof item?.id === "string" && typeof item.label === "string",
+ )
+ .map(({ id, label }) => ({ id, label }));
+ const raw = value.source as Partial<Record<string, unknown>> | null;
+ const source: TranscriptSource | null =
+ raw &&
+ typeof raw === "object" &&
+ (raw.kind === "input" || raw.kind === "clip" || raw.kind === "voice") &&
+ typeof raw.id === "string" &&
+ typeof raw.name === "string"
+ ? { kind: raw.kind, id: raw.id, name: raw.name }
+ : null;
+ return {
+ segments,
+ words,
+ speakers,
+ source,
+ language: typeof value.language === "string" ? value.language : null,
+ duration: finiteSeconds(value.duration),
+ };
+}
diff --git a/studio/frontend/src/features/audio/transcript-stream.ts b/studio/frontend/src/features/audio/transcript-stream.ts
index 10b34173d90..77f729b389f 100644
--- a/studio/frontend/src/features/audio/transcript-stream.ts
+++ b/studio/frontend/src/features/audio/transcript-stream.ts
@@ -1,7 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-export interface TranscriptRecord {
+import type { TranscriptDetails } from "./transcript-model.ts";
+
+type TranscriptTiming = Partial<
+ Pick<TranscriptDetails, "segments" | "words" | "speakers" | "source">
+>;
+
+export interface TranscriptRecord extends TranscriptTiming {
id: string;
title: string;
text: string;
@@ -10,19 +16,24 @@ export interface TranscriptRecord {
duration: number | null;
created_at: string;
archived: boolean;
+ speaker_names?: Record<string, string>;
+ segment_count?: number;
+ has_words?: boolean;
}
export interface TranscriptProgress {
text: string;
processed_seconds?: number;
duration?: number;
+ phase?: "loading" | "downloading_aligner" | "transcribing";
}
-export interface TranscriptResult {
+export interface TranscriptResult extends TranscriptTiming {
text: string;
model: string;
duration: number | null;
record: TranscriptRecord | null;
+ language?: string | null;
}
export async function readTranscriptStream(
diff --git a/studio/frontend/src/features/audio/transcription-progress.tsx b/studio/frontend/src/features/audio/transcription-progress.tsx
index 672734a4c67..d884eb6e63f 100644
--- a/studio/frontend/src/features/audio/transcription-progress.tsx
+++ b/studio/frontend/src/features/audio/transcription-progress.tsx
@@ -6,6 +6,13 @@ import { Button } from "@/components/ui/button";
import type { TranscriptProgress } from "./transcript-stream";
import "./transcription-progress.css";
+// audio.cpp reports no progress numbers, so the server says which step it is on instead.
+const PHASE_LABELS: Record<NonNullable<TranscriptProgress["phase"]>, string> = {
+ loading: "Loading the model…",
+ downloading_aligner: "Downloading the timing aligner…",
+ transcribing: "Transcribing…",
+};
+
export function TranscriptionProgress({
startedAt,
finishedAt,
@@ -50,9 +57,15 @@ export function TranscriptionProgress({
</span>
)}
<span role="status">
- {running ? (stopping ? "Stopping…" : "Transcribing…") : "Elapsed"}
+ {running
+ ? stopping
+ ? "Stopping…"
+ : progress?.phase
+ ? PHASE_LABELS[progress.phase]
+ : "Transcribing…"
+ : "Elapsed"}
</span>
- <span className="tabular-nums" aria-label={`Elapsed time ${elapsed}`}>
+ <span className="font-mono tabular-nums" aria-label={`Elapsed time ${elapsed}`}>
{elapsed}
</span>
{running && (
diff --git a/studio/frontend/tests/audio-generation-stop.test.ts b/studio/frontend/tests/audio-generation-stop.test.ts
index c778206ea76..2bec80bdc76 100644
--- a/studio/frontend/tests/audio-generation-stop.test.ts
+++ b/studio/frontend/tests/audio-generation-stop.test.ts
@@ -102,15 +102,10 @@ test("transcription survives page deactivation and aborts on unmount", () => {
);
assert.match(
source,
- /transcribeWithProgress\(\s*blob,\s*name,\s*\{[\s\S]*signal: controller\.signal/,
+ /transcribeSourceWithProgress\(\s*sourceRefOf\(source\),\s*source\.name,\s*\{[\s\S]*signal: controller\.signal/,
);
- const lifecycle = source.slice(
- source.indexOf("// Release the microphone"),
- source.indexOf("const handleTranscribeFile"),
- );
- assert.match(lifecycle, /if \(!active\) \{\s*stopAndDiscardRecording\(\);\s*\}/);
assert.match(
- lifecycle,
+ source,
/useEffect\(\(\) => \(\) => transcriptionAbort\.current\?\.abort\(\), \[\]\)/,
);
assert.doesNotMatch(
diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.ts
index e04823547f2..725cf7457eb 100644
--- a/studio/frontend/tests/audio-model-eject.test.ts
+++ b/studio/frontend/tests/audio-model-eject.test.ts
@@ -15,7 +15,7 @@ test("Audio exposes the shared picker eject action only while idle", () => {
source,
/onEject=\{\s*busy === null && selectorValue && !showLastPageModel\s*\? handleEject\s*: undefined\s*\}/,
);
- assert.match(source, /if \(busy !== null \|\| isRecording\)/);
+ assert.match(source, /const handleEject = useCallback\(\(\) => \{\s*if \(busy !== null\) \{/);
assert.match(
source,
/loaded=\{\s*mode === "transcribe"\s*\? sttReady\s*: showLastPageModel\s*\? false\s*: undefined\s*\}/,
@@ -129,7 +129,7 @@ test("a load confirmed after Audio is hidden is deferred, not sent", () => {
test("Transcribe eject only unloads a sidecar owned by the current selection", () => {
assert.match(
source,
- /const handleEject[\s\S]*stopAndDiscardRecording\(\);[\s\S]*if \(mode === "transcribe"\)/,
+ /const handleEject[\s\S]*?if \(mode === "transcribe"\)/,
);
// One release path, shared with the Generate-mode transition, so both stay owned.
// The selection is forgotten only after the unload lands, so a 500 leaves Eject usable.
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
index 37f7d172500..abbc3303781 100644
--- a/studio/frontend/tests/audio-page-policy.test.ts
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -18,7 +18,6 @@ import {
isTtsAudioType,
macTtsPickAction,
mergeGalleryPage,
- micStreamRequestIsCurrent,
minimaxMusicFramesForSeconds,
modelLoadNote,
nativeAudioInstructionsKind,
@@ -35,6 +34,8 @@ import { readSrc } from "./helpers/kit.ts";
import { readAudioWorkspaceSource } from "./helpers/audio-workspace.ts";
const audioPageSource = readAudioWorkspaceSource();
+const audioSourceCard = readSrc("features/audio/hooks/use-audio-source.ts");
+const audioSourceInput = readSrc("features/audio/components/audio-source-input.tsx");
const chatApiSource = readSrc("features/chat/api/chat-api.ts");
test("mode transitions cancel generation but wait for non-cancellable work", () => {
@@ -332,25 +333,17 @@ test("a pending engine selection is not replaced by an older resident sidecar",
assert.equal(resolveSttLoadedModel(status, "mtmd", false), "small");
});
-test("a resolved microphone permission stream is accepted only by its live request", () => {
- assert.equal(micStreamRequestIsCurrent(4, 4, true), true);
- assert.equal(micStreamRequestIsCurrent(4, 5, true), false);
- assert.equal(micStreamRequestIsCurrent(4, 4, false), false);
-});
-
test("MediaRecorder setup failures release the acquired microphone stream", () => {
- // start() now takes a timeslice so the byte cap is observable; the release on failure
- // is what this test is about and is unchanged.
assert.match(
- audioPageSource,
- /recorder\.start\(RECORDING_CHUNK_MS\);[\s\S]*?catch \{[\s\S]*?stopRecordStream\(\);/,
+ audioSourceCard,
+ /recorder = createAudioRecorder\(stream\);\s*\} catch \{\s*stopStream\(\);/,
);
});
test("leaving Audio clears an unresolved microphone permission wait", () => {
assert.match(
- audioPageSource,
- /const stopAndDiscardRecording[\s\S]*micRequestGeneration\.current \+= 1;[\s\S]*micPendingGeneration\.current = null;[\s\S]*setMicRequestPending\(false\)/,
+ audioSourceCard,
+ /\(\) => \(\) => \{\s*abortAll\(\);\s*for \(const track of streamRef\.current\?\.getTracks\(\) \?\? \[\]\) track\.stop\(\);/,
);
});
@@ -362,11 +355,8 @@ test("routed picks wait in the URL until Audio is idle", () => {
assert.match(audioPageSource, /\[\s*active,\s*busy,/);
});
-test("file transcription cannot overlap a pending microphone permission", () => {
- assert.match(
- audioPageSource,
- /type="file"[\s\S]*disabled=\{[\s\S]*micRequestPending[\s\S]*onChange=/,
- );
+test("picking a file cannot overlap a recording on the same card", () => {
+ assert.match(audioSourceInput, /disabled=\{disabled \|\| recording\}/);
});
test("gallery refresh preserves fallback selection and pagination identity", () => {
@@ -406,13 +396,6 @@ test("a refresh that overlaps a pin or move is dropped and rerun after it", () =
}
});
-test("Audio transcription uses backend language auto-detection", () => {
- const api = readSrc("features/audio/api.ts");
- const transcription = api.slice(api.indexOf("export async function transcribeWithProgress"), api.indexOf("export async function listTranscripts"));
- assert.doesNotMatch(transcription, /dictationLanguage|language:/);
- assert.match(transcription, /stream: "true"/);
-});
-
test("older STT status requests cannot overwrite newer residency", () => {
assert.match(
audioPageSource,
@@ -533,48 +516,29 @@ test("a refresh resets when an external archive moves the page boundary", () =>
});
});
-test("the recorder is gated on the same capability check the composer uses", () => {
- // Safari ships no MediaRecorder, and an http LAN origin (-H 0.0.0.0) is not a
- // secure context, so navigator.mediaDevices is undefined there. Without this
- // gate Record is enabled and its only outcome is "Could not access the
- // microphone", which blames the wrong thing.
+test("Record is offered only where the browser can capture audio", () => {
+ // Safari ships no MediaRecorder, and an http LAN origin (-H 0.0.0.0) has no navigator.mediaDevices.
assert.match(
- audioPageSource,
- /StudioModelDictationAdapter\.isSupported\(\)/,
- "the audio page must reuse the dictation capability check",
+ audioSourceCard,
+ /typeof navigator\.mediaDevices\?\.getUserMedia === "function"/,
);
assert.match(
- audioPageSource,
- /disabled=\{\s*!recordingSupported/,
- "Record must be disabled when recording is unsupported",
+ audioSourceInput,
+ /\.\.\.\(recordingSupported\(\) \? \[\{ value: "record", label: "Record" \}\] : \[\]\)/,
);
- // File upload stays available, so transcription still works on those hosts.
- assert.match(audioPageSource, /accept="audio\/\*"/);
+ assert.match(audioPageSource, /<AudioSourceInput/);
});
-test("a recording is stopped at the sidecar's duration and size limits", () => {
+test("a Transcribe recording is stopped at the 30 minute limit the inputs route accepts", () => {
// Without a cap the page buffered an over-long recording in memory and uploaded it only
- // for the backend to refuse it. Mirrors _MAX_AUDIO_SECONDS and the b64 upload ceiling.
+ // for the backend to refuse it. 30 minutes of 16 kHz PCM is ~58 MB, under the 200 MB cap.
assert.match(audioPageSource, /const RECORDING_MAX_SECONDS = 30 \* 60;/);
- assert.match(audioPageSource, /const RECORDING_MAX_BYTES = /);
- assert.match(audioPageSource, /const RECORDING_MAX_BYTES = 25 \* 1024 \* 1024;/);
- assert.match(
- audioPageSource,
- /if \(recordedBytes \+ event\.data\.size > RECORDING_MAX_BYTES\) \{\s*stopAtLimit\("size"\);/,
- );
+ assert.match(audioPageSource, /maxRecordSeconds=\{RECORDING_MAX_SECONDS\}/);
assert.match(
- audioPageSource,
- /window\.setTimeout\(\s*\(\) => stopAtLimit\("duration"\),\s*maxSeconds \* 1000,/,
- );
- // Uncompressed WAV on the PCM capture path (#9543) reaches the byte cap well
- // before the 30 minute one, so the duration enforced is the lower of the two.
- // Without this the recorder ran to 30 minutes and the upload was refused,
- // losing audio the user had already recorded.
- assert.match(
- audioPageSource,
- /const maxSeconds =\s*recorder instanceof PcmRecorder\s*\?\s*Math\.min\(\s*RECORDING_MAX_SECONDS,\s*recorder\.secondsWithin\(RECORDING_MAX_BYTES\),\s*\)\s*:\s*RECORDING_MAX_SECONDS;/,
+ audioSourceCard,
+ /window\.setTimeout\(\(\) => \{\s*if \(recorder\.state !== "inactive"\) recorder\.stop\(\);\s*\}, maxRecordSeconds \* 1000\);/,
);
- assert.match(audioPageSource, /window\.clearTimeout\(durationTimer\);/);
+ assert.match(audioSourceCard, /window\.clearTimeout\(limit\);/);
});
test("the trained-model list applies the native-aware macOS policy", () => {
diff --git a/studio/frontend/tests/audio-transcribe-rail.test.ts b/studio/frontend/tests/audio-transcribe-rail.test.ts
new file mode 100644
index 00000000000..90717927f03
--- /dev/null
+++ b/studio/frontend/tests/audio-transcribe-rail.test.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const rail = readSrc("features/audio/pages/transcribe-page.tsx");
+const host = readSrc("features/audio/audio-page.tsx");
+const api = readSrc("features/audio/transcribe-api.ts");
+const hook = readSrc("features/audio/hooks/use-transcription.ts");
+const view = readSrc("features/audio/components/transcript-view.tsx");
+const gallery = readSrc("features/audio/transcript-gallery.tsx");
+
+test("the rail takes audio through the shared input card, worded for Transcribe and uncapped", () => {
+ assert.match(
+ rail,
+ /<AudioHistoryProvider value=\{historyClips\}>\s*<div data-tour="audio-record">\s*<AudioSourceInput[\s\S]*?maxRecordSeconds=\{RECORDING_MAX_SECONDS\}\s*expiredMessage="This upload expired\. Add it again\."\s*usesFirstSeconds=\{null\}\s*recordHint="Record up to 30 minutes, then transcribe it\."/,
+ );
+});
+
+test("both switches come from the model's capabilities, an always-on one reads as a fact", () => {
+ assert.match(host, /transcribeSwitches\(\s*transcribeCaps\.caps,/);
+ assert.match(
+ rail,
+ /\(\["timestamps", "speakers"\] as const\)\.map[\s\S]*?value=\{switches\[name\]\}/,
+ );
+ assert.match(
+ rail,
+ /\{value\.always \? \([\s\S]*?Always on[\s\S]*?\) : \(\s*<Switch/,
+ );
+});
+
+test("the footer says why Transcribe is off, Stop replaces it, Mod+Enter runs it", () => {
+ assert.match(
+ rail,
+ /id=\{blocker \? "transcribe-blocker" : "transcribe-notice"\}[\s\S]*?\{blocker \? blocker\.reason : notice\}\s*<GenerateActions actions=\{blocker\?\.actions\} \/>/,
+ );
+ assert.match(rail, /onClick=\{running \? onStop : onTranscribe\}/);
+ assert.match(
+ host,
+ /generateShortcut\.current = \(\) => \{\s*if \(canTranscribe\) handleTranscribe\(\);\s*else if \(canGenerate\)/,
+ );
+ assert.match(
+ host,
+ /document\.getElementById\("transcribe-result"\)\?\.focus\(\)/,
+ );
+});
+
+test("runs send the source by id and the language the rail shows; a 404 upload marks the card expired", () => {
+ assert.doesNotMatch(api, /\bpath:|"path"|audio_path|FormData|body: blob/);
+ assert.match(hook, /transcribeSourceWithProgress\(\s*sourceRefOf\(source\),/);
+ assert.match(
+ api,
+ /throw new AudioApiError\(await readFastApiError\(response\), response\.status\)/,
+ );
+ assert.match(
+ hook,
+ /error\.status === 404 &&\s*source\.kind === "input"\s*\)\s*\{\s*onSourceExpired\?\.\(\);/,
+ );
+ assert.match(
+ host,
+ /setExpiredTranscribeSourceId\(source\.id\);\s*transcribeSourceHandle\.current\?\.markExpired\(\);/,
+ );
+ assert.match(rail, /transcribeLanguageFor\(language, languages\) \|\| AUTO/);
+ assert.match(host, /\{ language: transcribeLanguage, \.\.\.request \}/);
+});
+
+test("timestamps seek once the audio loaded, nothing autoplays, the playing row is followed", () => {
+ assert.match(view, /const player = ready \? control : null;/);
+ assert.match(
+ view,
+ /aria-label=\{`Play from \$\{stamp\}`\}\s*onClick=\{\(\) => player\.current\?\.seek\(segment\.start, true\)\}/,
+ );
+ assert.match(
+ view,
+ /controller\.abort\(\);\s*if \(url\) URL\.revokeObjectURL\(url\);/,
+ );
+ assert.doesNotMatch(view + rail, /autoPlay|\.play\(/);
+ assert.match(
+ view,
+ /if \(!playing \|\| active < 0 \|\| shown !== "segments"\) return;/,
+ );
+ assert.match(view, /onRename\(id, sanitizeSpeakerName\(draft\)\)/);
+});
+
+test("both export menus share the timestamp gate, and a download marks only the transcript it saved", () => {
+ assert.equal(rail.match(/<TranscriptExportItems/g)?.length, 1);
+ assert.equal(gallery.match(/<TranscriptExportItems/g)?.length, 1);
+ assert.match(
+ hook,
+ /const version = transcriptVersion\.current;[\s\S]*?await downloadTranscript\(format,[\s\S]*?names: speakerNames,[\s\S]*?transcriptVersion\.current === version\s*\)\s*setTranscriptExported\(true\);/,
+ );
+ assert.match(
+ gallery,
+ /full = await getTranscript\(record\.id\);[\s\S]*?await downloadTranscript\(format, \{[\s\S]*?details: detailsFrom\(full\),\s*names: full\.speaker_names \?\? \{\},/,
+ );
+ assert.doesNotMatch(gallery, /downloadFile|record\.text, record\.title/);
+});
diff --git a/studio/frontend/tests/audio-transcribe-store.test.ts b/studio/frontend/tests/audio-transcribe-store.test.ts
new file mode 100644
index 00000000000..669e7d69568
--- /dev/null
+++ b/studio/frontend/tests/audio-transcribe-store.test.ts
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+const { store } = installLocalStorageFake();
+registerBundlerResolver();
+
+const saved = {
+ source: { kind: "clip", id: "c1", name: "Interview", durationS: 61 },
+ ...{ language: "de", timestamps: true, speakers: false, view: "segments" },
+};
+store.set(
+ "unsloth_audio_transcribe_v1",
+ JSON.stringify({ state: saved, version: 1 }),
+);
+
+const { AUDIO_TRANSCRIBE_STORAGE_KEY, useAudioTranscribeStore } = await import(
+ "../src/features/audio/stores/audio-transcribe-store.ts"
+);
+
+test("Transcribe's settings come back after a reload and are written back under the versioned key", () => {
+ assert.deepEqual(useAudioTranscribeStore.getState(), saved);
+ const next = { ...saved, source: null, view: "text" as const };
+ useAudioTranscribeStore.setState(next);
+ assert.deepEqual(
+ JSON.parse(store.get(AUDIO_TRANSCRIBE_STORAGE_KEY) ?? "{}"),
+ {
+ state: next,
+ version: 1,
+ },
+ );
+});
diff --git a/studio/frontend/tests/audio-transcript-lifecycle.test.ts b/studio/frontend/tests/audio-transcript-lifecycle.test.ts
index ae0a078f359..ff76285f571 100644
--- a/studio/frontend/tests/audio-transcript-lifecycle.test.ts
+++ b/studio/frontend/tests/audio-transcript-lifecycle.test.ts
@@ -10,6 +10,14 @@ import { AUTH_SESSION_ENDING_EVENT } from "../src/features/auth/session-events.t
import { readTranscriptDraft, writeTranscriptDraft } from "../src/features/audio/transcript-draft.ts";
const source = readAudioWorkspaceSource();
+const draftDetails = {
+ segments: [{ start: 0, end: 1.5, text: "unsaved text", speaker: "S01" }],
+ words: [],
+ speakers: [{ id: "S01", label: "Speaker 1" }],
+ source: { kind: "input", id: "in-1", name: "speech.wav" },
+ language: "en",
+ duration: 1.5,
+};
test("macOS termination checks unsaved transcripts before allowing exit", () => {
const native = readText("../../src-tauri/src/main.rs");
@@ -65,29 +73,7 @@ function callback(name: string, scope: Record<string, unknown>) {
);
}
-test("declining replacement prevents recording setup", async () => {
- const events: string[] = [];
- const start = callback("handleRecordToggle", {
- isRecording: false,
- micPendingGeneration: { current: null },
- busyRef: { current: null },
- micRequestGeneration: { current: 0 },
- transcriptVersion: { current: 7 },
- setMicRequestPending: () => {},
- confirmTranscriptReplacement: () => {
- events.push("confirm");
- return false;
- },
- prepareTranscriptionModel: async () => {
- events.push("prepare");
- return null;
- },
- });
- await start();
- assert.deepEqual(events, ["confirm"]);
-});
-
-test("recording approval applies once and only to the transcript it covered", async () => {
+test("a run applies a confirmation once and only to the transcript it covered", async () => {
for (const approvedVersion of [7, 6, undefined]) {
const events: string[] = [];
const run = callback("runTranscription", {
@@ -106,18 +92,14 @@ test("recording approval applies once and only to the transcript it covered", as
setBusy: () => {},
AbortController,
});
- await run(new Blob(["recording"]), "Recording", approvedVersion);
+ await run(
+ { kind: "input", id: "i1", name: "Interview.wav", durationS: 3 },
+ { language: "", timestamps: false, speakers: false },
+ undefined,
+ approvedVersion,
+ );
assert.deepEqual(events, approvedVersion === 7 ? ["prepare"] : ["confirm"]);
}
- const recording = section(
- "const handleRecordToggle",
- "// Release the microphone",
- );
- assert.match(recording, /const confirmedVersion = transcriptVersion.current/);
- assert.match(
- recording,
- /runTranscription\(blob, "Recording", confirmedVersion\)/,
- );
});
test("changing model residency preserves the transcript and its recorded origin", () => {
@@ -133,7 +115,7 @@ test("changing model residency preserves the transcript and its recorded origin"
});
test("the previous result is replaced only after its replacement model is ready", () => {
- const run = section("const runTranscription", "const handleRecordToggle");
+ const run = section("const runTranscription", "const selectRecord");
assert.match(run, /confirmTranscriptReplacement\(\)/);
assert.ok(
run.indexOf("await prepareTranscriptionModel()") <
@@ -141,26 +123,28 @@ test("the previous result is replaced only after its replacement model is ready"
);
assert.ok(
run.indexOf("clearTranscript()") <
- run.indexOf("await transcribeWithProgress"),
+ run.indexOf("await transcribeSourceWithProgress"),
);
});
-test("leaving the page stops microphone capture while transcription can finish into history", () => {
- const lifecycle = section(
- "// Release the microphone",
- "const handleTranscribeFile",
+test("leaving the page lets a transcription finish into history; the input card owns the microphone", () => {
+ // The input card records; the page stays mounted when hidden, so hiding it must end a recording too.
+ assert.doesNotMatch(source, /getUserMedia|stopAndDiscardRecording/);
+ assert.match(
+ readSrc("features/audio/hooks/use-audio-source.ts"),
+ /activeRef\.current = active;\s*if \(!active\) stopRecording\(\);/,
);
assert.match(
- lifecycle,
- /if \(!active\) \{\s*stopAndDiscardRecording\(\);\s*\}/,
+ readSrc("features/audio/audio-page.tsx"),
+ /<AudioActiveProvider value=\{active\}>/,
);
assert.match(
- lifecycle,
+ source,
/useEffect\(\(\) => \(\) => transcriptionAbort.current\?\.abort\(\), \[\]\)/,
);
- const run = section("const runTranscription", "const handleRecordToggle");
+ const run = section("const runTranscription", "const selectRecord");
assert.doesNotMatch(
- run.slice(run.indexOf("await transcribeWithProgress")),
+ run.slice(run.indexOf("await transcribeSourceWithProgress")),
/!activeRef.current/,
);
});
@@ -234,6 +218,8 @@ test("logout checks unsaved transcripts before revoking the session or navigatin
draftKey: "test-draft",
transcribedName: "speech.wav",
transcriptModel: "tiny",
+ transcriptDetails: draftDetails,
+ speakerNames: { S01: "Ada" },
writeTranscriptDraft,
isTauri: false,
window,
@@ -266,7 +252,7 @@ test("logout checks unsaved transcripts before revoking the session or navigatin
assert.deepEqual(
readTranscriptDraft("test-draft"),
scenario === "decline" || scenario === "unmounted"
- ? { text: "unsaved text", title: "speech.wav", model: "tiny" }
+ ? { text: "unsaved text", title: "speech.wav", model: "tiny", details: draftDetails, speakerNames: { S01: "Ada" } }
: null,
);
}
@@ -298,3 +284,31 @@ test("remounting audio restores the unsaved transcript and its origin", () => {
const restored = new Function(...Object.keys(scope), outputText)(...Object.values(scope));
assert.deepEqual(restored, draft);
});
+
+test("a draft restores with or without timing details", () => {
+ const drafts = new Map<string, string>();
+ Object.defineProperty(globalThis, "sessionStorage", {
+ configurable: true,
+ value: {
+ getItem: (key: string) => drafts.get(key) ?? null,
+ setItem: (key: string, value: string) => drafts.set(key, value),
+ removeItem: (key: string) => drafts.delete(key),
+ },
+ });
+ drafts.set("old-draft", JSON.stringify({ text: "hello", title: "a.wav", model: "tiny" }));
+ assert.deepEqual(readTranscriptDraft("old-draft"), { text: "hello", title: "a.wav", model: "tiny" });
+
+ const draft = { text: "hi", title: "b.wav", model: "moss", details: draftDetails };
+ drafts.set(
+ "new-draft",
+ JSON.stringify({ ...draft, speakerNames: { S01: " Ada ", S99: "ghost", S02: 4 } }),
+ );
+ assert.deepEqual(readTranscriptDraft("new-draft"), { ...draft, speakerNames: { S01: "Ada" } });
+});
+
+test("a failed speaker rename rolls back only that speaker, on the same transcript", () => {
+ const rename = section("const renameSpeaker", "const handleCopyTranscript");
+ assert.match(rename, /if \(transcriptVersion\.current !== version\) return;/);
+ assert.match(rename, /\(current\[id\] \?\? ""\) === name \? withName\(current, id, previous\) : current/);
+ assert.doesNotMatch(rename, /setSpeakerNames\(previous\)/);
+});
diff --git a/studio/frontend/tests/audio-workspace-split.test.ts b/studio/frontend/tests/audio-workspace-split.test.ts
index 11eb4c583db..24822157e5b 100644
--- a/studio/frontend/tests/audio-workspace-split.test.ts
+++ b/studio/frontend/tests/audio-workspace-split.test.ts
@@ -46,11 +46,7 @@ test("a loaded model opens the page that fits it", () => {
slot,
/const loadedWorkflow = workflowForLoadedModel\(\{\s*current: useAudioWorkspaceStore\.getState\(\)\.workflow,\s*audioWorkflows: res\.audio_workflows,\s*music: isMusicGenerationModel\(repoId, res\.audio_type\),\s*\}\);[\s\S]{0,200}?rememberModel\(loadedWorkflow, repoId\);\s*if \(modeRef\.current === "speak"\) workspace\.commitWorkflow\(loadedWorkflow\);/,
);
- // A model already resident on mount uses the same rule, so a clone-only one opens Clone.
- assert.match(
- host,
- /workflowForLoadedModel\(\{\s*current: store\.workflow,\s*audioWorkflows: status\.audio_workflows,\s*music: musicGeneration,\s*\}\);\s*if \(next !== "speak" && next !== store\.workflow\) store\.adoptWorkflow\(next\);/,
- );
+ assert.match(host, /adoptWorkflow\("music"\)/);
});
test("?workflow= names the page ahead of ?task=, and both go through the workflow gate", () => {
@@ -152,10 +148,9 @@ test("Send to lists the other Audio pages from the shared workflow list", () =>
card,
/AUDIO_WORKFLOWS\.filter\(\s*\(tab\) => tab\.id !== current && handlers\[tab\.id\],?\s*\)/,
);
- // Bytes first: a failed fetch must not leave the user on another page.
assert.match(
host,
- /const blob = await fetchClipBlob\(clip\.url\);[\s\S]*?if \(!transitionWorkflow\("transcribe"\)\) return;/,
+ /if \(!transitionWorkflow\("transcribe"\)\) return;[\s\S]{0,200}?useAudioTranscribeStore\.setState\(\{\s*source: \{\s*kind: "clip",\s*id: clip\.id,/,
);
});
@@ -190,7 +185,7 @@ test("Send to waits for a running task instead of stopping it and dropping the c
// transcription was refused and the clip silently dropped.
assert.match(
host,
- /transcribe: \(\) => \{[\s\S]*?const busyNow = \(\) => \{\s*if \(busyRef\.current === null\) return false;\s*toast\.info\([^)]*\);\s*return true;\s*\};\s*if \(busyNow\(\)\) return;/,
+ /transcribe: \(\) => \{[\s\S]*?if \(busyRef\.current !== null\) \{\s*toast\.info\([^)]*\);\s*return;\s*\}\s*if \(!transitionWorkflow\("transcribe"\)\) return;/,
);
});
@@ -207,20 +202,3 @@ test("trained checkpoints are split between Speak and Music like the catalog", (
/trainedTtsModels\.filter\(\s*\(model\) =>\s*isMusicGenerationModel\(model\.id, model\.audioType\) ===\s*\(ttsWorkflow === "music"\),\s*\)/,
);
});
-
-test("picking a clip on one page keeps the other page's unsaved clip", () => {
- // A clip that failed to save exists only as the fallback; clicking a History row on the other
- // page cleared it, so returning to its page lost the clip.
- assert.match(
- gallery,
- /const otherPage =\s*clip !== undefined &&\s*fallbackClipRef\.current !== null &&\s*clipWorkflow\(clip\) !== fallbackClipRef\.current\.workflow;\s*if \(!keepFallback && !otherPage\) setFallbackClip\(null\);/,
- );
-});
-
-test("Send to checks again after the clip downloads, before switching pages", () => {
- // Generate pressed while the clip downloaded was stopped by the switch, and the clip dropped.
- assert.match(
- host,
- /const blob = await fetchClipBlob\(clip\.url\);[\s\S]*?if \(busyNow\(\)\) return;\s*if \(!transitionWorkflow\("transcribe"\)\) return;/,
- );
-});
diff --git a/studio/frontend/tests/pcm-recorder.test.ts b/studio/frontend/tests/pcm-recorder.test.ts
index dc227d3a56a..193ff10c971 100644
--- a/studio/frontend/tests/pcm-recorder.test.ts
+++ b/studio/frontend/tests/pcm-recorder.test.ts
@@ -353,7 +353,7 @@ test("secondsWithin keeps a WAV inside the upload cap", () => {
test("the recording call sites go through createAudioRecorder", () => {
for (const path of [
"../src/features/chat/adapters/studio-model-dictation-adapter.ts",
- "../src/features/audio/hooks/use-transcription.ts",
+ "../src/features/audio/hooks/use-audio-source.ts",
]) {
const source = readFileSync(new URL(path, import.meta.url), "utf8");
assert.equal(
diff --git a/studio/frontend/tests/transcribe-capabilities.test.ts b/studio/frontend/tests/transcribe-capabilities.test.ts
new file mode 100644
index 00000000000..68e506dcc92
--- /dev/null
+++ b/studio/frontend/tests/transcribe-capabilities.test.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ type SttCapabilities,
+ type TranscribeSwitch,
+ transcribeSwitches,
+} from "../src/features/audio/transcribe-capabilities.ts";
+import {
+ TRANSCRIBE_LANGUAGES,
+ transcribeLanguageFor,
+ transcribeLanguagesFor,
+} from "../src/features/audio/transcribe-languages.ts";
+
+const UNSUPPORTED: SttCapabilities = {
+ engine: "audiocpp",
+ family: "x",
+ timestamps: "unsupported",
+ speakers: false,
+ aligner: null,
+ cpu_only: false,
+};
+const off = { timestamps: false, speakers: false };
+const on = { timestamps: true, speakers: true };
+const switches = (over: Partial<SttCapabilities> | null, prefs = on) =>
+ transcribeSwitches(over && { ...UNSUPPORTED, ...over }, prefs, {
+ loading: false,
+ hasModel: true,
+ });
+const flags = (value: TranscribeSwitch) => [value.checked, value.disabled];
+
+test("unsupported: both switches off, each saying why and offering the speakers model", () => {
+ const { timestamps, speakers, request, notice } = switches({});
+ assert.deepEqual(
+ [...flags(timestamps), ...flags(speakers)],
+ [false, true, false, true],
+ );
+ assert.match(timestamps.hint, /plain text/);
+ assert.match(speakers.hint, /MOSS-Transcribe-Diarize and VibeVoice-ASR/);
+ assert.equal(speakers.suggestSpeakersModel, true);
+ assert.deepEqual([request, notice], [off, null]);
+});
+
+test("on_request: opt-in timestamps that say they download the aligner and reload", () => {
+ const aligner = { downloaded: false, size_bytes: 1_100_000_000 };
+ const qwen = { timestamps: "on_request", aligner } as const;
+ const optedOut = switches(qwen, off);
+ assert.deepEqual(flags(optedOut.timestamps), [false, false]);
+ assert.match(optedOut.timestamps.hint, /downloads it \(1\.1 GB\)/);
+ assert.deepEqual([optedOut.request, optedOut.notice], [off, null]);
+ const optedIn = switches(qwen);
+ assert.deepEqual(optedIn.request, { timestamps: true, speakers: false });
+ assert.match(
+ optedIn.notice ?? "",
+ /Downloads the timing aligner \(1\.1 GB\) and reloads/,
+ );
+ const loaded = switches({
+ ...qwen,
+ aligner: { ...aligner, downloaded: true },
+ });
+ assert.doesNotMatch(loaded.timestamps.hint, /downloads/);
+ assert.match(loaded.notice ?? "", /Reloads the model/);
+});
+
+test("always: timestamps read as always on, and the request only asks for speakers", () => {
+ const moss = { timestamps: "always", speakers: true } as const;
+ const result = switches(moss, { timestamps: false, speakers: true });
+ assert.deepEqual(
+ [flags(result.timestamps), result.timestamps.always],
+ [[true, true], true],
+ );
+ assert.deepEqual(result.request, { timestamps: false, speakers: true });
+ assert.deepEqual(switches(moss, off).request, off);
+});
+
+test("cpu_only says so before the run, after any aligner notice", () => {
+ assert.equal(
+ switches({ cpu_only: true }).notice,
+ "This model runs on the CPU.",
+ );
+ const qwen = { timestamps: "on_request", cpu_only: true } as const;
+ assert.match(
+ switches(qwen).notice ?? "",
+ /not loaded yet\. Runs on the CPU\.$/,
+ );
+});
+
+test("while unknown the switches wait, and without a model they say what to do", () => {
+ for (const [loading, hasModel, hint] of [
+ [true, true, /Checking/],
+ [false, false, /Pick a speech-to-text model/],
+ [false, true, /Transcribing still works/],
+ ] as const) {
+ const result = transcribeSwitches(null, on, { loading, hasModel });
+ assert.match(result.speakers.hint, hint);
+ assert.deepEqual(
+ [flags(result.timestamps), result.request],
+ [[false, true], off],
+ );
+ }
+});
+
+test("languages are ISO codes with Auto first; a saved one the model lacks is sent as detect", () => {
+ const names = TRANSCRIBE_LANGUAGES.map((entry) => entry.name);
+ assert.match(
+ names.join(),
+ /^Detect automatically,English,Chinese,.*,Cantonese$/,
+ );
+ assert.equal(transcribeLanguagesFor(undefined), TRANSCRIBE_LANGUAGES);
+ const canary = transcribeLanguagesFor(["en", "de", "es", "fr"]);
+ assert.deepEqual(canary.map((entry) => entry.code).join(), ",en,es,fr,de");
+ assert.equal(transcribeLanguageFor("ja", canary), "");
+ assert.equal(transcribeLanguageFor("de", canary), "de");
+ assert.equal(transcribeLanguageFor("de", transcribeLanguagesFor(["en"])), "");
+});
diff --git a/studio/frontend/tests/transcript-export.test.ts b/studio/frontend/tests/transcript-export.test.ts
new file mode 100644
index 00000000000..b1f5c51d7dd
--- /dev/null
+++ b/studio/frontend/tests/transcript-export.test.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ type TranscriptExport,
+ exportFileName,
+ exportTranscript,
+ toJson,
+ toSrt,
+ toTxt,
+ toVtt,
+} from "../src/features/audio/transcript-export.ts";
+import { EMPTY_TRANSCRIPT_DETAILS } from "../src/features/audio/transcript-model.ts";
+
+const seg = (start: number, end: number, text: string, speaker?: string) => ({
+ start,
+ end,
+ text,
+ speaker,
+});
+const plain: TranscriptExport = {
+ title: "note.m4a",
+ text: "Just text.",
+ model: "whisper-small",
+ names: {},
+ details: { ...EMPTY_TRANSCRIPT_DETAILS, duration: 4.5 },
+};
+const timed: TranscriptExport = {
+ ...plain,
+ names: { S02: "Bea" },
+ details: {
+ ...EMPTY_TRANSCRIPT_DETAILS,
+ segments: [
+ seg(1.234, 3, "Hello there.", "S01"),
+ seg(3, 3.5, "Hi!", "S02"),
+ seg(3661.001, 3662.25, "<b>Tom & Jerry</b>", "S02"),
+ ],
+ words: [{ start: 1.234, end: 1.6, word: "Hello" }],
+ speakers: [
+ { id: "S01", label: "Speaker 1" },
+ { id: "S02", label: "Speaker 2" },
+ ],
+ },
+};
+
+test("SRT numbers cues with comma milliseconds; VTT has a header, voice tags and escaped text", () => {
+ assert.equal(
+ toSrt(timed),
+ "1\n00:00:01,234 --> 00:00:03,000\nSpeaker 1: Hello there.\n\n" +
+ "2\n00:00:03,000 --> 00:00:03,500\nBea: Hi!\n\n" +
+ "3\n01:01:01,001 --> 01:01:02,250\nBea: <b>Tom & Jerry</b>\n",
+ );
+ assert.equal(
+ toVtt(timed),
+ "WEBVTT\n\n00:00:01.234 --> 00:00:03.000\n<v Speaker 1>Hello there.\n\n" +
+ "00:00:03.000 --> 00:00:03.500\n<v Bea>Hi!\n\n" +
+ "01:01:01.001 --> 01:01:02.250\n<v Bea>&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;\n",
+ );
+});
+
+test("cues: no names without speakers, no early end on a blank line, one cue over the clip without timing", () => {
+ const unnamed = { ...timed, details: { ...timed.details, speakers: [] } };
+ assert.doesNotMatch(toSrt(unnamed) + toVtt(unnamed), /Speaker 1|<v /);
+ const segments = [seg(0, 1, "one\n\n two"), seg(1, 2, " "), seg(2, 3, "x")];
+ const gaps = { ...plain, details: { ...plain.details, segments } };
+ assert.equal(
+ toSrt(gaps),
+ "1\n00:00:00,000 --> 00:00:01,000\none\ntwo\n\n2\n00:00:02,000 --> 00:00:03,000\nx\n",
+ );
+ assert.equal(toSrt(plain), "1\n00:00:00,000 --> 00:00:04,500\nJust text.\n");
+ assert.equal(
+ toVtt(plain),
+ "WEBVTT\n\n00:00:00.000 --> 00:00:04.500\nJust text.\n",
+ );
+ assert.equal(toSrt({ ...plain, text: "" }), "");
+ assert.equal(toVtt({ ...plain, text: "" }), "WEBVTT\n");
+});
+
+test("TXT is the plain text or paragraphs led by the current names; JSON keeps keys, names and words", () => {
+ assert.equal(toTxt(plain), "Just text.");
+ assert.equal(
+ toTxt(timed),
+ "Speaker 1: Hello there.\n\nBea: Hi! <b>Tom & Jerry</b>\n",
+ );
+ const json = JSON.parse(toJson(timed));
+ assert.deepEqual(
+ Object.keys(json).join(),
+ "title,model,language,duration,text,segments,words,speakers",
+ );
+ assert.deepEqual(json.speakers, [
+ { id: "S01", label: "Speaker 1", name: null },
+ { id: "S02", label: "Speaker 2", name: "Bea" },
+ ]);
+ assert.equal("words" in JSON.parse(toJson(plain)), false);
+});
+
+test("each format has its media type, and file names drop the extension and unsafe characters", () => {
+ for (const [format, mime, write] of [
+ ["txt", "text/plain;charset=utf-8", toTxt],
+ ["srt", "application/x-subrip;charset=utf-8", toSrt],
+ ["vtt", "text/vtt;charset=utf-8", toVtt],
+ ["json", "application/json;charset=utf-8", toJson],
+ ] as const)
+ assert.deepEqual(exportTranscript(format, timed), {
+ content: write(timed),
+ mime,
+ });
+ for (const [title, name] of [
+ ["meeting.wav", "meeting.srt"],
+ ['a/b\\c:d*e?"f<g>h|i.mp3', "a_b_c_d_e__f_g_h_i.srt"],
+ ["tab\there", "tab_here.srt"],
+ ["", "transcript.srt"],
+ [".wav", "transcript.srt"],
+ ])
+ assert.equal(exportFileName(title, "srt"), name);
+});
diff --git a/studio/frontend/tests/transcript-model.test.ts b/studio/frontend/tests/transcript-model.test.ts
new file mode 100644
index 00000000000..79695c13f6a
--- /dev/null
+++ b/studio/frontend/tests/transcript-model.test.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ EMPTY_TRANSCRIPT_DETAILS,
+ activeSegmentIndex,
+ detailsFrom,
+ formatTimestamp,
+ paragraphs,
+ sanitizeSpeakerName,
+ speakerLabel,
+} from "../src/features/audio/transcript-model.ts";
+
+const segments = [
+ { start: 0.5, end: 2, text: "One", speaker: "S01" },
+ { start: 3, end: 5, text: "two ", speaker: "S01" },
+ { start: 4.5, end: 7, text: "Three", speaker: "S02" },
+ { start: 6, end: 7, text: " ", speaker: "S01" },
+ { start: 7, end: 9, text: "four", speaker: "S01" },
+];
+
+test("the active segment is found at the edges, in gaps and across overlaps", () => {
+ const at = (seconds: number) => activeSegmentIndex(seconds, segments);
+ assert.deepEqual(
+ [0, 0.5, 2.5, 4.6, 7, 60, Number.NaN].map(at),
+ [-1, 0, 0, 2, 4, 4, -1],
+ );
+ assert.equal(activeSegmentIndex(1, []), -1);
+});
+
+test("speakers are named by rename, then default label, then raw id, and grouped into paragraphs", () => {
+ const speakers = [{ id: "S01", label: "Speaker 1" }];
+ assert.equal(speakerLabel("S01", speakers, {}), "Speaker 1");
+ assert.equal(speakerLabel("S01", speakers, { S01: " Alice " }), "Alice");
+ assert.equal(speakerLabel("S01", speakers, { S01: " " }), "Speaker 1");
+ assert.equal(speakerLabel("S09", speakers, {}), "S09");
+ assert.deepEqual(paragraphs(segments), [
+ { speaker: "S01", text: "One two" },
+ { speaker: "S02", text: "Three" },
+ { speaker: "S01", text: "four" },
+ ]);
+});
+
+test("timestamps read m:ss, h:mm:ss past an hour, and speaker names are one capped line", () => {
+ assert.deepEqual(
+ [0, 83.9, 3599.999, 3725, -4, Number.POSITIVE_INFINITY].map(
+ formatTimestamp,
+ ),
+ ["0:00", "1:23", "59:59", "1:02:05", "0:00", "0:00"],
+ );
+ assert.equal(sanitizeSpeakerName(" Ada\n Lovelace "), "Ada Lovelace");
+ assert.equal(sanitizeSpeakerName("x".repeat(80)), "x".repeat(40));
+});
+
+test("details drop malformed entries, server paths and unknown source kinds", () => {
+ const good = {
+ segments: [{ start: 1, end: 2, text: "ok", speaker: "S01" }],
+ words: [{ start: 0, end: 1, word: "ok" }],
+ speakers: [{ id: "S01", label: "Speaker 1" }],
+ source: { kind: "input", id: "abc", name: "a.wav" },
+ language: "en",
+ duration: 12,
+ };
+ const details = detailsFrom({
+ ...good,
+ segments: [
+ ...good.segments,
+ { start: 3, end: 2, text: "backwards" },
+ { start: "1", end: 2, text: "string time" },
+ { start: 1, end: 2 },
+ null,
+ ],
+ words: [...good.words, { start: 0, end: 1 }],
+ speakers: [...good.speakers, { id: 1 }],
+ source: { ...good.source, path: "/etc/passwd" },
+ });
+ assert.deepEqual(details, good);
+ assert.deepEqual(
+ detailsFrom({ ...good, source: { ...good.source, kind: "file" } }).source,
+ null,
+ );
+ assert.deepEqual(detailsFrom({}), EMPTY_TRANSCRIPT_DETAILS);
+});