pikesaku’s blog

個人的な勉強メモです。記載内容について一切の責任は持ちません。

Natural Language API Client Librariesを使う!

参考

cloud.google.com
 

作業の流れ

Cloud Shellでも認証設定必要だった。。。gcloudコマンドは認証設定なしで動いたのに。

①アカウント作成

f:id:pikesaku:20180519102101p:plain
 
f:id:pikesaku:20180519102249p:plain
 

JSONファイルダウンロード

 

③Cloud ShellにJSONファイルをアップロードし以下環境変数にファイルパス設定

export GOOGLE_APPLICATION_CREDENTIALS=/home/pike/hoge.json

 

④サンプルコード実行

a.py

# Imports the Google Cloud client library
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
# Instantiates a client
client = language.LanguageServiceClient()
# The text to analyze
text = u'Hello, world!'
document = types.Document(
    content=text,
    type=enums.Document.Type.PLAIN_TEXT)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))

 

$ python ./a.py
Text: Hello, world!
Sentiment: 0.300000011921, 0.300000011921
$

 
サービスアカウント設定しないとコード実行時に以下エラーになる。

Traceback (most recent call last):
  File "./a.py", line 16, in <module>
    sentiment = client.analyze_sentiment(document=document).document_sentiment
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/language_v1/gapic/language_service_client.py", line 180, in analyze_sentiment
    return self._analyze_sentiment(request, retry=retry, timeout=timeout)
  File "/usr/local/lib/python2.7/dist-packages/google/api_core/gapic_v1/method.py", line 139, in __call__
    return wrapped_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/google/api_core/retry.py", line 260, in retry_wrapped_func
    on_error=on_error,
  File "/usr/local/lib/python2.7/dist-packages/google/api_core/retry.py", line 177, in retry_target
    return target()
  File "/usr/local/lib/python2.7/dist-packages/google/api_core/timeout.py", line 206, in func_with_timeout
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/google/api_core/grpc_helpers.py", line 56, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "/usr/local/lib/python2.7/dist-packages/six.py", line 737, in raise_from
    raise value
google.api_core.exceptions.PermissionDenied: 403 Cloud Natural Language API has not been used in project 618104708054 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/
language.googleapis.com/overview?project=618104708054 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.