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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# File 'lib/visioner.rb', line 8
def self.rename_all(images)
images.each do |image_name|
begin
b64_data = Base64.encode64(File.open(image_name, "rb").read)
rescue
puts "Error: can't read file"
end
api_key = ENV['GOOGLE_VISION_API_KEY']
content_type = "Content-Type: application/json"
url = "https://vision.googleapis.com/v1/images:annotate?key=#{api_key}"
data = {
"requests": [
{
"image": {
"content": b64_data
},
"features": [
{
"type": "LABEL_DETECTION",
"maxResults": 1
}
]
}
]
}.to_json
url = URI(url)
req = Net::HTTP::Post.new(url, = {'Content-Type' =>'application/json'})
req.body = data
res = Net::HTTP.new(url.host, url.port)
res.use_ssl = true
name = ""
res.start do |http|
resp = http.request(req)
json = JSON.parse(resp.body)
if json && json["responses"] && json["responses"][0]["labelAnnotations"] && json["responses"][0]["labelAnnotations"][0]["description"]
name = json['responses'][0]['labelAnnotations'][0]['description']
end
end
unless name.empty?
counter = ''
while File.exist?(File.dirname(image_name) + "/" + name + counter.to_s + File.extname(image_name)) do
counter = counter.to_i + 1
end
puts "#{image_name} -> #{name + counter.to_s + File.extname(image_name)}"
File.rename(image_name, File.dirname(image_name) + "/" + name + counter.to_s + File.extname(image_name))
end
end
end
|