Skip to content

Instantly share code, notes, and snippets.

@jyunderwood
Last active July 6, 2024 16:36
Show Gist options
  • Save jyunderwood/46b601578d9522c0e9ab to your computer and use it in GitHub Desktop.
Save jyunderwood/46b601578d9522c0e9ab to your computer and use it in GitHub Desktop.
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
@jyunderwood
Copy link
Author

api_key = 'google_api_key'
demo_url = 'https://example.com/example.jpg'
text = OCR.scan(api_key: api_key, image_url: demo_url)
puts text

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment