Last active
July 6, 2024 16:36
-
-
Save jyunderwood/46b601578d9522c0e9ab to your computer and use it in GitHub Desktop.
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 'base64' | |
require 'open-uri' | |
require 'net/http' | |
require 'net/https' | |
require 'json' | |
class OCR | |
attr_reader :api_key, :image_url | |
def self.scan(api_key:, image_url:) | |
ocr = new(api_key: api_key, image_url: image_url) | |
return ocr.text | |
end | |
def initialize(api_key:, image_url:) | |
@api_key = api_key | |
@image_url = image_url | |
end | |
def request | |
begin | |
http = Net::HTTP.new request_uri.host, request_uri.port | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_PEER | |
req = Net::HTTP::Post.new request_uri | |
req.add_field 'Content-Type', 'application/json' | |
req.body = JSON.dump request_body | |
http.request(req) | |
rescue StandardError => e | |
puts "HTTP Request failed (#{e.message})" | |
end | |
end | |
def text | |
res = request | |
if res && res.body | |
json_body = JSON.parse res.body | |
if json_body['responses'] && json_body['responses'].first | |
response = json_body['responses'].first | |
if response['textAnnotations'] && response['textAnnotations'].first | |
annotation = response['textAnnotations'].first | |
annotation['description'] | |
end | |
end | |
end | |
end | |
private | |
def encoded_image | |
@encoded_image ||= Base64.encode64 open(URI.parse(image_url)).read | |
end | |
def request_body | |
{ | |
'requests' => [ | |
{ | |
'image' => { 'content' => encoded_image }, | |
'features' => [ | |
{ 'type' => 'TEXT_DETECTION' } | |
] | |
} | |
] | |
} | |
end | |
def request_uri | |
url = "https://vision.googleapis.com/v1/images:annotate?key=#{api_key}" | |
URI(url) | |
end | |
end |
Author
jyunderwood
commented
Feb 19, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment