LoginSignup
1
0

More than 3 years have passed since last update.

Google Cloud Vision APIをrailsに導入する際、ドキュメント通り進めてみた。

Last updated at Posted at 2020-09-25

環境

・Rails 6.0.3.3
・ruby 2.7.1

参考資料

Google Cloud Vision APIドキュメント
1、https://cloud.google.com/vision/docs/libraries?hl=ja

導入手順

1、gemインストール

gemfileに記述

source "https://rubygems.org"
gem "google-cloud-vision"

そのあとに、

bundle installl

※公式では「gem install google-cloud-vision」の手段での方法を推奨されているが、私のappではうまくいきませんでした。
後ほど出てくる

require "google/cloud/vision"

という記述でエラーが発生て詰まった。(これのせいで凄く時間食った)

2、認証の設定

Google Cloud Vision APIを利用するために専用のjsonファイルを作成し、対象のrailsappに読み込ませる必要がある。
・jsonファイルを作成
▶︎ドキュメント通りの手順で詰まることはない。出来上がったファイルはこんな感じ

{
  "type": "",
  "project_id": "",
  "private_key_id": "private_key_idの中身",
  "private_key": "-----BEGIN PRIVATE KEY-----の中身\=\n-----END PRIVATE KEY-----\n",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
}

・railsappに読み込ませる
▶︎.bash_profileに入力してパスを通す

export GOOGLE_APPLICATION_CREDENTIALS="$PATH:パスを書く/ファイル名.json"

3、実際に使ってみる。

routes.rb
get  "contents/index"  => "contents#index"
contents_controller.rb
class ContentsController < ApplicationController
  def index
  end
end
index.erb
<%=
# さっきインストールしたgemの読み込み
require "google/cloud/vision"

# インスタンス化
image_annotator = Google::Cloud::Vision.image_annotator

# 画像のパスを入力(ローカルでもネット上の画像でも問題ない)
file_name = "./resources/cat.jpg"

# 画像を認識した後に返す返り値
response = image_annotator.label_detection image: file_name
response.responses.each do |res|
  puts "Labels:"
  res.label_annotations.each do |label|
    puts label.description
  end
end
%>

4、contents/indexリダイアルすると…

スクリーンショット 2020-09-25 13.25.09.png

こんな感じの返り値が表示されてたら成功です!
(試しに猫の画像を取り込んだので「Cat」が出てますね。笑)

ここから、自分が欲しい情報を取得し整形することで、よしなに利用できます!
読んでくださりありがとうございました!!

1
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
1
0