Created
February 26, 2016 05:42
-
-
Save franckverrot/48775e0095872bb97782 to your computer and use it in GitHub Desktop.
Google Cloud Vision API client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
require "base64" | |
require 'net/http' | |
require 'json' | |
image_path = ARGV[0] | |
puts "Reading image #{image_path}..." | |
b64_data = Base64.encode64(File.open(image_path, "rb").read) | |
api_key = ENV.fetch('GOOGLE_CLOUD_VISION_API_KEY') { raise 'Missing env variable GOOGLE_CLOUD_VISION_API_KEY' } | |
url = "https://vision.googleapis.com/v1/images:annotate?key=#{api_key}" | |
data = { | |
"requests": [ | |
{ | |
"image": { | |
"content": b64_data | |
}, | |
"features": [ | |
{ | |
"type": "TEXT_DETECTION", | |
"maxResults": 1 | |
} | |
] | |
} | |
] | |
}.to_json | |
uri = URI(url) | |
req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' => 'application/json'}) | |
req.body = data | |
res = Net::HTTP.new(uri.host, uri.port) | |
res.use_ssl = true | |
res.start do |http| | |
resp = http.request(req) | |
json = JSON.parse(resp.body) | |
res = if json && json["responses"] && json["responses"][0]["textAnnotations"] && json["responses"][0]["textAnnotations"][0]["description"] | |
json["responses"][0]["textAnnotations"][0]["description"] | |
else | |
":-(" | |
end | |
puts res | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment