AWS Amplify의 번역기와 간단한 채팅

34446 단어 vueawsamplify

Here is the Spanish version translated by .
Cómo hacer un sencillo chat con traductor, usando AWS Amplify





AWS Amplify에는 다른 AWS 서비스와 관련된 많은 기능이 있습니다.
이 문서에서는 "AI/ML"범주인 "예측"을 사용합니다.
그 중 "번역 언어"를 사용합시다.
https://docs.amplify.aws/lib/predictions/translate/q/platform/js

1. 설정


  • Node.js(+실)

  • Vue CLI (+Vuetify)
  • Amplify CLI

  • 위의 항목을 설치하십시오.

    2. 프로젝트 생성



    Vue 프로젝트를 생성해 봅시다.

    $ 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)
    
    $
    

    그리고 Amplify 프로젝트를 설정합니다.

    $ 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. 인증 추가



    "언어 번역"기능에는 인증이 필요합니다.
    따라서 인증 기능을 추가하십시오.

    $ 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
    
    $
    

    그런 다음 프로젝트를 푸시합니다.

    $ 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. 예측 추가



    이제 주요 기능입니다.
    "언어 번역"기능을 사용하려면 예측을 추가하세요.

    $ 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
    
    $
    

    프로젝트를 푸시합니다.

    $ 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
    
    
    $
    

    귀하의 src/main.js가 아래에 있습니다.

    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')
    
    Amplify.addPluggable(new AmazonAIPredictionsProvider()) 쓰는 것을 잊으면 (나처럼) 이 시스템은 작동하지 않는다.
    이 문서를 확인해 봅시다.
    https://docs.amplify.aws/lib/predictions/getting-started/q/platform/js

    5. API 추가



    메시지 저장을 위한 API(GraphQL) 추가.

    $ 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
    
    $
    

    아래 변경amplify/backend/api/sampleamplifytransla/schema.graphql.

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

    프로젝트를 푸시합니다.

    $ 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. 시행



    좋습니다. 번역 기능을 포함하도록 채팅을 구현할 수 있습니다.

    코드 세부 사항에 대해 알고 싶다면 이 저장소를 참조하십시오.


    압정 / 샘플-증폭-번역기-채팅







    src/views/Chat.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>
    




    src/components/Timeline.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>
    



    7. 확인



    아래 동영상과 같은 대화를 볼 수 있습니다.



    AWS Amplify는 Amazon Translate를 사용하는 쉬운 방법 중 하나입니다.

    좋은 웹페이지 즐겨찾기