Skip to content

Rust: Add Comprehend Getting Started scenario using Code Loom #7553

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
53 changes: 53 additions & 0 deletions .doc_gen/metadata/comprehend_metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,15 @@ comprehend_DetectDominantLanguage:
snippet_tags:
- python.example_code.comprehend.ComprehendDetect
- python.example_code.comprehend.DetectDominantLanguage
Rust:
versions:
- sdk_version: 1
github: rustv1/examples/comprehend
sdkguide:
excerpts:
- description:
snippet_tags:
- comprehend.rust.detect-language
services:
comprehend: {DetectDominantLanguage}
comprehend_DetectEntities:
Expand Down Expand Up @@ -204,6 +213,15 @@ comprehend_DetectEntities:
snippet_tags:
- python.example_code.comprehend.ComprehendDetect
- python.example_code.comprehend.DetectEntities
Rust:
versions:
- sdk_version: 1
github: rustv1/examples/comprehend
sdkguide:
excerpts:
- description:
snippet_tags:
- comprehend.rust.detect-entities
services:
comprehend: {DetectEntities}
comprehend_DetectKeyPhrases:
Expand Down Expand Up @@ -291,6 +309,15 @@ comprehend_DetectSentiment:
snippet_tags:
- python.example_code.comprehend.ComprehendDetect
- python.example_code.comprehend.DetectSentiment
Rust:
versions:
- sdk_version: 1
github: rustv1/examples/comprehend
sdkguide:
excerpts:
- description:
snippet_tags:
- comprehend.rust.detect-sentiment
services:
comprehend: {DetectSentiment}
comprehend_DetectSyntax:
Expand Down Expand Up @@ -325,6 +352,23 @@ comprehend_DetectSyntax:
- python.example_code.comprehend.DetectSyntax
services:
comprehend: {DetectSyntax}
comprehend_Hello:
title: Hello &CMP;
title_abbrev: Hello &CMP;
synopsis: Get started using &CMP; by detecting the dominant language in text.
category: Hello
languages:
Rust:
versions:
- sdk_version: 1
github: rustv1/examples/comprehend
sdkguide:
excerpts:
- description:
snippet_tags:
- comprehend.rust.hello
services:
comprehend: {DetectDominantLanguage}
comprehend_Usage_DetectApis:
title: Detect document elements with &CMP; and an &AWS; SDK
title_abbrev: Detect document elements
Expand Down Expand Up @@ -354,6 +398,15 @@ comprehend_Usage_DetectApis:
- description: Call functions on the wrapper class to detect entities, phrases, and more in a document.
snippet_tags:
- python.example_code.comprehend.Usage_DetectApis
Rust:
versions:
- sdk_version: 1
github: rustv1/examples/comprehend
sdkguide:
excerpts:
- description: Run a comprehensive scenario demonstrating various Amazon Comprehend text analysis capabilities.
snippet_tags:
- comprehend.rust.getting-started
services:
comprehend: {DetectDominantLanguage, DetectEntities, DetectKeyPhrases, DetectPiiEntities, DetectSentiment, DetectSyntax}
comprehend_StartTopicsDetectionJob:
Expand Down
18 changes: 18 additions & 0 deletions rustv1/examples/comprehend/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "comprehend-code-examples"
version = "0.1.0"
authors = [
"AWS SDK for Rust Team <[email protected]>",
]
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
aws-config = { version = "1.0.1", features = ["behavior-version-latest"] }
aws-sdk-comprehend = { version = "1.3.0" }
aws-types = { version = "1.0.1" }
tokio = { version = "1.20.1", features = ["full"] }
clap = { version = "4.4", features = ["derive"] }
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
tracing = "0.1.40"
140 changes: 140 additions & 0 deletions rustv1/examples/comprehend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Amazon Comprehend code examples for the SDK for Rust

## Overview

Shows how to use the AWS SDK for Rust to work with Amazon Comprehend.

<!--custom.overview.start-->
<!--custom.overview.end-->

_Amazon Comprehend is a natural language processing (NLP) service that uses machine learning to find insights and relationships in text._

## ⚠ Important

* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/).
* Running the tests might result in charges to your AWS account.
* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege).
* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).

<!--custom.important.start-->
<!--custom.important.end-->

## Code examples

### Prerequisites

