Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored Polly code examples #556

Merged
merged 2 commits into from
Jun 30, 2021
Merged
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
4 changes: 2 additions & 2 deletions aws/sdk/examples/polly/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ edition = "2018"

[dependencies]
polly = { package = "aws-sdk-polly", path = "../../build/aws-sdk/polly" }
bytes = "1"
aws-types = { path = "../../build/aws-sdk/aws-types" }
tokio = { version = "1", features = ["full"] }
structopt = { version = "0.3", default-features = false }
tracing-subscriber = { version = "0.2.16", features = ["fmt"] }
aws-types = { path = "../../build/aws-sdk/aws-types" }

90 changes: 43 additions & 47 deletions aws/sdk/examples/polly/src/bin/describe-voices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,77 +3,73 @@
* SPDX-License-Identifier: Apache-2.0.
*/

use std::process;

use polly::{Client, Config, Region};

use aws_types::region::{EnvironmentProvider, ProvideRegion};

use aws_types::region::ProvideRegion;
use polly::{Client, Config, Error, Region, PKG_VERSION};
use structopt::StructOpt;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::SubscriberBuilder;

#[derive(Debug, StructOpt)]
struct Opt {
/// The region
/// The default AWS Region.
#[structopt(short, long)]
region: Option<String>,
default_region: Option<String>,

/// Display additional information
/// Whether to isplay additional information.
#[structopt(short, long)]
verbose: bool,
}

/// Displays a list of the voices in the region.
/// Displays a list of the voices in the Region.
/// # Arguments
///
/// * `[-d DEFAULT-REGION]` - The region in which the client is created.
/// If not supplied, uses the value of the **AWS_DEFAULT_REGION** environment variable.
/// * `[-d DEFAULT-REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() {
let Opt { region, verbose } = Opt::from_args();
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();

let region = EnvironmentProvider::new()
.region()
.or_else(|| region.as_ref().map(|region| Region::new(region.clone())))
let Opt {
default_region,
verbose,
} = Opt::from_args();

let region = default_region
.as_ref()
.map(|region| Region::new(region.clone()))
.or_else(|| aws_types::region::default_provider().region())
.unwrap_or_else(|| Region::new("us-west-2"));

println!();

if verbose {
println!("polly client version: {}\n", polly::PKG_VERSION);
println!("Polly version: {}", PKG_VERSION);
println!("Region: {:?}", &region);

SubscriberBuilder::default()
.with_env_filter("info")
.with_span_events(FmtSpan::CLOSE)
.init();
println!();
}

let config = Config::builder().region(region).build();
let client = Client::from_conf(config);

match client.describe_voices().send().await {
Ok(resp) => {
println!("Voices:");
let voices = resp.voices.unwrap_or_default();
for voice in &voices {
println!(
" Name: {}",
voice.name.as_deref().unwrap_or("No name!")
);
println!(
" Language: {}",
voice.language_name.as_deref().unwrap_or("No language!")
);
}
let resp = client.describe_voices().send().await?;

println!("Voices:");

let voices = resp.voices.unwrap_or_default();
for voice in &voices {
println!(
" Name: {}",
voice.name.as_deref().unwrap_or("No name!")
);
println!(
" Language: {}",
voice.language_name.as_deref().unwrap_or("No language!")
);
}

println!();
println!("Found {} voices", voices.len());
println!();

println!("\nFound {} voices\n", voices.len());
}
Err(e) => {
println!("Got an error describing voices:");
println!("{}", e);
process::exit(1);
}
};
Ok(())
}
108 changes: 52 additions & 56 deletions aws/sdk/examples/polly/src/bin/list-lexicons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,85 +3,81 @@
* SPDX-License-Identifier: Apache-2.0.
*/

use std::process;

use polly::{Client, Config, Region};

use aws_types::region::{EnvironmentProvider, ProvideRegion};

use aws_types::region::ProvideRegion;
use polly::{Client, Config, Error, Region, PKG_VERSION};
use structopt::StructOpt;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::SubscriberBuilder;

#[derive(Debug, StructOpt)]
struct Opt {
/// The region
/// The default AWS Region.
#[structopt(short, long)]
region: Option<String>,
default_region: Option<String>,

/// Activate verbose mode
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}

