Skip to content

Instantly share code, notes, and snippets.

@franckverrot
Created February 26, 2016 05:42
Show Gist options
  • Save franckverrot/48775e0095872bb97782 to your computer and use it in GitHub Desktop.
Save franckverrot/48775e0095872bb97782 to your computer and use it in GitHub Desktop.
Google Cloud Vision API client
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