From 1232614c942d0b1d1e8e5883db47ff794b10eff3 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 12:00:54 +0200 Subject: [PATCH 1/8] feat(session): add transcription sessions with timed segments and partials A session without :llm and :tts ends each turn after STT. STT adapters can emit AudioFlow.Transcript.Segment values and {:partial, text}, which become :segment and :partial_transcript events. Partials are excluded from the prompt, history and recordings. --- lib/audio_flow/recording.ex | 4 ++ lib/audio_flow/session.ex | 89 +++++++++++++++++++++++----- lib/audio_flow/transcript.ex | 54 +++++++++++++++++ lib/audio_flow/transcript/segment.ex | 63 ++++++++++++++++++++ lib/audio_flow/web_socket.ex | 20 +++++++ test/web_socket_test.exs | 32 ++++++++++ 6 files changed, 248 insertions(+), 14 deletions(-) create mode 100644 lib/audio_flow/transcript.ex create mode 100644 lib/audio_flow/transcript/segment.ex diff --git a/lib/audio_flow/recording.ex b/lib/audio_flow/recording.ex index 2ce4c2d..06074d5 100644 --- a/lib/audio_flow/recording.ex +++ b/lib/audio_flow/recording.ex @@ -82,6 +82,10 @@ defmodule AudioFlow.Recording do when kind in [:text, :transcript, :description] and is_binary(value), do: %{kind: Atom.to_string(kind), node: node_id(node), text: value} + # Partial transcripts are superseded by final text, so they are not saved. + defp recorded_event(recorder, :segment, %AudioFlow.Transcript.Segment{text: text}, node), + do: recorded_event(recorder, :transcript, text, node) + defp recorded_event(recorder, :audio, value, node) do if recorder.audio and Audio.valid?(value) do %{ diff --git a/lib/audio_flow/session.ex b/lib/audio_flow/session.ex index bf1016c..19cd2f2 100644 --- a/lib/audio_flow/session.ex +++ b/lib/audio_flow/session.ex @@ -16,6 +16,13 @@ defmodule AudioFlow.Session do `AudioFlow.Text` input goes directly to the LLM without an input stage. `:max_image_bytes` defaults to 6,291,456. Image-only sessions can omit `:stt`. Descriptions form one LLM prompt, then follow the same speech output path. + Omit both `:llm` and `:tts` for a transcription session. Its turns end after + the input stage, and text input returns `{:error, {:unsupported_input, :llm}}`. + An STT adapter can emit strings, `AudioFlow.Transcript.Segment` values, or + `{:partial, text}`. These become `{:transcript, text}`, `{:segment, segment}` + and `{:partial_transcript, text}` events. Partial text is an unstable hypothesis + that follows the final text emitted so far. It is not part of the prompt or the + history. Set `:history` to `true` or `[max_turns: 8, max_bytes: 16_384]` to retain successful user/assistant pairs. The LLM then receives a list of role/content message maps. History is disabled by default. @@ -40,6 +47,7 @@ defmodule AudioFlow.Session do alias AudioFlow.Image alias AudioFlow.Telemetry alias AudioFlow.Text + alias AudioFlow.Transcript.Segment @limits_schema [ timeout_ms: [type: :pos_integer, default: 30_000], @@ -103,12 +111,18 @@ defmodule AudioFlow.Session do defp init_adapters(%AudioFlow.Graph.Plan{}, nil, _options), do: %{} defp init_adapters(nil, nil, options) do - adapters = Map.new([:llm, :tts], &{&1, Keyword.fetch!(options, &1)}) - adapters = Map.merge(adapters, Map.new(Keyword.take(options, [:stt, :vision]))) + adapters = Map.new(Keyword.take(options, [:stt, :vision, :llm, :tts])) if not (Map.has_key?(adapters, :stt) or Map.has_key?(adapters, :vision)), do: raise(ArgumentError, "a session requires an :stt or :vision adapter") + if Map.has_key?(adapters, :llm) != Map.has_key?(adapters, :tts), + do: raise(ArgumentError, "a session requires both :llm and :tts, or neither") + + if not Map.has_key?(adapters, :llm) and + Keyword.get(options, :history, false) not in [false, nil], + do: raise(ArgumentError, "a transcription session does not support history") + adapters end @@ -413,7 +427,7 @@ defmodule AudioFlow.Session do defp submit_error(input, stage, limit, state) do cond do unsupported_kind?(input, state) -> {:unsupported_input, Plan.input_kind(input)} - missing_stage?(stage, state) -> {:unsupported_input, stage} + missing_stage?(stage || :llm, state) -> {:unsupported_input, stage || :llm} byte_size(input.data) > limit -> :input_too_large state.active != nil or state.candidate != nil -> :busy true -> nil @@ -427,7 +441,6 @@ defmodule AudioFlow.Session do do: not Map.has_key?(state.graph.inputs, Plan.input_kind(input)) defp missing_stage?(_stage, %{graph: graph}) when graph != nil, do: false - defp missing_stage?(nil, _state), do: false defp missing_stage?(stage, state), do: @@ -568,7 +581,7 @@ defmodule AudioFlow.Session do do: %{active | playout: AudioFlow.Playout.audio(active.playout, value)}, else: active - first = Map.put_new(active.first, kind, now() - active.started) + first = Map.put_new(active.first, first_kind(kind), now() - active.started) notify(state, if(node, do: {kind, value, node}, else: {kind, value})) %{ @@ -582,6 +595,9 @@ defmodule AudioFlow.Session do } end + defp first_kind(:segment), do: :transcript + defp first_kind(kind), do: kind + defp finish_output(state, :ok) do case AudioFlow.Output.call(state.output, :finish, [{self(), state.active.turn}]) do :ok -> :ok @@ -654,7 +670,10 @@ defmodule AudioFlow.Session do try do transcript = input_transcript(run, emit, key, input, stage, kind) - if transcript != "", do: respond(run, emit, {session, turn, output}, transcript) + + if transcript != "" and Map.has_key?(adapters, :llm), + do: respond(run, emit, {session, turn, output}, transcript) + :ok rescue error -> {:error, {:exception, Exception.message(error)}} @@ -667,19 +686,53 @@ defmodule AudioFlow.Session do defp input_transcript(run, emit, key, input, stage, kind) do if stage != nil do - run.(stage, input, fn text -> - emit.(kind, text) - Process.put(key, [text | Process.get(key)]) - :ok - end) + run.(stage, input, &input_output(&1, emit, key, stage, kind)) else Process.put(key, [input.data]) end - transcript = Process.get(key) |> Enum.reverse() |> Enum.join() |> String.trim() + transcript = Process.get(key) |> Enum.reverse() |> join_input() |> String.trim() input_context(input, transcript) end + defp input_output(text, emit, key, _stage, kind) when is_binary(text) do + emit.(kind, text) + Process.put(key, [text | Process.get(key)]) + :ok + end + + defp input_output(%Segment{} = segment, emit, key, :stt, _kind) do + emit.(:segment, segment) + Process.put(key, [segment | Process.get(key)]) + :ok + end + + defp input_output({:partial, text}, emit, _key, :stt, _kind) when is_binary(text), + do: emit.(:partial_transcript, text) + + defp input_output(_, _emit, _key, _stage, _kind), do: throw(:invalid_output) + + # Strings keep their own spacing. Segment text is joined with one space. + defp join_input(parts) do + parts + |> Enum.reduce({[], nil}, fn + %Segment{text: text}, {acc, previous} -> + text = String.trim(text) + + cond do + text == "" -> {acc, previous} + previous in [nil, :space] -> {[text | acc], :segment} + true -> {[text, " " | acc], :segment} + end + + text, {acc, _} -> + {[text | acc], if(String.ends_with?(text, [" ", "\n", "\t"]), do: :space, else: :text)} + end) + |> elem(0) + |> Enum.reverse() + |> IO.iodata_to_binary() + end + defp respond(run, emit, {session, turn, _output} = target, transcript) do prompt = fetch!(session, {:context, turn, transcript}) @@ -764,6 +817,9 @@ defmodule AudioFlow.Session do defp record_context(%{history: nil, active: active}, _, _), do: {:ok, active} + defp record_context(state, :segment, %Segment{text: text}), + do: record_context(state, :transcript, text) + defp record_context(state, kind, text) when kind in [:transcript, :description] do bytes = state.active.input_bytes + byte_size(text) @@ -800,14 +856,18 @@ defmodule AudioFlow.Session do defp flush_output(state), do: AudioFlow.Output.call(state.output, :flush, [{self(), state.output_turn}]) + defp output_bytes(%Segment{} = segment), do: Segment.bytes(segment) defp output_bytes(%{data: data}) when is_binary(data), do: byte_size(data) defp output_bytes(text) when is_binary(text), do: byte_size(text) defp output_bytes(vector) when is_list(vector), do: length(vector) * 8 defp valid_output?(:audio, audio), do: Audio.valid?(audio) - defp valid_output?(kind, text) when kind in [:text, :transcript, :description], - do: is_binary(text) + defp valid_output?(:segment, segment), do: Segment.valid?(segment) + + defp valid_output?(kind, text) + when kind in [:text, :transcript, :partial_transcript, :description], + do: is_binary(text) defp valid_output?(:image, image), do: Image.valid?(image) defp valid_output?(:vector, vector), do: is_list(vector) and Enum.all?(vector, &is_number/1) @@ -854,6 +914,7 @@ defmodule AudioFlow.Session do defp metrics(active) do %{ duration_us: now() - active.started, + first_partial_transcript_us: active.first[:partial_transcript], first_transcript_us: active.first[:transcript], first_description_us: active.first[:description], first_text_us: active.first[:text], diff --git a/lib/audio_flow/transcript.ex b/lib/audio_flow/transcript.ex new file mode 100644 index 0000000..540f1b0 --- /dev/null +++ b/lib/audio_flow/transcript.ex @@ -0,0 +1,54 @@ +defmodule AudioFlow.Transcript do + @moduledoc """ + A complete transcript: the joined text and its timed segments. + + `AudioFlow.Transcription.transcribe/3` returns this struct. `to_srt/1` and + `to_vtt/1` format segments as captions. Each segment must have start and end + times for caption output. + """ + alias AudioFlow.Transcript.Segment + + @enforce_keys [:text, :segments] + defstruct [:text, :segments] + + @type t :: %__MODULE__{text: String.t(), segments: [Segment.t()]} + + @doc "Build a transcript from ordered segments. Empty segments are dropped." + def new(segments) do + segments = Enum.reject(segments, &(&1.text == "")) + %__MODULE__{text: Enum.map_join(segments, " ", & &1.text), segments: segments} + end + + @doc "Format timed segments as SubRip (SRT) captions." + def to_srt(%__MODULE__{segments: segments}) do + segments + |> Enum.with_index(1) + |> Enum.map_join("\n", fn {segment, index} -> + "#{index}\n#{time(segment.start_ms, ",")} --> #{time(segment.end_ms, ",")}\n#{segment.text}\n" + end) + end + + @doc "Format timed segments as WebVTT captions." + def to_vtt(%__MODULE__{segments: segments}) do + cues = + Enum.map(segments, fn segment -> + "#{time(segment.start_ms, ".")} --> #{time(segment.end_ms, ".")}\n#{segment.text}\n" + end) + + Enum.join(["WEBVTT\n" | cues], "\n") + end + + defp time(ms, separator) when is_integer(ms) and ms >= 0 do + hours = div(ms, 3_600_000) + minutes = ms |> div(60_000) |> rem(60) + seconds = ms |> div(1000) |> rem(60) + + [hours, minutes, seconds] + |> Enum.map_join(":", &pad(&1, 2)) + |> Kernel.<>(separator <> pad(rem(ms, 1000), 3)) + end + + defp time(_, _), do: raise(ArgumentError, "caption segments require start and end times") + + defp pad(value, width), do: value |> Integer.to_string() |> String.pad_leading(width, "0") +end diff --git a/lib/audio_flow/transcript/segment.ex b/lib/audio_flow/transcript/segment.ex new file mode 100644 index 0000000..f9ac4b4 --- /dev/null +++ b/lib/audio_flow/transcript/segment.ex @@ -0,0 +1,63 @@ +defmodule AudioFlow.Transcript.Segment do + @moduledoc """ + One final transcript segment. An STT adapter can emit this in place of a + string to give timing. + + `start_ms` and `end_ms` are offsets from the start of the adapter input, or + `nil` when the engine gives no timing. `words` is a list of maps with `:word`, + `:start_ms` and `:end_ms`, and an optional `:confidence`. + """ + @enforce_keys [:text] + defstruct [:text, start_ms: nil, end_ms: nil, words: []] + + @type word :: %{ + required(:word) => String.t(), + required(:start_ms) => non_neg_integer(), + required(:end_ms) => non_neg_integer(), + optional(:confidence) => number() + } + @type t :: %__MODULE__{ + text: String.t(), + start_ms: non_neg_integer() | nil, + end_ms: non_neg_integer() | nil, + words: [word()] + } + + def valid?(%__MODULE__{text: text, start_ms: start_ms, end_ms: end_ms, words: words}) do + is_binary(text) and String.valid?(text) and time?(start_ms) and time?(end_ms) and + (start_ms == nil or end_ms == nil or start_ms <= end_ms) and is_list(words) and + Enum.all?(words, &word?/1) + end + + def valid?(_), do: false + + @doc "Move the segment and its words later by `offset_ms`. Missing times stay missing." + def shift(%__MODULE__{} = segment, offset_ms) do + %{ + segment + | start_ms: add(segment.start_ms, offset_ms), + end_ms: add(segment.end_ms, offset_ms), + words: + Enum.map( + segment.words, + &%{&1 | start_ms: &1.start_ms + offset_ms, end_ms: &1.end_ms + offset_ms} + ) + } + end + + @doc "Approximate payload size, for session output limits." + def bytes(%__MODULE__{text: text, words: words}), + do: byte_size(text) + Enum.reduce(words, 0, &(byte_size(&1.word) + 24 + &2)) + + defp add(nil, _), do: nil + defp add(ms, offset), do: ms + offset + + defp time?(ms), do: ms == nil or (is_integer(ms) and ms >= 0) + + defp word?(%{word: word, start_ms: start_ms, end_ms: end_ms} = map) do + is_binary(word) and is_integer(start_ms) and is_integer(end_ms) and 0 <= start_ms and + start_ms <= end_ms and (not Map.has_key?(map, :confidence) or is_number(map.confidence)) + end + + defp word?(_), do: false +end diff --git a/lib/audio_flow/web_socket.ex b/lib/audio_flow/web_socket.ex index ce47209..19e63be 100644 --- a/lib/audio_flow/web_socket.ex +++ b/lib/audio_flow/web_socket.ex @@ -50,6 +50,9 @@ defmodule AudioFlow.WebSocket do * `flush` when the client must discard queued playback * `turn_started`, `transcript`, `description`, `text`, `done`, and `cancelled`, each with the connection-local integer `turn` + * `partial_transcript` with unstable `text`, when the STT adapter emits + partial results. A `transcript` from a timed segment also has `start_ms`, + `end_ms` and `words` * `history_cleared` * `error` with a `reason`, and a `turn` when a turn failed @@ -213,6 +216,9 @@ defmodule AudioFlow.WebSocket do {kind, text} when kind in [:transcript, :description, :text] -> reply([json(%{type: kind, turn: id, text: text})], state) + {kind, value} when kind in [:segment, :partial_transcript] -> + reply([json(transcript_message(id, kind, value))], state) + {kind, text, node} when kind in [:transcript, :description, :text] and is_binary(text) -> reply([json(%{type: kind, turn: id, text: text, node: node})], state) @@ -319,6 +325,20 @@ defmodule AudioFlow.WebSocket do defp json(message), do: {:text, JSON.encode!(message)} + defp transcript_message(id, :partial_transcript, text), + do: %{type: :partial_transcript, turn: id, text: text} + + defp transcript_message(id, :segment, segment) do + %{ + type: :transcript, + turn: id, + text: segment.text, + start_ms: segment.start_ms, + end_ms: segment.end_ms, + words: segment.words + } + end + defp reply({frames, state}), do: reply(frames, state) defp reply([], state), do: {:ok, state} defp reply(frames, state), do: {:push, frames, state} diff --git a/test/web_socket_test.exs b/test/web_socket_test.exs index f72097c..18eccc2 100644 --- a/test/web_socket_test.exs +++ b/test/web_socket_test.exs @@ -61,6 +61,38 @@ defmodule AudioFlow.WebSocketTest do assert done["metrics"]["events"] == 3 end + test "a transcription session sends partials and timed transcripts" do + stt = + function(fn _, emit -> + emit.({:partial, "hel"}) + + emit.(%AudioFlow.Transcript.Segment{ + text: "hello", + start_ms: 0, + end_ms: 400, + words: [%{word: "hello", start_ms: 0, end_ms: 400}] + }) + end) + + socket = connect(session: [stt: stt]) + ready(socket) + Client.send_binary(socket, silence(800)) + Client.send_json(socket, %{type: "commit"}) + + assert_json(socket, %{"type" => "turn_started", "turn" => 1}) + assert_json(socket, %{"type" => "partial_transcript", "turn" => 1, "text" => "hel"}) + + assert_json(socket, %{ + "type" => "transcript", + "text" => "hello", + "start_ms" => 0, + "end_ms" => 400, + "words" => [%{"word" => "hello", "start_ms" => 0, "end_ms" => 400}] + }) + + assert_json(socket, %{"type" => "done", "turn" => 1}) + end + test "a typed message skips transcription and the format is sent once" do socket = connect() ready(socket) From 36902882f1c41b1a569ab72b286f2f0ae8b1cd9f Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 12:00:54 +0200 Subject: [PATCH 2/8] feat(stt): emit Deepgram partials and segments, map Whisper segments --- docs/providers.md | 8 ++- lib/audio_flow/adapters/deepgram.ex | 76 +++++++++++++++++++++++++++-- lib_ml/audio_flow/nx_adapter.ex | 18 +++++++ test/nx_adapter_test.exs | 14 ++++++ test/remote_providers_test.exs | 63 ++++++++++++++++++++++++ 5 files changed, 174 insertions(+), 5 deletions(-) diff --git a/docs/providers.md b/docs/providers.md index e4b9752..dce72e5 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -28,8 +28,12 @@ tts = {AudioFlow.Adapters.ElevenLabs, Deepgram uses Listen v1 WebSocket with mono `linear16` PCM at the input `Audio.sample_rate`, sends bounded binary frames, then `CloseStream`. It emits -only final transcript segments, separated by spaces; the concluding Metadata -message completes the run. Interim results are ignored. This is a streaming +final transcript segments, separated by spaces; the concluding Metadata +message completes the run. Interim results are ignored by default. With +`interim_results: true`, each nonempty interim result is emitted as +`{:partial, text}`. With `segments: true`, final results are emitted as +`AudioFlow.Transcript.Segment` values with `start_ms`, `end_ms` and word times; +a final result without valid times fails with `:invalid_event`. This is a streaming provider response for an already committed utterance, **not** microphone-to-STT live ingress or a persistent recognition session. Optional `:language` is sent as a query parameter. Empty final transcripts (silence) emit nothing. diff --git a/lib/audio_flow/adapters/deepgram.ex b/lib/audio_flow/adapters/deepgram.ex index 2d79717..d122952 100644 --- a/lib/audio_flow/adapters/deepgram.ex +++ b/lib/audio_flow/adapters/deepgram.ex @@ -1,7 +1,14 @@ defmodule AudioFlow.Adapters.Deepgram do - @moduledoc "Deepgram Listen v1 WebSocket STT for a committed PCM utterance. See docs/providers.md." + @moduledoc """ + Deepgram Listen v1 WebSocket STT for a committed PCM utterance. See docs/providers.md. + + Set `interim_results: true` to emit `{:partial, text}` for interim results. + Set `segments: true` to emit timed `AudioFlow.Transcript.Segment` values in + place of strings. + """ @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.Socket + alias AudioFlow.Transcript.Segment @impl true def run(audio, options, emit) do @@ -13,9 +20,11 @@ defmodule AudioFlow.Adapters.Deepgram do "encoding" => "linear16", "sample_rate" => audio.sample_rate, "channels" => 1, - "interim_results" => false + "interim_results" => Keyword.get(options, :interim_results, false) == true } + segments? = Keyword.get(options, :segments, false) == true + params = if options[:language], do: Map.put(params, "language", options[:language]), else: params @@ -38,11 +47,23 @@ defmodule AudioFlow.Adapters.Deepgram do %{ "type" => "Results", "is_final" => true, + "channel" => %{"alternatives" => [%{"transcript" => text} = alternative | _]} + } = event, + seen + when is_binary(text) -> + if segments?, + do: final_segment(event, alternative, seen, emit), + else: final_transcript(text, seen, emit) + + %{ + "type" => "Results", + "is_final" => false, "channel" => %{"alternatives" => [%{"transcript" => text} | _]} }, seen when is_binary(text) -> - final_transcript(text, seen, emit) + if text != "", do: :ok = emit.({:partial, text}) + {:cont, seen, []} %{"type" => "Metadata"}, _ -> :done @@ -60,6 +81,55 @@ defmodule AudioFlow.Adapters.Deepgram do ) end + defp final_segment(event, alternative, seen, emit) do + with {:ok, start_ms, end_ms} <- result_time(event), + {:ok, words} <- words(Map.get(alternative, "words", [])) do + text = alternative["transcript"] + + if text != "", + do: :ok = emit.(%Segment{text: text, start_ms: start_ms, end_ms: end_ms, words: words}) + + {:cont, seen or text != "", []} + end + end + + defp result_time(%{"start" => start, "duration" => duration}) + when is_number(start) and is_number(duration) and start >= 0 and duration >= 0, + do: {:ok, ms(start), ms(start + duration)} + + defp result_time(_), do: {:error, :invalid_event} + + defp words(words) when is_list(words) do + Enum.reduce_while(words, {:ok, []}, fn + %{"word" => word, "start" => start, "end" => stop} = item, {:ok, acc} + when is_binary(word) and is_number(start) and is_number(stop) and 0 <= start and + start <= stop -> + word = %{ + word: if(is_binary(item["punctuated_word"]), do: item["punctuated_word"], else: word), + start_ms: ms(start), + end_ms: ms(stop) + } + + word = + if is_number(item["confidence"]), + do: Map.put(word, :confidence, item["confidence"]), + else: word + + {:cont, {:ok, [word | acc]}} + + _, _ -> + {:halt, {:error, :invalid_event}} + end) + |> case do + {:ok, words} -> {:ok, Enum.reverse(words)} + error -> error + end + end + + defp words(_), do: {:error, :invalid_event} + + defp ms(seconds), do: round(seconds * 1000) + defp final_transcript(text, seen, emit) do if text != "", do: :ok = emit.(if(seen, do: " " <> text, else: text)) {:cont, seen or text != "", []} diff --git a/lib_ml/audio_flow/nx_adapter.ex b/lib_ml/audio_flow/nx_adapter.ex index 456babb..e349f86 100644 --- a/lib_ml/audio_flow/nx_adapter.ex +++ b/lib_ml/audio_flow/nx_adapter.ex @@ -28,6 +28,24 @@ defmodule AudioFlow.NxAdapter do def transcript(%{chunks: chunks}), do: Enum.map(chunks, & &1.text) + @doc """ + Emit segments from a Whisper result. The times are `nil` unless the serving + uses `timestamps: :segments`. That option fails to compile with the pinned + Bumblebee 0.8.0 and EXLA 1.0.0. + """ + def transcript_segments(%{chunks: chunks}) do + for chunk <- chunks do + %AudioFlow.Transcript.Segment{ + text: String.trim(chunk.text), + start_ms: ms(chunk.start_timestamp_seconds), + end_ms: ms(chunk.end_timestamp_seconds) + } + end + end + + defp ms(nil), do: nil + defp ms(seconds), do: round(seconds * 1000) + @doc "Convert packed RGB bytes to an HWC unsigned 8-bit image tensor." def image_input(%AudioFlow.Image{} = image) do if not AudioFlow.Image.valid?(image), do: raise(ArgumentError, "invalid RGB image") diff --git a/test/nx_adapter_test.exs b/test/nx_adapter_test.exs index ab181d3..5c7d530 100644 --- a/test/nx_adapter_test.exs +++ b/test/nx_adapter_test.exs @@ -2,6 +2,20 @@ if System.get_env("AUDIOFLOW_ML") == "1" do defmodule AudioFlow.NxAdapterTest do use ExUnit.Case, async: false + test "Whisper chunks become segments, with or without timestamps" do + result = %{ + chunks: [ + %{text: " Hello.", start_timestamp_seconds: 0.0, end_timestamp_seconds: 1.52}, + %{text: " Bye.", start_timestamp_seconds: nil, end_timestamp_seconds: nil} + ] + } + + assert [ + %AudioFlow.Transcript.Segment{text: "Hello.", start_ms: 0, end_ms: 1520}, + %AudioFlow.Transcript.Segment{text: "Bye.", start_ms: nil, end_ms: nil} + ] = AudioFlow.NxAdapter.transcript_segments(result) + end + test "a shared EXLA serving maps inputs and outputs across callers" do serving = Nx.Serving.jit(&Nx.multiply(&1, 2), compiler: EXLA) start_supervised!(AudioFlow.Models.child_spec(AudioFlow.TestServing, serving)) diff --git a/test/remote_providers_test.exs b/test/remote_providers_test.exs index 341ed6e..187fd83 100644 --- a/test/remote_providers_test.exs +++ b/test/remote_providers_test.exs @@ -284,6 +284,69 @@ defmodule AudioFlow.RemoteProvidersTest do refute_receive {:output, "draft"} end + test "Deepgram emits interim partials and timed segments when requested" do + options = socket_options() ++ [interim_results: true, segments: true] + task = start_run(Deepgram, options, 16_000) + assert_receive {:connected, socket} + assert_receive {:handshake, _, query, _} + assert URI.decode_query(query)["interim_results"] == "true" + + event(socket, %{ + type: "Results", + is_final: false, + start: 0.0, + duration: 0.4, + channel: %{alternatives: [%{transcript: "hel"}]} + }) + + event(socket, %{ + type: "Results", + is_final: true, + start: 1.25, + duration: 0.5, + channel: %{ + alternatives: [ + %{ + transcript: "hello there", + words: [ + %{word: "hello", start: 1.25, end: 1.5, confidence: 0.9}, + %{word: "there", punctuated_word: "there.", start: 1.5, end: 1.75} + ] + } + ] + } + }) + + event(socket, %{type: "Metadata"}) + assert :ok = Task.await(task) + assert_receive {:output, {:partial, "hel"}} + + assert_receive {:output, + %AudioFlow.Transcript.Segment{ + text: "hello there", + start_ms: 1250, + end_ms: 1750, + words: [ + %{word: "hello", start_ms: 1250, end_ms: 1500, confidence: 0.9}, + %{word: "there.", start_ms: 1500, end_ms: 1750} + ] + }} + end + + test "Deepgram rejects final segments without valid times" do + task = start_run(Deepgram, socket_options() ++ [segments: true], 16_000) + assert_receive {:connected, socket} + + event(socket, %{ + type: "Results", + is_final: true, + channel: %{alternatives: [%{transcript: "hello"}]} + }) + + assert {:error, :invalid_event} = Task.await(task) + refute_receive {:output, _} + end + test "remote errors, malformed events, incomplete close, and response budget fail" do for {message, extra, expected} <- [ {{:event, %{error: %{message: "private"}}}, [], :remote_error}, From 483693a882430a13dc0f5665ffc416b89ea92002 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 12:00:55 +0200 Subject: [PATCH 3/8] feat(transcription): add batch transcription of long audio AudioFlow.transcribe/3 cuts audio into fixed windows or VAD utterances, runs any STT adapter per section and returns a timed transcript with SRT and WebVTT output. AudioFlow.Wav reads mono 16-bit PCM WAV files. --- README.md | 59 +++++++++ examples/transcribe.exs | 44 +++++++ lib/audio_flow.ex | 6 + lib/audio_flow/transcription.ex | 194 ++++++++++++++++++++++++++++ lib/audio_flow/wav.ex | 59 +++++++++ test/transcription_test.exs | 218 ++++++++++++++++++++++++++++++++ 6 files changed, 580 insertions(+) create mode 100644 examples/transcribe.exs create mode 100644 lib/audio_flow/transcription.ex create mode 100644 lib/audio_flow/wav.ex create mode 100644 test/transcription_test.exs diff --git a/README.md b/README.md index 8b4c32b..1f45348 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,65 @@ consume its mailbox. The event limit bounds output per turn, but does not bound the owner's mailbox across turns. An adapter must also bound individual output sizes. Do not pass an untrusted client directly as the owner. +## Transcription + +A session without `:llm` and `:tts` is a transcription session. Each audio turn +runs only the STT adapter and then ends with `{:done, metrics}`. Text input +returns `{:error, {:unsupported_input, :llm}}`, and `:history` is rejected. + +```elixir +stt = {AudioFlow.Adapters.Deepgram, + [model: "nova-3", segments: true, interim_results: true, + api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]} +{:ok, session} = AudioFlow.start_session(stt: stt) +{:ok, turn} = AudioFlow.submit(session, audio) +``` + +An STT adapter can emit three kinds of values, in any session: + +| Adapter output | Session event | In the prompt and history | +| --- | --- | --- | +| `text` | `{:transcript, text}` | yes | +| `%AudioFlow.Transcript.Segment{}` | `{:segment, segment}` | yes, joined with spaces | +| `{:partial, text}` | `{:partial_transcript, text}` | no | + +A segment has `text`, `start_ms` and `end_ms` from the start of the turn audio, +and optional `words` with their own times. Times are `nil` when the engine does +not give them. A partial is an unstable hypothesis for the text that follows +the final text emitted so far. The metrics add `first_partial_transcript_us`. +The WebSocket transport sends segments as `transcript` messages with timing +fields, and partials as `partial_transcript` messages. Recordings keep segment +text and drop partials. Graph sessions do not use these values. + +Deepgram partials arrive while the provider processes a committed utterance, +not while the user speaks. `AudioFlow.NxAdapter.transcript_segments/1` maps +Whisper output to segments. With the pinned Bumblebee 0.8.0 and EXLA 1.0.0, +Whisper `timestamps: :segments` fails to compile, so these segments have no +times inside a session. + +For a long recording, use `AudioFlow.transcribe/3`. It cuts the audio into +sections, runs the STT adapter on each section in a supervised task, and returns +an `AudioFlow.Transcript` with times from the start of the input: + +```elixir +{:ok, audio} = AudioFlow.Wav.read("meeting.wav") +{:ok, transcript} = AudioFlow.transcribe(audio, stt, chunk_ms: 30_000, max_concurrency: 4) +transcript.text +File.write!("meeting.srt", AudioFlow.Transcript.to_srt(transcript)) +``` + +Fixed sections can cut a word at a boundary. Set `:vad` to a voice detector +tuple to send only detected utterances; the audio must then use the detector +sample rate. Each section has its own `:timeout_ms` (120 seconds by default), +and the first failure returns `{:error, {:section, index, reason}}`. +`:on_segment` receives each segment in order. `AudioFlow.Wav` reads only mono +16-bit PCM WAV. Convert other files with FFmpeg. To print captions for a file: + +```sh +AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav +DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram +``` + ## Conversation history Enable history when the LLM adapter accepts chat messages: diff --git a/examples/transcribe.exs b/examples/transcribe.exs new file mode 100644 index 0000000..d99eaf6 --- /dev/null +++ b/examples/transcribe.exs @@ -0,0 +1,44 @@ +# Transcribe a mono 16-bit WAV file and print SubRip (SRT) captions. +# +# AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav +# DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram +# +# Local Whisper needs 16 kHz input. Convert other files first: +# ffmpeg -i input.mp3 -ac 1 -ar 16000 -sample_fmt s16 input.wav +[path | rest] = System.argv() +{:ok, audio} = AudioFlow.Wav.read(path) + +stt = + case rest do + ["deepgram"] -> + {AudioFlow.Adapters.Deepgram, + [ + model: "nova-3", + segments: true, + api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end + ]} + + [] -> + repository = "openai/whisper-tiny" + revision = "169d4a4341b33bc18d8881c4b69c2e104e1cc0af" + + # Whisper segments get the section times. `timestamps: :segments` fails to + # compile with the pinned Bumblebee 0.8.0 and EXLA 1.0.0. + {:ok, whisper} = AudioFlow.Models.whisper(repository, load_options: [revision: revision]) + + {:ok, _} = + Supervisor.start_link([AudioFlow.Models.child_spec(AudioFlow.Whisper, whisper)], + strategy: :one_for_one + ) + + {AudioFlow.NxAdapter, + [ + serving: AudioFlow.Whisper, + input: &AudioFlow.NxAdapter.whisper_input/1, + output: &AudioFlow.NxAdapter.transcript_segments/1 + ]} + end + +# Deepgram accepts at most 2 MB per request, so use sections of 60 seconds or less. +{:ok, transcript} = AudioFlow.transcribe(audio, stt, chunk_ms: 30_000) +IO.puts(AudioFlow.Transcript.to_srt(transcript)) diff --git a/lib/audio_flow.ex b/lib/audio_flow.ex index 695d329..5ec4f9a 100644 --- a/lib/audio_flow.ex +++ b/lib/audio_flow.ex @@ -5,6 +5,8 @@ defmodule AudioFlow do Each session sends `{AudioFlow, session_pid, turn_ref, event}` to its owner. Events are `{:transcript, text}`, `{:description, text}`, `{:text, text}`, `{:audio, audio}`, `{:done, metrics}`, `{:cancelled, metrics}`, or `{:error, reason, metrics}`. + STT adapters can also cause `{:segment, %AudioFlow.Transcript.Segment{}}` and + `{:partial_transcript, text}` events. See `AudioFlow.Session`. A session that runs an `AudioFlow.Graph` sends node outputs as `{kind, value, node_id}`, where kind can also be `:image` or `:vector`. """ @@ -18,6 +20,10 @@ defmodule AudioFlow do def submit(session, %AudioFlow.Image{} = image), do: GenServer.call(session, {:submit, image}) def submit(session, %AudioFlow.Text{} = text), do: GenServer.call(session, {:submit, text}) def cancel(session), do: GenServer.call(session, :cancel) + + @doc "Transcribe long PCM audio with an STT adapter. See `AudioFlow.Transcription`." + defdelegate transcribe(audio, stt, options \\ []), to: AudioFlow.Transcription + @doc "Clear saved conversation text while idle. Returns `{:error, :busy}` during a turn." def clear_history(session), do: GenServer.call(session, :clear_history) def stop_session(session), do: DynamicSupervisor.terminate_child(AudioFlow.Sessions, session) diff --git a/lib/audio_flow/transcription.ex b/lib/audio_flow/transcription.ex new file mode 100644 index 0000000..e4179cf --- /dev/null +++ b/lib/audio_flow/transcription.ex @@ -0,0 +1,194 @@ +defmodule AudioFlow.Transcription do + @moduledoc """ + Transcribes long PCM audio with any STT adapter, outside a session. + + The audio is cut into sections. Each section goes to the adapter, and its + output becomes timed `AudioFlow.Transcript.Segment` values. Times are offsets + from the start of the full input. The result is an `AudioFlow.Transcript`. + + Without `:vad`, sections are fixed windows of `:chunk_ms`. A window boundary + can cut a word. With `:vad`, a voice detector tuple, sections are the detected + utterances, and silence is not sent to the adapter. The audio must then use + the detector sample rate. `:endpoint_options` go to `AudioFlow.VoiceInput.new/2`. + Utterance times are accurate to one detector frame. + + An adapter can emit strings, segments, or `{:partial, text}`. Strings from one + section form one segment that spans the section. Segment times are relative + to the section start; a segment without times gets the section bounds. + Partial results are ignored. + + Each section runs in a supervised task with `:timeout_ms`. Up to + `:max_concurrency` sections run at the same time; results keep their order. + `:on_segment` receives each segment in order, in the calling process. The + first failure stops the work and returns `{:error, {:section, index, reason}}`. + """ + alias AudioFlow.Adapter + alias AudioFlow.Audio + alias AudioFlow.Transcript + alias AudioFlow.Transcript.Segment + alias AudioFlow.VoiceInput + + @options_schema [ + chunk_ms: [type: :pos_integer, default: 30_000], + vad: [type: {:tuple, [:atom, :keyword_list]}], + endpoint_options: [type: :keyword_list, default: []], + timeout_ms: [type: :pos_integer, default: 120_000], + max_concurrency: [type: :pos_integer, default: 1], + on_segment: [type: {:fun, 1}] + ] + + @doc "Options:\n\n" <> NimbleOptions.docs(@options_schema) + def transcribe(%Audio{} = audio, {module, adapter_options} = stt, options \\ []) + when is_atom(module) and is_list(adapter_options) do + unless Audio.valid?(audio), do: raise(ArgumentError, "expected mono s16le PCM") + options = NimbleOptions.validate!(options, @options_schema) + + audio + |> sections(options) + |> Enum.with_index() + |> then( + &Task.Supervisor.async_stream_nolink( + AudioFlow.Tasks, + &1, + fn section -> + run_section(stt, section) + end, + max_concurrency: options[:max_concurrency], + timeout: options[:timeout_ms], + on_timeout: :kill_task, + ordered: true + ) + ) + |> Enum.reduce_while({:ok, [], 0}, &collect(&1, &2, options[:on_segment])) + |> case do + {:ok, segments, _} -> {:ok, Transcript.new(Enum.reverse(segments))} + error -> error + end + end + + defp collect({:ok, {:ok, segments}}, {:ok, acc, index}, on_segment) do + if on_segment, do: Enum.each(segments, on_segment) + {:cont, {:ok, Enum.reverse(segments, acc), index + 1}} + end + + defp collect({:ok, {:error, reason}}, {:ok, _, index}, _), + do: {:halt, {:error, {:section, index, reason}}} + + defp collect({:exit, :timeout}, {:ok, _, index}, _), + do: {:halt, {:error, {:section, index, :timeout}}} + + defp collect({:exit, reason}, {:ok, _, index}, _), + do: {:halt, {:error, {:section, index, {:task_exit, reason}}}} + + defp run_section(stt, {{audio, start_ms}, _index}) do + key = make_ref() + Process.put(key, []) + + Adapter.run(stt, audio, fn output -> + Process.put(key, [output!(output) | Process.get(key)]) + :ok + end) + + end_ms = start_ms + duration_ms(audio) + {:ok, Process.get(key) |> Enum.reverse() |> segments(start_ms, end_ms)} + rescue + error -> {:error, {:exception, Exception.message(error)}} + catch + {:adapter_error, _module, reason} -> {:error, reason} + reason -> {:error, reason} + end + + defp output!(text) when is_binary(text), do: text + defp output!({:partial, text}) when is_binary(text), do: nil + + defp output!(%Segment{} = segment) do + if Segment.valid?(segment), do: segment, else: throw(:invalid_output) + end + + defp output!(_), do: throw(:invalid_output) + + defp segments(outputs, start_ms, end_ms) do + {timed, text} = + Enum.reduce(outputs, {[], []}, fn + nil, acc -> acc + %Segment{} = segment, {timed, text} -> {[segment | timed], text} + string, {timed, text} -> {timed, [string | text]} + end) + + text = text |> Enum.reverse() |> Enum.join() |> String.trim() + + timed = + timed + |> Enum.reverse() + |> Enum.map(&place(&1, start_ms, end_ms)) + + if text == "", + do: timed, + else: timed ++ [%Segment{text: text, start_ms: start_ms, end_ms: end_ms}] + end + + defp place(segment, start_ms, end_ms) do + segment = Segment.shift(%{segment | text: String.trim(segment.text)}, start_ms) + %{segment | start_ms: segment.start_ms || start_ms, end_ms: segment.end_ms || end_ms} + end + + defp sections(audio, options) do + case options[:vad] do + nil -> windows(audio, options[:chunk_ms]) + vad -> utterances(audio, vad, options[:endpoint_options]) + end + end + + defp windows(%Audio{data: data, sample_rate: rate}, chunk_ms) do + size = max(2, div(rate * chunk_ms, 1000) * 2) + + Stream.unfold(0, fn + offset when offset >= byte_size(data) -> + nil + + offset -> + part = binary_part(data, offset, min(size, byte_size(data) - offset)) + {{%Audio{data: part, sample_rate: rate}, div(offset * 1000, rate * 2)}, offset + size} + end) + end + + # Push one detector frame at a time, so an utterance ends at the current offset. + defp utterances(%Audio{data: data, sample_rate: rate} = audio, vad, endpoint_options) do + input = VoiceInput.new(vad, endpoint_options) + + unless input.rate == rate, + do: raise(ArgumentError, "audio must use the detector rate of #{input.rate} Hz") + + total = byte_size(data) + + Stream.resource( + fn -> {input, 0} end, + fn + :done -> + {:halt, :done} + + {input, offset} when offset >= total -> + {events, _} = VoiceInput.flush(input) + {utterance_sections(events, total, audio.sample_rate), :done} + + {input, offset} -> + size = min(input.frame_bytes, total - offset) + frame = %Audio{data: binary_part(data, offset, size), sample_rate: rate} + {events, input} = VoiceInput.push(input, frame) + offset = offset + size + {utterance_sections(events, offset, rate), {input, offset}} + end, + fn _ -> :ok end + ) + end + + defp utterance_sections(events, end_offset, rate) do + for {:utterance, audio, _reason} <- events do + # A flushed final frame is padded, so it can extend past the input. + {audio, div(max(0, end_offset - byte_size(audio.data)) * 1000, rate * 2)} + end + end + + defp duration_ms(%Audio{data: data, sample_rate: rate}), + do: div(byte_size(data) * 1000, rate * 2) +end diff --git a/lib/audio_flow/wav.ex b/lib/audio_flow/wav.ex new file mode 100644 index 0000000..f041ff2 --- /dev/null +++ b/lib/audio_flow/wav.ex @@ -0,0 +1,59 @@ +defmodule AudioFlow.Wav do + @moduledoc """ + Reads mono signed 16-bit PCM WAV data as `AudioFlow.Audio`. + + Other encodings, channel counts and sample sizes return + `{:error, :unsupported_wav}`. Convert them first, for example with + `ffmpeg -i input -ac 1 -ar 16000 -sample_fmt s16 output.wav`. + """ + alias AudioFlow.Audio + + def read(path) do + with {:ok, data} <- File.read(path), do: decode(data) + end + + def decode(<<"RIFF", _size::little-32, "WAVE", chunks::binary>>), do: chunks(chunks, nil) + def decode(_), do: {:error, :invalid_wav} + + def encode(%Audio{data: data, sample_rate: rate}) do + size = byte_size(data) + + <<"RIFF", size + 36::little-32, "WAVE", "fmt ", 16::little-32, 1::little-16, 1::little-16, + rate::little-32, rate * 2::little-32, 2::little-16, 16::little-16, "data", size::little-32, + data::binary>> + end + + defp chunks(<<"fmt ", size::little-32, body::binary-size(size), rest::binary>>, _format) do + format = + case body do + <> + when format in [1, 0xFFFE] and rate > 0 -> + rate + + _ -> + :unsupported + end + + chunks(skip_pad(rest, size), format) + end + + defp chunks(<<"data", _::little-32, _::binary>>, :unsupported), do: {:error, :unsupported_wav} + + defp chunks(<<"data", size::little-32, rest::binary>>, rate) when is_integer(rate) do + # Streamed WAV files can have an unknown (0 or 0xFFFFFFFF) data size. + size = if size == 0 or size > byte_size(rest), do: byte_size(rest), else: size + size = size - rem(size, 2) + {:ok, %Audio{data: binary_part(rest, 0, size), sample_rate: rate}} + end + + defp chunks(<<_id::binary-size(4), size::little-32, rest::binary>>, format) + when byte_size(rest) >= size, + do: chunks(skip_pad(binary_part(rest, size, byte_size(rest) - size), size), format) + + defp chunks(_, _), do: {:error, :invalid_wav} + + # RIFF chunks are padded to an even size. + defp skip_pad(<<_, rest::binary>>, size) when rem(size, 2) == 1, do: rest + defp skip_pad(rest, _size), do: rest +end diff --git a/test/transcription_test.exs b/test/transcription_test.exs new file mode 100644 index 0000000..aa81002 --- /dev/null +++ b/test/transcription_test.exs @@ -0,0 +1,218 @@ +defmodule AudioFlow.TranscriptionTest do + use ExUnit.Case, async: true + alias AudioFlow.Audio + alias AudioFlow.Text + alias AudioFlow.Transcript + alias AudioFlow.Transcript.Segment + alias AudioFlow.Wav + + defp function(fun), do: {AudioFlow.Adapters.Function, [run: fun]} + + defp start(options) do + {:ok, session} = AudioFlow.start_session(options) + on_exit(fn -> if Process.alive?(session), do: AudioFlow.stop_session(session) end) + session + end + + # 16 kHz PCM where each sample holds its own millisecond offset. + defp timeline(ms) do + data = for i <- 0..(ms * 16 - 1), into: <<>>, do: <> + %Audio{data: data, sample_rate: 16_000} + end + + defp first_ms(%Audio{data: <>}), do: ms + + describe "transcription session" do + test "ends the turn after STT, with segments and partials as events" do + owner = self() + + stt = + function(fn _audio, emit -> + emit.({:partial, "hel"}) + emit.(%Segment{text: "hello", start_ms: 0, end_ms: 400}) + emit.({:partial, "wor"}) + emit.(%Segment{text: " world ", start_ms: 400, end_ms: 900}) + end) + + session = start(stt: stt, owner: owner) + {:ok, turn} = AudioFlow.submit(session, %Audio{data: <<0, 0>>, sample_rate: 16_000}) + + assert_receive {AudioFlow, ^session, ^turn, {:partial_transcript, "hel"}} + assert_receive {AudioFlow, ^session, ^turn, {:segment, %Segment{text: "hello"}}} + assert_receive {AudioFlow, ^session, ^turn, {:partial_transcript, "wor"}} + assert_receive {AudioFlow, ^session, ^turn, {:segment, %Segment{start_ms: 400}}} + assert_receive {AudioFlow, ^session, ^turn, {:done, metrics}} + assert metrics.events == 4 + assert metrics.first_partial_transcript_us <= metrics.first_transcript_us + assert metrics.first_text_us == nil + end + + test "rejects text input, history, and only one of :llm and :tts" do + stt = function(fn _, emit -> emit.("hi") end) + session = start(stt: stt) + assert {:error, {:unsupported_input, :llm}} = AudioFlow.submit(session, %Text{data: "hi"}) + + Process.flag(:trap_exit, true) + assert {:error, _} = AudioFlow.start_session(stt: stt, history: true) + assert {:error, _} = AudioFlow.start_session(stt: stt, llm: stt) + end + + test "invalid segments fail the turn" do + stt = function(fn _, emit -> emit.(%Segment{text: "x", start_ms: 5, end_ms: 1}) end) + session = start(stt: stt) + {:ok, turn} = AudioFlow.submit(session, %Audio{data: <<0, 0>>, sample_rate: 16_000}) + assert_receive {AudioFlow, ^session, ^turn, {:error, :invalid_output, _}} + end + end + + test "segment text forms the LLM prompt; partials are excluded" do + owner = self() + + stt = + function(fn _, emit -> + emit.({:partial, "Hel"}) + emit.(%Segment{text: "Hello"}) + emit.(%Segment{text: "world"}) + end) + + llm = + function(fn prompt, _emit -> + send(owner, {:prompt, prompt}) + :ok + end) + + tts = function(fn _, _ -> :ok end) + session = start(stt: stt, llm: llm, tts: tts) + {:ok, turn} = AudioFlow.submit(session, %Audio{data: <<0, 0>>, sample_rate: 16_000}) + assert_receive {:prompt, "Hello world"} + assert_receive {AudioFlow, ^session, ^turn, {:done, _}} + end + + describe "batch transcription" do + test "fixed windows give ordered segments with input offsets" do + owner = self() + + stt = + function(fn audio, emit -> + send(owner, {:section, first_ms(audio), byte_size(audio.data)}) + emit.("part #{first_ms(audio)}") + end) + + assert {:ok, transcript} = + AudioFlow.transcribe(timeline(2500), stt, + chunk_ms: 1000, + max_concurrency: 3, + on_segment: &send(owner, {:segment, &1.start_ms}) + ) + + assert transcript.text == "part 0 part 1000 part 2000" + + assert Enum.map(transcript.segments, &{&1.start_ms, &1.end_ms}) == + [{0, 1000}, {1000, 2000}, {2000, 2500}] + + assert_receive {:section, 2000, 16_000} + + for start <- [0, 1000, 2000], + do: assert_receive({:segment, ^start}) + end + + test "adapter segment times are shifted by the section start" do + stt = + function(fn audio, emit -> + emit.(%Segment{ + text: " w ", + start_ms: 100, + end_ms: 200, + words: [%{word: "w", start_ms: 100, end_ms: 200}] + }) + + if first_ms(audio) == 1000, do: emit.(%Segment{text: "untimed"}) + :ok + end) + + {:ok, transcript} = AudioFlow.transcribe(timeline(2000), stt, chunk_ms: 1000) + + assert [ + %Segment{text: "w", start_ms: 100, end_ms: 200}, + %Segment{text: "w", start_ms: 1100, words: [%{start_ms: 1100, end_ms: 1200}]}, + %Segment{text: "untimed", start_ms: 1000, end_ms: 2000} + ] = transcript.segments + end + + test "voice detection sends only utterances, at their input offsets" do + owner = self() + frame = fn level, count -> :binary.copy(<>, 512 * count) end + # 32 ms frames: 10 silent, 10 speech, 20 silent, 10 speech, 10 silent. + data = + frame.(0, 10) <> + frame.(32_000, 10) <> frame.(0, 20) <> frame.(32_000, 10) <> frame.(0, 10) + + stt = + function(fn audio, emit -> + send(owner, {:utterance, byte_size(audio.data)}) + emit.("speech") + end) + + {:ok, transcript} = + AudioFlow.transcribe(%Audio{data: data, sample_rate: 16_000}, stt, + vad: {AudioFlow.Test.FrameDetector, []}, + endpoint_options: [pre_roll_ms: 0, min_speech_ms: 32, min_silence_ms: 320] + ) + + assert transcript.text == "speech speech" + assert [first, second] = transcript.segments + assert first.start_ms == 320 + assert second.start_ms == 1280 + assert first.end_ms > 640 and second.end_ms > 1600 + end + + test "the first failing section stops the work" do + stt = + function(fn audio, emit -> + if first_ms(audio) == 1000, do: {:error, :quota}, else: emit.("ok") + end) + + assert {:error, {:section, 1, :quota}} = + AudioFlow.transcribe(timeline(3000), stt, chunk_ms: 1000) + + slow = function(fn _, _ -> Process.sleep(1000) end) + + assert {:error, {:section, 0, :timeout}} = + AudioFlow.transcribe(timeline(100), slow, timeout_ms: 20) + + bad = function(fn _, emit -> emit.(:nope) end) + assert {:error, {:section, 0, :invalid_output}} = AudioFlow.transcribe(timeline(100), bad) + end + end + + test "WAV round trip and captions" do + audio = %Audio{data: <<1, 0, 2, 0, 3, 0>>, sample_rate: 22_050} + assert {:ok, ^audio} = audio |> Wav.encode() |> Wav.decode() + + stereo = + <<"RIFF", 0::little-32, "WAVE", "fmt ", 16::little-32, 1::little-16, 2::little-16, + 8000::little-32, 32_000::little-32, 4::little-16, 16::little-16, "data", 0::little-32>> + + assert {:error, :unsupported_wav} = Wav.decode(stereo) + assert {:error, :invalid_wav} = Wav.decode("not a wav") + + transcript = + Transcript.new([ + %Segment{text: "Hello.", start_ms: 0, end_ms: 1500}, + %Segment{text: "", start_ms: 1500, end_ms: 1600}, + %Segment{text: "Bye.", start_ms: 3_661_001, end_ms: 3_662_000} + ]) + + assert transcript.text == "Hello. Bye." + + assert Transcript.to_srt(transcript) == + "1\n00:00:00,000 --> 00:00:01,500\nHello.\n\n" <> + "2\n01:01:01,001 --> 01:01:02,000\nBye.\n" + + assert Transcript.to_vtt(transcript) == + "WEBVTT\n\n00:00:00.000 --> 00:00:01.500\nHello.\n\n" <> + "01:01:01.001 --> 01:01:02.000\nBye.\n" + + assert_raise ArgumentError, fn -> Transcript.to_srt(Transcript.new([%Segment{text: "x"}])) end + end +end From 8a86d4d026f8f6cc19641ecdbda04c44e97c63ce Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 12:12:20 +0200 Subject: [PATCH 4/8] feat(stt): add ReqLLM transcription adapter for Voxtral and other models AudioFlow.Adapters.ReqLLMTranscription sends each turn as WAV through ReqLLM.transcribe/3. It supports Mistral Voxtral, OpenAI, Groq, ElevenLabs, OpenRouter and self-hosted OpenAI-compatible servers such as vLLM, with optional timed segments. --- README.md | 26 ++++ examples/transcribe.exs | 14 +++ .../adapters/req_llm_transcription.ex | 70 +++++++++++ test/req_llm_transcription_test.exs | 119 ++++++++++++++++++ 4 files changed, 229 insertions(+) create mode 100644 lib/audio_flow/adapters/req_llm_transcription.ex create mode 100644 test/req_llm_transcription_test.exs diff --git a/README.md b/README.md index 1f45348..b22bbfd 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,31 @@ Whisper output to segments. With the pinned Bumblebee 0.8.0 and EXLA 1.0.0, Whisper `timestamps: :segments` fails to compile, so these segments have no times inside a session. +### Speech-to-text models + +| Engine | Adapter | Models | +| --- | --- | --- | +| Local Whisper | `AudioFlow.NxAdapter` with `AudioFlow.Models.whisper/2` | Bumblebee Whisper checkpoints | +| Deepgram | `AudioFlow.Adapters.Deepgram` | Nova and other Listen models | +| ReqLLM providers | `AudioFlow.Adapters.ReqLLMTranscription` | Mistral Voxtral, OpenAI Whisper and GPT-4o transcription, Groq Whisper, ElevenLabs Scribe, OpenRouter | +| Self-hosted servers | `AudioFlow.Adapters.ReqLLMTranscription` with `:base_url` | vLLM with Voxtral or Whisper, and other OpenAI-compatible `/audio/transcriptions` servers | + +```elixir +voxtral = {AudioFlow.Adapters.ReqLLMTranscription, + [model: "mistral:voxtral-mini-latest", segments: true, + provider_options: [timestamp_granularities: "segment"]]} + +local_voxtral = {AudioFlow.Adapters.ReqLLMTranscription, + [model: "vllm:mistralai/Voxtral-Mini-3B-2507", base_url: "http://localhost:8000/v1"]} +``` + +The ReqLLM adapter sends each turn as one WAV upload and emits after the +response. ReqLLM reads the provider key from its environment variable, for +example `MISTRAL_API_KEY`, or from `:api_key`. Retries are off by default. +Mistral does not accept `timestamp_granularities` together with `:language`. +Set `segments: true` only with segment timestamps; ReqLLM puts word timestamps +in the same list. + For a long recording, use `AudioFlow.transcribe/3`. It cuts the audio into sections, runs the STT adapter on each section in a supervised task, and returns an `AudioFlow.Transcript` with times from the start of the input: @@ -153,6 +178,7 @@ and the first failure returns `{:error, {:section, index, reason}}`. ```sh AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram +MISTRAL_API_KEY=... mix run examples/transcribe.exs input.wav mistral:voxtral-mini-latest ``` ## Conversation history diff --git a/examples/transcribe.exs b/examples/transcribe.exs index d99eaf6..4abbb2d 100644 --- a/examples/transcribe.exs +++ b/examples/transcribe.exs @@ -2,6 +2,10 @@ # # AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav # DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram +# MISTRAL_API_KEY=... mix run examples/transcribe.exs input.wav mistral:voxtral-mini-latest +# +# Any ReqLLM transcription model works, for example groq:whisper-large-v3-turbo +# or openai:gpt-4o-transcribe. For a local vLLM server, set AUDIOFLOW_STT_BASE_URL. # # Local Whisper needs 16 kHz input. Convert other files first: # ffmpeg -i input.mp3 -ac 1 -ar 16000 -sample_fmt s16 input.wav @@ -18,6 +22,16 @@ stt = api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end ]} + [model] -> + base_url = System.get_env("AUDIOFLOW_STT_BASE_URL") + + {AudioFlow.Adapters.ReqLLMTranscription, + [model: model, segments: true] ++ + if(String.starts_with?(model, "mistral:"), + do: [provider_options: [timestamp_granularities: "segment"]], + else: [] + ) ++ if(base_url, do: [base_url: base_url], else: [])} + [] -> repository = "openai/whisper-tiny" revision = "169d4a4341b33bc18d8881c4b69c2e104e1cc0af" diff --git a/lib/audio_flow/adapters/req_llm_transcription.ex b/lib/audio_flow/adapters/req_llm_transcription.ex new file mode 100644 index 0000000..ab930e4 --- /dev/null +++ b/lib/audio_flow/adapters/req_llm_transcription.ex @@ -0,0 +1,70 @@ +defmodule AudioFlow.Adapters.ReqLLMTranscription do + @moduledoc """ + STT through `ReqLLM.transcribe/3`, for any ReqLLM transcription provider. + + This covers Mistral Voxtral, OpenAI Whisper and GPT-4o transcription, Groq + Whisper, ElevenLabs Scribe, OpenRouter, and self-hosted OpenAI-compatible + servers such as vLLM with Voxtral or Whisper: + + {AudioFlow.Adapters.ReqLLMTranscription, model: "mistral:voxtral-mini-latest"} + {AudioFlow.Adapters.ReqLLMTranscription, model: "groq:whisper-large-v3-turbo"} + {AudioFlow.Adapters.ReqLLMTranscription, + model: "vllm:mistralai/Voxtral-Mini-3B-2507", base_url: "http://localhost:8000/v1"} + + Pass `:model` as any ReqLLM model input. The other options go to ReqLLM + unchanged, for example `:language`, `:provider_options`, `:base_url`, + `:api_key` and `:receive_timeout`. `:max_retries` defaults to 0, because the + session deadline bounds the turn. The input PCM is sent as a WAV file. The + adapter makes one request for each turn and emits after the response. + + By default the adapter emits the transcript text. Set `segments: true` to emit + timed `AudioFlow.Transcript.Segment` values. Request segment timestamps from + the provider: for Mistral, set `provider_options: [timestamp_granularities: + "segment"]`. ReqLLM puts word timestamps in the same list as segments, so do + not request word timestamps with `segments: true`. When the response has no + segments, the adapter emits the text. + """ + @behaviour AudioFlow.Adapter + alias AudioFlow.Audio + alias AudioFlow.Transcript.Segment + + @impl true + def run(%Audio{} = audio, options, emit) do + unless Audio.valid?(audio) and audio.data != <<>>, + do: raise(ArgumentError, "expected nonempty mono s16le PCM") + + {model, options} = Keyword.pop!(options, :model) + {segments?, options} = Keyword.pop(options, :segments, false) + options = Keyword.put_new(options, :max_retries, 0) + wav = AudioFlow.Wav.encode(audio) + + case ReqLLM.transcribe(model, {:binary, wav, "audio/wav"}, options) do + {:ok, result} -> + outputs(result, segments? == true) |> Enum.each(&(:ok = emit.(&1))) + + {:error, %{status: status}} when is_integer(status) -> + {:error, {:http_status, status}} + + {:error, error} when is_exception(error) -> + {:error, {:transcription, Exception.message(error)}} + + {:error, reason} -> + {:error, {:transcription, reason}} + end + end + + def run(_input, _options, _emit), do: raise(ArgumentError, "expected AudioFlow.Audio input") + + defp outputs(%{segments: [_ | _] = segments}, true) do + for segment <- segments, text = String.trim(segment.text), text != "" do + %Segment{text: text, start_ms: ms(segment.start_second), end_ms: ms(segment.end_second)} + end + end + + defp outputs(%{text: text}, _segments?) when is_binary(text) do + if String.trim(text) == "", do: [], else: [text] + end + + defp ms(seconds) when is_number(seconds) and seconds >= 0, do: round(seconds * 1000) + defp ms(_), do: nil +end diff --git a/test/req_llm_transcription_test.exs b/test/req_llm_transcription_test.exs new file mode 100644 index 0000000..3a4d903 --- /dev/null +++ b/test/req_llm_transcription_test.exs @@ -0,0 +1,119 @@ +defmodule AudioFlow.ReqLLMTranscriptionTest do + use ExUnit.Case, async: true + alias AudioFlow.Adapters.ReqLLMTranscription, as: STT + alias AudioFlow.Audio + alias AudioFlow.Transcript.Segment + + defmodule Endpoint do + @behaviour Plug + import Plug.Conn + + def init(options), do: options + + def call(conn, %{owner: owner, status: status, body: body}) do + options = Plug.Parsers.init(parsers: [:multipart], length: 1_000_000) + conn = Plug.Parsers.call(conn, options) + %Plug.Upload{} = upload = conn.params["file"] + + send(owner, { + :request, + conn.request_path, + get_req_header(conn, "authorization"), + Map.delete(conn.params, "file"), + {upload.content_type, File.read!(upload.path)} + }) + + conn |> put_resp_content_type("application/json") |> send_resp(status, JSON.encode!(body)) + end + end + + defp server(body, status \\ 200) do + plug = {Endpoint, %{owner: self(), status: status, body: body}} + + server = + start_supervised!({Bandit, plug: plug, port: 0, ip: {127, 0, 0, 1}, startup_log: false}) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + [base_url: "http://127.0.0.1:#{port}/v1", api_key: "test-key"] + end + + defp run(options) do + audio = %Audio{data: <<1, 0, 2, 0>>, sample_rate: 16_000} + owner = self() + + result = + STT.run(audio, options, fn value -> + send(owner, {:output, value}) + :ok + end) + + {result, collect([])} + end + + defp collect(acc) do + receive do + {:output, value} -> collect([value | acc]) + after + 0 -> Enum.reverse(acc) + end + end + + test "Voxtral receives WAV and provider options, and timed segments are emitted" do + body = %{ + model: "voxtral-mini-latest", + text: "Hello there. Bye.", + segments: [ + %{text: " Hello there.", start: 0.0, end: 1.25}, + %{text: " ", start: 1.25, end: 1.3}, + %{text: "Bye.", start: 1.5, end: 2.0} + ] + } + + options = + server(body) ++ + [ + model: "mistral:voxtral-mini-latest", + segments: true, + provider_options: [timestamp_granularities: "segment"] + ] + + assert {:ok, outputs} = run(options) + + assert outputs == [ + %Segment{text: "Hello there.", start_ms: 0, end_ms: 1250}, + %Segment{text: "Bye.", start_ms: 1500, end_ms: 2000} + ] + + assert_receive {:request, "/v1/audio/transcriptions", ["Bearer test-key"], params, file} + assert params["model"] == "voxtral-mini-latest" + assert params["timestamp_granularities"] == "segment" + assert params["max_retries"] == nil + + assert {:ok, %Audio{data: <<1, 0, 2, 0>>, sample_rate: 16_000}} = + AudioFlow.Wav.decode(elem(file, 1)) + + assert elem(file, 0) == "audio/wav" + end + + test "text is emitted without segments, and empty text emits nothing" do + options = server(%{text: "Hello world"}) ++ [model: "openai:whisper-1", language: "en"] + assert {:ok, ["Hello world"]} = run(options) + assert_receive {:request, _, _, %{"language" => "en", "model" => "whisper-1"}, _} + + options = server(%{text: " "}) ++ [model: "groq:whisper-large-v3-turbo"] + assert {:ok, []} = run(options) + end + + test "an HTTP failure fails the turn without output" do + options = server(%{error: %{message: "bad key"}}, 401) ++ [model: "openai:whisper-1"] + assert {{:error, {:http_status, 401}}, []} = run(options) + end + + test "a transcription session runs with this adapter" do + options = server(%{text: "Hello from Voxtral"}) ++ [model: "mistral:voxtral-mini-latest"] + {:ok, session} = AudioFlow.start_session(stt: {STT, options}) + {:ok, turn} = AudioFlow.submit(session, %Audio{data: <<1, 0>>, sample_rate: 16_000}) + assert_receive {AudioFlow, ^session, ^turn, {:transcript, "Hello from Voxtral"}}, 5000 + assert_receive {AudioFlow, ^session, ^turn, {:done, _}} + end +end From dc0cf5ac748eabb2268ede38eb8bc1e5fe4c9f52 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 12:12:21 +0200 Subject: [PATCH 5/8] feat(graph): add mistral.stt node for Voxtral transcription --- README.md | 2 +- lib/audio_flow/graph/providers.ex | 15 ++++++++++++++- test/req_llm_transcription_test.exs | 19 +++++++++++++++++++ ui/README.md | 11 ++++++----- 4 files changed, 40 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index b22bbfd..4ae1160 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ response. ReqLLM reads the provider key from its environment variable, for example `MISTRAL_API_KEY`, or from `:api_key`. Retries are off by default. Mistral does not accept `timestamp_granularities` together with `:language`. Set `segments: true` only with segment timestamps; ReqLLM puts word timestamps -in the same list. +in the same list. The graph editor has a `mistral.stt` node for Voxtral. For a long recording, use `AudioFlow.transcribe/3`. It cuts the audio into sections, runs the STT adapter on each section in a supervised task, and returns diff --git a/lib/audio_flow/graph/providers.ex b/lib/audio_flow/graph/providers.ex index c70ddef..3363c78 100644 --- a/lib/audio_flow/graph/providers.ex +++ b/lib/audio_flow/graph/providers.ex @@ -7,6 +7,7 @@ defmodule AudioFlow.Graph.Nodes.Providers do @behaviour AudioFlow.Graph.Node @providers %{ "deepgram.stt" => {AudioFlow.Adapters.Deepgram, "DEEPGRAM_API_KEY"}, + "mistral.stt" => {AudioFlow.Adapters.ReqLLMTranscription, "MISTRAL_API_KEY"}, "elevenlabs.tts" => {AudioFlow.Adapters.ElevenLabs, "ELEVENLABS_API_KEY"}, "cartesia.tts" => {AudioFlow.Adapters.Cartesia, "CARTESIA_API_KEY"} } @@ -16,7 +17,7 @@ defmodule AudioFlow.Graph.Nodes.Providers do @impl true def nodes do for {type, {_adapter, env}} <- Enum.sort(@providers) do - stt? = type == "deepgram.stt" + stt? = String.ends_with?(type, ".stt") %{ type: type, @@ -59,6 +60,18 @@ defmodule AudioFlow.Graph.Nodes.Providers do end @impl true + # ReqLLM reads MISTRAL_API_KEY at request time. A trusted endpoint is the API base URL. + def adapter("mistral.stt", options) do + endpoint = Application.get_env(:audio_flow, :speech_provider_endpoints, %{})["mistral.stt"] + {timeout, options} = Map.pop(options, :timeout_ms, 30_000) + {model, options} = Map.pop!(options, :model) + + {AudioFlow.Adapters.ReqLLMTranscription, + Map.to_list(options) ++ + [model: %{provider: :mistral, id: model}, receive_timeout: timeout] ++ + if(endpoint, do: [base_url: endpoint], else: [])} + end + def adapter(type, options) do {module, env} = Map.fetch!(@providers, type) endpoint = Application.get_env(:audio_flow, :speech_provider_endpoints, %{})[type] diff --git a/test/req_llm_transcription_test.exs b/test/req_llm_transcription_test.exs index 3a4d903..8068147 100644 --- a/test/req_llm_transcription_test.exs +++ b/test/req_llm_transcription_test.exs @@ -109,6 +109,25 @@ defmodule AudioFlow.ReqLLMTranscriptionTest do assert {{:error, {:http_status, 401}}, []} = run(options) end + test "the mistral.stt graph node runs Voxtral with a fixed provider and the server key" do + assert Enum.any?(AudioFlow.Graph.Nodes.Providers.nodes(), &(&1.type == "mistral.stt")) + + {STT, node_options} = + AudioFlow.Graph.Nodes.Providers.adapter("mistral.stt", %{ + model: "voxtral-mini-latest", + language: "en", + timeout_ms: 5000 + }) + + assert node_options[:model] == %{provider: :mistral, id: "voxtral-mini-latest"} + assert node_options[:receive_timeout] == 5000 + refute Keyword.has_key?(node_options, :api_key) + + options = Keyword.merge(node_options, server(%{text: "Bonjour"})) + assert {:ok, ["Bonjour"]} = run(options) + assert_receive {:request, _, _, %{"model" => "voxtral-mini-latest", "language" => "en"}, _} + end + test "a transcription session runs with this adapter" do options = server(%{text: "Hello from Voxtral"}) ++ [model: "mistral:voxtral-mini-latest"] {:ok, session} = AudioFlow.start_session(stt: {STT, options}) diff --git a/ui/README.md b/ui/README.md index 6b30233..94ffabc 100644 --- a/ui/README.md +++ b/ui/README.md @@ -126,11 +126,12 @@ returns passed: false. Saved graphs select their last text-output node and respect graph history settings. MCP offers evaluate_conversation with id/script. These checks do not grade audio or classify intents with a model. -Remote speech nodes are deepgram.stt, elevenlabs.tts and cartesia.tts. Create a -starter, select its node, and save model, language code and voice options. -Cartesia also requires an explicit API version; see [contracts](../docs/providers.md). -Set only the selected provider's DEEPGRAM_API_KEY, ELEVENLABS_API_KEY or -CARTESIA_API_KEY in the **server environment**, using your secret manager. +Remote speech nodes are deepgram.stt, mistral.stt (Voxtral), elevenlabs.tts and +cartesia.tts. Create a starter, select its node, and save model, language code +and voice options. Cartesia also requires an explicit API version; see +[contracts](../docs/providers.md). Set only the selected provider's +DEEPGRAM_API_KEY, MISTRAL_API_KEY, ELEVENLABS_API_KEY or CARTESIA_API_KEY in the +**server environment**, using your secret manager. Never paste credentials into graphs, scripts or browser/MCP payloads. Speech nodes accept neither raw keys nor arbitrary environment-variable names or URLs. A missing key disables dashboard runs and returns an MCP prerequisite error. From 8cce6c4128ad7e76b905c7ca341de3e6da931983 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 12:48:27 +0200 Subject: [PATCH 6/8] feat(stt)!: add common STT interface for ReqLLM and Bumblebee All speech-to-text now uses one interface, AudioFlow.STT, with the same :model, :language and :segments options and the same output: - AudioFlow.STT.ReqLLM for external services through ReqLLM.transcribe/3 (Mistral Voxtral, Deepgram, OpenAI, Groq, ElevenLabs, OpenRouter, vLLM). - AudioFlow.STT.DeepgramProvider, a ReqLLM provider for the Deepgram pre-recorded API, registered at application start. - AudioFlow.STT.Bumblebee for local Whisper, loaded on first use through AudioFlow.Servings, with one serving per model and language. - AudioFlow.Resampler converts any input rate for local models. Graph STT nodes, the examples and the chat example use these adapters. The chat example serves Qwen3-ASR through vLLM in place of the MLX sidecar. BREAKING CHANGE: AudioFlow.Adapters.Deepgram (WebSocket) is removed; use AudioFlow.STT.ReqLLM with "deepgram:". Deepgram interim partials are no longer emitted. AudioFlow.Adapters.ReqLLMTranscription is renamed to AudioFlow.STT.ReqLLM. NxAdapter.whisper_input/1, transcript/1 and transcript_segments/1 are removed; use AudioFlow.STT.Bumblebee. --- examples/chat/lib/chat/catalog.ex | 24 +- examples/chat/lib/chat/engine.ex | 3 +- examples/chat/lib/chat/setup.ex | 4 +- examples/chat/native/engine.ex | 66 +++--- examples/chat/native/qwen3_asr.ex | 96 -------- examples/chat/priv/python/qwen3_asr.py | 50 ----- examples/models.exs | 19 +- examples/transcribe.exs | 62 ++---- lib/audio_flow/adapters/deepgram.ex | 137 ------------ .../adapters/req_llm_transcription.ex | 70 ------ lib/audio_flow/application.ex | 3 + lib/audio_flow/graph/providers.ex | 18 +- lib/audio_flow/resampler.ex | 79 +++++++ lib/audio_flow/stt.ex | 53 +++++ lib/audio_flow/stt/deepgram_provider.ex | 86 ++++++++ lib/audio_flow/stt/req_llm.ex | 108 +++++++++ lib_ml/audio_flow/graph/models.ex | 21 +- lib_ml/audio_flow/nx_adapter.ex | 28 --- lib_ml/audio_flow/stt/bumblebee.ex | 106 +++++++++ test/graph_models_test.exs | 13 +- test/model_language_graph_test.exs | 5 +- test/native_pipeline_test.exs | 22 +- test/nx_adapter_test.exs | 47 ++-- test/remote_providers_test.exs | 95 +------- test/req_llm_transcription_test.exs | 138 ------------ test/resampler_test.exs | 51 +++++ test/stt_req_llm_test.exs | 206 ++++++++++++++++++ 27 files changed, 832 insertions(+), 778 deletions(-) delete mode 100644 examples/chat/native/qwen3_asr.ex delete mode 100644 examples/chat/priv/python/qwen3_asr.py delete mode 100644 lib/audio_flow/adapters/deepgram.ex delete mode 100644 lib/audio_flow/adapters/req_llm_transcription.ex create mode 100644 lib/audio_flow/resampler.ex create mode 100644 lib/audio_flow/stt.ex create mode 100644 lib/audio_flow/stt/deepgram_provider.ex create mode 100644 lib/audio_flow/stt/req_llm.ex create mode 100644 lib_ml/audio_flow/stt/bumblebee.ex delete mode 100644 test/req_llm_transcription_test.exs create mode 100644 test/resampler_test.exs create mode 100644 test/stt_req_llm_test.exs diff --git a/examples/chat/lib/chat/catalog.ex b/examples/chat/lib/chat/catalog.ex index f4a2b07..b5c166b 100644 --- a/examples/chat/lib/chat/catalog.ex +++ b/examples/chat/lib/chat/catalog.ex @@ -1,6 +1,7 @@ defmodule Chat.Catalog do @moduledoc """ - The models the chat can switch between. All run on the Apple GPU through MLX. + The models the chat can switch between. Local models run on the Apple GPU + through MLX. Qwen3-ASR runs on a separate vLLM server. `:memory_gb` estimates the loaded weights. Whisper loads in f32, so it uses about twice its f16 download. Compiled kernels and caches add to this. @@ -31,21 +32,22 @@ defmodule Chat.Catalog do revision: "41f01f3fe87f28c78e2fbf8b568835947dd65ed9", memory_gb: 3.2 }, + # Bumblebee has no Qwen3-ASR model. These use a vLLM server at + # CHAT_ASR_BASE_URL (default http://localhost:8000/v1) through ReqLLM. + # The server holds the weights, so they do not count in this process. %{ id: "qwen3-asr-0.6b", - label: "Qwen3-ASR 0.6B (8-bit)", - engine: :qwen3_asr, - repo: "mlx-community/Qwen3-ASR-0.6B-8bit", - revision: "89e96d92ba34aca20b3e29fb10cc284097d1219f", - memory_gb: 1.0 + label: "Qwen3-ASR 0.6B (vLLM)", + engine: :req_llm, + model: "vllm:Qwen/Qwen3-ASR-0.6B", + memory_gb: 0.0 }, %{ id: "qwen3-asr-1.7b", - label: "Qwen3-ASR 1.7B (8-bit)", - engine: :qwen3_asr, - repo: "mlx-community/Qwen3-ASR-1.7B-8bit", - revision: "a8379a2e2f9e313c9292cdf1af4055ab56d50d55", - memory_gb: 2.5 + label: "Qwen3-ASR 1.7B (vLLM)", + engine: :req_llm, + model: "vllm:Qwen/Qwen3-ASR-1.7B", + memory_gb: 0.0 } ] diff --git a/examples/chat/lib/chat/engine.ex b/examples/chat/lib/chat/engine.ex index d1ef6fa..1e62149 100644 --- a/examples/chat/lib/chat/engine.ex +++ b/examples/chat/lib/chat/engine.ex @@ -13,7 +13,8 @@ defmodule Chat.Engine do do: %{ id: __MODULE__, start: - {Supervisor, :start_link, [[Chat.Qwen3ASR, Chat.LocalEngine], [strategy: :one_for_one]]} + {Supervisor, :start_link, + [[AudioFlow.Servings, Chat.LocalEngine], [strategy: :one_for_one]]} }, else: %{id: __MODULE__, start: {Agent, :start_link, [fn -> nil end]}} end diff --git a/examples/chat/lib/chat/setup.ex b/examples/chat/lib/chat/setup.ex index f372bfa..7b4b634 100644 --- a/examples/chat/lib/chat/setup.ex +++ b/examples/chat/lib/chat/setup.ex @@ -81,9 +81,9 @@ defmodule Chat.Setup do [ stt: - {Adapters.Deepgram, + {AudioFlow.STT.ReqLLM, [ - model: env.("DEEPGRAM_MODEL") || "nova-3", + model: "deepgram:" <> (env.("DEEPGRAM_MODEL") || "nova-3"), api_key: key(env, "DEEPGRAM_API_KEY"), language: s["language"] ]}, diff --git a/examples/chat/native/engine.ex b/examples/chat/native/engine.ex index 0977901..6fb7d82 100644 --- a/examples/chat/native/engine.ex +++ b/examples/chat/native/engine.ex @@ -3,8 +3,9 @@ defmodule Chat.LocalEngine do Loads, swaps, and reports the shared models. One model per stage is loaded. Whisper and Kokoro run through Bumblebee and Transmuter on the EMLX GPU - backend. Qwen3 replies run through the native EMLXAxon generator. Qwen3-ASR - runs in the `Chat.Qwen3ASR` sidecar. Sessions call `Chat.Stage`, which reads + backend. Whisper uses the common local STT adapter, `AudioFlow.STT.Bumblebee`. + Qwen3 replies run through the native EMLXAxon generator. Qwen3-ASR runs on a + vLLM server through `AudioFlow.STT.ReqLLM`. Sessions call `Chat.Stage`, which reads the current adapter for each turn, so a switch applies to the next turn and keeps conversation history. @@ -18,8 +19,8 @@ defmodule Chat.LocalEngine do alias AudioFlow.Adapters.Function alias AudioFlow.Audio alias AudioFlow.NxAdapter + alias AudioFlow.STT.Bumblebee, as: LocalSTT alias Chat.Catalog - alias Chat.Qwen3ASR alias EMLXAxon.Qwen3.Loader @gpu {EMLX.Backend, device: :gpu} @@ -178,31 +179,21 @@ defmodule Chat.LocalEngine do model = Catalog.fetch!(:stt, id) silence = %Audio{data: :binary.copy(<<0, 0>>, 16_000), sample_rate: 16_000} - case model.engine do - :whisper -> - {:ok, serving} = - AudioFlow.Models.whisper(model.repo, - load_options: [revision: model.revision], - model_options: [backend: @gpu], - defn_options: @defn - ) - - {name, pid} = start_serving(:"Chat.STT.#{id}", serving) - - adapter = - {NxAdapter, - serving: name, input: &NxAdapter.whisper_input/1, output: &NxAdapter.transcript/1} - - Nx.Serving.batched_run(name, NxAdapter.whisper_input(silence)) - {:ok, %{adapter: adapter, serving: name, pid: pid}} - - :qwen3_asr -> - with {:ok, _} <- Qwen3ASR.load(model), - {:ok, _} <- Qwen3ASR.transcribe(model, silence.data) do - run = &transcribe_qwen3(model, &1, &2) - {:ok, %{adapter: {Function, run: run}, sidecar: true}} - end - end + adapter = + case model.engine do + :whisper -> + {LocalSTT, + model: model.repo, + revision: model.revision, + serving_options: [model_options: [backend: @gpu], defn_options: @defn]} + + :req_llm -> + base_url = System.get_env("CHAT_ASR_BASE_URL", "http://localhost:8000/v1") + {AudioFlow.STT.ReqLLM, model: model.model, base_url: base_url, api_key: "local"} + end + + # The first request loads the model, or checks the server, and compiles kernels. + with :ok <- warm_up(adapter, silence), do: {:ok, %{adapter: adapter}} end defp load(:llm, id) do @@ -214,11 +205,13 @@ defmodule Chat.LocalEngine do {:ok, %{adapter: {Function, run: &generate(tokenizer, weights, &1, &2)}}} end - defp transcribe_qwen3(model, %Audio{data: data}, emit) do - case Qwen3ASR.transcribe(model, data) do - {:ok, text} -> emit.(text) - {:error, reason} -> {:error, reason} + defp warm_up({module, options} = adapter, audio) do + with {:ok, _} <- + if(module == LocalSTT, do: module.preload(options), else: {:ok, nil}) do + AudioFlow.Adapter.run(adapter, audio, fn _ -> :ok end) end + catch + {:adapter_error, _module, reason} -> {:error, reason} end # Streams sentence chunks, so speech starts after the first sentence. @@ -257,11 +250,10 @@ defmodule Chat.LocalEngine do defp release(_state, %{pid: pid}), do: DynamicSupervisor.terminate_child(Chat.Servings, pid) - # The sidecar holds one model. Keep it while the STT stage uses it. - defp release(state, %{sidecar: true}) do - if not Map.get(state.loaded[:stt] || %{}, :sidecar, false) and - Catalog.fetch!(:stt, state.selection.stt).engine != :qwen3_asr, - do: Qwen3ASR.stop() + # Loads of the same model share one serving. Keep it while the STT stage uses it. + defp release(state, %{adapter: {LocalSTT, options} = adapter}) do + if get_in(state.loaded, [:stt, :adapter]) != adapter, + do: LocalSTT.release(options) :ok end diff --git a/examples/chat/native/qwen3_asr.ex b/examples/chat/native/qwen3_asr.ex deleted file mode 100644 index f4b5018..0000000 --- a/examples/chat/native/qwen3_asr.ex +++ /dev/null @@ -1,96 +0,0 @@ -defmodule Chat.Qwen3ASR do - @moduledoc """ - Qwen3-ASR through mlx-audio, in a Python process that `uv` manages. - - Bumblebee has no Qwen3-ASR model, so this stage runs outside Nx. The process - starts on first use and keeps one model loaded. Requests are JSON lines; see - `priv/python/qwen3_asr.py`. Its standard error goes to `log_path/0`. - """ - use GenServer - - def start_link(_), do: GenServer.start_link(__MODULE__, nil, name: __MODULE__) - - @doc "Load a model. Downloads it on first use." - def load(model, timeout \\ :infinity), - do: GenServer.call(__MODULE__, {:request, Map.take(model, [:repo, :revision]), nil}, timeout) - - @doc "Transcribe mono 16 kHz s16le PCM." - def transcribe(model, pcm, timeout \\ 60_000), - do: GenServer.call(__MODULE__, {:request, Map.take(model, [:repo, :revision]), pcm}, timeout) - - @doc "Stop the process and free its model memory." - def stop, do: GenServer.call(__MODULE__, :stop) - - def log_path, do: Path.join(System.tmp_dir!(), "audioflow-chat-qwen3-asr.log") - - @impl true - def init(nil), do: {:ok, %{port: nil, next: 1, pending: %{}, buffer: ""}} - - @impl true - def handle_call(:stop, _from, %{port: nil} = state), do: {:reply, :ok, state} - - def handle_call(:stop, _from, state) do - Port.close(state.port) - fail_pending(state, "Qwen3-ASR process stopped") - {:reply, :ok, %{state | port: nil, pending: %{}, buffer: ""}} - end - - def handle_call({:request, model, pcm}, from, state) do - state = ensure_port(state) - - request = - %{id: state.next, model: model.repo, revision: model.revision} - |> then(&if(pcm, do: Map.put(&1, :pcm, Base.encode64(pcm)), else: &1)) - - Port.command(state.port, [Jason.encode!(request), ?\n]) - - {:noreply, %{state | next: state.next + 1, pending: Map.put(state.pending, state.next, from)}} - end - - @impl true - def handle_info({port, {:data, {:noeol, data}}}, %{port: port} = state), - do: {:noreply, %{state | buffer: state.buffer <> data}} - - def handle_info({port, {:data, {:eol, data}}}, %{port: port} = state) do - line = state.buffer <> data - state = %{state | buffer: ""} - - case Jason.decode(line) do - {:ok, %{"id" => id} = reply} -> - {from, pending} = Map.pop(state.pending, id) - result = if reply["error"], do: {:error, reply["error"]}, else: {:ok, reply["text"]} - if from, do: GenServer.reply(from, result) - {:noreply, %{state | pending: pending}} - - _ -> - {:noreply, state} - end - end - - def handle_info({port, {:exit_status, status}}, %{port: port} = state) do - fail_pending(state, "Qwen3-ASR process exited (#{status}). See #{log_path()}") - {:noreply, %{state | port: nil, pending: %{}, buffer: ""}} - end - - def handle_info(_, state), do: {:noreply, state} - - defp fail_pending(state, message), - do: Enum.each(state.pending, fn {_, from} -> GenServer.reply(from, {:error, message}) end) - - defp ensure_port(%{port: nil} = state) do - uv = System.find_executable("uv") || raise "Qwen3-ASR needs uv: https://docs.astral.sh/uv/" - script = Application.app_dir(:chat, "priv/python/qwen3_asr.py") - - port = - Port.open({:spawn_executable, System.find_executable("sh")}, [ - :binary, - :exit_status, - {:line, 65_536}, - args: ["-c", ~s(exec "$0" run --quiet "$1" 2>>"$2"), uv, script, log_path()] - ]) - - %{state | port: port} - end - - defp ensure_port(state), do: state -end diff --git a/examples/chat/priv/python/qwen3_asr.py b/examples/chat/priv/python/qwen3_asr.py deleted file mode 100644 index 274b803..0000000 --- a/examples/chat/priv/python/qwen3_asr.py +++ /dev/null @@ -1,50 +0,0 @@ -# /// script -# requires-python = ">=3.11,<3.14" -# dependencies = ["mlx-audio==0.6.3"] -# /// -"""Qwen3-ASR on the Apple GPU through mlx-audio, for the chat example. - -Protocol: one JSON object per line on stdin and stdout. - {"id": 1, "model": "mlx-community/Qwen3-ASR-0.6B-8bit", "revision": "", - "pcm": ""} - -> {"id": 1, "text": "..."} or {"id": 1, "error": "..."} -The first request for a model loads it. One model stays loaded. A request -without "pcm" only loads the model. -""" - -import base64 -import json -import sys - -import numpy as np -from mlx_audio.stt.utils import load_model - -loaded = {} - - -def model_for(name, revision): - key = (name, revision) - if key not in loaded: - loaded.clear() - loaded[key] = load_model(name, revision=revision) - return loaded[key] - - -def reply(message): - sys.stdout.write(json.dumps(message) + "\n") - sys.stdout.flush() - - -for line in sys.stdin: - request = json.loads(line) - try: - model = model_for(request["model"], request.get("revision")) - if "pcm" not in request: - reply({"id": request["id"], "text": ""}) - continue - pcm = np.frombuffer(base64.b64decode(request["pcm"]), dtype=" - {AudioFlow.Adapters.Deepgram, - [ - model: "nova-3", - segments: true, - api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end - ]} - - [model] -> - base_url = System.get_env("AUDIOFLOW_STT_BASE_URL") - - {AudioFlow.Adapters.ReqLLMTranscription, - [model: model, segments: true] ++ - if(String.starts_with?(model, "mistral:"), - do: [provider_options: [timestamp_granularities: "segment"]], - else: [] - ) ++ if(base_url, do: [base_url: base_url], else: [])} - - [] -> - repository = "openai/whisper-tiny" - revision = "169d4a4341b33bc18d8881c4b69c2e104e1cc0af" - - # Whisper segments get the section times. `timestamps: :segments` fails to - # compile with the pinned Bumblebee 0.8.0 and EXLA 1.0.0. - {:ok, whisper} = AudioFlow.Models.whisper(repository, load_options: [revision: revision]) - - {:ok, _} = - Supervisor.start_link([AudioFlow.Models.child_spec(AudioFlow.Whisper, whisper)], - strategy: :one_for_one - ) - - {AudioFlow.NxAdapter, - [ - serving: AudioFlow.Whisper, - input: &AudioFlow.NxAdapter.whisper_input/1, - output: &AudioFlow.NxAdapter.transcript_segments/1 - ]} + if String.contains?(model, ":") do + base_url = System.get_env("AUDIOFLOW_STT_BASE_URL") + {AudioFlow.STT.ReqLLM, common ++ if(base_url, do: [base_url: base_url], else: [])} + else + {:ok, _} = AudioFlow.Servings.start_link() + revision = if model == "openai/whisper-tiny", do: "169d4a4341b33bc18d8881c4b69c2e104e1cc0af" + options = common ++ [revision: revision] + {:ok, _} = AudioFlow.STT.Bumblebee.preload(options) + {AudioFlow.STT.Bumblebee, options} end -# Deepgram accepts at most 2 MB per request, so use sections of 60 seconds or less. {:ok, transcript} = AudioFlow.transcribe(audio, stt, chunk_ms: 30_000) IO.puts(AudioFlow.Transcript.to_srt(transcript)) diff --git a/lib/audio_flow/adapters/deepgram.ex b/lib/audio_flow/adapters/deepgram.ex deleted file mode 100644 index d122952..0000000 --- a/lib/audio_flow/adapters/deepgram.ex +++ /dev/null @@ -1,137 +0,0 @@ -defmodule AudioFlow.Adapters.Deepgram do - @moduledoc """ - Deepgram Listen v1 WebSocket STT for a committed PCM utterance. See docs/providers.md. - - Set `interim_results: true` to emit `{:partial, text}` for interim results. - Set `segments: true` to emit timed `AudioFlow.Transcript.Segment` values in - place of strings. - """ - @behaviour AudioFlow.Adapter - alias AudioFlow.Adapters.Providers.Socket - alias AudioFlow.Transcript.Segment - - @impl true - def run(audio, options, emit) do - Socket.audio!(audio) - endpoint = Keyword.get(options, :endpoint, "wss://api.deepgram.com/v1/listen") - - params = %{ - "model" => Keyword.fetch!(options, :model), - "encoding" => "linear16", - "sample_rate" => audio.sample_rate, - "channels" => 1, - "interim_results" => Keyword.get(options, :interim_results, false) == true - } - - segments? = Keyword.get(options, :segments, false) == true - - params = - if options[:language], do: Map.put(params, "language", options[:language]), else: params - - chunks = for <>, do: {:binary, chunk} - remainder = rem(byte_size(audio.data), 16_000) - - chunks = - if remainder > 0, - do: - chunks ++ - [{:binary, binary_part(audio.data, byte_size(audio.data) - remainder, remainder)}], - else: chunks - - Socket.run( - Socket.url(endpoint, params), - [{"authorization", "Token " <> Socket.key(options)}], - chunks ++ [Socket.json(%{type: "CloseStream"})], - false, - fn - %{ - "type" => "Results", - "is_final" => true, - "channel" => %{"alternatives" => [%{"transcript" => text} = alternative | _]} - } = event, - seen - when is_binary(text) -> - if segments?, - do: final_segment(event, alternative, seen, emit), - else: final_transcript(text, seen, emit) - - %{ - "type" => "Results", - "is_final" => false, - "channel" => %{"alternatives" => [%{"transcript" => text} | _]} - }, - seen - when is_binary(text) -> - if text != "", do: :ok = emit.({:partial, text}) - {:cont, seen, []} - - %{"type" => "Metadata"}, _ -> - :done - - %{"type" => "Error"}, _ -> - {:error, :remote_error} - - %{"type" => type}, seen when type in ["Results", "SpeechStarted", "UtteranceEnd"] -> - {:cont, seen, []} - - _, _ -> - {:error, :invalid_event} - end, - options - ) - end - - defp final_segment(event, alternative, seen, emit) do - with {:ok, start_ms, end_ms} <- result_time(event), - {:ok, words} <- words(Map.get(alternative, "words", [])) do - text = alternative["transcript"] - - if text != "", - do: :ok = emit.(%Segment{text: text, start_ms: start_ms, end_ms: end_ms, words: words}) - - {:cont, seen or text != "", []} - end - end - - defp result_time(%{"start" => start, "duration" => duration}) - when is_number(start) and is_number(duration) and start >= 0 and duration >= 0, - do: {:ok, ms(start), ms(start + duration)} - - defp result_time(_), do: {:error, :invalid_event} - - defp words(words) when is_list(words) do - Enum.reduce_while(words, {:ok, []}, fn - %{"word" => word, "start" => start, "end" => stop} = item, {:ok, acc} - when is_binary(word) and is_number(start) and is_number(stop) and 0 <= start and - start <= stop -> - word = %{ - word: if(is_binary(item["punctuated_word"]), do: item["punctuated_word"], else: word), - start_ms: ms(start), - end_ms: ms(stop) - } - - word = - if is_number(item["confidence"]), - do: Map.put(word, :confidence, item["confidence"]), - else: word - - {:cont, {:ok, [word | acc]}} - - _, _ -> - {:halt, {:error, :invalid_event}} - end) - |> case do - {:ok, words} -> {:ok, Enum.reverse(words)} - error -> error - end - end - - defp words(_), do: {:error, :invalid_event} - - defp ms(seconds), do: round(seconds * 1000) - - defp final_transcript(text, seen, emit) do - if text != "", do: :ok = emit.(if(seen, do: " " <> text, else: text)) - {:cont, seen or text != "", []} - end -end diff --git a/lib/audio_flow/adapters/req_llm_transcription.ex b/lib/audio_flow/adapters/req_llm_transcription.ex deleted file mode 100644 index ab930e4..0000000 --- a/lib/audio_flow/adapters/req_llm_transcription.ex +++ /dev/null @@ -1,70 +0,0 @@ -defmodule AudioFlow.Adapters.ReqLLMTranscription do - @moduledoc """ - STT through `ReqLLM.transcribe/3`, for any ReqLLM transcription provider. - - This covers Mistral Voxtral, OpenAI Whisper and GPT-4o transcription, Groq - Whisper, ElevenLabs Scribe, OpenRouter, and self-hosted OpenAI-compatible - servers such as vLLM with Voxtral or Whisper: - - {AudioFlow.Adapters.ReqLLMTranscription, model: "mistral:voxtral-mini-latest"} - {AudioFlow.Adapters.ReqLLMTranscription, model: "groq:whisper-large-v3-turbo"} - {AudioFlow.Adapters.ReqLLMTranscription, - model: "vllm:mistralai/Voxtral-Mini-3B-2507", base_url: "http://localhost:8000/v1"} - - Pass `:model` as any ReqLLM model input. The other options go to ReqLLM - unchanged, for example `:language`, `:provider_options`, `:base_url`, - `:api_key` and `:receive_timeout`. `:max_retries` defaults to 0, because the - session deadline bounds the turn. The input PCM is sent as a WAV file. The - adapter makes one request for each turn and emits after the response. - - By default the adapter emits the transcript text. Set `segments: true` to emit - timed `AudioFlow.Transcript.Segment` values. Request segment timestamps from - the provider: for Mistral, set `provider_options: [timestamp_granularities: - "segment"]`. ReqLLM puts word timestamps in the same list as segments, so do - not request word timestamps with `segments: true`. When the response has no - segments, the adapter emits the text. - """ - @behaviour AudioFlow.Adapter - alias AudioFlow.Audio - alias AudioFlow.Transcript.Segment - - @impl true - def run(%Audio{} = audio, options, emit) do - unless Audio.valid?(audio) and audio.data != <<>>, - do: raise(ArgumentError, "expected nonempty mono s16le PCM") - - {model, options} = Keyword.pop!(options, :model) - {segments?, options} = Keyword.pop(options, :segments, false) - options = Keyword.put_new(options, :max_retries, 0) - wav = AudioFlow.Wav.encode(audio) - - case ReqLLM.transcribe(model, {:binary, wav, "audio/wav"}, options) do - {:ok, result} -> - outputs(result, segments? == true) |> Enum.each(&(:ok = emit.(&1))) - - {:error, %{status: status}} when is_integer(status) -> - {:error, {:http_status, status}} - - {:error, error} when is_exception(error) -> - {:error, {:transcription, Exception.message(error)}} - - {:error, reason} -> - {:error, {:transcription, reason}} - end - end - - def run(_input, _options, _emit), do: raise(ArgumentError, "expected AudioFlow.Audio input") - - defp outputs(%{segments: [_ | _] = segments}, true) do - for segment <- segments, text = String.trim(segment.text), text != "" do - %Segment{text: text, start_ms: ms(segment.start_second), end_ms: ms(segment.end_second)} - end - end - - defp outputs(%{text: text}, _segments?) when is_binary(text) do - if String.trim(text) == "", do: [], else: [text] - end - - defp ms(seconds) when is_number(seconds) and seconds >= 0, do: round(seconds * 1000) - defp ms(_), do: nil -end diff --git a/lib/audio_flow/application.ex b/lib/audio_flow/application.ex index 8196911..9101652 100644 --- a/lib/audio_flow/application.ex +++ b/lib/audio_flow/application.ex @@ -4,6 +4,9 @@ defmodule AudioFlow.Application do @impl true def start(_type, _args) do + # ReqLLM has no Deepgram provider; AudioFlow.STT.ReqLLM uses this one. + {:ok, :deepgram} = ReqLLM.Providers.register(AudioFlow.STT.DeepgramProvider) + children = [ {Finch, diff --git a/lib/audio_flow/graph/providers.ex b/lib/audio_flow/graph/providers.ex index 3363c78..83f69ed 100644 --- a/lib/audio_flow/graph/providers.ex +++ b/lib/audio_flow/graph/providers.ex @@ -6,12 +6,14 @@ defmodule AudioFlow.Graph.Nodes.Providers do """ @behaviour AudioFlow.Graph.Node @providers %{ - "deepgram.stt" => {AudioFlow.Adapters.Deepgram, "DEEPGRAM_API_KEY"}, - "mistral.stt" => {AudioFlow.Adapters.ReqLLMTranscription, "MISTRAL_API_KEY"}, + "deepgram.stt" => {AudioFlow.STT.ReqLLM, "DEEPGRAM_API_KEY"}, + "mistral.stt" => {AudioFlow.STT.ReqLLM, "MISTRAL_API_KEY"}, "elevenlabs.tts" => {AudioFlow.Adapters.ElevenLabs, "ELEVENLABS_API_KEY"}, "cartesia.tts" => {AudioFlow.Adapters.Cartesia, "CARTESIA_API_KEY"} } + @stt_providers %{"deepgram.stt" => :deepgram, "mistral.stt" => :mistral} + def providers, do: @providers @impl true @@ -60,15 +62,17 @@ defmodule AudioFlow.Graph.Nodes.Providers do end @impl true - # ReqLLM reads MISTRAL_API_KEY at request time. A trusted endpoint is the API base URL. - def adapter("mistral.stt", options) do - endpoint = Application.get_env(:audio_flow, :speech_provider_endpoints, %{})["mistral.stt"] + # STT nodes use ReqLLM with a fixed provider, so graph data cannot select another + # one. ReqLLM reads the provider key at request time. A trusted endpoint is the + # API base URL. + def adapter(type, options) when is_map_key(@stt_providers, type) do + endpoint = Application.get_env(:audio_flow, :speech_provider_endpoints, %{})[type] {timeout, options} = Map.pop(options, :timeout_ms, 30_000) {model, options} = Map.pop!(options, :model) - {AudioFlow.Adapters.ReqLLMTranscription, + {AudioFlow.STT.ReqLLM, Map.to_list(options) ++ - [model: %{provider: :mistral, id: model}, receive_timeout: timeout] ++ + [model: %{provider: @stt_providers[type], id: model}, receive_timeout: timeout] ++ if(endpoint, do: [base_url: endpoint], else: [])} end diff --git a/lib/audio_flow/resampler.ex b/lib/audio_flow/resampler.ex new file mode 100644 index 0000000..6be2fc7 --- /dev/null +++ b/lib/audio_flow/resampler.ex @@ -0,0 +1,79 @@ +defmodule AudioFlow.Resampler do + @moduledoc """ + Converts complete mono s16le PCM to another sample rate. + + It uses a polyphase windowed-sinc filter with 8 zero crossings on each side. + The cut-off is 0.9 of the lower Nyquist frequency, so downsampling removes + content that would alias. The conversion is not stateful: convert a complete + utterance, not separate stream chunks. It runs in Elixir. On an Apple M-series + CPU, one minute of 48 kHz input takes about 1.8 seconds, and one minute of + 8 kHz input about 0.9 seconds. + """ + alias AudioFlow.Audio + + @zero_crossings 8 + + def convert(%Audio{sample_rate: rate} = audio, rate), do: audio + + def convert(%Audio{} = audio, rate) when is_integer(rate) and rate > 0 do + unless Audio.valid?(audio), do: raise(ArgumentError, "expected mono s16le PCM") + divisor = Integer.gcd(audio.sample_rate, rate) + up = div(rate, divisor) + down = div(audio.sample_rate, divisor) + + count = div(byte_size(audio.data), 2) + output_count = div(count * up, down) + {table, half} = table(up, down) + # Zero padding keeps every filter window inside the input. + padding = :binary.copy(<<0, 0>>, half) + input = padding <> audio.data <> padding + width = 4 * half + + data = + for k <- 0..(output_count - 1)//1, into: <<>> do + position = k * down + # Window start: input sample center - half + 1, shifted by the padding. + start = div(position, up) + 1 + window = binary_part(input, 2 * start, width) + value = dot(window, elem(table, rem(position, up)), 0.0) + < round() |> max(-32_768) |> min(32_767)::little-signed-16>> + end + + %Audio{data: data, sample_rate: rate} + end + + defp dot(<>, [weight | weights], acc), + do: dot(rest, weights, acc + weight * sample) + + defp dot(<<>>, [], acc), do: acc + + # One weight list for each output phase. Weight j of phase p applies to input + # sample center - half + 1 + j, at distance (j + 1 - half - p / up) samples. + defp table(up, down) do + cutoff = 0.9 * min(1.0, up / down) + half = ceil(@zero_crossings / cutoff) + + phases = + for phase <- 0..(up - 1) do + offset = phase / up + + weights = + for j <- 0..(2 * half - 1) do + distance = j + 1 - half - offset + kernel(distance, cutoff, half) + end + + sum = Enum.sum(weights) + Enum.map(weights, &(&1 / sum)) + end + + {List.to_tuple(phases), half} + end + + defp kernel(distance, cutoff, half) do + window = 0.5 + 0.5 * :math.cos(:math.pi() * distance / half) + x = :math.pi() * cutoff * distance + sinc = if abs(x) < 1.0e-9, do: 1.0, else: :math.sin(x) / x + if abs(distance) >= half, do: 0.0, else: cutoff * sinc * window + end +end diff --git a/lib/audio_flow/stt.ex b/lib/audio_flow/stt.ex new file mode 100644 index 0000000..bbbaccb --- /dev/null +++ b/lib/audio_flow/stt.ex @@ -0,0 +1,53 @@ +defmodule AudioFlow.STT do + @moduledoc """ + The common speech-to-text interface. + + External services use `AudioFlow.STT.ReqLLM`, through ReqLLM. Local models use + `AudioFlow.STT.Bumblebee`, through Bumblebee. Both are `AudioFlow.Adapter` + modules with the same contract, so a session, a graph or + `AudioFlow.transcribe/3` can use either one: + + {AudioFlow.STT.ReqLLM, model: "mistral:voxtral-mini-latest", language: "en"} + {AudioFlow.STT.ReqLLM, model: "deepgram:nova-3", segments: true} + {AudioFlow.STT.Bumblebee, model: "openai/whisper-small", language: "en"} + + Both take: + + * `:model` - required. A ReqLLM model input, or a Hugging Face repository. + * `:language` - an ISO 639-1 code, or `nil` for detection. + * `:segments` - when `true`, emit `AudioFlow.Transcript.Segment` values in + place of text. Segment times are `nil` when the engine gives none. + + The input is one `AudioFlow.Audio` utterance at any sample rate. The adapter + converts it to the format that the engine needs. The adapter emits after the + engine finishes, as text strings or segments, never partial results. Other + options are specific to the engine. + """ + + @common_schema [ + model: [type: :any, required: true, doc: "The model to use."], + language: [type: {:or, [:string, nil]}, default: nil, doc: "ISO 639-1 language code."], + segments: [type: :boolean, default: false, doc: "Emit timed segments."] + ] + + @doc "Common options:\n\n" <> NimbleOptions.docs(@common_schema) + def common_schema, do: @common_schema + + @doc """ + Split adapter options into validated common options and the other options. + """ + def split_options!(options) do + {common, rest} = Keyword.split(options, Keyword.keys(@common_schema)) + {Map.new(NimbleOptions.validate!(common, @common_schema)), rest} + end + + @doc "Emit engine text or segments under the common `:segments` option." + def emit(segments, text, segments?, emit) do + outputs = + if segments? and segments != [], + do: Enum.reject(segments, &(&1.text == "")), + else: if(String.trim(text) == "", do: [], else: [text]) + + Enum.each(outputs, &(:ok = emit.(&1))) + end +end diff --git a/lib/audio_flow/stt/deepgram_provider.ex b/lib/audio_flow/stt/deepgram_provider.ex new file mode 100644 index 0000000..5cc216c --- /dev/null +++ b/lib/audio_flow/stt/deepgram_provider.ex @@ -0,0 +1,86 @@ +defmodule AudioFlow.STT.DeepgramProvider do + @moduledoc """ + A ReqLLM provider for Deepgram pre-recorded transcription (`POST /v1/listen`). + + ReqLLM has no Deepgram provider, so AudioFlow registers this one when it + starts. Use it through `AudioFlow.STT.ReqLLM` with a model such as + `"deepgram:nova-3"`. The key comes from `DEEPGRAM_API_KEY` or `:api_key`. + + `:language` becomes the `language` query parameter. `:provider_options` become + other query parameters, for example `smart_format: true` or + `utterances: true`. With `utterances: true`, Deepgram utterances become + ReqLLM segments with start and end times. + """ + use ReqLLM.Provider, + id: :deepgram, + default_base_url: "https://api.deepgram.com", + default_env_key: "DEEPGRAM_API_KEY" + + alias ReqLLM.Error.Invalid.Parameter + alias ReqLLM.Provider.Defaults + alias ReqLLM.Step + alias ReqLLM.Transcription.Result + + @impl ReqLLM.Provider + def prepare_request(:transcription, model_spec, audio_data, opts) do + with {:ok, model} <- ReqLLM.model(model_spec) do + timeout = Keyword.get(opts, :receive_timeout, 120_000) + http_options = Keyword.get(opts, :req_http_options, []) + + params = + [model: model.id, language: Keyword.get(opts, :language)] ++ + Enum.into(Keyword.get(opts, :provider_options, []), []) + + request = + Req.new( + [ + url: "/v1/listen", + method: :post, + base_url: Keyword.get(opts, :base_url, default_base_url()), + params: for({key, value} <- params, value != nil, do: {key, to_string(value)}), + headers: [ + {"authorization", "Token " <> ReqLLM.Keys.get!(model, opts)}, + {"content-type", Keyword.get(opts, :media_type, "audio/wav")} + ], + body: audio_data, + receive_timeout: timeout + ] ++ Defaults.merge_finch_options(http_options, pool_timeout: timeout) + ) + |> Step.Retry.attach(opts) + |> Step.Error.attach() + |> Req.Request.append_response_steps(deepgram_result: &result/1) + + {:ok, request} + end + end + + def prepare_request(operation, _model_spec, _input, _opts) do + {:error, + Parameter.exception( + parameter: "operation: #{inspect(operation)} is not supported by Deepgram" + )} + end + + @doc false + def result({request, %Req.Response{status: status, body: body} = response}) + when status in 200..299 and is_map(body) do + channel = get_in(body, ["results", "channels", Access.at(0)]) || %{} + alternative = get_in(channel, ["alternatives", Access.at(0)]) || %{} + utterances = get_in(body, ["results", "utterances"]) || [] + + segments = + for %{"transcript" => text, "start" => start, "end" => stop} <- utterances, + do: %{text: text, start_second: start, end_second: stop} + + result = %Result{ + text: alternative["transcript"] || "", + segments: segments, + language: channel["detected_language"], + duration_in_seconds: get_in(body, ["metadata", "duration"]) + } + + {request, %{response | body: result}} + end + + def result(pair), do: pair +end diff --git a/lib/audio_flow/stt/req_llm.ex b/lib/audio_flow/stt/req_llm.ex new file mode 100644 index 0000000..62e8799 --- /dev/null +++ b/lib/audio_flow/stt/req_llm.ex @@ -0,0 +1,108 @@ +defmodule AudioFlow.STT.ReqLLM do + @moduledoc """ + Speech-to-text with an external service, through `ReqLLM.transcribe/3`. + + This adapter follows the common `AudioFlow.STT` interface. `:model` is any + ReqLLM model input, for example: + + * `"mistral:voxtral-mini-latest"` - Mistral Voxtral + * `"deepgram:nova-3"` - Deepgram, through `AudioFlow.STT.DeepgramProvider` + * `"openai:gpt-4o-transcribe"` or `"openai:whisper-1"` + * `"groq:whisper-large-v3-turbo"`, ElevenLabs Scribe and OpenRouter models + * `"vllm:mistralai/Voxtral-Mini-3B-2507"` with `:base_url` - a self-hosted + server with an OpenAI-compatible `/audio/transcriptions` endpoint + + Other options go to ReqLLM unchanged, for example `:provider_options`, + `:base_url`, `:api_key` and `:receive_timeout`. `:api_key` can also be a + function of no arguments, called for each request. ReqLLM reads the API key from + the provider environment variable, for example `MISTRAL_API_KEY`, when + `:api_key` is not set. `:max_retries` defaults to 0, because the session + deadline bounds the turn. + + The input PCM is sent as one WAV file. The adapter makes one request for each + utterance. With `segments: true`, the adapter asks Mistral and Deepgram for + segment timestamps. OpenAI-compatible providers return segments for Whisper + models without a request; GPT-4o transcription models return only text, so + the adapter then emits text. ReqLLM puts word timestamps in the same list as + segments, so do not request word timestamps. Mistral does not accept segment + timestamps together with `:language`; the adapter then sends only the + language, and emits text. + """ + @behaviour AudioFlow.Adapter + alias AudioFlow.Audio + alias AudioFlow.STT + alias AudioFlow.Transcript.Segment + + @impl true + def run(%Audio{} = audio, options, emit) do + unless Audio.valid?(audio) and audio.data != <<>>, + do: raise(ArgumentError, "expected nonempty mono s16le PCM") + + {common, options} = STT.split_options!(options) + {:ok, model} = ReqLLM.model(model_input(common.model)) + + options = + options + |> Keyword.put_new(:max_retries, 0) + |> resolve_key() + |> put_language(common.language) + |> put_segments(model.provider, common.segments, common.language) + + case ReqLLM.transcribe(model, {:binary, AudioFlow.Wav.encode(audio), "audio/wav"}, options) do + {:ok, result} -> + STT.emit(segments(result.segments), result.text, common.segments, emit) + + {:error, %{status: status}} when is_integer(status) -> + {:error, {:http_status, status}} + + {:error, error} when is_exception(error) -> + {:error, {:transcription, Exception.message(error)}} + + {:error, reason} -> + {:error, {:transcription, reason}} + end + end + + def run(_input, _options, _emit), do: raise(ArgumentError, "expected AudioFlow.Audio input") + + # A key function runs at request time, so session options need not hold the key. + defp resolve_key(options) do + case Keyword.get(options, :api_key) do + key when is_function(key, 0) -> Keyword.put(options, :api_key, key.()) + _ -> options + end + end + + # Deepgram models are not in the ReqLLM catalog; an inline spec avoids a warning. + defp model_input("deepgram:" <> id), do: %{provider: :deepgram, id: id} + defp model_input(model), do: model + + defp put_language(options, nil), do: options + defp put_language(options, language), do: Keyword.put(options, :language, language) + + defp put_segments(options, :mistral, true, nil), + do: put_provider_option(options, :timestamp_granularities, "segment") + + defp put_segments(options, :deepgram, true, _language), + do: put_provider_option(options, :utterances, true) + + defp put_segments(options, _provider, _segments?, _language), do: options + + defp put_provider_option(options, key, value) do + provider_options = options |> Keyword.get(:provider_options, []) |> Enum.into([]) + Keyword.put(options, :provider_options, Keyword.put_new(provider_options, key, value)) + end + + defp segments(segments) do + for segment <- segments do + %Segment{ + text: String.trim(segment.text), + start_ms: ms(segment.start_second), + end_ms: ms(segment.end_second) + } + end + end + + defp ms(seconds) when is_number(seconds) and seconds >= 0, do: round(seconds * 1000) + defp ms(_), do: nil +end diff --git a/lib_ml/audio_flow/graph/models.ex b/lib_ml/audio_flow/graph/models.ex index 39b3680..aae8a52 100644 --- a/lib_ml/audio_flow/graph/models.ex +++ b/lib_ml/audio_flow/graph/models.ex @@ -62,7 +62,7 @@ defmodule AudioFlow.Graph.Nodes.Models do %{ type: "whisper.stt", title: "Whisper", - description: "Speech recognition. Needs 16 kHz mono PCM.", + description: "Speech recognition with local Whisper.", input: :audio, output: :text, event: :transcript, @@ -163,19 +163,14 @@ defmodule AudioFlow.Graph.Nodes.Models do @impl true def adapter("whisper.stt", %{model: model} = options) do language = Map.get(options, :language, "auto") - language_options = ModelLanguages.whisper_options!(model, language) + # Validate when the graph is built, not on the first turn. + ModelLanguages.whisper_options!(model, language) - serving( - {:whisper, model, language}, - fn -> - Models.whisper( - model, - [load_options: load(@whisper, model), model_options: exla()] ++ language_options - ) - end, - input: &NxAdapter.whisper_input/1, - output: &NxAdapter.transcript/1 - ) + {AudioFlow.STT.Bumblebee, + model: model, + language: if(language == "auto", do: nil, else: language), + revision: @whisper[model], + serving_options: [model_options: exla()]} end def adapter("qwen3.llm", options) do diff --git a/lib_ml/audio_flow/nx_adapter.ex b/lib_ml/audio_flow/nx_adapter.ex index e349f86..425dd48 100644 --- a/lib_ml/audio_flow/nx_adapter.ex +++ b/lib_ml/audio_flow/nx_adapter.ex @@ -18,34 +18,6 @@ defmodule AudioFlow.NxAdapter do :ok end - @doc "Convert mono PCM to a Whisper input tensor, without hidden resampling." - def whisper_input(%AudioFlow.Audio{sample_rate: 16_000, data: data}) do - samples = for <>, do: sample / 32_768 - Nx.tensor(samples, type: :f32) - end - - def whisper_input(_), do: raise(ArgumentError, "Whisper requires 16000 Hz mono PCM") - - def transcript(%{chunks: chunks}), do: Enum.map(chunks, & &1.text) - - @doc """ - Emit segments from a Whisper result. The times are `nil` unless the serving - uses `timestamps: :segments`. That option fails to compile with the pinned - Bumblebee 0.8.0 and EXLA 1.0.0. - """ - def transcript_segments(%{chunks: chunks}) do - for chunk <- chunks do - %AudioFlow.Transcript.Segment{ - text: String.trim(chunk.text), - start_ms: ms(chunk.start_timestamp_seconds), - end_ms: ms(chunk.end_timestamp_seconds) - } - end - end - - defp ms(nil), do: nil - defp ms(seconds), do: round(seconds * 1000) - @doc "Convert packed RGB bytes to an HWC unsigned 8-bit image tensor." def image_input(%AudioFlow.Image{} = image) do if not AudioFlow.Image.valid?(image), do: raise(ArgumentError, "invalid RGB image") diff --git a/lib_ml/audio_flow/stt/bumblebee.ex b/lib_ml/audio_flow/stt/bumblebee.ex new file mode 100644 index 0000000..1c2c7f5 --- /dev/null +++ b/lib_ml/audio_flow/stt/bumblebee.ex @@ -0,0 +1,106 @@ +defmodule AudioFlow.STT.Bumblebee do + @moduledoc """ + Speech-to-text with a local Whisper model, through Bumblebee. + + This adapter follows the common `AudioFlow.STT` interface. `:model` is a + Hugging Face Whisper repository, for example `"openai/whisper-small"`. + + {AudioFlow.STT.Bumblebee, model: "openai/whisper-small", language: "en"} + + Bumblebee fixes the language when it builds a serving. So the adapter loads + one shared serving for each model, revision, language and serving options, + through `AudioFlow.Servings`, on first use. All sessions share it. Add + `AudioFlow.Servings` to the inference children. Call `preload/1` at startup, + because the first load can take minutes. English-only `.en` models accept + only `nil` or `"en"`. + + Other options: + + * `:revision` - the repository revision. + * `:serving_options` - options for `AudioFlow.Models.whisper/2`, for + example `model_options: [backend: EXLA.Backend]` or + `defn_options: [compiler: EMLX]`. They default to EXLA. + + The input is converted to 16 kHz with `AudioFlow.Resampler`. With + `segments: true`, each Whisper chunk becomes a segment without times: with + the pinned Bumblebee 0.8.0 and EXLA 1.0.0, Whisper `timestamps: :segments` + fails to compile. `AudioFlow.transcribe/3` gives these segments their + section times. + """ + @behaviour AudioFlow.Adapter + alias AudioFlow.Audio + alias AudioFlow.STT + alias AudioFlow.Transcript.Segment + + @options_schema [ + revision: [type: {:or, [:string, nil]}, default: nil], + serving_options: [type: :keyword_list, default: [model_options: [backend: EXLA.Backend]]] + ] + + @impl true + def run(%Audio{} = audio, options, emit) do + unless Audio.valid?(audio) and audio.data != <<>>, + do: raise(ArgumentError, "expected nonempty mono s16le PCM") + + {common, serving} = options!(options) + + case fetch(common, serving) do + {:ok, name} -> + %{chunks: chunks} = Nx.Serving.batched_run(name, input(audio)) + segments = for chunk <- chunks, do: %Segment{text: String.trim(chunk.text)} + STT.emit(segments, Enum.map_join(chunks, & &1.text), common.segments, emit) + + {:error, reason} -> + {:error, {:model_load, reason}} + end + end + + def run(_input, _options, _emit), do: raise(ArgumentError, "expected AudioFlow.Audio input") + + @doc "Load the serving for these adapter options. Returns `{:ok, name}` or `{:error, reason}`." + def preload(options) do + {common, serving} = options!(options) + fetch(common, serving) + end + + @doc "Stop the serving for these adapter options. The next use loads it again." + def release(options) do + {common, serving} = options!(options) + AudioFlow.Servings.release(key(common, serving)) + end + + @doc "Convert PCM at any sample rate to the 16 kHz float tensor that Whisper needs." + def input(%Audio{} = audio) do + %Audio{data: data} = AudioFlow.Resampler.convert(audio, 16_000) + samples = for <>, do: sample / 32_768 + Nx.tensor(samples, type: :f32) + end + + defp options!(options) do + {common, rest} = STT.split_options!(options) + unless is_binary(common.model), do: raise(ArgumentError, "model must be a repository name") + {common, Map.new(NimbleOptions.validate!(rest, @options_schema))} + end + + defp key(common, serving), + do: {:whisper, common.model, serving.revision, common.language, serving.serving_options} + + defp fetch(common, serving) do + language_options = + AudioFlow.ModelLanguages.whisper_options!(common.model, common.language || "auto") + + key = key(common, serving) + load_options = if serving.revision, do: [revision: serving.revision], else: [] + + if Process.whereis(AudioFlow.Servings.Loader) == nil do + {:error, :servings_not_started} + else + AudioFlow.Servings.fetch(key, fn -> + AudioFlow.Models.whisper( + common.model, + [load_options: load_options] ++ serving.serving_options ++ language_options + ) + end) + end + end +end diff --git a/test/graph_models_test.exs b/test/graph_models_test.exs index ecf4253..f1a9a86 100644 --- a/test/graph_models_test.exs +++ b/test/graph_models_test.exs @@ -58,10 +58,15 @@ if System.get_env("AUDIOFLOW_ML") == "1" do {option.name, Map.get(option, :default, "x")} end - assert {AudioFlow.Graph.ModelAdapter, adapter} = - Models.adapter(spec.type, options) - - assert is_function(adapter[:build], 0) + case Models.adapter(spec.type, options) do + # Speech recognition uses the common local STT adapter. + {AudioFlow.STT.Bumblebee, adapter} -> + assert {_, _} = + AudioFlow.STT.split_options!(Keyword.take(adapter, [:model, :language])) + + {AudioFlow.Graph.ModelAdapter, adapter} -> + assert is_function(adapter[:build], 0) + end end # British voices share one serving with British English phonemes. diff --git a/test/model_language_graph_test.exs b/test/model_language_graph_test.exs index c0499ad..23c38ce 100644 --- a/test/model_language_graph_test.exs +++ b/test/model_language_graph_test.exs @@ -34,8 +34,9 @@ if System.get_env("AUDIOFLOW_ML") == "1" do {_, spanish} = Models.adapter("whisper.stt", %{model: "openai/whisper-tiny", language: "es"}) - assert auto[:key] == {:whisper, "openai/whisper-tiny", "auto"} - assert auto[:key] != spanish[:key] + assert auto[:language] == nil + assert spanish[:language] == "es" + assert auto[:revision] == spanish[:revision] assert_raise ArgumentError, ~r/English-only/, fn -> Models.adapter("whisper.stt", %{model: "openai/whisper-tiny.en", language: "es"}) diff --git a/test/native_pipeline_test.exs b/test/native_pipeline_test.exs index 4f87039..d6b5e3b 100644 --- a/test/native_pipeline_test.exs +++ b/test/native_pipeline_test.exs @@ -9,6 +9,7 @@ if System.get_env("AUDIOFLOW_ML") == "1" and System.get_env("AUDIOFLOW_MEDIA") = alias AudioFlow.Models alias AudioFlow.NxAdapter alias AudioFlow.Playback + alias AudioFlow.STT.Bumblebee alias Membrane.Testing.Notification test "recorded speech crosses the real Membrane, Whisper, Qwen3, and Kokoro path", %{ @@ -41,11 +42,15 @@ if System.get_env("AUDIOFLOW_ML") == "1" and System.get_env("AUDIOFLOW_MEDIA") = input_path = Path.join(tmp_dir, "speech.s16le") File.write!(input_path, pcm) - {:ok, whisper} = - Models.whisper("openai/whisper-tiny", - load_options: [revision: "169d4a4341b33bc18d8881c4b69c2e104e1cc0af"], - model_options: [backend: EXLA.Backend] - ) + start_supervised!(AudioFlow.Servings) + + whisper = [ + model: "openai/whisper-tiny", + revision: "169d4a4341b33bc18d8881c4b69c2e104e1cc0af" + ] + + {:ok, _} = Bumblebee.preload(whisper) + stt = {Bumblebee, whisper} {:ok, llm} = Models.language_model("Qwen/Qwen3-0.6B", @@ -65,18 +70,13 @@ if System.get_env("AUDIOFLOW_ML") == "1" and System.get_env("AUDIOFLOW_MEDIA") = load_options: [revision: "e71cae966052b992a7eca6b17738916ce0eca4ec"] ) - start_supervised!(Models.child_spec(AudioFlow.NativeWhisper, whisper)) start_supervised!(Models.child_spec(AudioFlow.NativeLLM, llm)) start_supervised!(Models.child_spec(AudioFlow.NativeTTS, kokoro)) start_supervised!(Models.child_spec(AudioFlow.NativeVAD, silero)) playback = start_supervised!({Playback, sink: Membrane.Testing.Sink, observer: self()}) options = [ - stt: - {NxAdapter, - serving: AudioFlow.NativeWhisper, - input: &NxAdapter.whisper_input/1, - output: &NxAdapter.transcript/1}, + stt: stt, llm: {NxAdapter, serving: AudioFlow.NativeLLM, diff --git a/test/nx_adapter_test.exs b/test/nx_adapter_test.exs index 5c7d530..1140439 100644 --- a/test/nx_adapter_test.exs +++ b/test/nx_adapter_test.exs @@ -1,20 +1,8 @@ if System.get_env("AUDIOFLOW_ML") == "1" do defmodule AudioFlow.NxAdapterTest do use ExUnit.Case, async: false - - test "Whisper chunks become segments, with or without timestamps" do - result = %{ - chunks: [ - %{text: " Hello.", start_timestamp_seconds: 0.0, end_timestamp_seconds: 1.52}, - %{text: " Bye.", start_timestamp_seconds: nil, end_timestamp_seconds: nil} - ] - } - - assert [ - %AudioFlow.Transcript.Segment{text: "Hello.", start_ms: 0, end_ms: 1520}, - %AudioFlow.Transcript.Segment{text: "Bye.", start_ms: nil, end_ms: nil} - ] = AudioFlow.NxAdapter.transcript_segments(result) - end + alias AudioFlow.Audio + alias AudioFlow.STT.Bumblebee test "a shared EXLA serving maps inputs and outputs across callers" do serving = Nx.Serving.jit(&Nx.multiply(&1, 2), compiler: EXLA) @@ -38,23 +26,42 @@ if System.get_env("AUDIOFLOW_ML") == "1" do end end - test "PCM conversion preserves signed sample values and rejects other rates" do - audio = %AudioFlow.Audio{ + test "local STT input keeps signed 16 kHz samples and resamples other rates" do + audio = %Audio{ data: <<-32_768::little-signed-16, 0::little-signed-16, 16_384::little-signed-16>>, sample_rate: 16_000 } - assert Nx.to_flat_list(AudioFlow.NxAdapter.whisper_input(audio)) == [-1.0, 0.0, 0.5] + assert Nx.to_flat_list(Bumblebee.input(audio)) == [-1.0, 0.0, 0.5] + + eight_khz = %Audio{data: :binary.copy(<<0, 0>>, 800), sample_rate: 8000} + assert Nx.size(Bumblebee.input(eight_khz)) == 1600 + end + + test "local STT reports a missing serving registry and rejects bad options" do + audio = %Audio{data: <<0, 0>>, sample_rate: 16_000} + emit = fn _ -> :ok end + + assert {:error, {:model_load, :servings_not_started}} = + Bumblebee.run(audio, [model: "openai/whisper-tiny"], emit) + + assert_raise ArgumentError, ~r/English-only/, fn -> + Bumblebee.run( + audio, + [model: "openai/whisper-tiny.en", language: "es"], + emit + ) + end - assert_raise ArgumentError, fn -> - AudioFlow.NxAdapter.whisper_input(%{audio | sample_rate: 8000}) + assert_raise NimbleOptions.ValidationError, fn -> + Bumblebee.run(audio, [model: "openai/whisper-tiny", unknown: 1], emit) end end test "synthesis PCM clamps model overshoot and emits little-endian samples" do output = %{audio: Nx.tensor([-1.5, -0.5, 0.0, 0.5, 1.5]), sampling_rate: 16_000} - assert [%AudioFlow.Audio{data: pcm, sample_rate: 16_000}] = + assert [%Audio{data: pcm, sample_rate: 16_000}] = AudioFlow.NxAdapter.speech_audio(output) assert pcm == diff --git a/test/remote_providers_test.exs b/test/remote_providers_test.exs index 187fd83..a164f96 100644 --- a/test/remote_providers_test.exs +++ b/test/remote_providers_test.exs @@ -1,7 +1,6 @@ defmodule AudioFlow.RemoteProvidersTest do use ExUnit.Case, async: true alias AudioFlow.Adapters.Cartesia - alias AudioFlow.Adapters.Deepgram alias AudioFlow.Adapters.ElevenLabs alias AudioFlow.Adapters.GeminiLive alias AudioFlow.Adapters.OpenAIRealtime @@ -260,93 +259,6 @@ defmodule AudioFlow.RemoteProvidersTest do end end - test "Deepgram sends PCM and CloseStream, excludes interim results and retains final segments" do - task = start_run(Deepgram, socket_options(), 16_000) - assert_receive {:connected, socket} - assert_receive {:handshake, _, query, headers} - assert URI.decode_query(query)["encoding"] == "linear16" - assert {"authorization", "Token test-key"} in headers - assert_receive {:client, ^socket, :binary, <<1, 0, 2, 0>>} - assert_receive {:client, ^socket, :text, %{"type" => "CloseStream"}} - - for {text, final} <- [{"draft", false}, {"Hello", true}, {"world", true}] do - event(socket, %{ - type: "Results", - is_final: final, - channel: %{alternatives: [%{transcript: text}]} - }) - end - - event(socket, %{type: "Metadata"}) - assert :ok = Task.await(task) - assert_receive {:output, "Hello"} - assert_receive {:output, " world"} - refute_receive {:output, "draft"} - end - - test "Deepgram emits interim partials and timed segments when requested" do - options = socket_options() ++ [interim_results: true, segments: true] - task = start_run(Deepgram, options, 16_000) - assert_receive {:connected, socket} - assert_receive {:handshake, _, query, _} - assert URI.decode_query(query)["interim_results"] == "true" - - event(socket, %{ - type: "Results", - is_final: false, - start: 0.0, - duration: 0.4, - channel: %{alternatives: [%{transcript: "hel"}]} - }) - - event(socket, %{ - type: "Results", - is_final: true, - start: 1.25, - duration: 0.5, - channel: %{ - alternatives: [ - %{ - transcript: "hello there", - words: [ - %{word: "hello", start: 1.25, end: 1.5, confidence: 0.9}, - %{word: "there", punctuated_word: "there.", start: 1.5, end: 1.75} - ] - } - ] - } - }) - - event(socket, %{type: "Metadata"}) - assert :ok = Task.await(task) - assert_receive {:output, {:partial, "hel"}} - - assert_receive {:output, - %AudioFlow.Transcript.Segment{ - text: "hello there", - start_ms: 1250, - end_ms: 1750, - words: [ - %{word: "hello", start_ms: 1250, end_ms: 1500, confidence: 0.9}, - %{word: "there.", start_ms: 1500, end_ms: 1750} - ] - }} - end - - test "Deepgram rejects final segments without valid times" do - task = start_run(Deepgram, socket_options() ++ [segments: true], 16_000) - assert_receive {:connected, socket} - - event(socket, %{ - type: "Results", - is_final: true, - channel: %{alternatives: [%{transcript: "hello"}]} - }) - - assert {:error, :invalid_event} = Task.await(task) - refute_receive {:output, _} - end - test "remote errors, malformed events, incomplete close, and response budget fail" do for {message, extra, expected} <- [ {{:event, %{error: %{message: "private"}}}, [], :remote_error}, @@ -390,12 +302,7 @@ defmodule AudioFlow.RemoteProvidersTest do end end - test "Deepgram errors and Gemini interruptions fail without fabricated output" do - task = start_run(Deepgram, socket_options(), 16_000) - assert_receive {:connected, socket} - event(socket, %{type: "Error", description: "private"}) - assert {:error, :remote_error} = Task.await(task) - + test "Gemini interruptions fail without fabricated output" do task = start_run(GeminiLive, socket_options(), 16_000) assert_receive {:connected, socket} event(socket, %{serverContent: %{interrupted: true}}) diff --git a/test/req_llm_transcription_test.exs b/test/req_llm_transcription_test.exs deleted file mode 100644 index 8068147..0000000 --- a/test/req_llm_transcription_test.exs +++ /dev/null @@ -1,138 +0,0 @@ -defmodule AudioFlow.ReqLLMTranscriptionTest do - use ExUnit.Case, async: true - alias AudioFlow.Adapters.ReqLLMTranscription, as: STT - alias AudioFlow.Audio - alias AudioFlow.Transcript.Segment - - defmodule Endpoint do - @behaviour Plug - import Plug.Conn - - def init(options), do: options - - def call(conn, %{owner: owner, status: status, body: body}) do - options = Plug.Parsers.init(parsers: [:multipart], length: 1_000_000) - conn = Plug.Parsers.call(conn, options) - %Plug.Upload{} = upload = conn.params["file"] - - send(owner, { - :request, - conn.request_path, - get_req_header(conn, "authorization"), - Map.delete(conn.params, "file"), - {upload.content_type, File.read!(upload.path)} - }) - - conn |> put_resp_content_type("application/json") |> send_resp(status, JSON.encode!(body)) - end - end - - defp server(body, status \\ 200) do - plug = {Endpoint, %{owner: self(), status: status, body: body}} - - server = - start_supervised!({Bandit, plug: plug, port: 0, ip: {127, 0, 0, 1}, startup_log: false}) - - {:ok, {_, port}} = ThousandIsland.listener_info(server) - [base_url: "http://127.0.0.1:#{port}/v1", api_key: "test-key"] - end - - defp run(options) do - audio = %Audio{data: <<1, 0, 2, 0>>, sample_rate: 16_000} - owner = self() - - result = - STT.run(audio, options, fn value -> - send(owner, {:output, value}) - :ok - end) - - {result, collect([])} - end - - defp collect(acc) do - receive do - {:output, value} -> collect([value | acc]) - after - 0 -> Enum.reverse(acc) - end - end - - test "Voxtral receives WAV and provider options, and timed segments are emitted" do - body = %{ - model: "voxtral-mini-latest", - text: "Hello there. Bye.", - segments: [ - %{text: " Hello there.", start: 0.0, end: 1.25}, - %{text: " ", start: 1.25, end: 1.3}, - %{text: "Bye.", start: 1.5, end: 2.0} - ] - } - - options = - server(body) ++ - [ - model: "mistral:voxtral-mini-latest", - segments: true, - provider_options: [timestamp_granularities: "segment"] - ] - - assert {:ok, outputs} = run(options) - - assert outputs == [ - %Segment{text: "Hello there.", start_ms: 0, end_ms: 1250}, - %Segment{text: "Bye.", start_ms: 1500, end_ms: 2000} - ] - - assert_receive {:request, "/v1/audio/transcriptions", ["Bearer test-key"], params, file} - assert params["model"] == "voxtral-mini-latest" - assert params["timestamp_granularities"] == "segment" - assert params["max_retries"] == nil - - assert {:ok, %Audio{data: <<1, 0, 2, 0>>, sample_rate: 16_000}} = - AudioFlow.Wav.decode(elem(file, 1)) - - assert elem(file, 0) == "audio/wav" - end - - test "text is emitted without segments, and empty text emits nothing" do - options = server(%{text: "Hello world"}) ++ [model: "openai:whisper-1", language: "en"] - assert {:ok, ["Hello world"]} = run(options) - assert_receive {:request, _, _, %{"language" => "en", "model" => "whisper-1"}, _} - - options = server(%{text: " "}) ++ [model: "groq:whisper-large-v3-turbo"] - assert {:ok, []} = run(options) - end - - test "an HTTP failure fails the turn without output" do - options = server(%{error: %{message: "bad key"}}, 401) ++ [model: "openai:whisper-1"] - assert {{:error, {:http_status, 401}}, []} = run(options) - end - - test "the mistral.stt graph node runs Voxtral with a fixed provider and the server key" do - assert Enum.any?(AudioFlow.Graph.Nodes.Providers.nodes(), &(&1.type == "mistral.stt")) - - {STT, node_options} = - AudioFlow.Graph.Nodes.Providers.adapter("mistral.stt", %{ - model: "voxtral-mini-latest", - language: "en", - timeout_ms: 5000 - }) - - assert node_options[:model] == %{provider: :mistral, id: "voxtral-mini-latest"} - assert node_options[:receive_timeout] == 5000 - refute Keyword.has_key?(node_options, :api_key) - - options = Keyword.merge(node_options, server(%{text: "Bonjour"})) - assert {:ok, ["Bonjour"]} = run(options) - assert_receive {:request, _, _, %{"model" => "voxtral-mini-latest", "language" => "en"}, _} - end - - test "a transcription session runs with this adapter" do - options = server(%{text: "Hello from Voxtral"}) ++ [model: "mistral:voxtral-mini-latest"] - {:ok, session} = AudioFlow.start_session(stt: {STT, options}) - {:ok, turn} = AudioFlow.submit(session, %Audio{data: <<1, 0>>, sample_rate: 16_000}) - assert_receive {AudioFlow, ^session, ^turn, {:transcript, "Hello from Voxtral"}}, 5000 - assert_receive {AudioFlow, ^session, ^turn, {:done, _}} - end -end diff --git a/test/resampler_test.exs b/test/resampler_test.exs new file mode 100644 index 0000000..1b334cc --- /dev/null +++ b/test/resampler_test.exs @@ -0,0 +1,51 @@ +defmodule AudioFlow.ResamplerTest do + use ExUnit.Case, async: true + alias AudioFlow.Audio + alias AudioFlow.Resampler + + defp tone(frequency, rate, seconds, amplitude \\ 10_000) do + data = + for i <- 0..(round(rate * seconds) - 1), into: <<>> do + value = round(amplitude * :math.sin(2 * :math.pi() * frequency * i / rate)) + <> + end + + %Audio{data: data, sample_rate: rate} + end + + # Root mean square of the middle half, away from the edges. + defp rms(%Audio{data: data}) do + samples = for <>, do: s + count = length(samples) + middle = Enum.slice(samples, div(count, 4), div(count, 2)) + :math.sqrt(Enum.sum(Enum.map(middle, &(&1 * &1))) / length(middle)) + end + + test "the same rate returns the input" do + audio = tone(440, 16_000, 0.01) + assert Resampler.convert(audio, 16_000) == audio + end + + test "common rates convert to 16 kHz with the expected length and level" do + for rate <- [8000, 22_050, 24_000, 44_100, 48_000] do + input = tone(1000, rate, 0.25) + output = Resampler.convert(input, 16_000) + assert output.sample_rate == 16_000 + assert byte_size(output.data) == div(byte_size(input.data) * 16_000, rate * 2) * 2 + assert_in_delta rms(output), rms(input), rms(input) * 0.03 + end + end + + test "downsampling removes content above the new Nyquist frequency" do + output = Resampler.convert(tone(11_000, 48_000, 0.25), 16_000) + assert rms(output) < 100 + end + + test "invalid input and rates are rejected" do + assert_raise ArgumentError, fn -> + Resampler.convert(%Audio{data: <<0>>, sample_rate: 8000}, 16_000) + end + + assert_raise FunctionClauseError, fn -> Resampler.convert(tone(1, 8000, 0.01), 0) end + end +end diff --git a/test/stt_req_llm_test.exs b/test/stt_req_llm_test.exs new file mode 100644 index 0000000..b20ca70 --- /dev/null +++ b/test/stt_req_llm_test.exs @@ -0,0 +1,206 @@ +defmodule AudioFlow.STTReqLLMTest do + use ExUnit.Case, async: true + alias AudioFlow.Audio + alias AudioFlow.Graph.Nodes.Providers + alias AudioFlow.STT.ReqLLM, as: STT + alias AudioFlow.Transcript.Segment + + # Records multipart (OpenAI-compatible) and raw-body (Deepgram) requests. + defmodule Endpoint do + @behaviour Plug + import Plug.Conn + + def init(options), do: options + + def call(conn, %{owner: owner, status: status, body: body}) do + conn = Plug.Conn.fetch_query_params(conn) + auth = get_req_header(conn, "authorization") + + {params, file} = + case get_req_header(conn, "content-type") do + ["multipart/form-data" <> _] -> + options = Plug.Parsers.init(parsers: [:multipart], length: 1_000_000) + conn = Plug.Parsers.call(conn, options) + upload = conn.params["file"] + + {Map.delete(conn.params, "file"), {upload.content_type, File.read!(upload.path)}} + + [type] -> + {:ok, data, _} = read_body(conn) + {conn.query_params, {type, data}} + end + + send(owner, {:request, conn.request_path, auth, params, file}) + conn |> put_resp_content_type("application/json") |> send_resp(status, JSON.encode!(body)) + end + end + + defp server(body, status \\ 200) do + plug = {Endpoint, %{owner: self(), status: status, body: body}} + + server = + start_supervised!({Bandit, plug: plug, port: 0, ip: {127, 0, 0, 1}, startup_log: false}) + + {:ok, {_, port}} = ThousandIsland.listener_info(server) + "http://127.0.0.1:#{port}" + end + + defp run(options, audio \\ %Audio{data: <<1, 0, 2, 0>>, sample_rate: 16_000}) do + owner = self() + + result = + STT.run(audio, options, fn value -> + send(owner, {:output, value}) + :ok + end) + + {result, collect([])} + end + + defp collect(acc) do + receive do + {:output, value} -> collect([value | acc]) + after + 0 -> Enum.reverse(acc) + end + end + + test "Voxtral receives WAV, and segments: true requests and emits timed segments" do + body = %{ + text: "Hello there. Bye.", + segments: [ + %{text: " Hello there.", start: 0.0, end: 1.25}, + %{text: " ", start: 1.25, end: 1.3}, + %{text: "Bye.", start: 1.5, end: 2.0} + ] + } + + url = server(body) <> "/v1" + options = [model: "mistral:voxtral-mini-latest", segments: true, base_url: url, api_key: "k"] + assert {:ok, outputs} = run(options) + + assert outputs == [ + %Segment{text: "Hello there.", start_ms: 0, end_ms: 1250}, + %Segment{text: "Bye.", start_ms: 1500, end_ms: 2000} + ] + + assert_receive {:request, "/v1/audio/transcriptions", ["Bearer k"], params, file} + assert params["model"] == "voxtral-mini-latest" + assert params["timestamp_granularities"] == "segment" + assert {"audio/wav", wav} = file + assert {:ok, %Audio{data: <<1, 0, 2, 0>>, sample_rate: 16_000}} = AudioFlow.Wav.decode(wav) + end + + test "Mistral gets only the language when both are set, and text is emitted" do + url = server(%{text: "Bonjour"}) <> "/v1" + + options = [ + model: "mistral:voxtral-mini-latest", + language: "fr", + segments: true, + base_url: url, + api_key: "k" + ] + + assert {:ok, ["Bonjour"]} = run(options) + assert_receive {:request, _, _, params, _} + assert params["language"] == "fr" + refute Map.has_key?(params, "timestamp_granularities") + end + + test "Deepgram goes through the ReqLLM provider with a raw WAV body" do + body = %{ + metadata: %{duration: 2.5}, + results: %{ + channels: [%{alternatives: [%{transcript: "hello world"}]}], + utterances: [ + %{transcript: "hello", start: 0.25, end: 0.75}, + %{transcript: "world", start: 1.0, end: 1.5} + ] + } + } + + url = server(body) + + options = [ + model: "deepgram:nova-3", + language: "en", + segments: true, + base_url: url, + api_key: "dg", + provider_options: [smart_format: true] + ] + + audio = %Audio{data: <<1, 0, 2, 0>>, sample_rate: 8000} + assert {:ok, segments} = run(options, audio) + + assert segments == [ + %Segment{text: "hello", start_ms: 250, end_ms: 750}, + %Segment{text: "world", start_ms: 1000, end_ms: 1500} + ] + + assert_receive {:request, "/v1/listen", ["Token dg"], params, {"audio/wav", wav}} + + assert params == %{ + "model" => "nova-3", + "language" => "en", + "smart_format" => "true", + "utterances" => "true" + } + + assert {:ok, %Audio{sample_rate: 8000}} = AudioFlow.Wav.decode(wav) + + url = server(%{results: %{channels: [%{alternatives: [%{transcript: "hi"}]}]}}) + assert {:ok, ["hi"]} = run(model: "deepgram:nova-3", base_url: url, api_key: fn -> "lazy" end) + assert_receive {:request, "/v1/listen", ["Token lazy"], _, _} + end + + test "text without segments, empty text, and HTTP failures" do + url = server(%{text: "Hello world"}) <> "/v1" + options = [model: "openai:whisper-1", language: "en", base_url: url, api_key: "k"] + assert {:ok, ["Hello world"]} = run(options) + assert_receive {:request, _, _, %{"language" => "en", "model" => "whisper-1"}, _} + + url = server(%{text: " "}) <> "/v1" + assert {:ok, []} = run(model: "groq:whisper-large-v3-turbo", base_url: url, api_key: "k") + + url = server(%{error: %{message: "bad key"}}, 401) <> "/v1" + + assert {{:error, {:http_status, 401}}, []} = + run(model: "openai:whisper-1", base_url: url, api_key: "k") + end + + test "the common options are validated" do + assert_raise NimbleOptions.ValidationError, fn -> + run(model: "openai:whisper-1", segments: "yes") + end + + assert_raise NimbleOptions.ValidationError, fn -> run(language: "en") end + end + + test "remote STT graph nodes use a fixed provider and the server key" do + for {type, provider} <- [{"mistral.stt", :mistral}, {"deepgram.stt", :deepgram}] do + assert Enum.any?(Providers.nodes(), &(&1.type == type)) + + assert {STT, options} = + Providers.adapter(type, %{ + model: "m", + language: "en", + timeout_ms: 5000 + }) + + assert options[:model] == %{provider: provider, id: "m"} + assert options[:receive_timeout] == 5000 + refute Keyword.has_key?(options, :api_key) + end + end + + test "a transcription session runs with this adapter" do + url = server(%{text: "Hello from Voxtral"}) <> "/v1" + options = [model: "mistral:voxtral-mini-latest", base_url: url, api_key: "k"] + {:ok, session} = AudioFlow.start_session(stt: {STT, options}) + {:ok, turn} = AudioFlow.submit(session, %Audio{data: <<1, 0>>, sample_rate: 16_000}) + assert_receive {AudioFlow, ^session, ^turn, {:transcript, "Hello from Voxtral"}}, 5000 + assert_receive {AudioFlow, ^session, ^turn, {:done, _}} + end +end From f70479462ec47d01fa61b9dc767059988c39b6ff Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 12:48:27 +0200 Subject: [PATCH 7/8] docs(stt): describe the common STT interface and ReqLLM Deepgram --- README.md | 127 +++++++++++------- docs/providers.md | 26 ++-- examples/chat/README.md | 18 ++- mise.toml | 2 +- site/src/content/docs/docs/chat-example.md | 12 +- .../content/docs/docs/features/providers.md | 24 ++-- .../content/docs/docs/guides/local-models.md | 4 +- ui/README.md | 7 +- 8 files changed, 131 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index 4ae1160..9af953b 100644 --- a/README.md +++ b/README.md @@ -98,15 +98,74 @@ sizes. Do not pass an untrusted client directly as the owner. ## Transcription +### Speech-to-text interface + +All speech-to-text adapters use one interface, `AudioFlow.STT`. External +services go through ReqLLM with `AudioFlow.STT.ReqLLM`. Local models go through +Bumblebee with `AudioFlow.STT.Bumblebee`. Both take the same options and give +the same output, so you can change the engine without other changes: + +```elixir +voxtral = {AudioFlow.STT.ReqLLM, model: "mistral:voxtral-mini-latest", language: "en"} +deepgram = {AudioFlow.STT.ReqLLM, model: "deepgram:nova-3", segments: true} +whisper = {AudioFlow.STT.Bumblebee, model: "openai/whisper-small", language: "en"} +``` + +| Option | Meaning | +| --- | --- | +| `:model` | Required. A ReqLLM model, or a Hugging Face Whisper repository. | +| `:language` | An ISO 639-1 code, or `nil` (the default) for detection. | +| `:segments` | `true` to emit timed `AudioFlow.Transcript.Segment` values in place of text. | + +The input is one `AudioFlow.Audio` utterance at any sample rate. The adapter +converts it for the engine. Output arrives when the engine finishes; there are +no partial results. Errors fail the turn. + +| Engine | Adapter | Models | +| --- | --- | --- | +| External services | `AudioFlow.STT.ReqLLM` | Mistral Voxtral, Deepgram, OpenAI Whisper and GPT-4o transcription, Groq Whisper, ElevenLabs Scribe, OpenRouter | +| Self-hosted servers | `AudioFlow.STT.ReqLLM` with `:base_url` | vLLM with Voxtral, Qwen3-ASR or Whisper, and other OpenAI-compatible `/audio/transcriptions` servers | +| Local models | `AudioFlow.STT.Bumblebee` | Bumblebee Whisper checkpoints | + +`AudioFlow.STT.ReqLLM` sends each utterance as one WAV upload. ReqLLM reads the +provider key from its environment variable, for example `MISTRAL_API_KEY` or +`DEEPGRAM_API_KEY`, or from `:api_key`, which can be a function. Other options +go to `ReqLLM.transcribe/3`. Retries are off by default, because the session +deadline bounds the turn. ReqLLM has no Deepgram provider, so AudioFlow +registers `AudioFlow.STT.DeepgramProvider` for the Deepgram `/v1/listen` API. + +```elixir +local_voxtral = {AudioFlow.STT.ReqLLM, + model: "vllm:mistralai/Voxtral-Mini-3B-2507", base_url: "http://localhost:8000/v1"} +``` + +With `segments: true`, the adapter asks Mistral and Deepgram for segment times. +OpenAI-compatible Whisper servers return segments without a request. GPT-4o +transcription models give only text, so the adapter then emits text. Mistral +does not accept segment times together with `:language`; the adapter then +sends only the language and emits text. + +`AudioFlow.STT.Bumblebee` loads one shared serving for each model, revision, +language and serving options, through `AudioFlow.Servings`, on first use. +Bumblebee fixes the Whisper language when it builds the serving. Add +`AudioFlow.Servings` to the inference children, and call +`AudioFlow.STT.Bumblebee.preload/1` at startup, because the first load can take +minutes. `:serving_options` select the backend and compiler (EXLA by default). +The adapter converts the input to 16 kHz with `AudioFlow.Resampler`. With the +pinned Bumblebee 0.8.0 and EXLA 1.0.0, Whisper `timestamps: :segments` fails to +compile, so local segments have no times inside a session. + +The graph editor has `whisper.stt` (local), `deepgram.stt` and `mistral.stt` +nodes. The remote nodes use a fixed provider and the server key. + +### Transcription sessions + A session without `:llm` and `:tts` is a transcription session. Each audio turn runs only the STT adapter and then ends with `{:done, metrics}`. Text input returns `{:error, {:unsupported_input, :llm}}`, and `:history` is rejected. ```elixir -stt = {AudioFlow.Adapters.Deepgram, - [model: "nova-3", segments: true, interim_results: true, - api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]} -{:ok, session} = AudioFlow.start_session(stt: stt) +{:ok, session} = AudioFlow.start_session(stt: deepgram) {:ok, turn} = AudioFlow.submit(session, audio) ``` @@ -120,42 +179,15 @@ An STT adapter can emit three kinds of values, in any session: A segment has `text`, `start_ms` and `end_ms` from the start of the turn audio, and optional `words` with their own times. Times are `nil` when the engine does -not give them. A partial is an unstable hypothesis for the text that follows -the final text emitted so far. The metrics add `first_partial_transcript_us`. -The WebSocket transport sends segments as `transcript` messages with timing -fields, and partials as `partial_transcript` messages. Recordings keep segment -text and drop partials. Graph sessions do not use these values. - -Deepgram partials arrive while the provider processes a committed utterance, -not while the user speaks. `AudioFlow.NxAdapter.transcript_segments/1` maps -Whisper output to segments. With the pinned Bumblebee 0.8.0 and EXLA 1.0.0, -Whisper `timestamps: :segments` fails to compile, so these segments have no -times inside a session. - -### Speech-to-text models - -| Engine | Adapter | Models | -| --- | --- | --- | -| Local Whisper | `AudioFlow.NxAdapter` with `AudioFlow.Models.whisper/2` | Bumblebee Whisper checkpoints | -| Deepgram | `AudioFlow.Adapters.Deepgram` | Nova and other Listen models | -| ReqLLM providers | `AudioFlow.Adapters.ReqLLMTranscription` | Mistral Voxtral, OpenAI Whisper and GPT-4o transcription, Groq Whisper, ElevenLabs Scribe, OpenRouter | -| Self-hosted servers | `AudioFlow.Adapters.ReqLLMTranscription` with `:base_url` | vLLM with Voxtral or Whisper, and other OpenAI-compatible `/audio/transcriptions` servers | - -```elixir -voxtral = {AudioFlow.Adapters.ReqLLMTranscription, - [model: "mistral:voxtral-mini-latest", segments: true, - provider_options: [timestamp_granularities: "segment"]]} - -local_voxtral = {AudioFlow.Adapters.ReqLLMTranscription, - [model: "vllm:mistralai/Voxtral-Mini-3B-2507", base_url: "http://localhost:8000/v1"]} -``` +not give them. The `AudioFlow.STT` adapters do not emit partials. A custom +adapter can emit them: a partial is an unstable hypothesis for the text that +follows the final text emitted so far. The metrics add +`first_partial_transcript_us`. The WebSocket transport sends segments as +`transcript` messages with timing fields, and partials as `partial_transcript` +messages. Recordings keep segment text and drop partials. Graph sessions do not +use these values. -The ReqLLM adapter sends each turn as one WAV upload and emits after the -response. ReqLLM reads the provider key from its environment variable, for -example `MISTRAL_API_KEY`, or from `:api_key`. Retries are off by default. -Mistral does not accept `timestamp_granularities` together with `:language`. -Set `segments: true` only with segment timestamps; ReqLLM puts word timestamps -in the same list. The graph editor has a `mistral.stt` node for Voxtral. +### Long recordings For a long recording, use `AudioFlow.transcribe/3`. It cuts the audio into sections, runs the STT adapter on each section in a supervised task, and returns @@ -163,7 +195,7 @@ an `AudioFlow.Transcript` with times from the start of the input: ```elixir {:ok, audio} = AudioFlow.Wav.read("meeting.wav") -{:ok, transcript} = AudioFlow.transcribe(audio, stt, chunk_ms: 30_000, max_concurrency: 4) +{:ok, transcript} = AudioFlow.transcribe(audio, voxtral, chunk_ms: 30_000, max_concurrency: 4) transcript.text File.write!("meeting.srt", AudioFlow.Transcript.to_srt(transcript)) ``` @@ -172,12 +204,13 @@ Fixed sections can cut a word at a boundary. Set `:vad` to a voice detector tuple to send only detected utterances; the audio must then use the detector sample rate. Each section has its own `:timeout_ms` (120 seconds by default), and the first failure returns `{:error, {:section, index, reason}}`. -`:on_segment` receives each segment in order. `AudioFlow.Wav` reads only mono -16-bit PCM WAV. Convert other files with FFmpeg. To print captions for a file: +`:on_segment` receives each segment in order. Segments without times get the +times of their section. `AudioFlow.Wav` reads only mono 16-bit PCM WAV. Convert +other files with FFmpeg. To print captions for a file: ```sh -AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav -DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram +AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav openai/whisper-small +DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram:nova-3 MISTRAL_API_KEY=... mix run examples/transcribe.exs input.wav mistral:voxtral-mini-latest ``` @@ -263,6 +296,7 @@ AUDIOFLOW_ML=1 mix run path/to/your_session.exs ``` `AudioFlow.Models.whisper/2` builds a Whisper serving with Bumblebee and EXLA. +`AudioFlow.STT.Bumblebee` uses it. `AudioFlow.Models.language_model/2` builds a streaming text serving. The selected repository must have a model architecture and tokenizer supported by Bumblebee. There is no automatic claim of support for each model named in the brief. @@ -342,8 +376,9 @@ the calling process. It can call an application-owned ONNX serving in the same way. `AudioFlow.Adapters.Function` can call a remote API or another local engine. Remote clients must set their own connection and request timeouts. -Whisper input conversion requires 16 kHz PCM. Resample before submission. -Whisper output is currently read after utterance transcription. LLM output is +For speech recognition, use `AudioFlow.STT.Bumblebee` (see +[Transcription](#transcription)). It converts the input to 16 kHz. Whisper +output is read after utterance transcription. LLM output is streamed and grouped into sentences before synthesis. This is not yet a continuous streaming speech recognizer. diff --git a/docs/providers.md b/docs/providers.md index dce72e5..fc0e8bb 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -12,8 +12,8 @@ accepting the same types). Model and voice IDs must be available to your account Keys may be strings or zero-argument functions; functions allow runtime rotation. ```elixir -stt = {AudioFlow.Adapters.Deepgram, - [model: "nova-3", api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]} +stt = {AudioFlow.STT.ReqLLM, + [model: "deepgram:nova-3", api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]} tts = {AudioFlow.Adapters.Cartesia, [model: "sonic-3.6", voice_id: System.fetch_env!("CARTESIA_VOICE_ID"), @@ -26,17 +26,15 @@ tts = {AudioFlow.Adapters.ElevenLabs, api_key: fn -> System.fetch_env!("ELEVENLABS_API_KEY") end]} ``` -Deepgram uses Listen v1 WebSocket with mono `linear16` PCM at the input -`Audio.sample_rate`, sends bounded binary frames, then `CloseStream`. It emits -final transcript segments, separated by spaces; the concluding Metadata -message completes the run. Interim results are ignored by default. With -`interim_results: true`, each nonempty interim result is emitted as -`{:partial, text}`. With `segments: true`, final results are emitted as -`AudioFlow.Transcript.Segment` values with `start_ms`, `end_ms` and word times; -a final result without valid times fails with `:invalid_event`. This is a streaming -provider response for an already committed utterance, **not** microphone-to-STT -live ingress or a persistent recognition session. Optional `:language` is sent -as a query parameter. Empty final transcripts (silence) emit nothing. +All speech-to-text from external services goes through ReqLLM with +`AudioFlow.STT.ReqLLM`, for Mistral Voxtral, Deepgram, OpenAI, Groq, ElevenLabs, +OpenRouter and self-hosted vLLM servers. See the common STT interface in the +[README](https://github.com/flowcopilot/audioflow#transcription). ReqLLM has no +Deepgram provider, so AudioFlow registers `AudioFlow.STT.DeepgramProvider`. +It sends the utterance as one WAV body to the pre-recorded `POST /v1/listen` +API, with `model`, optional `language` and `:provider_options` as query +parameters. With `segments: true`, it requests `utterances=true` and emits each +utterance as a timed segment. Deepgram interim results are not used. Cartesia uses `/tts/bytes` and ElevenLabs uses `/text-to-speech/:voice_id/stream`. Both stream raw signed 16-bit little-endian mono PCM as `AudioFlow.Audio`, default @@ -162,7 +160,7 @@ Wire shapes were checked against official documentation on 2026-11-03: - [OpenAI Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations) - [Gemini Live WebSocket reference](https://ai.google.dev/api/live) -- [Deepgram Listen streaming reference](https://developers.deepgram.com/reference/speech-to-text/listen-streaming) +- [Deepgram pre-recorded utterances](https://developers.deepgram.com/docs/utterances) - [Cartesia bytes TTS](https://docs.cartesia.ai/api-reference/tts/bytes) - [ElevenLabs streaming TTS](https://elevenlabs.io/docs/api-reference/text-to-speech/stream) diff --git a/examples/chat/README.md b/examples/chat/README.md index a23232a..a53da75 100644 --- a/examples/chat/README.md +++ b/examples/chat/README.md @@ -30,9 +30,8 @@ or model downloads are needed. Use the same profile for all Mix commands. ## Run native models on Apple Silicon The repository `mise.toml` pins Erlang, Elixir, Node.js, and -[uv](https://docs.astral.sh/uv/). uv runs the separate Qwen3-ASR Python -process; reply model downloads use Elixir's `hf_hub` and need no Python or -`uvx`. Kokoro also needs `espeak-ng`, which mise does not provide. +[uv](https://docs.astral.sh/uv/). Model downloads use Elixir's `hf_hub` and +need no Python. Kokoro also needs `espeak-ng`, which mise does not provide. ```sh mise install @@ -54,7 +53,7 @@ model per stage stays loaded. | Stage | Models | Runtime | | --- | --- | --- | | Speech recognition | Whisper tiny, small, large v3 turbo | Bumblebee on the EMLX GPU backend | -| Speech recognition | Qwen3-ASR 0.6B and 1.7B, 8-bit | mlx-audio in a Python process managed by uv | +| Speech recognition | Qwen3-ASR 0.6B and 1.7B | a vLLM server at `CHAT_ASR_BASE_URL`, through ReqLLM | | Reply | Qwen3 0.6B, 1.7B, 4B, and 8B, 4-bit | native EMLXAxon Qwen3 generation | | Speech | Kokoro 82M, four voices | Transmuter on the EMLX GPU backend | @@ -69,11 +68,16 @@ Measured on an Apple M5 with 24 GB of memory, after the first turn: | Models | First text | First audio | | --- | ---: | ---: | | Whisper small, Qwen3 1.7B | 0.9 s | 1.5 s | -| Qwen3-ASR 0.6B, Qwen3 0.6B | 0.3 s | 0.8 s | The first turn after a switch compiles the new model. It took up to 6 s to the -first audio. Bumblebee has no Qwen3-ASR model, so Qwen3-ASR runs outside the -BEAM. Its log is `$TMPDIR/audioflow-chat-qwen3-asr.log`. Model checkpoints for +first audio. + +Speech recognition uses the common `AudioFlow.STT` interface: local Whisper +through `AudioFlow.STT.Bumblebee`, and external services through +`AudioFlow.STT.ReqLLM`. Bumblebee has no Qwen3-ASR model, so Qwen3-ASR needs a +separate vLLM server, for example `vllm serve Qwen/Qwen3-ASR-1.7B`. Set +`CHAT_ASR_BASE_URL` when it does not listen on `http://localhost:8000/v1`. vLLM +needs a supported GPU; it does not use the Apple GPU. Model checkpoints for the reply stage use hf_hub's cache, by default `~/.cache/huggingface/hub/models--OWNER--REPO/snapshots/REVISION`. The pinned revisions in `Chat.Catalog` are passed unchanged, and this directory diff --git a/mise.toml b/mise.toml index ea7217f..714b6a6 100644 --- a/mise.toml +++ b/mise.toml @@ -1,7 +1,7 @@ [tools] erlang = "29.1.2" elixir = "1.20.4-otp-29" -# examples/chat: asset build, model downloads, and the Qwen3-ASR sidecar. +# examples/chat: asset build and model downloads. # Kokoro also needs espeak-ng, which mise does not provide: brew install espeak-ng node = "24.22.2" uv = "0.13.6" diff --git a/site/src/content/docs/docs/chat-example.md b/site/src/content/docs/docs/chat-example.md index 1feb3d2..7e1b89e 100644 --- a/site/src/content/docs/docs/chat-example.md +++ b/site/src/content/docs/docs/chat-example.md @@ -13,9 +13,8 @@ Apple Silicon Mac with macOS 26.2 or later. ## Run -The repository `mise.toml` pins Erlang, Elixir, Node.js, and uv. uv runs the -separate Qwen3-ASR Python process. The reply models download through Elixir's -`hf_hub` and need no Python. Kokoro also needs `espeak-ng`, which mise does not +The repository `mise.toml` pins Erlang, Elixir, Node.js, and uv. The models +download through Elixir's `hf_hub` and need no Python. Kokoro also needs `espeak-ng`, which mise does not provide. ```sh @@ -37,7 +36,7 @@ A switch applies to the next turn and keeps the conversation history. | Stage | Models | Runtime | | --- | --- | --- | | Speech recognition | Whisper tiny, small, large v3 turbo | Bumblebee on the EMLX GPU backend | -| Speech recognition | Qwen3-ASR 0.6B and 1.7B, 8-bit | mlx-audio in a Python process managed by uv | +| Speech recognition | Qwen3-ASR 0.6B and 1.7B | a vLLM server at `CHAT_ASR_BASE_URL`, through ReqLLM | | Reply | Qwen3 0.6B, 1.7B, 4B, and 8B, 4-bit | Native EMLXAxon Qwen3 generation | | Speech | Kokoro 82M, four voices | Transmuter on the EMLX GPU backend | @@ -52,11 +51,14 @@ Measured on an Apple M5 with 24 GB of memory, after the first turn: | Models | First text | First audio | | --- | ---: | ---: | | Whisper small, Qwen3 1.7B | 0.9 s | 1.5 s | -| Qwen3-ASR 0.6B, Qwen3 0.6B | 0.3 s | 0.8 s | The first turn after a model switch compiles the new model. It took up to 6 s to the first audio. +Bumblebee has no Qwen3-ASR model, so Qwen3-ASR needs a separate vLLM server, +for example `vllm serve Qwen/Qwen3-ASR-1.7B`. Set `CHAT_ASR_BASE_URL` when it +does not listen on `http://localhost:8000/v1`. + ## Model cache Reply model checkpoints use the `hf_hub` cache, by default diff --git a/site/src/content/docs/docs/features/providers.md b/site/src/content/docs/docs/features/providers.md index 53ac789..a1dfe9a 100644 --- a/site/src/content/docs/docs/features/providers.md +++ b/site/src/content/docs/docs/features/providers.md @@ -1,6 +1,6 @@ --- title: Remote speech providers -description: Deepgram, Cartesia, ElevenLabs, OpenAI Realtime, and Gemini Live adapters. +description: ReqLLM speech-to-text (Deepgram, Voxtral and others), Cartesia, ElevenLabs, OpenAI Realtime, and Gemini Live adapters. --- These adapters make real network requests. The regression suite uses local HTTP @@ -15,8 +15,8 @@ accepting the same types). Model and voice IDs must be available to your account Keys may be strings or zero-argument functions; functions allow runtime rotation. ```elixir -stt = {AudioFlow.Adapters.Deepgram, - [model: "nova-3", api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]} +stt = {AudioFlow.STT.ReqLLM, + [model: "deepgram:nova-3", api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]} tts = {AudioFlow.Adapters.Cartesia, [model: "sonic-3.6", voice_id: System.fetch_env!("CARTESIA_VOICE_ID"), @@ -29,13 +29,15 @@ tts = {AudioFlow.Adapters.ElevenLabs, api_key: fn -> System.fetch_env!("ELEVENLABS_API_KEY") end]} ``` -Deepgram uses Listen v1 WebSocket with mono `linear16` PCM at the input -`Audio.sample_rate`, sends bounded binary frames, then `CloseStream`. It emits -only final transcript segments, separated by spaces; the concluding Metadata -message completes the run. Interim results are ignored. This is a streaming -provider response for an already committed utterance, **not** microphone-to-STT -live ingress or a persistent recognition session. Optional `:language` is sent -as a query parameter. Empty final transcripts (silence) emit nothing. +All speech-to-text from external services goes through ReqLLM with +`AudioFlow.STT.ReqLLM`, for Mistral Voxtral, Deepgram, OpenAI, Groq, ElevenLabs, +OpenRouter and self-hosted vLLM servers. See the common STT interface in the +[README](https://github.com/flowcopilot/audioflow#transcription). ReqLLM has no +Deepgram provider, so AudioFlow registers `AudioFlow.STT.DeepgramProvider`. +It sends the utterance as one WAV body to the pre-recorded `POST /v1/listen` +API, with `model`, optional `language` and `:provider_options` as query +parameters. With `segments: true`, it requests `utterances=true` and emits each +utterance as a timed segment. Deepgram interim results are not used. Cartesia uses `/tts/bytes` and ElevenLabs uses `/text-to-speech/:voice_id/stream`. Both stream raw signed 16-bit little-endian mono PCM as `AudioFlow.Audio`, default @@ -161,7 +163,7 @@ Wire shapes were checked against official documentation on 2026-11-03: - [OpenAI Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations) - [Gemini Live WebSocket reference](https://ai.google.dev/api/live) -- [Deepgram Listen streaming reference](https://developers.deepgram.com/reference/speech-to-text/listen-streaming) +- [Deepgram pre-recorded utterances](https://developers.deepgram.com/docs/utterances) - [Cartesia bytes TTS](https://docs.cartesia.ai/api-reference/tts/bytes) - [ElevenLabs streaming TTS](https://elevenlabs.io/docs/api-reference/text-to-speech/stream) diff --git a/site/src/content/docs/docs/guides/local-models.md b/site/src/content/docs/docs/guides/local-models.md index 4a48594..9e14111 100644 --- a/site/src/content/docs/docs/guides/local-models.md +++ b/site/src/content/docs/docs/guides/local-models.md @@ -41,8 +41,8 @@ short spoken-reply instruction. Its format is checked against the pinned model's original Jinja template. Other language models need their own prompt format. -Whisper input requires 16 kHz PCM. Resample before submission. Whisper output -is read after utterance transcription. Language model output is streamed and +Use `AudioFlow.STT.Bumblebee` for Whisper. It converts the input to 16 kHz. +Whisper output is read after utterance transcription. Language model output is streamed and grouped into sentences before synthesis. ## Kokoro diff --git a/ui/README.md b/ui/README.md index 94ffabc..ab8fa7a 100644 --- a/ui/README.md +++ b/ui/README.md @@ -94,8 +94,8 @@ AUDIOFLOW_ML=1 mix phx.server A model loads on the first turn that uses it, and all sessions share it. The first turn can take minutes to download and compile. Set the graph setting `timeout_ms` to allow for this. Models run with EXLA on the CPU. -Kokoro speaks at 24 kHz and Whisper needs 16 kHz, so put an -`audio.resample` node between them. The graph keeps the +Kokoro speaks at 24 kHz. The Whisper node converts its input to 16 kHz, so an +`audio.resample` node between them is optional. The graph keeps the name of the API key variable (`api_key_env`), not the key. To add node types, write an `AudioFlow.Graph.Node` module and set the list: @@ -147,7 +147,8 @@ ffmpeg -i speech.wav -ac 1 -ar 16000 -f s16le speech.pcm The runner displays transcripts and PCM byte counts, with per-node WAV playback after completion (first 8 MB total PCM; no mixing or resampling). Use the [chat app](../examples/chat/README.md) for interactive voice. -Deepgram receives an already committed utterance, not continuous mic ingress. +Speech-to-text nodes receive an already committed utterance, not continuous +mic ingress. Remote STT nodes use ReqLLM, and whisper.stt uses Bumblebee. OpenAI Realtime and Gemini Live emit mixed transcript/text/audio and cannot occupy single-output graph nodes. Use their dedicated Session examples in [providers.md](../docs/providers.md). From d6d69c01a59d18932a8fcf5d315e70260338be34 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 14:21:21 +0200 Subject: [PATCH 8/8] docs(site): add transcription guide Add the STT interface, transcription sessions and long recordings to the site. Link the guide from the Sessions and WebSocket guides, and list the partial_transcript event and segment timing fields. --- site/astro.config.mjs | 1 + site/src/content/docs/docs/guides/sessions.md | 3 + .../content/docs/docs/guides/transcription.md | 122 ++++++++++++++++++ .../src/content/docs/docs/guides/websocket.md | 6 +- 4 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 site/src/content/docs/docs/guides/transcription.md diff --git a/site/astro.config.mjs b/site/astro.config.mjs index a2c7b1e..acb34bc 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -35,6 +35,7 @@ export default defineConfig({ label: 'Guides', items: [ 'docs/guides/sessions', + 'docs/guides/transcription', 'docs/guides/history', 'docs/guides/local-models', 'docs/guides/http-inference', diff --git a/site/src/content/docs/docs/guides/sessions.md b/site/src/content/docs/docs/guides/sessions.md index 99000fe..1b25273 100644 --- a/site/src/content/docs/docs/guides/sessions.md +++ b/site/src/content/docs/docs/guides/sessions.md @@ -9,6 +9,9 @@ Each conversation is one session process. The process that starts a session is its owner. The owner receives transcript, text, audio, and terminal events. See the `AudioFlow` module for the event format. +A session without `:llm` and `:tts` only transcribes. See +[Transcription](../transcription/). + ```elixir {:ok, session} = AudioFlow.start_session(AudioFlow.Adapters.Demo.options()) audio = %AudioFlow.Audio{data: <<0, 0>>, sample_rate: 16_000} diff --git a/site/src/content/docs/docs/guides/transcription.md b/site/src/content/docs/docs/guides/transcription.md new file mode 100644 index 0000000..c5fc16f --- /dev/null +++ b/site/src/content/docs/docs/guides/transcription.md @@ -0,0 +1,122 @@ +--- +title: Transcription +description: One speech-to-text interface, transcription sessions, and long recordings. +sidebar: + order: 12 +--- + +## Speech-to-text interface + +All speech-to-text adapters use one interface, `AudioFlow.STT`. External +services go through ReqLLM with `AudioFlow.STT.ReqLLM`. Local models go through +Bumblebee with `AudioFlow.STT.Bumblebee`. Both take the same options and give +the same output, so you can change the engine without other changes: + +```elixir +voxtral = {AudioFlow.STT.ReqLLM, model: "mistral:voxtral-mini-latest", language: "en"} +deepgram = {AudioFlow.STT.ReqLLM, model: "deepgram:nova-3", segments: true} +whisper = {AudioFlow.STT.Bumblebee, model: "openai/whisper-small", language: "en"} +``` + +| Option | Meaning | +| --- | --- | +| `:model` | Required. A ReqLLM model, or a Hugging Face Whisper repository. | +| `:language` | An ISO 639-1 code, or `nil` (the default) for detection. | +| `:segments` | `true` to emit timed `AudioFlow.Transcript.Segment` values in place of text. | + +The input is one `AudioFlow.Audio` utterance at any sample rate. The adapter +converts it for the engine. Output arrives when the engine finishes; there are +no partial results. Errors fail the turn. + +| Engine | Adapter | Models | +| --- | --- | --- | +| External services | `AudioFlow.STT.ReqLLM` | Mistral Voxtral, Deepgram, OpenAI Whisper and GPT-4o transcription, Groq Whisper, ElevenLabs Scribe, OpenRouter | +| Self-hosted servers | `AudioFlow.STT.ReqLLM` with `:base_url` | vLLM with Voxtral, Qwen3-ASR or Whisper, and other OpenAI-compatible `/audio/transcriptions` servers | +| Local models | `AudioFlow.STT.Bumblebee` | Bumblebee Whisper checkpoints | + +`AudioFlow.STT.ReqLLM` sends each utterance as one WAV upload. ReqLLM reads the +provider key from its environment variable, for example `MISTRAL_API_KEY` or +`DEEPGRAM_API_KEY`, or from `:api_key`, which can be a function. Other options +go to `ReqLLM.transcribe/3`. Retries are off by default, because the session +deadline bounds the turn. ReqLLM has no Deepgram provider, so AudioFlow +registers `AudioFlow.STT.DeepgramProvider` for the Deepgram `/v1/listen` API. + +```elixir +local_voxtral = {AudioFlow.STT.ReqLLM, + model: "vllm:mistralai/Voxtral-Mini-3B-2507", base_url: "http://localhost:8000/v1"} +``` + +With `segments: true`, the adapter asks Mistral and Deepgram for segment times. +OpenAI-compatible Whisper servers return segments without a request. GPT-4o +transcription models give only text, so the adapter then emits text. Mistral +does not accept segment times together with `:language`; the adapter then +sends only the language and emits text. + +`AudioFlow.STT.Bumblebee` loads one shared serving for each model, revision, +language and serving options, through `AudioFlow.Servings`, on first use. +Bumblebee fixes the Whisper language when it builds the serving. Add +`AudioFlow.Servings` to the inference children, and call +`AudioFlow.STT.Bumblebee.preload/1` at startup, because the first load can take +minutes. `:serving_options` select the backend and compiler (EXLA by default). +The adapter converts the input to 16 kHz with `AudioFlow.Resampler`. With the +pinned Bumblebee 0.8.0 and EXLA 1.0.0, Whisper `timestamps: :segments` fails to +compile, so local segments have no times inside a session. + +The graph editor has `whisper.stt` (local), `deepgram.stt` and `mistral.stt` +nodes. The remote nodes use a fixed provider and the server key. + +## Transcription sessions + +A session without `:llm` and `:tts` is a transcription session. Each audio turn +runs only the STT adapter and then ends with `{:done, metrics}`. Text input +returns `{:error, {:unsupported_input, :llm}}`, and `:history` is rejected. + +```elixir +{:ok, session} = AudioFlow.start_session(stt: deepgram) +{:ok, turn} = AudioFlow.submit(session, audio) +``` + +An STT adapter can emit three kinds of values, in any session: + +| Adapter output | Session event | In the prompt and history | +| --- | --- | --- | +| `text` | `{:transcript, text}` | yes | +| `%AudioFlow.Transcript.Segment{}` | `{:segment, segment}` | yes, joined with spaces | +| `{:partial, text}` | `{:partial_transcript, text}` | no | + +A segment has `text`, `start_ms` and `end_ms` from the start of the turn audio, +and optional `words` with their own times. Times are `nil` when the engine does +not give them. The `AudioFlow.STT` adapters do not emit partials. A custom +adapter can emit them: a partial is an unstable hypothesis for the text that +follows the final text emitted so far. The metrics add +`first_partial_transcript_us`. The WebSocket transport sends segments as +`transcript` messages with timing fields, and partials as `partial_transcript` +messages. Recordings keep segment text and drop partials. Graph sessions do not +use these values. + +## Long recordings + +For a long recording, use `AudioFlow.transcribe/3`. It cuts the audio into +sections, runs the STT adapter on each section in a supervised task, and returns +an `AudioFlow.Transcript` with times from the start of the input: + +```elixir +{:ok, audio} = AudioFlow.Wav.read("meeting.wav") +{:ok, transcript} = AudioFlow.transcribe(audio, voxtral, chunk_ms: 30_000, max_concurrency: 4) +transcript.text +File.write!("meeting.srt", AudioFlow.Transcript.to_srt(transcript)) +``` + +Fixed sections can cut a word at a boundary. Set `:vad` to a voice detector +tuple to send only detected utterances; the audio must then use the detector +sample rate. Each section has its own `:timeout_ms` (120 seconds by default), +and the first failure returns `{:error, {:section, index, reason}}`. +`:on_segment` receives each segment in order. Segments without times get the +times of their section. `AudioFlow.Wav` reads only mono 16-bit PCM WAV. Convert +other files with FFmpeg. To print captions for a file: + +```sh +AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav openai/whisper-small +DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram:nova-3 +MISTRAL_API_KEY=... mix run examples/transcribe.exs input.wav mistral:voxtral-mini-latest +``` diff --git a/site/src/content/docs/docs/guides/websocket.md b/site/src/content/docs/docs/guides/websocket.md index 191b53d..b133f35 100644 --- a/site/src/content/docs/docs/guides/websocket.md +++ b/site/src/content/docs/docs/guides/websocket.md @@ -46,8 +46,10 @@ The server sends binary frames of mono s16le reply PCM for the current turn. An `output_format` event with `sample_rate` comes before the first binary frame, and before each change of rate. JSON events have a `type` field: `ready`, `speech_started`, `turn_started`, `transcript`, `description`, `text`, -`done`, `cancelled`, `flush`, `history_cleared`, and `error`. Turn events -include a connection-local integer `turn`. When the client receives `flush`, +`partial_transcript`, `done`, `cancelled`, `flush`, `history_cleared`, and +`error`. Turn events include a connection-local integer `turn`. A `transcript` +event for an STT segment also has `start_ms`, `end_ms` and `words`. See +[Transcription](../transcription/). When the client receives `flush`, it must discard its queued playback. After a cancellation, the connection drops output from the old turn. An invalid client message gets an `error` event, and the connection stays open.