| 1 | use anyhow::{Context, Result, ensure}; |
| 2 | use serde_json::{Value, json}; |
| 3 | use unicode_width::UnicodeWidthChar; |
| 4 | |
| 5 | use super::wire::{ERROR_BODY_MAX_BYTES, bounded_error_text, read_bounded_response_bytes}; |
| 6 | use super::{CodewhaleClient, SpeechSynthesisRequest, SpeechSynthesisResponse}; |
| 7 | use crate::llm_client::sanitize_http_error_body; |
| 8 | |
| 9 | pub(crate) const MODELS: &[&str] = &[ |
| 10 | "speech-2.8-hd", |
| 11 | "speech-2.8-turbo", |
| 12 | "speech-2.6-hd", |
| 13 | "speech-2.6-turbo", |
| 14 | "speech-02-hd", |
| 15 | "speech-02-turbo", |
| 16 | "speech-01-hd", |
| 17 | "speech-01-turbo", |
| 18 | ]; |
| 19 | pub(crate) const FORMATS: &[&str] = &["mp3", "wav", "flac", "pcm"]; |
| 20 | pub(crate) const DEFAULT_MODEL: &str = "speech-2.8-hd"; |
| 21 | const DEFAULT_VOICE: &str = "English_expressive_narrator"; |
| 22 | const RESPONSE_MAX_BYTES: usize = 128 * 1024 * 1024; |
| 23 | const DEFAULT_SAMPLE_RATE: f64 = 32_000.0; |
| 24 | const PCM_BYTES_PER_SAMPLE: f64 = 2.0; |
| 25 | const DEFAULT_MP3_BITS_PER_SECOND: f64 = 128_000.0; |
| 26 | const HEX_DIGITS_PER_BYTE: f64 = 2.0; |
| 27 | const SLOWEST_SPOKEN_TEXT_UNITS_PER_SECOND: f64 = 10.0; |
| 28 | const WIDE_CHARACTER_UNITS: usize = 3; |
| 29 | |
| 30 | fn response_bytes_per_audio_second(format: &str) -> f64 { |
| 31 | let audio_bytes = if format == "mp3" { |
| 32 | DEFAULT_MP3_BITS_PER_SECOND / 8.0 |
| 33 | } else { |
| 34 | DEFAULT_SAMPLE_RATE * PCM_BYTES_PER_SAMPLE |
| 35 | }; |
| 36 | audio_bytes * HEX_DIGITS_PER_BYTE |
| 37 | } |
| 38 | |
| 39 | fn spoken_units(text: &str) -> usize { |
| 40 | text.chars() |
| 41 | .map(|c| { |
| 42 | if c.width().unwrap_or(0) >= 2 { |
| 43 | WIDE_CHARACTER_UNITS |
| 44 | } else { |
| 45 | 1 |
| 46 | } |
| 47 | }) |
| 48 | .sum() |
| 49 | } |
| 50 | |
| 51 | fn longest_audio_seconds(text: &str) -> f64 { |
| 52 | let mut pause_seconds = 0.0; |
| 53 | let mut spoken = 0; |
| 54 | let mut rest = text; |
| 55 | while let Some(start) = rest.find("<#") { |
| 56 | spoken += spoken_units(&rest[..start]); |
| 57 | rest = &rest[start + 2..]; |
| 58 | if let Some((pause, after)) = rest.split_once("#>") |
| 59 | && let Ok(pause) = pause.trim().parse::<f64>() |
| 60 | { |
| 61 | pause_seconds += pause.max(0.0); |
| 62 | rest = after; |
| 63 | } else { |
| 64 | spoken += 2; |
| 65 | } |
| 66 | } |
| 67 | pause_seconds + (spoken + spoken_units(rest)) as f64 / SLOWEST_SPOKEN_TEXT_UNITS_PER_SECOND |
| 68 | } |
| 69 | |
| 70 | fn fits_response_limit(text: &str, format: &str) -> bool { |
| 71 | longest_audio_seconds(text) * response_bytes_per_audio_second(format) |
| 72 | <= RESPONSE_MAX_BYTES as f64 |
| 73 | } |
| 74 | |
| 75 | impl CodewhaleClient { |
| 76 | pub(crate) fn uses_minimax_speech(&self) -> bool { |
| 77 | self.api_provider == codewhale_config::ProviderKind::Minimax |
| 78 | && self.wire_format == codewhale_config::provider::WireFormat::ChatCompletions |
| 79 | } |
| 80 | |
| 81 | pub(super) async fn synthesize_minimax_speech( |
| 82 | &self, |
| 83 | request: SpeechSynthesisRequest, |
| 84 | ) -> Result<SpeechSynthesisResponse> { |
| 85 | let model = request.model.trim(); |
| 86 | let text = request.text.trim(); |
| 87 | ensure!(MODELS.contains(&model), "Unsupported MiniMax speech model"); |
| 88 | ensure!( |
| 89 | !text.is_empty() && text.chars().count() < 10_000, |
| 90 | "MiniMax speech requires 1 to 9,999 characters" |
| 91 | ); |
| 92 | ensure!( |
| 93 | request.instruction.is_none(), |
| 94 | "MiniMax speech accepts spoken text and a voice ID" |
| 95 | ); |
| 96 | let voice = request |
| 97 | .voice |
| 98 | .as_deref() |
| 99 | .map(str::trim) |
| 100 | .filter(|voice| !voice.is_empty()) |
| 101 | .unwrap_or(DEFAULT_VOICE); |
| 102 | ensure!( |
| 103 | !voice.starts_with("data:"), |
| 104 | "MiniMax speech requires a voice ID" |
| 105 | ); |
| 106 | let format = request.audio_format.trim().to_ascii_lowercase(); |
| 107 | let format = if format == "pcm16" { "pcm" } else { &format }; |
| 108 | ensure!( |
| 109 | FORMATS.contains(&format), |
| 110 | "Unsupported MiniMax speech format" |
| 111 | ); |
| 112 | ensure!( |
| 113 | fits_response_limit(text, format), |
| 114 | "MiniMax {format} audio for this text could exceed the {} MiB response limit; shorten the text{}", |
| 115 | RESPONSE_MAX_BYTES / (1024 * 1024), |
| 116 | if format == "mp3" { |
| 117 | "" |
| 118 | } else { |
| 119 | " or request mp3" |
| 120 | } |
| 121 | ); |
| 122 | let response = self |
| 123 | .http_client |
| 124 | .post(super::api_url(&self.base_url, "t2a_v2")) |
| 125 | .json(&json!({ |
| 126 | "model": model, "text": text, "stream": false, "output_format": "hex", |
| 127 | "voice_setting": {"voice_id": voice}, "audio_setting": {"format": format} |
| 128 | })) |
| 129 | .send() |
| 130 | .await |
| 131 | .map_err(|err| { |
| 132 | anyhow::anyhow!("MiniMax speech request failed: {}", err.without_url()) |
| 133 | })?; |
| 134 | let status = response.status(); |
| 135 | let provider = Some(self.api_provider.provider().display_name()); |
| 136 | if !status.is_success() { |
| 137 | let body = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 138 | anyhow::bail!( |
| 139 | "MiniMax speech failed: HTTP {status}: {}", |
| 140 | sanitize_http_error_body(provider, status.as_u16(), &body) |
| 141 | ); |
| 142 | } |
| 143 | let body = read_bounded_response_bytes(response, RESPONSE_MAX_BYTES).await?; |
| 144 | let payload: Value = |
| 145 | serde_json::from_slice(&body).context("MiniMax speech response is not JSON")?; |
| 146 | let code = payload |
| 147 | .pointer("/base_resp/status_code") |
| 148 | .and_then(Value::as_i64) |
| 149 | .context("MiniMax speech response is missing its status code")?; |
| 150 | if code != 0 { |
| 151 | let message = payload |
| 152 | .pointer("/base_resp/status_msg") |
| 153 | .and_then(Value::as_str) |
| 154 | .map(|message| sanitize_http_error_body(provider, status.as_u16(), message)) |
| 155 | .filter(|message| !message.is_empty()); |
| 156 | match message { |
| 157 | Some(message) => { |
| 158 | anyhow::bail!("MiniMax speech failed with status {code}: {message}") |
| 159 | } |
| 160 | None => anyhow::bail!("MiniMax speech failed with status {code}"), |
| 161 | } |
| 162 | } |
| 163 | ensure!( |
| 164 | payload.pointer("/data/status").and_then(Value::as_u64) == Some(2), |
| 165 | "MiniMax speech response is incomplete" |
| 166 | ); |
| 167 | let audio = payload |
| 168 | .pointer("/data/audio") |
| 169 | .and_then(Value::as_str) |
| 170 | .filter(|value| !value.is_empty()) |
| 171 | .context("MiniMax speech response is missing audio")?; |
| 172 | Ok(SpeechSynthesisResponse { |
| 173 | model: model.to_owned(), |
| 174 | audio_format: format.to_owned(), |
| 175 | audio_bytes: hex::decode(audio).context("Invalid hexadecimal MiniMax speech audio")?, |
| 176 | transcript: None, |
| 177 | voice: Some(voice.to_owned()), |
| 178 | }) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | #[cfg(test)] |
| 183 | mod tests { |
| 184 | use super::*; |
| 185 | use wiremock::matchers::{body_partial_json, method, path}; |
| 186 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 187 | |
| 188 | fn minimax_client(base_url: &str) -> CodewhaleClient { |
| 189 | let config: codewhale_runtime::config::Config = toml::from_str(&format!( |
| 190 | "provider = 'minimax'\n[providers.minimax]\napi_key = 'test-key'\nbase_url = '{base_url}/v1'" |
| 191 | )) |
| 192 | .unwrap(); |
| 193 | CodewhaleClient::new(&config).unwrap() |
| 194 | } |
| 195 | |
| 196 | fn request(text: &str, format: &str) -> SpeechSynthesisRequest { |
| 197 | SpeechSynthesisRequest { |
| 198 | model: DEFAULT_MODEL.to_owned(), |
| 199 | text: text.to_owned(), |
| 200 | instruction: None, |
| 201 | audio_format: format.to_owned(), |
| 202 | voice: None, |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | #[tokio::test] |
| 207 | async fn minimax_speech_errors_keep_provider_detail_without_the_url() { |
| 208 | let _home = crate::test_support::SealedHome::new(); |
| 209 | let server = MockServer::start().await; |
| 210 | let reply = |text: &str, response: ResponseTemplate| { |
| 211 | Mock::given(method("POST")) |
| 212 | .and(path("/v1/t2a_v2")) |
| 213 | .and(body_partial_json(serde_json::json!({"text": text}))) |
| 214 | .respond_with(response) |
| 215 | .expect(1) |
| 216 | }; |
| 217 | reply( |
| 218 | "unauthorized", |
| 219 | ResponseTemplate::new(401).set_body_json(serde_json::json!({ |
| 220 | "base_resp": {"status_code": 1004, "status_msg": "login fail: Please carry the API secret key"} |
| 221 | })), |
| 222 | ) |
| 223 | .mount(&server) |
| 224 | .await; |
| 225 | reply( |
| 226 | "unknown voice", |
| 227 | ResponseTemplate::new(200).set_body_json(serde_json::json!({ |
| 228 | "base_resp": {"status_code": 2054, "status_msg": "voice id not exist"} |
| 229 | })), |
| 230 | ) |
| 231 | .mount(&server) |
| 232 | .await; |
| 233 | reply( |
| 234 | "gateway page", |
| 235 | ResponseTemplate::new(200).set_body_string("<html>upstream unavailable</html>"), |
| 236 | ) |
| 237 | .mount(&server) |
| 238 | .await; |
| 239 | let client = minimax_client(&server.uri()); |
| 240 | let host = server.uri().trim_start_matches("http://").to_owned(); |
| 241 | |
| 242 | let error = client |
| 243 | .synthesize_speech(request("unauthorized", "wav")) |
| 244 | .await |
| 245 | .unwrap_err() |
| 246 | .to_string(); |
| 247 | assert!(error.contains("HTTP 401"), "{error}"); |
| 248 | assert!(error.contains("login fail"), "{error}"); |
| 249 | assert!(!error.contains(&host), "{error}"); |
| 250 | |
| 251 | let error = client |
| 252 | .synthesize_speech(request("unknown voice", "mp3")) |
| 253 | .await |
| 254 | .unwrap_err() |
| 255 | .to_string(); |
| 256 | assert_eq!( |
| 257 | error, |
| 258 | "MiniMax speech failed with status 2054: voice id not exist" |
| 259 | ); |
| 260 | |
| 261 | let error = format!( |
| 262 | "{:#}", |
| 263 | client |
| 264 | .synthesize_speech(request("gateway page", "mp3")) |
| 265 | .await |
| 266 | .unwrap_err() |
| 267 | ); |
| 268 | assert!( |
| 269 | error.contains("MiniMax speech response is not JSON"), |
| 270 | "{error}" |
| 271 | ); |
| 272 | |
| 273 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 274 | let closed = listener.local_addr().unwrap().to_string(); |
| 275 | tokio::spawn(async move { |
| 276 | while let Ok((stream, _)) = listener.accept().await { |
| 277 | drop(stream); |
| 278 | } |
| 279 | }); |
| 280 | let error = minimax_client(&format!("http://{closed}")) |
| 281 | .synthesize_speech(request("hello", "mp3")) |
| 282 | .await |
| 283 | .unwrap_err() |
| 284 | .to_string(); |
| 285 | assert!( |
| 286 | error.starts_with("MiniMax speech request failed"), |
| 287 | "{error}" |
| 288 | ); |
| 289 | assert!(!error.contains(&closed), "{error}"); |
| 290 | } |
| 291 | |
| 292 | #[tokio::test] |
| 293 | async fn minimax_speech_refuses_audio_that_could_exceed_the_response_cap_before_sending() { |
| 294 | assert!(fits_response_limit(&"a".repeat(9_999), "wav")); |
| 295 | assert!(fits_response_limit(&"\u{8a9e}".repeat(9_999), "mp3")); |
| 296 | assert!(!fits_response_limit(&"\u{8a9e}".repeat(3_600), "wav")); |
| 297 | assert!(fits_response_limit(&"\u{0436}".repeat(9_000), "wav")); |
| 298 | assert!(fits_response_limit(&"\u{0915}".repeat(9_000), "wav")); |
| 299 | assert!(!fits_response_limit(&"\u{0436}".repeat(10_500), "wav")); |
| 300 | assert!(fits_response_limit("Hello <#0.5#> world", "wav")); |
| 301 | assert!(!fits_response_limit(&"<#99.99#>".repeat(11), "wav")); |
| 302 | assert!(fits_response_limit(&"<#99.99#>".repeat(11), "mp3")); |
| 303 | assert!(!fits_response_limit("<#inf#>", "mp3")); |
| 304 | |
| 305 | let _home = crate::test_support::SealedHome::new(); |
| 306 | let server = MockServer::start().await; |
| 307 | Mock::given(method("POST")) |
| 308 | .and(path("/v1/t2a_v2")) |
| 309 | .and(body_partial_json( |
| 310 | serde_json::json!({"audio_setting": {"format": "mp3"}}), |
| 311 | )) |
| 312 | .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ |
| 313 | "base_resp": {"status_code": 0}, "data": {"status": 2, "audio": "fffb"} |
| 314 | }))) |
| 315 | .expect(1) |
| 316 | .mount(&server) |
| 317 | .await; |
| 318 | let client = minimax_client(&server.uri()); |
| 319 | let long_chinese = "\u{8a9e}".repeat(3_600); |
| 320 | for format in ["wav", "pcm", "flac"] { |
| 321 | let error = client |
| 322 | .synthesize_speech(request(&long_chinese, format)) |
| 323 | .await |
| 324 | .unwrap_err() |
| 325 | .to_string(); |
| 326 | assert!( |
| 327 | error.contains("could exceed the 128 MiB response limit") |
| 328 | && error.ends_with("or request mp3"), |
| 329 | "{error}" |
| 330 | ); |
| 331 | } |
| 332 | let audio = client |
| 333 | .synthesize_speech(request(&long_chinese, "mp3")) |
| 334 | .await |
| 335 | .unwrap(); |
| 336 | assert_eq!(audio.audio_bytes, [0xff, 0xfb]); |
| 337 | assert_eq!(server.received_requests().await.unwrap().len(), 1); |
| 338 | } |
| 339 | } |
| 340 |