文章を投稿できる既存アプリにGoogle Natural Language APIを追加導入し
感情スコアを画面上に表示させます。
1.前提条件、前準備
APIを使用するための前準備(概要だけ記載)
①google側準備
・Google Cloud Platformに登録
・新しいプロジェクトを作成
・APIキーを生成
・Vision APIの有効化
②rails側準備
・gemfile に dotenv-rails 追加
・envファイルに生成したAPIキーを記載
・Google Cloud Vision APIを呼ぶためのライブラリを作成
※「lib/vision.rb」作成
・Google Natural Language APIを呼ぶためのライブラリを作成
※「lib/language.rb」作成
・自作したライブラリを読み込む
※「config/application.rb」に追記
2.変更前状態
文章を新規投稿・更新できる、postモデルが存在。
以下はposts_controllerのファイル
class PostsController < ApplicationController
....
def show
@post = Post.find(params[:id])
end
def create
@newpost = Post.new(post_params)
@newpost.save
redirect_to posts_path
end
def update
@post = Post.find(params[:id])
@post.update(post_params)
redirect_to posts_path
end
....
end
投稿内容を表示させるviewファイル
次からは投稿内容を表すカラム「postbody」に対して感情スコアを出させるようにします
<div>
<%= simple_format(@post.postbody) %>
</div>
3.Google Natural Language API導入
感情スコア用のカラム(score)をpostsモデルに追加します。
$ rails g migration AddScoreToPosts 'score:decimal{5,3}'
$ rails db:migrate
以下では、create,updateアクション内に以下の記述をすることで、
新規投稿時、投稿更新時に投稿内容本文(postbody)を
「Language.get_data(post_params[:postbody])」 でAPI側に渡しています。
その後、API側から返ってきた値をもとに、スコアを作成しています。
class PostsController < ApplicationController
....
def show
@post = Post.find(params[:id])
end
def create
@newpost = Post.new(post_params)
@newpost.score = Language.get_data(post_params[:postbody]) #←追加箇所1
@newpost.save
redirect_to posts_path
end
def update
@post = Post.find(params[:id])
@post.update(post_params)
@post.score = Language.get_data(post_params[:postbody]) #←追加箇所2
@post.save #←追加箇所3
redirect_to posts_path
end
....
end
updateアクションの「@post.save 」は本筋とは関係ありませんが、
自分の場合、付けずにいたらscoreの更新がされなかったので追加致しました。
※Postsモデルにscoreカラムを追加した時に既存投稿のscoreはnilとなってます。
<div>
<%= simple_format(@post.postbody) %>
</div>
<p class="sentiment-score">感情分析スコア <%= @post.score %> / 1.0</p> #←追加箇所
新規投稿・更新すると、その内容に応じて、-1.0〜1.0の値が入るようになります。
以下のようにすれば投稿内容のスコアに応じて投稿内容を非表示にすることもできます。
<div>
<% if @post.score >= -0.2 %>
<%= simple_format(@post.postbody)%> #-0.2以上なら表示
<% else %>
感情スコアが低いため非表示にしてます。 #-0.2未満なら非表示に
<% end %>
</div>
<p class="sentiment-score">感情分析スコア <%= @post.score %> / 1.0</p>