LoginSignup
3
1

More than 3 years have passed since last update.

AutoMLTranslationAPIを使用して作ったモデルで自動翻訳

Posted at

はじめに

前回投稿したGoogle AutoMLの学習をしたモデルを使用して、ファイルの中身を翻訳して指定してファイルに出力してくれるようにしてみました!
たくさんの文章を翻訳して検証したり、翻訳時間を計測する仕組みを作るのも楽になりました:sunny:

開発環境

・Windows10
・VScode
・Python3

実装

AutoMLのAPIを使用するのにサービスアカウントを取得する必要があります。


from google.cloud import automl_v1beta1 as automl
import os

#model_id → AutoMLtranslationで作成したモデルのID
model_id =  '...'
#file_path → 翻訳したい文章のかいてあるファイルのファイルパス
file_path = '...'
#サービスアカウントの作成時にダウンロードしたサービスアカウントキーファイルのパスを設定
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "..."

automl_client = automl.AutoMlClient()
prediction_client = automl.PredictionServiceClient()

#file_pathに指定したファイルを開く
with open(file_path, "rb") as content_file:
    #ファイルの中身を1行ずつ読んで処理
    content = content_file.readline()
    while content:
        content.decode("utf-8")
        payload = {"text_snippet": {"content": content}}
        params = {}
        response = prediction_client.predict(model_id, payload, params)
        translated_content = response.payload[0].translation.translated_content
        #'...'に翻訳結果を入力したいファイルを指定。なければ作成されます。
        with open('...', mode='a',newline="",encoding='utf-8')as f:
            #指定したファイルを開いて翻訳結果を書き込む
            f.write(u"{}".format(translated_content.content))
        content = content_file.readline()
content.decode("utf-8")

詰まったとこ

google.cloudがimportできないことがあって少し詰まったので解決方法をかいておきます
VScodeのsettingファイルに記入してあるpythonのpathと実際のpathが違うことによるエラーだったようです。

which python

このコマンドを実行した後に出てくるpathがpythonのある場所なのでそのpathを./vscode/setting.jsonにあるpython.pythonPathに設定したところ、エラーが出なくなりました!

/vscode/setting.json
{
  "python.pythonPath": "..."
}

終わりに

APIにすぐしてくれるってとっても便利だなぁと感じました!
しばらくAutoMLのデータばっかり作っていたのでPythonを触るいい機会でした:blush:
APIにリクエストを投げるところと結果の取得のところはほとんどサンプルコードの引用ですが、
ファイルの内容を一文ずつ処理したりとか、翻訳結果を一つずつファイルに出力するところは自分で考えてコードを書いたので、楽しかったです:sunny:
シンプルなコードですが参考にしていただけると嬉しいです!

参考文献

外部モジュールをimportすると、「Unable to import 'module-name' pylint(import error)」と表示される
AutoML Translation ドキュメント

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1