use derive_builder::Builder;
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use crate::{
DeepSeekClient, DeepSeekError, DeepSeekRequest, api_post_byte_stream, api_post_bytes,
spawn_blocking_stream,
};
use tokio::sync::mpsc;
#[derive(Clone, PartialEq, Serialize, Builder)]
#[builder(
pattern = "owned",
setter(into, strip_option),
build_fn(validate = "Self::validate"),
name = "TTSRequestBuilder"
)]
pub struct TTSRequest {
#[serde(skip_serializing)]
pub client: DeepSeekClient,
pub text: String,
#[builder(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub voice_id: Option<VoiceId>,
#[builder(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<AudioFormat>,
#[builder(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub filter_markdown: Option<bool>,
}
impl TTSRequestBuilder {
fn validate(&self) -> Result<(), String> {
if let Some(text) = self.text.as_ref()
&& text.trim().is_empty()
{
return Err("text must not be empty".to_string());
}
Ok(())
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum VoiceId {
Stella,
Tide,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AudioFormat {
Wav,
Pcm,
}
pub type TTSStreamItem = Result<Vec<u8>, DeepSeekError>;
pub struct TTSStreamBlocking {
pub rx: std::sync::mpsc::Receiver<TTSStreamItem>,
}
impl Iterator for TTSStreamBlocking {
type Item = TTSStreamItem;
fn next(&mut self) -> Option<Self::Item> {
self.rx.recv().ok()
}
}
impl DeepSeekRequest for TTSRequest {
type Response = Vec<u8>;
type StreamItem = TTSStreamItem;
type BlockingStream = TTSStreamBlocking;
async fn send(self) -> Result<Self::Response, DeepSeekError> {
let client = self.client.clone();
api_post_bytes("/v1/tools/tts", &self, client).await
}
async fn stream(self) -> Result<mpsc::Receiver<Self::StreamItem>, DeepSeekError> {
let client = self.client.clone();
let response = api_post_byte_stream("/v1/tools/tts", &self, client).await?;
let (tx, rx) = mpsc::channel(32);
tokio::spawn(async move {
let mut body = response.bytes_stream();
while let Some(chunk) = body.next().await {
let item = chunk
.map(|bytes| bytes.to_vec())
.map_err(DeepSeekError::from);
let failed = item.is_err();
if tx.send(item).await.is_err() || failed {
break;
}
}
});
Ok(rx)
}
fn stream_blocking(self) -> Result<Self::BlockingStream, DeepSeekError> {
let rx = spawn_blocking_stream(self.stream())?;
Ok(TTSStreamBlocking { rx })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DEFAULT_BASE_URL;
use serde_json::json;
fn client() -> DeepSeekClient {
DeepSeekClient::new("sk-...", DEFAULT_BASE_URL.clone())
}
fn builder() -> TTSRequestBuilder {
TTSRequestBuilder::default()
.client(client())
.text("Hello from DeepSeek.")
}
#[test]
fn request_serializes_text_and_skips_optional_fields() {
let req = builder().build().unwrap();
assert_eq!(
serde_json::to_value(&req).unwrap(),
json!({"text": "Hello from DeepSeek."})
);
}
#[test]
fn request_serializes_all_fields_when_set() {
let req = builder()
.voice_id(VoiceId::Tide)
.format(AudioFormat::Pcm)
.filter_markdown(false)
.build()
.unwrap();
assert_eq!(
serde_json::to_value(&req).unwrap(),
json!({
"text": "Hello from DeepSeek.",
"voice_id": "tide",
"format": "pcm",
"filter_markdown": false
})
);
}
#[test]
fn enums_serialize_api_values() {
assert_eq!(
serde_json::to_value(VoiceId::Stella).unwrap(),
json!("stella")
);
assert_eq!(serde_json::to_value(VoiceId::Tide).unwrap(), json!("tide"));
assert_eq!(
serde_json::to_value(AudioFormat::Wav).unwrap(),
json!("wav")
);
assert_eq!(
serde_json::to_value(AudioFormat::Pcm).unwrap(),
json!("pcm")
);
}
#[test]
fn validation_rejects_empty_text() {
assert!(builder().text("").build().is_err());
assert!(builder().text(" ").build().is_err());
assert!(TTSRequestBuilder::default().text("Hi").build().is_err());
assert!(builder().build().is_ok());
}
}