/// Displays a list of the lexicons in the region.
/// Displays a list of the lexicons in the Region.
/// # Arguments
///
/// * `[-d DEFAULT-REGION]` - The region in which the client is created.
/// If not supplied, uses the value of the **AWS_DEFAULT_REGION** environment variable.
/// * `[-d DEFAULT-REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() {
let Opt { region, verbose } = Opt::from_args();
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();

let region = EnvironmentProvider::new()
.region()
.or_else(|| region.as_ref().map(|region| Region::new(region.clone())))
let Opt {
default_region,
verbose,
} = Opt::from_args();

let region = default_region
.as_ref()
.map(|region| Region::new(region.clone()))
.or_else(|| aws_types::region::default_provider().region())
.unwrap_or_else(|| Region::new("us-west-2"));

if verbose {
println!("polly client version: {}\n", polly::PKG_VERSION);
println!("Region: {:?}", &region);
println!();

SubscriberBuilder::default()
.with_env_filter("info")
.with_span_events(FmtSpan::CLOSE)
.init();
if verbose {
println!("Polly version: {}", PKG_VERSION);
println!("Region: {:?}", &region);
println!();
}

let config = Config::builder().region(region).build();

let client = Client::from_conf(config);

match client.list_lexicons().send().await {
Ok(resp) => {
println!("Lexicons:");
let lexicons = resp.lexicons.unwrap_or_default();
let resp = client.list_lexicons().send().await?;

println!("Lexicons:");

let lexicons = resp.lexicons.unwrap_or_default();

for lexicon in &lexicons {
println!(
" Name: {}",
lexicon.name.as_deref().unwrap_or_default()
);
println!(
" Language: {:?}\n",
lexicon
.attributes
.as_ref()
.map(|attrib| attrib
.language_code
.as_ref()
.expect("languages must have language codes"))
.expect("languages must have attributes")
);
}

println!();
println!("Found {} lexicons.", lexicons.len());
println!();

for lexicon in &lexicons {
println!(
" Name: {}",
lexicon.name.as_deref().unwrap_or_default()
);
println!(
" Language: {:?}\n",
lexicon
.attributes
.as_ref()
.map(|attrib| attrib
.language_code
.as_ref()
.expect("languages must have language codes"))
.expect("languages must have attributes")
);
}
println!("\nFound {} lexicons.\n", lexicons.len());
}
Err(e) => {
println!("Got an error listing lexicons:");
println!("{}", e);
process::exit(1);
}
};
Ok(())
}
51 changes: 48 additions & 3 deletions aws/sdk/examples/polly/src/bin/polly-helloworld.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,21 @@
* SPDX-License-Identifier: Apache-2.0.
*/

use aws_types::region::ProvideRegion;
use polly::model::{Engine, Voice};
use std::error::Error;
use polly::{Client, Config, Error, Region, PKG_VERSION};
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
/// The default AWS Region.
#[structopt(short, long)]
default_region: Option<String>,

/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}

/// Displays a list of the voices and their language, and those supporting a neural engine, in the region.
/// # Arguments
Expand All @@ -14,17 +27,44 @@ use std::error::Error;
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let client = polly::Client::from_env();
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();

let Opt {
default_region,
verbose,
} = Opt::from_args();

let region = default_region
.as_ref()
.map(|region| Region::new(region.clone()))
.or_else(|| aws_types::region::default_provider().region())
.unwrap_or_else(|| Region::new("us-west-2"));

println!();

if verbose {
println!("Polly version: {}", PKG_VERSION);
println!("Region: {:?}", &region);
println!();
}

let config = Config::builder().region(region).build();
let client = Client::from_conf(config);

let mut tok = None;
let mut voices: Vec<Voice> = vec![];

// Below is an an example of how pagination can be implemented manually.
loop {
let mut req = client.describe_voices();

if let Some(tok) = tok {
req = req.next_token(tok);
}

let resp = req.send().await?;

for voice in resp.voices.unwrap_or_default() {
println!(
"I can speak as: {} in {:?}",
Expand All @@ -33,11 +73,13 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
);
voices.push(voice);
}

tok = match resp.next_token {
Some(next) => Some(next),
None => break,
};
}

let neural_voices = voices
.iter()
.filter(|voice| {
Expand All @@ -50,6 +92,9 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
.map(|voice| voice.id.as_ref().unwrap())
.collect::<Vec<_>>();

println!();
println!("Voices supporting a neural engine: {:?}", neural_voices);
println!();

Ok(())
}
Loading