If you edit the user's profile image with refile
Image analysis of the uploaded image with Cloud Vision API
In the case of a radical image, it cannot be saved in the DB.
・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
The following has been implemented.
-Login function implementation ・ Implementation of posting function
Cloud Vision API
How to calculate latitude / longitude using Geolocation API
Service Account
Add Service Account
service account name (appropriate)
and click Create
Continue
Create Key
JSON
and click Create
Close
Done
Cloud Vision API
Category | Contents |
---|---|
adult | Whether it is an adult image |
spoof | Whether it's an internet meme |
medical | Whether it's an internet meme |
violence | Whether it is a violent image |
racy | Whether it's a racy image |
Evaluation value | Degree |
---|---|
UNKNOWN | Cannot be analyzed |
VERY_UNLIKELY | Very low |
UNLIKELY | Low |
POSSIBLE | potential |
LIKELY | high |
VERY_LIKELY | Very expensive |
Regardless of the evaluation category, the evaluation value is LIKELY
or VERY_LIKELY
If it is included, we will implement it so that it will not be saved in the DB.
Gemfile
gem 'google-cloud-vision'
Terminal
$ bundle
Terminal
$ touch lib/vision.rb
lib/vision.rb
require 'base64'
require 'json'
require 'net/https'
module Vision
class << self
def image_analysis(profile_image)
image_annotator = Google::Cloud::Vision::ImageAnnotator.new(
version: :v1,
credentials: JSON.parse(File.open('Key file name') do |f| f.read end)
)
#Request parameter creation
image = profile_image #Image you want to analyze(argument)
requests_content = { image: { content: image }, features: [{ type: :SAFE_SEARCH_DETECTION }] }
requests = [requests_content]
#Send images to Cloud Vision API
response = image_annotator.batch_annotate_images(requests)
result = response.responses[0].safe_search_annotation.to_h
#The analysis result is "LIKELY" or "VERY"_Returns false if "LIKELY" is included, true otherwise
if result.values.include?(:LIKELY) || result.values.include?(:VERY_LIKELY)
return false
else
return true
end
end
end
end
users_controller.rb
def update
#When the image is edited
if params[:user][:profile_image].present?
#parameter(image)As a "tempfile" and assign it to a variable
profile_image = File.open(params[:user][:profile_image].tempfile)
#Image analysis with Cloud Vision API and assign the analysis result to a variable
result = Vision.image_analysis(profile_image)
else
#Substitute "true" if the image has not been edited
result = true
end
#Conditional branching depending on the analysis result
if result == true
@user.update(user_params)
redirect_to user_user_path(@user)
elsif result == false
flash[:notice] = 'Image is inappropriate'
render 'edit'
end
end
Recommended Posts