Page updated Jan 16, 2024

Translate language

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 convert? (Use arrow keys)
9❯ Translate text into a different language
10 Generate speech audio from text
11 Transcribe text from audio
12
13? Provide a friendly name for your resource
14 <Enter a friendly name here>
15
16? What is the source language? (Use arrow keys)
17 <Select your default source language>
18
19? What is the target language? (Use arrow keys)
20 <Select your default target language>
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 translating text. In order to override any choices you made in regards to target or source languages while adding this resource using the Amplify CLI, you can pass in them in directly as parameters as shown below.

1func translateText(text: String) async throws -> String {
2 do {
3 let result = try await Amplify.Predictions.convert(
4 .translateText(text, from: .english, to: .italian)
5 )
6 print("Translated text: \(result.text)")
7 return result.text
8 } catch let error as PredictionsError {
9 print("Error translating text: \(error)")
10 throw error
11 } catch {
12 print("Unexpected error: \(error)")
13 throw error
14 }
15}
1func translateText(text: String) -> AnyCancellable {
2 Amplify.Publisher.create {
3 try await Amplify.Predictions.convert(
4 .translateText(text, from: .english, to: .italian)
5 )
6 }
7 .sink(receiveCompletion: { completion in
8 if case let .failure(error) = completion {
9 print("Error translating text: \(error)")
10 }
11 }, receiveValue: { value in
12 print("Translated text: \(value.text)")
13 })
14}

As a result of running this code, you will see the translated text printed to the console.