How to start using Google Vision in Rails
30 Jan 2017I won’t explain how to use carrierwave and upload images to Rails here. Lets assume this part is ready and well understand.
Create Google API account
Whole process is not very easy nor obvious. I’ll explain what I remember without telling all the details to let you grow some hate towards Google :)
-
You must create account. Keep in mind you need to attach credit card to end signing process.
-
Create new project.
-
Generate and download JSON key file. The file you downloaded is base64 encoded JSON.
Funny that you must decode it by yourself and Google doesn’t tell you about it, isn’t it?
cat instaupload-ad4695a0c2d0.txt | base64 --decode > instaupload-ad4695a0c2d0.json
Rails code
I found existing Ruby sample code how to use Google gem.
-
Add official Google API gem.
gem 'google-cloud'
-
I prefer to use
service
for that kind of operation, for example: put code inside class inapp/services/google_faces.rb
. -
Sign in into Google API:
vision = Google::Cloud::Vision.new( project: "instaupload", keyfile: "instaupload-ad4695a0c2d0.json" )
-
Upload image to Google API:
# photo is an instance of Photo model which has attached `image` as `carrierwave` `ImageUploader` image = vision.image photo.image.path faces = image.faces
-
Wait for results and iterate:
faces.each do |face| Rails.logger.debug "Face bounds:" face.bounds.face.each do |vector| Rails.logger.debug "(#{vector.x}, #{vector.y})" end x1 = face.bounds.face[0].x.to_i y1 = face.bounds.face[0].y.to_i x2 = face.bounds.face[2].x.to_i y2 = face.bounds.face[2].y.to_i