From 88bfaf2d4175bc72042a8bdde0ffd3a07a9e19c6 Mon Sep 17 00:00:00 2001 From: Eric Kalosa-Kenyon Date: Sat, 17 Jun 2023 12:55:08 -0400 Subject: [PATCH] add audio.rs; publish to lib.rs --- src/audio.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 63 insertions(+) create mode 100644 src/audio.rs diff --git a/src/audio.rs b/src/audio.rs new file mode 100644 index 0000000..9f49fc9 --- /dev/null +++ b/src/audio.rs @@ -0,0 +1,62 @@ +//! Given an audio file, the model will return its transcription. + +use std::path::Path; + +use super::{openai_post_multipart, ApiResponseOrError}; +use derive_builder::Builder; +use serde::{Deserialize, Serialize}; +use reqwest::multipart::{Form, Part}; + +#[derive(Deserialize, Clone)] +pub struct Transcription { + pub text: String, +} + +#[derive(Serialize, Builder, Debug, Clone)] +#[builder(pattern = "owned")] +#[builder(name = "TranscriptionBuilder")] +#[builder(setter(strip_option, into))] +pub struct TranscriptionRequest { + /// ID of the model to use. + /// You can use the [List models](https://beta.openai.com/docs/api-reference/models/list) + /// API to see all of your available models, + /// or see our [Model overview](https://beta.openai.com/docs/models/overview) + /// for descriptions of them. + /// At time of writing, only "whisper-1" is allowed. + pub model: String, + pub file_name: String, +} + +impl Transcription { + /// Creates a completion for the provided prompt and parameters + async fn create(request: &TranscriptionRequest) -> ApiResponseOrError { + let model = request.model.clone(); + let upload_file_path = Path::new(request.file_name.as_str()); + let upload_file_path = upload_file_path.canonicalize()?; + let simple_name = upload_file_path + .file_name() + .unwrap() + .to_str() + .unwrap() + .to_string() + .clone(); + let async_file = tokio::fs::File::open(upload_file_path).await?; + let file_part = Part::stream(async_file) + .file_name(simple_name) + .mime_str("audio/wav")?; + let form = Form::new() + .part("file", file_part) + .text("model", model); + openai_post_multipart("audio/transcriptions", form).await + } + + pub fn builder(model: &str) -> TranscriptionBuilder { + TranscriptionBuilder::create_empty().model(model) + } +} + +impl TranscriptionBuilder { + pub async fn create(self) -> ApiResponseOrError { + Transcription::create(&self.build().unwrap()).await + } +} diff --git a/src/lib.rs b/src/lib.rs index f1b912a..8191487 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ use reqwest::{header::AUTHORIZATION, Client, Method, RequestBuilder, Response}; use reqwest_eventsource::{CannotCloneRequestError, EventSource, RequestBuilderExt}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; +pub mod audio; pub mod chat; pub mod completions; pub mod edits;