Commit a4f2f512 authored by Doug's avatar Doug Committed by Russell Cohen
Browse files

Refactored Polly code examples (#556)

* Refactored Polly code examples to use common example pattern; re-ordered crates in Cargo.toml

* Updated Polly code examples to use ? instead of expect()
parent c1dedbcf
Loading
Loading
Loading
Loading
+2 −2
Original line number Diff line number Diff line
@@ -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" }
+43 −47
Original line number Diff line number Diff line
@@ -3,59 +3,58 @@
 * 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) => {
    let resp = client.describe_voices().send().await?;

    println!("Voices:");

    let voices = resp.voices.unwrap_or_default();
    for voice in &voices {
        println!(
@@ -68,12 +67,9 @@ async fn main() {
        );
    }

            println!("\nFound {} voices\n", voices.len());
        }
        Err(e) => {
            println!("Got an error describing voices:");
            println!("{}", e);
            process::exit(1);
        }
    };
    println!();
    println!("Found {} voices", voices.len());
    println!();

    Ok(())
}
+52 −56
Original line number Diff line number Diff line
@@ -3,60 +3,58 @@
 * 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 Opt {
        default_region,
        verbose,
    } = Opt::from_args();

    let region = EnvironmentProvider::new()
        .region()
        .or_else(|| region.as_ref().map(|region| Region::new(region.clone())))
    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.list_lexicons().send().await {
        Ok(resp) => {
    let resp = client.list_lexicons().send().await?;

    println!("Lexicons:");

    let lexicons = resp.lexicons.unwrap_or_default();

    for lexicon in &lexicons {
@@ -76,12 +74,10 @@ async fn main() {
                .expect("languages must have attributes")
        );
    }
            println!("\nFound {} lexicons.\n", lexicons.len());
        }
        Err(e) => {
            println!("Got an error listing lexicons:");
            println!("{}", e);
            process::exit(1);
        }
    };

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

    Ok(())
}
+48 −3
Original line number Diff line number Diff line
@@ -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
@@ -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 {:?}",
@@ -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| {
@@ -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(())
}
+32 −41
Original line number Diff line number Diff line
@@ -3,79 +3,74 @@
 * 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>,

    /// The name of the lexicon
    /// The name of the lexicon.
    #[structopt(short, long)]
    name: String,

    /// The word to replace
    /// The word to replace.
    #[structopt(short, long)]
    from: String,

    /// The replacement
    /// The replacement.
    #[structopt(short, long)]
    to: String,

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

/// Stores a pronunciation lexicon in an AWS Region.
/// Stores a pronunciation lexicon in a Region.
/// # Arguments
///
/// * `-f FROM` - The original text to customize.
/// * `-n NAME` - The name of the lexicon.
/// * `-t TO` - The customized version of the original text.
/// * `[-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() {
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt::init();

    let Opt {
        from,
        name,
        region,
        default_region,
        to,
        verbose,
    } = Opt::from_args();

    let region = EnvironmentProvider::new()
        .region()
        .or_else(|| region.as_ref().map(|region| Region::new(region.clone())))
    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);
        println!("Lexicon name:     {}", name);
        println!("Text to replace:  {}", from);
        println!("Replacement text: {}", to);

        SubscriberBuilder::default()
            .with_env_filter("info")
            .with_span_events(FmtSpan::CLOSE)
            .init();
        println!("Lexicon name:     {}", &name);
        println!("Text to replace:  {}", &from);
        println!("Replacement text: {}", &to);
        println!();
    }

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

    let client = Client::from_conf(config);

    let content = format!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>
@@ -85,18 +80,14 @@ async fn main() {
    <lexeme><grapheme>{}</grapheme><alias>{}</alias></lexeme>
    </lexicon>", from, to);

    match client
    client
        .put_lexicon()
        .name(name)
        .content(content)
        .send()
        .await
    {
        Ok(_) => println!("Added lexicon"),
        Err(e) => {
            println!("Got an error adding lexicon:");
            println!("{}", e);
            process::exit(1);
        }
    };
        .await?;

    println!("Added lexicon");

    Ok(())
}
Loading