LoginSignup
7
5

More than 5 years have passed since last update.

HerokuでCloud Natural Language APIを使う

Last updated at Posted at 2017-06-11

目的

Cloud Natural Language API をHerokuで利用したい

課題

APIを利用するためには、Googleの認証が必要です。認証の際に、サービスアカウントキーの指定が必要ですが、認証キーはファイル形式でしか取得できません。Herokuは、ファイルをアップロードすることができないため、そのままでは認証できません。ファイル形式ではなく、JSONのテキストのまま読み込む必要があります。

解決方法

ENV['GOOGLE_CLOUD_KEYFILE_JSON']を使う。
GOOGLE_CLOUD_KEYFILE_JSONは、ファイルオープンせずにJSONのテキストをそのまま読み込みます。

設定方法

heroku config:set GOOGLE_CLOUD_KEYFILE_JSON="$(< ./keyfile.json)"

※ keyfile.jsonは、サービスアカウントキーファイルです。サービスアカウントを作成するとダウンロードされるファイルです。実際のファイル名は、[project_name].json

実行

環境変数が設定されていれば、Google::Cloud::Languageに設定を渡す必要はありません。

require "google/cloud/language"

language = Google::Cloud::Language.new

content = "Star Wars is a great movie. The Death Star is fearsome."
document = language.document content
annotation = document.annotate

annotation.entities.count #=> 3
annotation.sentiment.score #=> 0.10000000149011612
annotation.sentiment.magnitude #=> 1.100000023841858
annotation.sentences.count #=> 2
annotation.tokens.count #=> 13

引用元: https://github.com/GoogleCloudPlatform/google-cloud-ruby/tree/master/google-cloud-language

Tips

Heroku以外でファイルが置ける場合は、環境変数GOOGLE_CLOUD_KEYFILE=/path/to/keyfile.jsonのほうがオススメです。

参考

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