Simple Chat with Translator by AWS Amplify
Tags: aws, amplify, vue
Published: 2021-05-25 10:25:53

> Here is the Spanish version translated by [Chema Bescós](https://www.linkedin.com/in/josemariabescos/).
> [Cómo hacer un sencillo chat con traductor, usando AWS Amplify](https://www.ibidemgroup.com/edu/traduccion-automatica-chat-aws-amplify/)

{% youtube SzoN0_m2-7I %}

AWS Amplify has many functions related to other AWS services.
This article uses "Predictions," which is the category of "AI/ML."
Among them, let's use "Translate language."
https://docs.amplify.aws/lib/predictions/translate/q/platform/js 

## 1. Setup

* Node.js (+ yarn)
* [Vue CLI](https://cli.vuejs.org/guide/prototyping.html) (+Vuetify)
* [Amplify CLI](https://docs.amplify.aws/cli/start/install)

Install above items.

## 2. Create Project

Let's create a Vue project.

```
$ vue create sample-amplify-translator-chat


Vue CLI v4.5.13
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router,
 Vuex, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback 
in production) Yes
? Pick a linter / formatter config: Prettier
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated confi
g files
? Save this as a preset for future projects? No

(snip)

$ cd sample-amplify-translator-chat
$ vue add vuetify

(snip)

? Choose a preset: Default (recommended)

(snip)

$
```

And set Amplify project.

```
$ amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project sampleamplifytransla
The following configuration will be applied:

Project information
| Name: sampleamplifytransla
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: vue
| Source Directory Path: src
| Distribution Directory Path: dist
| Build Command: npm run-script build
| Start Command: npm run-script serve

? Initialize the project with the above configuration? No
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using vue
? Source Directory Path:  src
? Distribution Directory Path: dist
? Build Command:  yarn build
? Start Command: yarn serve
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS profile

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Please choose the profile you want to use default
Adding backend environment dev to AWS Amplify Console app: XXXXXXXXXXXXXX
⠇ Initializing project in the cloud...

(snip)

Your project has been successfully initialized and connected to the cloud!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add <category>" will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything

$
```

## 3. Add Auth

"Translate language" function has to need Auth.
So, add Auth function.

```
$ amplify add auth
Using service: Cognito, provided by: awscloudformation
 
 The current configured provider is Amazon Cognito. 
 
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections. 
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.
Successfully added auth resource sampleamplifytransla4290ed5c locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

$
```

Then push the project.

```
$ amplify push
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name                | Operation | Provider plugin   |
| -------- | ---------------------------- | --------- | ----------------- |
| Auth     | sampleamplifytransla4290ed5c | Create    | awscloudformation |
? Are you sure you want to continue? Yes
⠦ Updating resources in the cloud. This may take a few minutes...

(snip)

UPDATE_COMPLETE_CLEANUP_IN_PROGRESS amplify-sampleamplifytransla-dev-221649 AWS::CloudFormation::Stack Mon May 24 2021 22:42:33 GMT+0900 (日本標準時) 
UPDATE_COMPLETE                     amplify-sampleamplifytransla-dev-221649 AWS::CloudFormation::Stack Mon May 24 2021 22:42:34 GMT+0900 (日本標準時) 
✔ All resources are updated in the cloud


$
```

## 4. Add Predictions

Now, the primary function.
Add Predictions to use the "Translate language" function.

```
$ amplify add predictions
? Please select from one of the categories below Convert
? What would you like to convert? Translate text into a different language
? Provide a friendly name for your resource translateText20591e92
? What is the source language? English
? What is the target language? Japanese
? Who should have access? Auth and Guest users
Auth configuration is required to allow unauthenticated users, but it is not configured properly.
Successfully updated auth resource locally.
Successfully added resource translateText20591e92 locally

Some next steps:
"amplify push" builds all of your local backend resources and provisions them in the cloud
"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud

$
```

Push the project.

```
$ amplify push
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category    | Resource name                | Operation | Provider plugin   |
| ----------- | ---------------------------- | --------- | ----------------- |
| Predictions | translateText39476081        | Create    | awscloudformation |
| Auth        | sampleamplifytransla0530875a | Update    | awscloudformation |
? Are you sure you want to continue? Yes
⠋ Updating resources in the cloud. This may take a few minutes...

(snip)

UPDATE_COMPLETE authsampleamplifytransla4290ed5c        AWS::CloudFormation::Stack Mon May 24 2021 22:51:01 GMT+0900 (日本標準時) 
UPDATE_COMPLETE amplify-sampleamplifytransla-dev-221649 AWS::CloudFormation::Stack Mon May 24 2021 22:51:01 GMT+0900 (日本標準時) 
✔ All resources are updated in the cloud


$
```

Your `src/main.js` is below.

``` javascript
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify'

import '@aws-amplify/ui-vue'
import Amplify from 'aws-amplify'
import awsconfig from './aws-exports'

Amplify.configure(awsconfig)
import { AmazonAIPredictionsProvider } from '@aws-amplify/predictions'
Amplify.addPluggable(new AmazonAIPredictionsProvider())

Vue.config.productionTip = false

new Vue({
  router,
  store,
  vuetify,
  render: (h) => h(App),
}).$mount('#app')
```

If you forget to write `Amplify.addPluggable(new AmazonAIPredictionsProvider())` (like me), this system is not work.
Let's check this document.
https://docs.amplify.aws/lib/predictions/getting-started/q/platform/js

## 5. Add API

Add API(GraphQL) for saving messages.

```
$ amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: sampleamplifytransla
? Choose the default authorization type for the API API key
? Enter a description for the API key: 
? After how many days from now the API key should expire (1-365): 7
? Do you want to configure advanced settings for the GraphQL API No, I am done.
? Do you have an annotated GraphQL schema? No
? Choose a schema template: Single object with fields (e.g., “Todo” with ID, name, description)

The following types do not have '@auth' enabled. Consider using @auth with @model
         - Todo
Learn more about @auth here: https://docs.amplify.aws/cli/graphql-transformer/auth


GraphQL schema compiled successfully.

Edit your schema at /[YOUR_DIRECTORY]/sample-amplify-translator-chat/amplify/backend/api/sampleamplifytransla/schema.graphql or place .graphql files in a directory at /[YOUR_DIRECTORY]/sample-amplify-translator-chat/amplify/backend/api/sampleamplifytransla/schema
? Do you want to edit the schema now? No
Successfully added resource sampleamplifytransla locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

$
```

Change `amplify/backend/api/sampleamplifytransla/schema.graphql` below.

``` graphql
type Message @model {
  id: ID!
  userName: String!
  originalMessage: String!
  translatedMessage: String!
  createdAt: AWSDateTime
}
```

Push the project.

```
$ amplify push
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category    | Resource name                | Operation | Provider plugin   |
| ----------- | ---------------------------- | --------- | ----------------- |
| Api         | sampleamplifytransla         | Create    | awscloudformation |
| Auth        | sampleamplifytransla4290ed5c | No Change | awscloudformation |
| Predictions | translateText20591e92        | No Change | awscloudformation |
? Are you sure you want to continue? Yes

The following types do not have '@auth' enabled. Consider using @auth with @model
         - Message
Learn more about @auth here: https://docs.amplify.aws/cli/graphql-transformer/auth


GraphQL schema compiled successfully.

Edit your schema at /[YOUR_DIRECTORY]/sample-amplify-translator-chat/amplify/backend/api/sampleamplifytransla/schema.graphql or place .graphql files in a directory at /[YOUR_DIRECTORY]/sample-amplify-translator-chat/amplify/backend/api/sampleamplifytransla/schema
? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
⠇ Updating resources in the cloud. This may take a few minutes...

(snip)

✔ Generated GraphQL operations successfully and saved at src/graphql
✔ All resources are updated in the cloud

GraphQL endpoint: https://XXXXXXXXXXXXXXXXXXXXXXXXXX.appsync-api.ap-northeast-1.amazonaws.com/graphql
GraphQL API KEY: XXX-XXXXXXXXXXXXXXXXXXXXXXXXXX


$
```


## 6. Implementation

OK, we can implement the chat to include the translate function.

If you want to know about code detail, please see this repository.
{% github tacck/sample-amplify-translator-chat no-readme %}

{% details src/views/Chat.vue %}
``` vue
<template>
  <v-container>
    <v-row>
      <v-col class="pb-0" cols="12" sm="8">
        <v-text-field
          v-model="userName"
          label="User Name"
          outlined
        ></v-text-field
      ></v-col>
      <v-col class="pb-0" cols="6" sm="2">
        <v-select
          :items="languages"
          label="Original Language"
          outlined
          v-model="fromLang"
        ></v-select>
      </v-col>
      <v-col class="pb-0" cols="6" sm="2">
        <v-select
          :items="languages"
          label="Translate to"
          outlined
          v-model="toLang"
        ></v-select>
      </v-col>
      <v-col class="pt-0" cols="12">
        <v-text-field
          v-model="message"
          label="Message"
          outlined
          append-outer-icon="mdi-send"
          @click:append-outer="sendMessage"
        ></v-text-field></v-col
    ></v-row>
    <Timeline :messages="computedSortedMessages"></Timeline>
  </v-container>
</template>

<script>
import { API, graphqlOperation, Predictions } from 'aws-amplify'
import { listMessages } from '@/graphql/queries'
import { createMessage } from '@/graphql/mutations'
import { onCreateMessage } from '@/graphql/subscriptions'

import Timeline from '../components/Timeline'

export default {
  components: { Timeline },
  computed: {
    computedSortedMessages: function () {
      return this.messages
        .slice()
        .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
    },
  },
  data: function () {
    return {
      userName: '',
      message: '',
      fromLang: '',
      toLang: '',
      messages: [],
      languages: ['en', 'ja'],
      onCreateMessageSubscription: null,
    }
  },
  created: async function () {
    const result = await API.graphql(graphqlOperation(listMessages))
    console.log(result)
    this.messages = result.data.listMessages.items

    this.unsubscribe = API.graphql(graphqlOperation(onCreateMessage)).subscribe(
      {
        next: ({ provider, value }) => {
          console.log({ provider, value })
          this.messages.push(value.data.onCreateMessage)
        },
      },
    )
  },
  beforeDestroy: function () {
    if (this.onCreateMessageSubscription) {
      this.onCreateMessageSubscription.unsubscribe()
      this.onCreateMessageSubscription = null
    }
  },
  methods: {
    sendMessage: async function () {
      console.log('sendMessage', this.message)
      const result = await Predictions.convert({
        translateText: {
          source: {
            text: this.message,
            language: this.fromLang,
            // supported languages https://docs.aws.amazon.com/translate/latest/dg/how-it-works.html#how-it-works-language-codes
          },
          targetLanguage: this.toLang,
        },
      })
      console.log(result)

      const message = await API.graphql(
        graphqlOperation(createMessage, {
          input: {
            userName: this.userName,
            originalMessage: this.message,
            translatedMessage: result.text,
          },
        }),
      )
      console.log(message)

      this.userName = ''
      this.message = ''
      this.fromLang = ''
      this.toLang = ''
    },
  },
}
</script>

<style></style>
```
{% enddetails %}

{% details src/components/Timeline.vue %}
``` vue
<template>
  <v-row>
    <v-col class="pb-0" cols="12" v-for="message in messages" :key="message.id">
      <v-card class="ma-4">
        <v-row>
          <v-col cols="12" class="px-5 text-h5 font-weight-light">
            {{ message.userName }}</v-col
          >
        </v-row>
        <v-row>
          <v-col class="py-0" cols="6">
            <v-card outlined color="grey lighten-3">
              <v-card-subtitle class="caption">Original</v-card-subtitle>
              <v-card-text class="body-1">
                {{ message.originalMessage }}</v-card-text
              >
            </v-card></v-col
          >
          <v-col class="px-8" cols="6">{{ message.translatedMessage }}</v-col>
        </v-row>
      </v-card>
    </v-col>
  </v-row>
</template>

<script>
export default {
  props: {
    messages: {
      type: Array,
    },
  },
}
</script>

<style></style>
```
{% enddetails %}

## 7. Checking

You can see the chat like the below movie.

{% youtube SzoN0_m2-7I %}

AWS Amplify is one of the easy ways to use Amazon Translate.