super-voice-daemon/src/daemon/transcription.rs
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-3.0-only |
2 | | use crate::daemon::types::SuperSTTDaemon; |
3 | | use crate::stt_models::dispatch::{DispatchError, dispatch_transcription}; |
4 | | use log::{debug, error, info, warn}; |
5 | | use super_voice_shared::models::contexts::ExtraContext; |
6 | | use super_voice_shared::models::protocol::{DaemonResponse, ErrorCode}; |
7 | | use super_voice_shared::utils::audio::validate_audio; |
8 | | |
9 | | /// Distinguishes a genuine backend failure from "no model is loaded" so |
10 | | /// [`SuperSTTDaemon::handle_transcribe`] can attach |
11 | | /// [`ErrorCode::ModelNotLoaded`] only to the latter — the former has no |
12 | | /// better code than the default uncoded (`500`) error. |
13 | | enum RunTranscriptionError { |
14 | | /// The backend itself failed to produce a transcription. |
15 | | Failed(anyhow::Error), |
16 | | /// No model is loaded; the request is well-formed and will succeed once |
17 | | /// one is (see `docs/protocol/endpoints/v1/transcribe.md`). |
18 | | NotLoaded, |
19 | | } |
20 | | |
21 | | impl SuperSTTDaemon { |
22 | | /// Handle transcribe command |
23 | 7 | pub async fn handle_transcribe( |
24 | 7 | &self, |
25 | 7 | audio_data: Vec<f32>, |
26 | 7 | sample_rate: u32, |
27 | 7 | client_id: String, |
28 | 7 | language: Option<String>, |
29 | 7 | extra: Option<ExtraContext>, |
30 | 7 | ) -> DaemonResponse { |
31 | 7 | info!("Processing transcription request from client: {client_id4 }"); |
32 | | |
33 | | // Validate audio |
34 | 7 | if let Err(e) = validate_audio(&audio_data, sample_rate) { |
35 | 0 | warn!("Audio validation failed: {e}"); |
36 | 0 | return DaemonResponse::error_with_code( |
37 | 0 | ErrorCode::InvalidValue, |
38 | 0 | &format!("Invalid audio data: {e}"), |
39 | 0 | ); |
40 | 7 | } |
41 | 7 | debug!("Audio validation completed"0 ); |
42 | | |
43 | | // Every stage the transcript runs through loads at once. A load that |
44 | | // fails is logged; this answer's code says only that no model is |
45 | | // loaded, which the inference below reports. |
46 | 7 | let _ = self.ensure_pipeline_loaded().await; |
47 | 7 | crate::daemon::recording::log_extra_context(extra.as_ref()); |
48 | | |
49 | | // Process audio |
50 | 7 | let processed_audio = match self.audio_processor.process_audio(&audio_data, sample_rate) { |
51 | 7 | Ok(p) => p, |
52 | | Err(e) => { |
53 | 0 | warn!("Failed to process audio: {e}"); |
54 | 0 | return DaemonResponse::error(&format!("Failed to process audio: {e}")); |
55 | | } |
56 | | }; |
57 | | |
58 | | // Run the model inference (online or blocking path) |
59 | 7 | let transcription_result = self |
60 | 7 | .run_transcription(processed_audio, language.as_deref(), extra.as_ref()) |
61 | 7 | .await; |
62 | | // The models' idle time starts when the transcription ends. |
63 | 7 | self.finished_using_pipeline(); |
64 | | |
65 | | // Handle the result of the transcription task |
66 | 7 | match transcription_result { |
67 | | Ok(Ok((transcription, _duration))) => { |
68 | 4 | DaemonResponse::success().with_transcription(transcription) |
69 | | } |
70 | | // No model loaded: coded so this pre-captured path carries the |
71 | | // same `error_code` as the daemon-mic paths (see |
72 | | // docs/protocol/endpoints/v1/transcribe.md). `message` matches the |
73 | | // literal identifier every other coded error on this endpoint uses |
74 | | // (`recording_in_progress`, `stream_realtime_with_audio_data`, …); |
75 | | // `error_code` — not `message` — is the field clients switch on. |
76 | | Ok(Err(RunTranscriptionError::NotLoaded)) => { |
77 | 2 | DaemonResponse::error_with_code(ErrorCode::ModelNotLoaded, "model_not_loaded") |
78 | | } |
79 | | Ok(Err(RunTranscriptionError::Failed(e))) => { |
80 | 1 | DaemonResponse::error(&format!("Transcription failed: {e}")) |
81 | | } |
82 | | Err(e) => { |
83 | 0 | error!("Transcription task failed: {e}"); |
84 | 0 | DaemonResponse::error(&format!("Task execution failed: {e}")) |
85 | | } |
86 | | } |
87 | 7 | } |
88 | | |
89 | | /// Resolve the effective language for the currently-loaded model. |
90 | | /// `request_override` is an optional per-request language (BCP-47 or |
91 | | /// `"auto"`) from an external `POST /v1/stt/transcribe`. Per the |
92 | | /// transcription-language design it takes precedence over all configured |
93 | | /// resolution and is **passed straight through** — the backend validates it |
94 | | /// (it is not re-adapted against the model's supported set). When it is |
95 | | /// `None`, fall back to the configured resolution (per-model language → |
96 | | /// primary language → model default). A returned `None` means "omit |
97 | | /// `language`" (the model uses its primary). |
98 | 7 | pub(crate) async fn resolve_active_language( |
99 | 7 | &self, |
100 | 7 | request_override: Option<&str>, |
101 | 7 | ) -> Option<String> { |
102 | 7 | if let Some(lang) = request_override { |
103 | 1 | return Some(lang.to_string()); |
104 | 6 | } |
105 | | let def = { |
106 | 6 | let guard = self.model.read().await; |
107 | 6 | guard.as_ref().map(|loaded| loaded.definition4 .clone())?2 |
108 | | }; |
109 | 4 | let config = self.config.read().await; |
110 | 4 | crate::daemon::language::resolve_language( |
111 | 4 | def.is_multilingual, |
112 | 4 | config.model_language(&def.source, &def.name), |
113 | 4 | config.primary_language(), |
114 | 4 | &def.supported_languages, |
115 | 4 | ) |
116 | 4 | .wire |
117 | 7 | } |
118 | | |
119 | | /// Run the model inference, dispatching to the async (online) or blocking |
120 | | /// (local) path based on whether the loaded model is an online API model. |
121 | | /// |
122 | | /// Returns `Ok(Ok((text, duration)))` on success, `Ok(Err(_))` when the |
123 | | /// backend failed or no model is loaded (distinguished by |
124 | | /// [`RunTranscriptionError`] so the caller can attach the right |
125 | | /// [`ErrorCode`]), or `Err(_)` if the blocking task itself panicked. |
126 | 7 | async fn run_transcription( |
127 | 7 | &self, |
128 | 7 | processed_audio: Vec<f32>, |
129 | 7 | request_language: Option<&str>, |
130 | 7 | extra: Option<&ExtraContext>, |
131 | 7 | ) -> Result<Result<(String, std::time::Duration), RunTranscriptionError>, tokio::task::JoinError> |
132 | 7 | { |
133 | 7 | let language = self.resolve_active_language(request_language).await; |
134 | 7 | let start_time = std::time::Instant::now(); |
135 | | |
136 | 7 | match dispatch_transcription( |
137 | 7 | &self.model, |
138 | 7 | processed_audio, |
139 | 7 | 16000, |
140 | 7 | language.clone(), |
141 | 7 | extra.cloned(), |
142 | 7 | ) |
143 | 7 | .await |
144 | | { |
145 | | Ok(text) => { |
146 | 4 | let duration = start_time.elapsed(); |
147 | 4 | info!("Transcription completed in {duration3 :?}"); |
148 | | // Post-processing is part of producing the final transcript, so |
149 | | // it lands inside the reported duration. Best-effort: this |
150 | | // returns the raw text unchanged when it is off or fails. It |
151 | | // also logs the raw text and the processed one side by side. |
152 | 4 | let text = self.post_process_final(text, language, extra).await; |
153 | 4 | Ok(Ok((text, start_time.elapsed()))) |
154 | | } |
155 | | // A real backend failure is surfaced, not masked as empty success — |
156 | | // "no speech" is an `Ok("")` from the backend, so `Failed` here is a |
157 | | // genuine error the caller must report. |
158 | | Err(DispatchError::Failed(e)) => { |
159 | 1 | warn!("Transcription failed: {e0 }"); |
160 | | // Unprefixed: the caller's message already says the |
161 | | // transcription failed. |
162 | 1 | Ok(Err(RunTranscriptionError::Failed(e))) |
163 | | } |
164 | | Err(DispatchError::NotLoaded) => { |
165 | 2 | error!("Model not loaded"1 ); |
166 | 2 | Ok(Err(RunTranscriptionError::NotLoaded)) |
167 | | } |
168 | 0 | Err(DispatchError::Join(e)) => Err(e), |
169 | | } |
170 | 7 | } |
171 | | } |