Class: Cardreader::Vision

Inherits:
Object
  • Object
show all
Defined in:
lib/cardreader/vision.rb

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Vision



4
5
6
# File 'lib/cardreader/vision.rb', line 4

def initialize(key)
  @key = key
end

Instance Method Details

#post(image) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/cardreader/vision.rb', line 8

def post(image)
  uri = "https://vision.googleapis.com/v1/images:annotate?key=#{@key}"
  base64_image = Base64.strict_encode64(File.new(image, 'rb').read)
  body = {
    requests: [{
      image: {
        content: base64_image
      },
      features: [
        {
          type: 'TEXT_DETECTION',
          maxResults: 1
        }
      ]
    }]
  }.to_json
  
  uri = URI.parse(uri)
  https = Net::HTTP.new(uri.host, uri.port)
  https.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri)
  request["Content-Type"] = "application/json"
  response = https.request(request, body)
  
  #text = JSON.parse(response.body)["responses"][0]["fullTextAnnotation"]["text"]
  
  
  blocks = JSON.parse(response.body)["responses"][0]["fullTextAnnotation"]["pages"][0]["blocks"]
  
  page = []
  blocks.each do |block|
    text = ""
    block["paragraphs"][0]["words"].each do |word|
    text += " "
      word["symbols"].each do |symbol|
        text += symbol["text"]
      end
    end
    page << text
  end
  return page.join("\n")
end