LoginSignup
0
0

More than 5 years have passed since last update.

さくらの専有サーバで Google 感情分析してみる

Last updated at Posted at 2017-10-17

Googleアカウント

https://cloud.google.com/natural-language/pricing?hl=ja
事前にアカウントを作っておく。
クレジットカード登録必要。

https://console.cloud.google.com
プロジェクトを作成。

https://cloud.google.com/docs/authentication/getting-started?hl=ja
【IAM と管理者 > IAM】からプロジェクト内にIAMを作成する。
【IAM と管理者 > サービスアカウント > 作成】で入力したサービスアカウントIDでIAMが作成される。
その際、【新しい秘密鍵の提供 > JSON】にチェックを入れて、JSONをダウンロードする。

【API とサービス > ダッシュボード】から Google Cloud Natural Language API を有効化しておく。

composerのインストール

/home/hoge/www/huga/composer
諸事情によりcomposerディレクトリを作ってその中にインストールする。

  1. SSHで接続。
  2. cshになっているのでbashに変更。
  3. パスワードを要求されるので入力。
change
% which bash
/usr/local/bin/bash
% chsh -s /usr/local/bin/bash

exitで閉じてから再度ログインすると変更されているので、ディレクトリを指定してインストール。

install
$ curl -sS https://getcomposer.org/installer | php -- --install-dir=/home/hoge/www/huga/composer

Natural Language API Client Libraries のインストール

https://cloud.google.com/natural-language/docs/reference/libraries?hl=ja#client-libraries-usage-php
https://cloud.google.com/natural-language/docs/analyzing-sentiment?hl=ja#language-sentiment-string-php

composerからGoogleの感情分析ライブラリをインストールする。
/composer/vendor 配下に色々落ちてくる。

$ cd /home/hoge/www/huga/composer
$ php composer.phar require google/cloud-language

PHPソース

use Google\Cloud\Language\LanguageClient;
use Google\Cloud\Language\Annotation;
use Google\Cloud\Storage\StorageClient;

require_once('composer/vendor/autoload.php');

//サービスアカウント作成時にダウンロードしたjsonをアップロードしておき、環境変数に追加
putenv('hoge.json');

$o_languageClient = new LanguageClient([
    'projectId' => 'hoge',  //サービスアカウント名
]);
$result = $$o_languageClient->analyzeSentiment('わーい!たーのしー!');

curlでもできるっぽい

https://codelabs.developers.google.com/codelabs/cloud-nl-intro-ja/index.html
https://cloud.google.com/natural-language/docs/analyzing-entities?hl=ja#language-entities-string-protocol
↑のプロトコルタブとか。
ただし分析する内容がPOSTできず、添付ファイルとして送らないといけない。

$params = [
    'encodingType'  => 'UTF8',
    'document'      => [
        'type'      => 'PLAIN_TEXT',
        'content'   => 'I Want To Believe'
    ]
];
exec('curl "https://language.googleapis.com/v1/documents:analyzeSentiment?key=***" -s -X POST -H "Content-Type: application/json" -d "' . addslashes( json_encode($params) ) . '"', $results);

実行するたびに添付ファイルを作りたくない場合はこれでいける。


参考

https://qiita.com/tonosamart/items/e1d7ee95bf1b2a4532ff
http://kawairi.jp/weblog/vita/2014123118987
http://tnamao.hatenablog.com/entry/2015/07/05/223707
https://kohkimakimoto.github.io/getcomposer.org_doc_jp/doc/00-intro.html
https://qiita.com/k_akakura/items/f318993fb87a976683a2

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