Skip to content

Commit 9fd5da7

Browse files
committed
Rust: Add Comprehend Getting Started scenario using Code Loom
1 parent 29d8410 commit 9fd5da7

File tree

13 files changed

+1073
-0
lines changed

13 files changed

+1073
-0
lines changed

.doc_gen/metadata/comprehend_metadata.yaml

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,15 @@ comprehend_DetectDominantLanguage:
172172
snippet_tags:
173173
- python.example_code.comprehend.ComprehendDetect
174174
- python.example_code.comprehend.DetectDominantLanguage
175+
Rust:
176+
versions:
177+
- sdk_version: 1
178+
github: rustv1/examples/comprehend
179+
sdkguide:
180+
excerpts:
181+
- description:
182+
snippet_tags:
183+
- comprehend.rust.detect-language
175184
services:
176185
comprehend: {DetectDominantLanguage}
177186
comprehend_DetectEntities:
@@ -204,6 +213,15 @@ comprehend_DetectEntities:
204213
snippet_tags:
205214
- python.example_code.comprehend.ComprehendDetect
206215
- python.example_code.comprehend.DetectEntities
216+
Rust:
217+
versions:
218+
- sdk_version: 1
219+
github: rustv1/examples/comprehend
220+
sdkguide:
221+
excerpts:
222+
- description:
223+
snippet_tags:
224+
- comprehend.rust.detect-entities
207225
services:
208226
comprehend: {DetectEntities}
209227
comprehend_DetectKeyPhrases:
@@ -291,6 +309,15 @@ comprehend_DetectSentiment:
291309
snippet_tags:
292310
- python.example_code.comprehend.ComprehendDetect
293311
- python.example_code.comprehend.DetectSentiment
312+
Rust:
313+
versions:
314+
- sdk_version: 1
315+
github: rustv1/examples/comprehend
316+
sdkguide:
317+
excerpts:
318+
- description:
319+
snippet_tags:
320+
- comprehend.rust.detect-sentiment
294321
services:
295322
comprehend: {DetectSentiment}
296323
comprehend_DetectSyntax:
@@ -325,6 +352,23 @@ comprehend_DetectSyntax:
325352
- python.example_code.comprehend.DetectSyntax
326353
services:
327354
comprehend: {DetectSyntax}
355+
comprehend_Hello:
356+
title: Hello &CMP;
357+
title_abbrev: Hello &CMP;
358+
synopsis: Get started using &CMP; by detecting the dominant language in text.
359+
category: Hello
360+
languages:
361+
Rust:
362+
versions:
363+
- sdk_version: 1
364+
github: rustv1/examples/comprehend
365+
sdkguide:
366+
excerpts:
367+
- description:
368+
snippet_tags:
369+
- comprehend.rust.hello
370+
services:
371+
comprehend: {DetectDominantLanguage}
328372
comprehend_Usage_DetectApis:
329373
title: Detect document elements with &CMP; and an &AWS; SDK
330374
title_abbrev: Detect document elements
@@ -354,6 +398,15 @@ comprehend_Usage_DetectApis:
354398
- description: Call functions on the wrapper class to detect entities, phrases, and more in a document.
355399
snippet_tags:
356400
- python.example_code.comprehend.Usage_DetectApis
401+
Rust:
402+
versions:
403+
- sdk_version: 1
404+
github: rustv1/examples/comprehend
405+
sdkguide:
406+
excerpts:
407+
- description: Run a comprehensive scenario demonstrating various Amazon Comprehend text analysis capabilities.
408+
snippet_tags:
409+
- comprehend.rust.getting-started
357410
services:
358411
comprehend: {DetectDominantLanguage, DetectEntities, DetectKeyPhrases, DetectPiiEntities, DetectSentiment, DetectSyntax}
359412
comprehend_StartTopicsDetectionJob:
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[package]
2+
name = "comprehend-code-examples"
3+
version = "0.1.0"
4+
authors = [
5+
"AWS SDK for Rust Team <[email protected]>",
6+
]
7+
edition = "2021"
8+
9+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
10+
11+
[dependencies]
12+
aws-config = { version = "1.0.1", features = ["behavior-version-latest"] }
13+
aws-sdk-comprehend = { version = "1.3.0" }
14+
aws-types = { version = "1.0.1" }
15+
tokio = { version = "1.20.1", features = ["full"] }
16+
clap = { version = "4.4", features = ["derive"] }
17+
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
18+
tracing = "0.1.40"
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# Amazon Comprehend code examples for the SDK for Rust
2+
3+
## Overview
4+
5+
Shows how to use the AWS SDK for Rust to work with Amazon Comprehend.
6+
7+
<!--custom.overview.start-->
8+
<!--custom.overview.end-->
9+
10+
_Amazon Comprehend is a natural language processing (NLP) service that uses machine learning to find insights and relationships in text._
11+
12+
## ⚠ Important
13+
14+
* 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/).
15+
* Running the tests might result in charges to your AWS account.
16+
* 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).
17+
* 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).
18+
19+
<!--custom.important.start-->
20+
<!--custom.important.end-->
21+
22+
## Code examples
23+
24+
### Prerequisites
25+
26+
For prerequisites, see the [README](../../README.md#Prerequisites) in the `rustv1` folder.
27+
28+
### Get started
29+
30+
- [Hello Amazon Comprehend](src/bin/hello.rs#L25) (`DetectDominantLanguage`)
31+
32+
### Single actions
33+
34+
Code excerpts that show you how to call individual service functions.
35+
36+
- [DetectDominantLanguage](src/bin/detect-language.rs#L18) (`DetectDominantLanguage`)
37+
- [DetectEntities](src/bin/detect-entities.rs#L18) (`DetectEntities`)
38+
- [DetectSentiment](src/bin/detect-sentiment.rs#L18) (`DetectSentiment`)
39+
40+
### Scenarios
41+
42+
Code examples that show you how to accomplish a specific task by calling multiple functions within the same service.
43+
44+
- [Get started with Amazon Comprehend](src/bin/getting-started.rs) (`DetectDominantLanguage`, `DetectEntities`, `DetectKeyPhrases`, `DetectSentiment`, `DetectPiiEntities`, `DetectSyntax`)
45+
46+
## Run the examples
47+
48+
### Instructions
49+
50+
<!--custom.instructions.start-->
51+
<!--custom.instructions.end-->
52+
53+
#### Hello Amazon Comprehend
54+
55+
This example shows you how to get started using Amazon Comprehend.
56+
57+
```
58+
cargo run --bin hello
59+
```
60+
61+
#### Get started with Amazon Comprehend
62+
63+
This example shows you how to do the following:
64+
65+
- Detect the dominant language in text.
66+
- Extract entities from text.
67+
- Detect key phrases in text.
68+
- Analyze sentiment in text.
69+
- Detect personally identifiable information (PII) in text.
70+
- Analyze syntax in text.
71+
72+
```
73+
cargo run --bin getting-started
74+
```
75+
76+
#### Detect dominant language
77+
78+
This example shows you how to detect the dominant language in text.
79+
80+
```
81+
cargo run --bin detect-language
82+
```
83+
84+
You can also specify custom text:
85+
86+
```
87+
cargo run --bin detect-language -- --text "Bonjour, comment allez-vous?"
88+
```
89+
90+
#### Detect entities
91+
92+
This example shows you how to detect entities in text.
93+
94+
```
95+
cargo run --bin detect-entities
96+
```
97+
98+
You can also specify custom text and language:
99+
100+
```
101+
cargo run --bin detect-entities -- --text "John works at Amazon in Seattle" --language-code "en"
102+
```
103+
104+
#### Detect sentiment
105+
106+
This example shows you how to detect sentiment in text.
107+
108+
```
109+
cargo run --bin detect-sentiment
110+
```
111+
112+
You can also specify custom text and language:
113+
114+
```
115+
cargo run --bin detect-sentiment -- --text "I love this product!" --language-code "en"
116+
```
117+
118+
### Tests
119+
120+
⚠ Running tests might result in charges to your AWS account.
121+
122+
To find instructions for running these tests, see the [README](../../README.md#Tests) in the `rustv1` folder.
123+
124+
<!--custom.tests.start-->
125+
<!--custom.tests.end-->
126+
127+
## Additional resources
128+
129+
- [Amazon Comprehend Developer Guide](https://docs.aws.amazon.com/comprehend/latest/dg/what-is.html)
130+
- [Amazon Comprehend API Reference](https://docs.aws.amazon.com/comprehend/latest/APIReference/Welcome.html)
131+
- [SDK for Rust Amazon Comprehend reference](https://docs.rs/aws-sdk-comprehend/latest/aws_sdk_comprehend/)
132+
133+
<!--custom.resources.start-->
134+
<!--custom.resources.end-->
135+
136+
---
137+
138+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
139+
140+
SPDX-License-Identifier: Apache-2.0
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
#![allow(clippy::result_large_err)]
5+
6+
use aws_config::meta::region::RegionProviderChain;
7+
use aws_sdk_comprehend::{config::Region, Client, Error};
8+
use clap::Parser;
9+
10+
#[derive(Debug, Parser)]
11+
struct Opt {
12+
/// The text to analyze for entities.
13+
#[structopt(short, long)]
14+
text: Option<String>,
15+
16+
/// The language code (e.g., "en" for English).
17+
#[structopt(short, long)]
18+
language_code: Option<String>,
19+
20+
/// The AWS Region.
21+
#[structopt(short, long)]
22+
region: Option<String>,
23+
24+
/// Whether to display additional information.
25+
#[structopt(short, long)]
26+
verbose: bool,
27+
}
28+
29+
// snippet-start:[comprehend.rust.detect-entities]
30+
/// Detects entities in the provided text using Amazon Comprehend.
31+
async fn detect_entities(client: &aws_sdk_comprehend::Client, text: &str, language_code: &str) -> Result<(), Error> {
32+
let response = client
33+
.detect_entities()
34+
.text(text)
35+
.language_code(language_code.into())
36+
.send()
37+
.await?;
38+
39+
println!("Detected entities:");
40+
if let Some(entities) = response.entities {
41+
if entities.is_empty() {
42+
println!(" No entities detected.");
43+
} else {
44+
for entity in entities {
45+
println!(
46+
" {}: {} (confidence: {:.2}%)",
47+
entity.r#type().unwrap().as_str(),
48+
entity.text().unwrap_or("unknown"),
49+
entity.score().unwrap_or(0.0) * 100.0
50+
);
51+
}
52+
}
53+
} else {
54+
println!(" No entities detected.");
55+
}
56+
57+
Ok(())
58+
}
59+
// snippet-end:[comprehend.rust.detect-entities]
60+
61+
/// Detects entities in text using Amazon Comprehend.
62+
///
63+
/// # Arguments
64+
///
65+
/// * `[-t TEXT]` - The text to analyze. If not provided, uses a default sample.
66+
/// * `[-l LANGUAGE_CODE]` - The language code (e.g., "en"). If not provided, defaults to "en".
67+
/// * `[-r REGION]` - The Region in which the client is created.
68+
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
69+
/// If the environment variable is not set, defaults to **us-west-2**.
70+
/// * `[-v]` - Whether to display additional information.
71+
#[tokio::main]
72+
async fn main() -> Result<(), Error> {
73+
tracing_subscriber::fmt::init();
74+
let Opt { text, language_code, region, verbose } = Opt::parse();
75+
76+
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
77+
.or_default_provider()
78+
.or_else(Region::new("us-west-2"));
79+
80+
if verbose {
81+
println!("Comprehend client version: {}", aws_sdk_comprehend::meta::PKG_VERSION);
82+
println!(
83+
"Region: {}",
84+
region_provider.region().await.unwrap().as_ref()
85+
);
86+
println!();
87+
}
88+
89+
let shared_config = aws_config::from_env().region(region_provider).load().await;
90+
let client = Client::new(&shared_config);
91+
92+
let text_to_analyze = text.as_deref().unwrap_or(
93+
"John Doe works at Amazon Web Services in Seattle, Washington. He can be reached at [email protected]."
94+
);
95+
let lang_code = language_code.as_deref().unwrap_or("en");
96+
97+
println!("Analyzing text: \"{}\"", text_to_analyze);
98+
println!("Language code: {}", lang_code);
99+
println!();
100+
101+
detect_entities(&client, text_to_analyze, lang_code).await?;
102+
103+
Ok(())
104+
}

0 commit comments

Comments
 (0)