use derive_builder::Builder;
use reqwest::multipart;
use serde::{Deserialize, Serialize};
use crate::{DeepSeekClient, api_post_multipart, error::DeepSeekError};
#[derive(Clone, PartialEq, Serialize, Builder)]
#[builder(
pattern = "owned",
setter(into, strip_option),
build_fn(validate = "Self::validate"),
name = "ASRRequestBuilder"
)]
pub struct ASRRequest {
#[serde(skip_serializing)]
pub client: DeepSeekClient,
pub file: Vec<u8>,
pub filename: String,
}
impl ASRRequestBuilder {
fn validate(&self) -> Result<(), String> {
if let Some(file) = self.file.as_ref()
&& file.is_empty()
{
return Err("file must not be empty".to_string());
}
if let Some(filename) = self.filename.as_ref()
&& filename.trim().is_empty()
{
return Err("filename must not be empty".to_string());
}
Ok(())
}
}
impl ASRRequest {
pub async fn send(self) -> Result<ASRResponse, DeepSeekError> {
let part = multipart::Part::bytes(self.file).file_name(self.filename);
let form = multipart::Form::new().part("file", part);
api_post_multipart("/v1/tools/asr", form, self.client.clone()).await
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ASRResponse {
pub request_id: String,
pub text: String,
pub duration_ms: u64,
}
#[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() -> ASRRequestBuilder {
ASRRequestBuilder::default()
.client(client())
.file(vec![0u8; 4])
.filename("speech.wav")
}
#[test]
fn validation_rejects_empty_inputs() {
assert!(builder().file(Vec::new()).build().is_err());
assert!(builder().filename(" ").build().is_err());
assert!(
ASRRequestBuilder::default()
.file(vec![0u8])
.filename("speech.wav")
.build()
.is_err()
);
assert!(builder().build().is_ok());
}
#[test]
fn response_deserializes_api_example() {
let value = json!({
"request_id": "0b8c1c7e-3c0e-4d0f-9d3a-5f2a6f7e8b90",
"text": "What is the weather like in Shanghai today?",
"duration_ms": 3200
});
let resp: ASRResponse = serde_json::from_value(value).unwrap();
assert_eq!(resp.text, "What is the weather like in Shanghai today?");
assert_eq!(resp.duration_ms, 3200);
}
}