AWS Amplify iOSでテキストを英語から日本語に翻訳する #reinvent

ネイティブアプリ用の新しいSDK「Amplify iOS」と「Amplify Android」がプレビューにて公開されました。iOSではPrediction(予測機能)が実装されています。本記事では、Amplify iOSを使って翻訳機能を試してみました。
2019.12.31

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

翻訳アプリを作ってみよう!

re:Invent 2019の期間中、ネイティブアプリ用の新しいSDKAmplify iOSAmplify Androidがプレビューにて公開されました。

その中でPrediction(予測機能)が新たに追加されました。これによりテキスト翻訳、音声からテキストへの生成、画像認識、テキストから音声、テキストからの洞察などといったユースケースに対応したアプリが作れるようになっています。

本記事では、Amplify iOSを使って翻訳機能を試してみました。AWSサービスとしてはAmazon Translateを利用する形となります。

インストール

それではまずはインストールしていきます。なお、AmplifyのiOSアプリ向けプロジェクトはすでに作成済みの前提で進めます。また、今回は対話形式でのインストールが必要なためAmplify CLIを利用します。

まずは predictions というプラグインを追加します。

$ 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 : translateText269e8b3d
? What is the source language? : English
? What is the target language? : Japanese
? Who should have access? : Auth and Guest users

Prediction機能は以下のように分類されているので、自分の作りたい機能に合わせて設定します。本記事では Convert を選択しています。

? Please select from one of the categories below
  Identify
❯ Convert
  Interpret
  Infer
  Learn More

ローカルでの設定が完了したので amplify push でAWSリソースを作成します。

$ amplify push

| Category    | Resource name          | Operation | Provider plugin   |
| ----------- | ---------------------- | --------- | ----------------- |
| Predictions | translateText269e8b3d  | Create    | awscloudformation |
| Api         | amplifyDatasource      | No Change | awscloudformation |
| Auth        | amplifysample93d65ae8  | No Change | awscloudformation |

以上でAWSリソースの作成は完了です。

次に AWSPredictionsPlugin というPodを追加します。Podfile 全体としては以下のようになります。

target 'AmplifySample' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for AmplifySample
  pod 'Amplify'
  pod 'AWSPluginsCore'
  pod 'AWSPredictionsPlugin'
  pod 'AWSMobileClient', '~> 2.12.0'
end

最後に pod install を実行して終わりです。

$ pod install --repo-update

実装

今回は翻訳を行いたいだけなので、iOSアプリでは画面なしで実装します。

まずは AppDelegate でセットアップする処理を書きます。

AppDelegate.swift

import UIKit
import Amplify
import AWSPredictionsPlugin
import AmplifyPlugins

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let predictionsPlugin = AWSPredictionsPlugin()
        do {
            try Amplify.add(plugin: predictionsPlugin)
            try Amplify.configure()
            print("Amplify initialized")
        } catch {
            print("Failed to configure Amplify \(error)")
        }
        return true
    }

}

次に ViewController で翻訳を行う処理を実装します。translateText() というメソッドを用意しました。

ViewController.swift

import UIKit
import Amplify

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        translateText()
    }
    
    func translateText() {
        let text = "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."
        _ = Amplify.Predictions.convert(
            textToTranslate: text,
            language: .english,
            targetLanguage: .japanese,
            options: PredictionsTranslateTextRequest.Options(),
            listener: { (event) in
                switch event {
                case .completed(let result):
                    print(result.text)
                case .failed(let result):
                    print(result)
                default:
                    print(event)
                }
        })
    }

}

試してみる

それでは実行してみましょう。本記事では以下のテキストを翻訳してみます。

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.

コンソールログに以下のように出力されるかと思います。英語から日本語に翻訳できていることが確認できます。

テキストを翻訳する例を次に示します。 Amplify CLIを使用してこのリソースを追加する際に、ターゲット言語またはソース言語に関して行った選択を上書きするには、以下に示すようにパラメータとして直接渡すことができます。

グローバルに使えるアプリで使おう!

Amazon Translateが日本語をサポートしたことによって、日本向けのアプリでも翻訳機能が便利に扱えるようになりました。ぜひグローバルなアプリを作る場合に導入を検討してみてください。