For prerequisites, see the [README](../../README.md#Prerequisites) in the `rustv1` folder.

### Get started

- [Hello Amazon Comprehend](src/bin/hello.rs#L25) (`DetectDominantLanguage`)

### Single actions

Code excerpts that show you how to call individual service functions.

- [DetectDominantLanguage](src/bin/detect-language.rs#L18) (`DetectDominantLanguage`)
- [DetectEntities](src/bin/detect-entities.rs#L18) (`DetectEntities`)
- [DetectSentiment](src/bin/detect-sentiment.rs#L18) (`DetectSentiment`)

### Scenarios

Code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

- [Get started with Amazon Comprehend](src/bin/getting-started.rs) (`DetectDominantLanguage`, `DetectEntities`, `DetectKeyPhrases`, `DetectSentiment`, `DetectPiiEntities`, `DetectSyntax`)

## Run the examples

### Instructions

<!--custom.instructions.start-->
<!--custom.instructions.end-->

#### Hello Amazon Comprehend

This example shows you how to get started using Amazon Comprehend.

```
cargo run --bin hello
```

#### Get started with Amazon Comprehend

This example shows you how to do the following:

- Detect the dominant language in text.
- Extract entities from text.
- Detect key phrases in text.
- Analyze sentiment in text.
- Detect personally identifiable information (PII) in text.
- Analyze syntax in text.

```
cargo run --bin getting-started
```

#### Detect dominant language

This example shows you how to detect the dominant language in text.

```
cargo run --bin detect-language
```

You can also specify custom text:

```
cargo run --bin detect-language -- --text "Bonjour, comment allez-vous?"
```

#### Detect entities

This example shows you how to detect entities in text.

```
cargo run --bin detect-entities
```

You can also specify custom text and language:

```
cargo run --bin detect-entities -- --text "John works at Amazon in Seattle" --language-code "en"
```

#### Detect sentiment

This example shows you how to detect sentiment in text.

```
cargo run --bin detect-sentiment
```

You can also specify custom text and language:

```
cargo run --bin detect-sentiment -- --text "I love this product!" --language-code "en"
```

### Tests

⚠ Running tests might result in charges to your AWS account.

To find instructions for running these tests, see the [README](../../README.md#Tests) in the `rustv1` folder.

<!--custom.tests.start-->
<!--custom.tests.end-->

## Additional resources

- [Amazon Comprehend Developer Guide](https://docs.aws.amazon.com/comprehend/latest/dg/what-is.html)
- [Amazon Comprehend API Reference](https://docs.aws.amazon.com/comprehend/latest/APIReference/Welcome.html)
- [SDK for Rust Amazon Comprehend reference](https://docs.rs/aws-sdk-comprehend/latest/aws_sdk_comprehend/)

<!--custom.resources.start-->
<!--custom.resources.end-->

---

Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
104 changes: 104 additions & 0 deletions rustv1/examples/comprehend/src/bin/detect-entities.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

#![allow(clippy::result_large_err)]

use aws_config::meta::region::RegionProviderChain;
use aws_sdk_comprehend::{config::Region, Client, Error};
use clap::Parser;

#[derive(Debug, Parser)]
struct Opt {
/// The text to analyze for entities.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Meh - these comments sorta suck

#[structopt(short, long)]
text: Option<String>,

/// The language code (e.g., "en" for English).
#[structopt(short, long)]
language_code: Option<String>,

/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,

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

// snippet-start:[comprehend.rust.detect-entities]
/// Detects entities in the provided text using Amazon Comprehend.
async fn detect_entities(client: &aws_sdk_comprehend::Client, text: &str, language_code: &str) -> Result<(), Error> {
let response = client
.detect_entities()
.text(text)
.language_code(language_code.into())
.send()
.await?;

println!("Detected entities:");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fine for an example

if let Some(entities) = response.entities {
if entities.is_empty() {
println!(" No entities detected.");
} else {
for entity in entities {
println!(
" {}: {} (confidence: {:.2}%)",
entity.r#type().unwrap().as_str(),
entity.text().unwrap_or("unknown"),
entity.score().unwrap_or(0.0) * 100.0
);
}
}
} else {
println!(" No entities detected.");
}

Ok(())
}
// snippet-end:[comprehend.rust.detect-entities]

/// Detects entities in text using Amazon Comprehend.
///
/// # Arguments
///
/// * `[-t TEXT]` - The text to analyze. If not provided, uses a default sample.
/// * `[-l LANGUAGE_CODE]` - The language code (e.g., "en"). If not provided, defaults to "en".
/// * `[-r 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() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { text, language_code, region, verbose } = Opt::parse();

let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));

if verbose {
println!("Comprehend client version: {}", aws_sdk_comprehend::meta::PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
}

let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);

let text_to_analyze = text.as_deref().unwrap_or(
"John Doe works at Amazon Web Services in Seattle, Washington. He can be reached at [email protected]."
);
let lang_code = language_code.as_deref().unwrap_or("en");

println!("Analyzing text: \"{}\"", text_to_analyze);
println!("Language code: {}", lang_code);
println!();

detect_entities(&client, text_to_analyze, lang_code).await?;

Ok(())
}
Loading
Loading