Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 20 additions & 17 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,46 @@ categories = ["api-bindings", "multimedia::audio"]
[dependencies]
# TODO Investigate which of these dependencies can go behind features.
bytes = "1"
futures = "0.3"
http = "0.2"
futures = "^0.3"
http = "1.3"
pin-project = "1"
reqwest = { version = "0.11.22", default-features = false, features = [
reqwest = { version = "^0.12", default-features = false, features = [
"json",
"rustls-tls",
"stream",
] }
serde = { version = "1.0.215", features = ["derive"] }
serde = { version = "^1.0.219", features = ["derive"] }
serde_json = "1"
serde_urlencoded = "0.7"
thiserror = "1"
tokio = { version = "1.38.0", features = ["full"] }
tokio-stream = "0.1.15"
tokio-tungstenite = { version = "0.20.1", features = [
"rustls-tls-webpki-roots",
thiserror = "2"
tokio = { version = "^1.45.1", features = ["full"] }
tokio-stream = "^0.1.17"
tokio-tungstenite = { version = "^0.27.0", features = [
], optional = true }
tokio-util = { version = "0.7.1", features = ["codec", "io"] }
tungstenite = { version = "0.20.1", optional = true }
tokio-util = { version = "^0.7", features = ["codec", "io"] }
tungstenite = { version = "^0.27", optional = true }
url = "2"
uuid = { version = "1", features = ["serde"] }
# Dependencies below are specified only to satisfy minimal-versions.
sha256 = "1.5.0"
anyhow = "1.0.86"
sha256 = "^1.6.0"
anyhow = "^1.0.98"
tracing = ">=0.1.41"

[dev-dependencies]
cpal = "0.13"
cpal = "^0.16"
crossbeam = "0.8"
audio = "0.2.0"
rodio = { version = "0.17.0" }
rodio = { version = "0.20" }
pkg-config = { version = "0.3.30" }

[features]
default = ["manage", "listen", "speak"]
default = ["__default_no_tls", "rust-tls"]
default_native_tls = ["__default_no_tls", "native-tls" ]
__default_no_tls = ["manage", "listen", "speak"]
manage = []
listen = ["dep:tungstenite", "dep:tokio-tungstenite"]
speak = []
rust-tls = ["tokio-tungstenite?/rustls-tls-webpki-roots", "reqwest/rustls-tls"]
native-tls = ["reqwest/native-tls", "tokio-tungstenite?/native-tls"]

[[example]]
name = "prerecorded_from_file"
Expand Down
2 changes: 1 addition & 1 deletion examples/speak/rest/text_to_speech_to_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ async fn main() -> Result<(), DeepgramError> {
.await?;

let elapsed_time = start_time.elapsed();
println!("Time to download audio: {:.2?}", elapsed_time);
println!("Time to download audio: {elapsed_time:.2?}");

Ok(())
}
2 changes: 1 addition & 1 deletion examples/speak/rest/text_to_speech_to_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ async fn main() -> Result<(), DeepgramError> {
// Print timing information if not already printed
if !time_to_first_byte_printed {
let elapsed_time = start_time.elapsed();
println!("Time to first audio byte: {:.2?}", elapsed_time);
println!("Time to first audio byte: {elapsed_time:.2?}");
time_to_first_byte_printed = true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async fn main() -> Result<(), DeepgramError> {
let response: Response = customized_request_builder.send().await?.json().await?;

let transcript = &response.results.channels[0].alternatives[0].transcript;
println!("{}", transcript);
println!("{transcript}");

Ok(())
}
2 changes: 1 addition & 1 deletion examples/transcription/rest/prerecorded_from_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async fn main() -> Result<(), DeepgramError> {
.await?;

let transcript = &response.results.channels[0].alternatives[0].transcript;
println!("{}", transcript);
println!("{transcript}");

Ok(())
}
4 changes: 2 additions & 2 deletions examples/transcription/rest/prerecorded_from_url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ async fn main() -> Result<(), DeepgramError> {
.await?;

let transcript = &response.results.channels[0].alternatives[0].transcript;
println!("{}", transcript);
println!("{transcript}");

println!("{:?}", response);
println!("{response:?}");

Ok(())
}
2 changes: 1 addition & 1 deletion examples/transcription/websocket/callback_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ async fn main() -> Result<(), DeepgramError> {

println!("Deepgram Request ID: {}", results.request_id());
while let Some(result) = results.next().await {
println!("got: {:?}", result);
println!("got: {result:?}");
}

Ok(())
Expand Down
68 changes: 27 additions & 41 deletions examples/transcription/websocket/microphone_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::thread;

use bytes::{BufMut, Bytes, BytesMut};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::Sample;
use cpal::{Sample, SampleFormat};
use crossbeam::channel::RecvError;
use deepgram::common::options::Encoding;
use futures::channel::mpsc::{self, Receiver as FuturesReceiver};
Expand All @@ -12,6 +12,25 @@ use futures::SinkExt;

use deepgram::{Deepgram, DeepgramError};

macro_rules! create_stream {
($device:ident, $config:expr, $sync_tx:ident, $sample_type:ty) => {
$device
.build_input_stream(
&$config.into(),
move |data: &[$sample_type], _: &_| {
let mut bytes = BytesMut::with_capacity(data.len() * 2);
for sample in data {
bytes.put_i16_le(sample.to_sample());
}
$sync_tx.send(bytes.freeze()).unwrap();
},
|_| panic!(),
None,
)
.unwrap()
};
}

fn microphone_as_stream() -> FuturesReceiver<Result<Bytes, RecvError>> {
let (sync_tx, sync_rx) = crossbeam::channel::unbounded();
let (mut async_tx, async_rx) = mpsc::channel(1);
Expand All @@ -30,45 +49,12 @@ fn microphone_as_stream() -> FuturesReceiver<Result<Bytes, RecvError>> {
// dbg!(&config);

let stream = match config.sample_format() {
cpal::SampleFormat::F32 => device
.build_input_stream(
&config.into(),
move |data: &[f32], _: &_| {
let mut bytes = BytesMut::with_capacity(data.len() * 2);
for sample in data {
bytes.put_i16_le(sample.to_i16());
}
sync_tx.send(bytes.freeze()).unwrap();
},
|_| panic!(),
)
.unwrap(),
cpal::SampleFormat::I16 => device
.build_input_stream(
&config.into(),
move |data: &[i16], _: &_| {
let mut bytes = BytesMut::with_capacity(data.len() * 2);
for sample in data {
bytes.put_i16_le(*sample);
}
sync_tx.send(bytes.freeze()).unwrap();
},
|_| panic!(),
)
.unwrap(),
cpal::SampleFormat::U16 => device
.build_input_stream(
&config.into(),
move |data: &[u16], _: &_| {
let mut bytes = BytesMut::with_capacity(data.len() * 2);
for sample in data {
bytes.put_i16_le(sample.to_i16());
}
sync_tx.send(bytes.freeze()).unwrap();
},
|_| panic!(),
)
.unwrap(),
SampleFormat::F32 => create_stream!(device, config, sync_tx, f32),
SampleFormat::I16 => create_stream!(device, config, sync_tx, i16),
SampleFormat::U16 => create_stream!(device, config, sync_tx, u16),
sample_format => {
panic!("Unsupported sample format: {sample_format:?}");
}
};

stream.play().unwrap();
Expand Down Expand Up @@ -109,7 +95,7 @@ async fn main() -> Result<(), DeepgramError> {

println!("Deepgram Request ID: {}", results.request_id());
while let Some(result) = results.next().await {
println!("got: {:?}", result);
println!("got: {result:?}");
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/transcription/websocket/simple_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async fn main() -> Result<(), DeepgramError> {

println!("Deepgram Request ID: {}", results.request_id());
while let Some(result) = results.next().await {
println!("got: {:?}", result);
println!("got: {result:?}");
}

Ok(())
Expand Down
4 changes: 2 additions & 2 deletions src/common/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2288,7 +2288,7 @@ impl Serialize for SerializableOptions<'_> {

if let Some(extra) = extra {
for (key, value) in extra.iter() {
seq.serialize_element(&("extra", format!("{}:{}", key, value)))?;
seq.serialize_element(&("extra", format!("{key}:{value}")))?;
}
}

Expand Down Expand Up @@ -2706,7 +2706,7 @@ mod serialize_options_tests {

let expected = limited_letters
.iter()
.map(|letter| format!("{}={}", key, letter))
.map(|letter| format!("{key}={letter}"))
.collect::<Vec<String>>()
.join("&");

Expand Down
13 changes: 7 additions & 6 deletions src/listen/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use tokio_tungstenite::{tungstenite::protocol::Message, MaybeTlsStream, WebSocke
use tungstenite::{
handshake::client,
protocol::frame::coding::{Data, OpCode},
Utf8Bytes,
};
use url::Url;
use uuid::Uuid;
Expand Down Expand Up @@ -517,7 +518,7 @@ async fn run_worker(
// eprintln!("<worker> received websocket close");
return Err(DeepgramError::WebsocketClose {
code: closeframe.code.into(),
reason: closeframe.reason.into_owned(),
reason: closeframe.reason.to_string(),
});
}

Expand Down Expand Up @@ -571,13 +572,13 @@ async fn run_worker(
if is_open {
match message {
Some(WsMessage::Audio(audio))=> {
send_message!(ws_stream_send, response_tx, Message::Binary(audio.0));
send_message!(ws_stream_send, response_tx, Message::Binary(Bytes::from(audio.0)));
last_sent_message = tokio::time::Instant::now();

}
Some(WsMessage::ControlMessage(msg)) => {
send_message!(ws_stream_send, response_tx, Message::Text(
serde_json::to_string(&msg).unwrap_or_default()
Utf8Bytes::from(serde_json::to_string(&msg).unwrap_or_default())
));
last_sent_message = tokio::time::Instant::now();
if msg == ControlMessage::CloseStream {
Expand All @@ -587,7 +588,7 @@ async fn run_worker(
None => {
// Input stream is shut down. Keep processing responses.
send_message!(ws_stream_send, response_tx, Message::Text(
serde_json::to_string(&ControlMessage::CloseStream).unwrap_or_default()
Utf8Bytes::from(serde_json::to_string(&ControlMessage::CloseStream).unwrap_or_default())
));
is_open = false;
}
Expand All @@ -598,9 +599,9 @@ async fn run_worker(
}
// eprintln!("<worker> post loop");
if let Err(err) = ws_stream_send
.send(Message::Text(
.send(Message::Text(Utf8Bytes::from(
serde_json::to_string(&ControlMessage::CloseStream).unwrap_or_default(),
))
)))
.await
{
// If the response channel is closed, there's nothing to be done about it now.
Expand Down
11 changes: 3 additions & 8 deletions src/manage/billing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ impl Billing<'_> {
/// # }
/// ```
pub async fn list_balance(&self, project_id: &str) -> crate::Result<Balances> {
let url = format!(
"https://api.deepgram.com/v1/projects/{}/balances",
project_id,
);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/balances",);

send_and_translate_response(self.0.client.get(url)).await
}
Expand Down Expand Up @@ -111,10 +108,8 @@ impl Billing<'_> {
/// # }
/// ```
pub async fn get_balance(&self, project_id: &str, balance_id: &str) -> crate::Result<Balance> {
let url = format!(
"https://api.deepgram.com/v1/projects/{}/balances/{}",
project_id, balance_id,
);
let url =
format!("https://api.deepgram.com/v1/projects/{project_id}/balances/{balance_id}",);

send_and_translate_response(self.0.client.get(url)).await
}
Expand Down
2 changes: 1 addition & 1 deletion src/manage/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl Invitations<'_> {
/// # }
/// ```
pub async fn leave_project(&self, project_id: &str) -> crate::Result<Message> {
let url = format!("https://api.deepgram.com/v1/projects/{}/leave", project_id,);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/leave",);

send_and_translate_response(self.0.client.delete(url)).await
}
Expand Down
14 changes: 4 additions & 10 deletions src/manage/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl Keys<'_> {
/// # }
/// ```
pub async fn list(&self, project_id: &str) -> crate::Result<MembersAndApiKeys> {
let url = format!("https://api.deepgram.com/v1/projects/{}/keys", project_id);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/keys");

send_and_translate_response(self.0.client.get(url)).await
}
Expand Down Expand Up @@ -113,10 +113,7 @@ impl Keys<'_> {
/// # }
/// ```
pub async fn get(&self, project_id: &str, key_id: &str) -> crate::Result<MemberAndApiKey> {
let url = format!(
"https://api.deepgram.com/v1/projects/{}/keys/{}",
project_id, key_id,
);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/keys/{key_id}",);

send_and_translate_response(self.0.client.get(url)).await
}
Expand Down Expand Up @@ -156,7 +153,7 @@ impl Keys<'_> {
/// # }
/// ```
pub async fn create(&self, project_id: &str, options: &Options) -> crate::Result<NewApiKey> {
let url = format!("https://api.deepgram.com/v1/projects/{}/keys", project_id);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/keys");
let request = self
.0
.client
Expand Down Expand Up @@ -200,10 +197,7 @@ impl Keys<'_> {
/// # }
/// ```
pub async fn delete(&self, project_id: &str, key_id: &str) -> crate::Result<Message> {
let url = format!(
"https://api.deepgram.com/v1/projects/{}/keys/{}",
project_id, key_id,
);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/keys/{key_id}",);

send_and_translate_response(self.0.client.delete(url)).await
}
Expand Down
10 changes: 2 additions & 8 deletions src/manage/members.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ impl Members<'_> {
/// # }
/// ```
pub async fn list_members(&self, project_id: &str) -> crate::Result<response::Members> {
let url = format!(
"https://api.deepgram.com/v1/projects/{}/members",
project_id,
);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/members",);

send_and_translate_response(self.0.client.get(url)).await
}
Expand Down Expand Up @@ -110,10 +107,7 @@ impl Members<'_> {
/// # }
/// ```
pub async fn remove_member(&self, project_id: &str, member_id: &str) -> crate::Result<Message> {
let url = format!(
"https://api.deepgram.com/v1/projects/{}/members/{}",
project_id, member_id,
);
let url = format!("https://api.deepgram.com/v1/projects/{project_id}/members/{member_id}",);

send_and_translate_response(self.0.client.delete(url)).await
}
Expand Down
Loading
Loading