Page updated Jan 16, 2024

Interpret sentiment

The following API allows you to analyze text for language, entities (places, people), key phrases, sentiment (positive, neutral, negative), and syntax (pronouns, verbs, adjectives).

For analyzing language on iOS we use both AWS backend services as well as Apple's on-device Natural Language Framework to provide you with the most accurate results. If your device is offline, we will return results only Natural Language. On the other hand, if you are able to connect to AWS Services, we will return a unioned result from both the service and Natural Language. Switching between backend services and Natural Language is done automatically without any additional configuration required.

Set up your backend

This will allow you to determine key phrases, sentiment, language, syntax, and entities from text. If you haven't already done so, run amplify init inside your project and then amplify add auth (we recommend selecting the default configuration).

Run amplify add predictions, then use the following answers:

1? Please select from one of the categories below
2 Identify
3 Convert
4❯ Interpret
5 Infer
6 Learn More
7
8? What would you like to interpret? (Use arrow keys)
9❯ Interpret Text
10
11? Provide a friendly name for your resource
12 <Enter a friendly name here>
13
14? What kind of interpretation would you like?
15 Language
16 Entity
17 Keyphrase
18 Sentiment
19 Syntax
20❯ All
21
22? Who should have access?
23 Auth users only
24❯ Auth and Guest users

Run amplify push to create the resources in the cloud

Working with the API

Here is an example of sending text for interpretation such as sentiment analysis or natural language characteristics.

1func interpret(text: String) async throws -> Predictions.Interpret.Result {
2 do {
3 let result = try await Amplify.Predictions.interpret(text: text)
4 print("Interpreted text: \(result)")
5 return result
6 } catch let error as PredictionsError {
7 print("Error interpreting text: \(error)")
8 throw error
9 } catch {
10 print("Unexpected error: \(error)")
11 throw error
12 }
13}
1func interpret(text: String) -> AnyCancellable {
2 Amplify.Publisher.create {
3 try await Amplify.Predictions.interpret(text: text)
4 }
5 .sink(receiveCompletion: { completion in
6 if case let .failure(error) = completion {
7 print("Error interpreting text: \(error)")
8 }
9 }, receiveValue: { value in
10 print("Interpreted text: \(value)")
11 })
12}