0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby で Natural Language API を叩く

Posted at

ゴール

以下を Ruby から叩く。

API 呼び出すための準備

ドキュメント見ながら「SDK と認証をテストする」をやってみる

基本的には、Google Cloud Console からポチポチするだけ
Cloud SDK のインストールで pyenv を入れるところ少しハマった
個人記事ではなくドキュメント見ましょう(自戒)

Gem から API を叩く

require 'google/apis/language_v1'

# Doc: https://googleapis.dev/ruby/google-api-client/v0.23.6/Google/Apis/LanguageV1/CloudNaturalLanguageService.html
service = Google::Apis::LanguageV1::CloudNaturalLanguageService.new
service.key = '...'

# リクエスト仕様を確認しつつ設定
attrs = {
  document: {
    type: 'PLAIN_TEXT',
    language: 'ja',
    content: 'テスト',
  },
  encoding_type: 'UTF8'
}

# Doc: https://googleapis.dev/ruby/google-api-client/v0.23.6/Google/Apis/LanguageV1/AnalyzeEntitiesRequest.html
request = Google::Apis::LanguageV1::AnalyzeEntitiesRequest.new(attrs)

# Doc: https://googleapis.dev/ruby/google-api-client/v0.23.6/Google/Apis/LanguageV1/AnalyzeEntitiesResponse.html
response = service.analyze_document_entities(request)
response.entities[0].type
response.entities[0].salience
response.entities[0].metadata['wikipedia_url']
...

それ以外のやり方

  • 他にも Gem がある
    • こっちはサービスアカウントでの認証が出来た
    • ダウンロードした json パスの環境変数を読み込んでくれるので、別途 API キーを指定する必要がない
# Doc: https://googleapis.dev/ruby/google-cloud-language-v1/latest/index.html
require "google/cloud/language/v1"

# Doc: https://googleapis.dev/ruby/google-cloud-language-v1/latest/Google/Cloud/Language/V1/LanguageService/Client.html
# .configure から、リトライ・タイムアウト等設定できるっぽい
client = ::Google::Cloud::Language::V1::LanguageService::Client.new

# リクエスト仕様を確認しつつ設定
attrs = {
  document: {
    type: 'PLAIN_TEXT',
    language: 'ja',
    content: 'テスト',
  },
  encoding_type: 'UTF8'
}

# Doc: https://googleapis.dev/ruby/google-cloud-language-v1/latest/Google/Cloud/Language/V1/AnalyzeEntitiesRequest.html
request = ::Google::Cloud::Language::V1::AnalyzeEntitiesRequest.new(attrs)

# Doc: https://googleapis.dev/ruby/google-cloud-language-v1/latest/Google/Cloud/Language/V1/AnalyzeEntitiesResponse.html
response = client.analyze_entities(request)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?