Skip to main content

zai_rs/model/audio_to_text/
data.rs

1use std::{path::Path, sync::Arc};
2
3use serde::Serialize;
4use validator::Validate;
5
6use super::{super::traits::*, request::AudioToTextBody};
7use crate::client::{
8    endpoints::{ApiBase, EndpointConfig, paths},
9    error::codes,
10    http::{HttpClient, HttpClientConfig, parse_typed_response, send_multipart_request},
11};
12
13/// Audio transcription request (multipart/form-data)
14pub struct AudioToTextRequest<N>
15where
16    N: ModelName + AudioToText + Serialize,
17{
18    pub key: String,
19    url: String,
20    endpoint_config: EndpointConfig,
21    api_base: ApiBase,
22    http_config: Arc<HttpClientConfig>,
23    pub body: AudioToTextBody<N>,
24    file_path: Option<String>,
25}
26
27impl<N> AudioToTextRequest<N>
28where
29    N: ModelName + AudioToText + Serialize + Clone,
30{
31    pub fn new(model: N, key: String) -> Self {
32        let endpoint_config = EndpointConfig::default();
33        let api_base = ApiBase::PaasV4;
34        let url = endpoint_config.url(&api_base, paths::AUDIO_TRANSCRIPTIONS);
35        Self {
36            key,
37            url,
38            endpoint_config,
39            api_base,
40            http_config: Arc::new(HttpClientConfig::default()),
41            body: AudioToTextBody::new(model),
42            file_path: None,
43        }
44    }
45
46    pub fn with_file_path(mut self, path: impl Into<String>) -> Self {
47        self.file_path = Some(path.into());
48        self
49    }
50
51    pub fn with_temperature(mut self, temperature: f32) -> Self {
52        self.body = self.body.with_temperature(temperature);
53        self
54    }
55
56    pub fn with_stream(mut self, stream: bool) -> Self {
57        self.body = self.body.with_stream(stream);
58        self
59    }
60
61    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
62        self.body = self.body.with_request_id(request_id);
63        self
64    }
65
66    pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
67        self.body = self.body.with_user_id(user_id);
68        self
69    }
70
71    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
72        self.api_base = ApiBase::Custom(base_url.into());
73        self.url = self
74            .endpoint_config
75            .url(&self.api_base, paths::AUDIO_TRANSCRIPTIONS);
76        self
77    }
78
79    pub fn with_endpoint_config(mut self, endpoint_config: EndpointConfig) -> Self {
80        self.endpoint_config = endpoint_config;
81        self.url = self
82            .endpoint_config
83            .url(&self.api_base, paths::AUDIO_TRANSCRIPTIONS);
84        self
85    }
86
87    pub fn with_http_config(mut self, config: HttpClientConfig) -> Self {
88        self.http_config = Arc::new(config);
89        self
90    }
91
92    pub fn validate(&self) -> crate::ZaiResult<()> {
93        // Check body constraints
94
95        self.body
96            .validate()
97            .map_err(crate::client::error::ZaiError::from)?;
98        // Ensure file path exists
99
100        let p =
101            self.file_path
102                .as_ref()
103                .ok_or_else(|| crate::client::error::ZaiError::ApiError {
104                    code: 1200,
105                    message: "file_path is required".to_string(),
106                })?;
107
108        if !Path::new(p).exists() {
109            return Err(crate::client::error::ZaiError::FileError {
110                code: codes::SDK_FILE_NOT_FOUND,
111                message: format!("file_path not found: {}", p),
112            });
113        }
114
115        Ok(())
116    }
117
118    pub async fn send(&self) -> crate::ZaiResult<super::response::AudioToTextResponse>
119    where
120        N: Clone + Send + Sync + 'static,
121    {
122        self.validate()?;
123
124        let resp = self.post().await?;
125
126        parse_typed_response::<super::response::AudioToTextResponse>(resp).await
127    }
128}
129
130impl<N> HttpClient for AudioToTextRequest<N>
131where
132    N: ModelName + AudioToText + Serialize + Clone + Send + Sync + 'static,
133{
134    type Body = AudioToTextBody<N>;
135    type ApiUrl = String;
136    type ApiKey = String;
137
138    fn api_url(&self) -> &Self::ApiUrl {
139        &self.url
140    }
141
142    fn api_key(&self) -> &Self::ApiKey {
143        &self.key
144    }
145
146    fn body(&self) -> &Self::Body {
147        &self.body
148    }
149
150    fn post(
151        &self,
152    ) -> impl std::future::Future<Output = crate::ZaiResult<reqwest::Response>> + Send {
153        let key = self.key.clone();
154
155        let url = self.url.clone();
156        let config = self.http_config.clone();
157
158        let body = self.body.clone();
159
160        let file_path_opt = self.file_path.clone();
161
162        async move {
163            let file_path =
164                file_path_opt.ok_or_else(|| crate::client::error::ZaiError::ApiError {
165                    code: 1200,
166                    message: "file_path is required".to_string(),
167                })?;
168
169            let file_name = Path::new(&file_path)
170                .file_name()
171                .and_then(|s| s.to_str())
172                .unwrap_or("audio.wav")
173                .to_string();
174            let file_bytes = tokio::fs::read(&file_path).await?;
175
176            // Basic MIME guess by extension
177            let mime = if file_name.to_ascii_lowercase().ends_with(".mp3") {
178                "audio/mpeg"
179            } else {
180                "audio/wav"
181            };
182
183            let temperature = body.temperature;
184            let stream = body.stream;
185            let request_id = body.request_id.clone();
186            let user_id = body.user_id.clone();
187            let model_name: String = body.model.into();
188            send_multipart_request(reqwest::Method::POST, url, key, config, move || {
189                let part = reqwest::multipart::Part::bytes(file_bytes.clone())
190                    .file_name(file_name.clone())
191                    .mime_str(mime)?;
192                let mut form = reqwest::multipart::Form::new()
193                    .part("file", part)
194                    .text("model", model_name.clone());
195                if let Some(t) = temperature {
196                    form = form.text("temperature", t.to_string());
197                }
198                if let Some(s) = stream {
199                    form = form.text("stream", s.to_string());
200                }
201                if let Some(rid) = request_id.as_ref() {
202                    form = form.text("request_id", rid.clone());
203                }
204                if let Some(uid) = user_id.as_ref() {
205                    form = form.text("user_id", uid.clone());
206                }
207                Ok(form)
208            })
209            .await
210        }
211    }
212
213    fn http_config(&self) -> Arc<HttpClientConfig> {
214        self.http_config.clone()
215    }
216}