返回 CodeWhale
voice.rs
1 use axum::Json;
2 use axum::extract::State;
3 use base64::Engine as _;
4 use serde::Deserialize;
5 use serde_json::{Value, json};
6
7 use super::{ApiError, RuntimeApiState};
8 use codewhale_engine::deepseek_media::DEEPSEEK_TTS_MAX_CHARS;
9 use codewhale_engine::voice as voice_core;
10 use voice_core::{DictateError, DictateMode, UPLOAD_AUDIO_MAX_BYTES};
11
12 static DICTATE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
13
14 pub(super) async fn voice_status(
15 State(state): State<RuntimeApiState>,
16 ) -> Result<Json<Value>, ApiError> {
17 let (asr_kind, asr_model, upload_available, tts_available, tts_voices) = {
18 let config = state.config.read();
19 let (asr_kind, asr_model) = voice_core::asr_choice(&config);
20 let upload_available = voice_core::upload_available(&config);
21 let tts_available = voice_core::tts_available(&config);
22 let tts_voices = voice_core::tts_voices(&config);
23 (
24 asr_kind,
25 asr_model,
26 upload_available,
27 tts_available,
28 tts_voices,
29 )
30 };
31 Ok(Json(json!({
32 "available": voice_core::is_available(),
33 "upload_available": upload_available,
34 "tts_available": tts_available,
35 "recorder": voice_core::recorder_command(),
36 "asr": { "kind": asr_kind, "model": asr_model },
37 "modes": ["insert", "send", "control"],
38 "send_phrases": voice_core::SEND_PHRASES,
39 "max_record_seconds": voice_core::MAX_RECORD_SECS,
40 "max_upload_bytes": UPLOAD_AUDIO_MAX_BYTES,
41 "tts_voices": tts_voices,
42 })))
43 }
44
45 fn dictate_failure(error: DictateError) -> Json<Value> {
46 Json(json!({
47 "ok": false,
48 "reason": error.reason(),
49 "message": error.to_string(),
50 }))
51 }
52
53 fn dictate_success(outcome: voice_core::DictationOutcome) -> Json<Value> {
54 Json(json!({
55 "ok": true,
56 "text": outcome.text,
57 "send": outcome.send,
58 "assisted": outcome.assisted,
59 "asr": { "kind": outcome.asr_kind, "model": outcome.asr_model },
60 }))
61 }
62
63 async fn dictate(state: &RuntimeApiState, mode: DictateMode) -> Result<Json<Value>, ApiError> {
64 let config = state.config.read().clone();
65 let _permit = DICTATE_LOCK.lock().await;
66 match voice_core::dictate_once(&config, mode).await {
67 Ok(outcome) => Ok(dictate_success(outcome)),
68 Err(error) => Ok(dictate_failure(error)),
69 }
70 }
71
72 pub(super) async fn voice_dictate(
73 State(state): State<RuntimeApiState>,
74 ) -> Result<Json<Value>, ApiError> {
75 dictate(&state, DictateMode::Insert).await
76 }
77
78 pub(super) async fn voice_send(
79 State(state): State<RuntimeApiState>,
80 ) -> Result<Json<Value>, ApiError> {
81 dictate(&state, DictateMode::Send).await
82 }
83
84 #[derive(Deserialize)]
85 #[serde(deny_unknown_fields)]
86 pub(super) struct VoiceControlRequest {
87 #[serde(default)]
88 composer: String,
89 }
90
91 pub(super) async fn voice_control(
92 State(state): State<RuntimeApiState>,
93 body: Option<Json<VoiceControlRequest>>,
94 ) -> Result<Json<Value>, ApiError> {
95 let composer = body
96 .map(|Json(request)| request.composer)
97 .unwrap_or_default();
98 dictate(&state, DictateMode::Control(composer)).await
99 }
100
101 #[derive(Deserialize)]
102 #[serde(deny_unknown_fields)]
103 pub(super) struct VoiceTranscribeRequest {
104 audio_base64: String,
105 #[serde(default)]
106 mime_type: Option<String>,
107 #[serde(default)]
108 mode: Option<String>,
109 #[serde(default)]
110 composer: Option<String>,
111 #[serde(default)]
112 language: Option<String>,
113 }
114
115 pub(super) async fn voice_transcribe(
116 State(state): State<RuntimeApiState>,
117 Json(request): Json<VoiceTranscribeRequest>,
118 ) -> Result<Json<Value>, ApiError> {
119 let max_encoded_len = (UPLOAD_AUDIO_MAX_BYTES / 3 + 2) * 4 + 16;
120 if request.audio_base64.len() > max_encoded_len {
121 return Ok(dictate_failure(DictateError::InvalidInput(format!(
122 "encoded audio exceeds maximum size for {UPLOAD_AUDIO_MAX_BYTES} byte upload"
123 ))));
124 }
125 let Ok(audio_bytes) =
126 base64::engine::general_purpose::STANDARD.decode(request.audio_base64.trim())
127 else {
128 return Ok(dictate_failure(DictateError::InvalidInput(
129 "audio_base64 is not valid base64".to_string(),
130 )));
131 };
132 let mode = match request.mode.as_deref().unwrap_or("insert").trim() {
133 "" | "insert" => DictateMode::Insert,
134 "send" => DictateMode::Send,
135 "control" => DictateMode::Control(request.composer.unwrap_or_default()),
136 other => {
137 return Ok(dictate_failure(DictateError::InvalidInput(format!(
138 "unsupported voice mode '{other}'"
139 ))));
140 }
141 };
142 let mime_type = request.mime_type.as_deref().unwrap_or("audio/wav");
143 let config = state.config.read().clone();
144 match voice_core::transcribe_uploaded_audio(
145 &config,
146 &audio_bytes,
147 mime_type,
148 mode,
149 request.language.as_deref(),
150 )
151 .await
152 {
153 Ok(outcome) => Ok(dictate_success(outcome)),
154 Err(error) => Ok(dictate_failure(error)),
155 }
156 }
157
158 #[derive(Deserialize)]
159 #[serde(deny_unknown_fields)]
160 pub(super) struct VoiceTtsRequest {
161 text: String,
162 #[serde(default)]
163 voice: Option<String>,
164 #[serde(default)]
165 voice_id: Option<String>,
166 #[serde(default)]
167 format: Option<String>,
168 #[serde(default)]
169 filter_markdown: Option<bool>,
170 }
171
172 fn tts_failure(reason: &str, message: impl Into<String>) -> Json<Value> {
173 Json(json!({
174 "ok": false,
175 "reason": reason,
176 "message": message.into(),
177 }))
178 }
179
180 pub(super) async fn voice_tts(
181 State(state): State<RuntimeApiState>,
182 Json(request): Json<VoiceTtsRequest>,
183 ) -> Result<Json<Value>, ApiError> {
184 if request.text.trim().is_empty() {
185 return Ok(tts_failure("invalid_input", "speech text cannot be empty"));
186 }
187 if request.text.chars().count() > DEEPSEEK_TTS_MAX_CHARS {
188 return Ok(tts_failure(
189 "invalid_input",
190 format!("speech text exceeds maximum of {DEEPSEEK_TTS_MAX_CHARS} characters"),
191 ));
192 }
193 let voice = request.voice.as_deref().or(request.voice_id.as_deref());
194 let filter_markdown = request.filter_markdown.unwrap_or(true);
195 let config = state.config.read().clone();
196 match voice_core::synthesize_voice_tts_with_options(
197 &config,
198 &request.text,
199 voice,
200 request.format.as_deref(),
201 filter_markdown,
202 )
203 .await
204 {
205 Ok(outcome) => Ok(Json(json!({
206 "ok": true,
207 "mime_type": outcome.content_type,
208 "audio_base64": base64::engine::general_purpose::STANDARD.encode(&outcome.audio_bytes),
209 "voice_id": outcome.voice,
210 "provider": outcome.provider,
211 "model": outcome.model,
212 "format": outcome.format,
213 }))),
214 Err(err) => Ok(tts_failure(err.reason(), err.to_string())),
215 }
216 }
217
217 lines RUST