openai_rust/
audio.rs

1use reqwest::{Client, multipart};
2use crate::client::get_api_key;
3
4#[derive(Debug)]
5pub enum AudioError {
6    MissingApiKey,
7    RequestError(reqwest::Error),
8    InvalidResponse,
9}
10
11impl From<reqwest::Error> for AudioError {
12    fn from(err: reqwest::Error) -> Self {
13        AudioError::RequestError(err)
14    }
15}
16
17/// Transcribes an audio file using Whisper.
18pub async fn openai_transcribe_audio(filepath: &str) -> Result<String, AudioError> {
19    send_audio_request(filepath, "https://api.openai.com/v1/audio/transcriptions").await
20}
21
22/// Translates an audio file to English using Whisper.
23pub async fn openai_translate_audio(filepath: &str) -> Result<String, AudioError> {
24    send_audio_request(filepath, "https://api.openai.com/v1/audio/translations").await
25}
26
27/// Shared internal function to send audio requests.
28async fn send_audio_request(filepath: &str, url: &str) -> Result<String, AudioError> {
29    let api_key = get_api_key().ok_or(AudioError::MissingApiKey)?;
30
31    let client = Client::new();
32
33    let file_part = multipart::Part::file(filepath).await.map_err(|_| AudioError::InvalidResponse)?;
34    let form = multipart::Form::new()
35        .part("file", file_part)
36        .text("model", "whisper-1");
37
38    let response = client
39        .post(url)
40        .bearer_auth(api_key)
41        .multipart(form)
42        .send()
43        .await?;
44
45    let json: serde_json::Value = response.json().await?;
46    if let Some(text) = json["text"].as_str() {
47        Ok(text.to_string())
48    } else {
49        Err(AudioError::InvalidResponse)
50    }
51}