LoginSignup
3
3

More than 5 years have passed since last update.

Node.js[CentOS6]から自然言語[Cloud Natural Language API]を使ってみる。

Last updated at Posted at 2018-05-21

Node.jsから自然言語Apiを使ってみた。

こんにちは。
新卒マイナス1年目エンジニアの和尚です。

自分用メモ。
とりあえず使うことが目的なのでかなり適当です。

開発前の環境
* CentOS6
* Python --version 3.5
* Node.js --version 8.11

1. Cloud SDKをインストールする

まずPythonのバージョンが3.5.2だったので2.7.*をpyenvからインストールする、

1.バージョン確認

$ python --version

2.pyenvで現在インストールされているのバージョン確認(2.7.*がインストールされていれば4へ)

$ pyenv versions

3.pyenvで2.7.*をインストール(今回は2.7.13)

$ pyenv install 2.7.13

4.バージョンを2.7.13にする。

$ pyenv local 2.7.13

5.pythonのバージョンを確認して2.7.13になっていればOK

6.cloud SKDをインストールして確認する。(管理者権限で)

$ curl https://sdk.cloud.google.com | bash
$ exec -l $SHELL
$ gcloud --version

2.Nodeのファイルを作成

1.ディレクトリ作成

$ mkdir node_la
$ cd node_la

2.packege.json作成

$ npm init -y

3.実行ファイル作成

$ touch server.js

3.Google Cloud側の設定

1.google cloudのコンソールから自然言語apiを有効化する。

2.apiの認証画面からサービスアカウントキーを作成。役割はprojectのオーナーでOK。

3.ダウンロードされたjsonファイルをnode_laに配置

4.使ってみる

1.cloud sdkとディレクトリから使えるようにする。(設定したものを選んでいく)

$ gcloud init

2.クライアントライブラリインストール

$ npm install --save @google-cloud/language

3.環境変数にjsonのパスを指定する(セキュリティを全く考えていないので、適宜変えてください)

$ export GOOGLE_APPLICATION_CREDENTIALS=./[ファイル名].json

4.server.jsにコードを書く

server.js
const language = require('@google-cloud/language');

// Instantiates a client
const client = new language.LanguageServiceClient();

// The text to analyze
const text = 'Hello, world!';

const document = {
  content: text,
  type: 'PLAIN_TEXT',
};

// Detects the sentiment of the text
client
  .analyzeSentiment({document: document})
  .then(results => {
    const sentiment = results[0].documentSentiment;

    console.log(`Text: ${text}`);
    console.log(`Sentiment score: ${sentiment.score}`);
    console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

5.実行してみて表示されれば成功

$ node server.js
Text: Hello, world!
Sentiment score: 0.30000001192092896
Sentiment magnitude: 0.30000001192092896

かなり大雑把ですが、こんな感じでnodeから自然言語apiを叩いてみました。

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