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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
# File 'lib/visioner.rb', line 33
def self.rename_all(images, options)
images.each do |image_name|
if File.extname(image_name) != '.jpg'
puts "Error: can only rename jpg files. Continuing..."
next
end
begin
b64_data = Base64.encode64(File.open(image_name, "rb").read)
rescue
puts "Error: can't read file. Exiting..."
end
api_key = ENV['GOOGLE_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']
name = name.tr(" ", "-")
end
end
unless name.empty?
counter = nil
while File.exist?(File.dirname(image_name) + "/" + name + counter.to_s + File.extname(image_name)) do
counter = 1 if counter == nil
counter = counter.to_i + 1
end
exif = EXIFR::JPEG.new(image_name)
date = ''
if options[:date]
date = File.mtime(image_name).strftime('%m-%d-%Y') date = exif.date_time_original.strftime('%m-%d-%Y') + '_' if exif.date_time_original
end
country = ''
if options[:country]
country = 'unknown' country = self.get_country(exif.gps.latitude, exif.gps.longitude) + '_' if exif.gps_latitude && exif.gps_longitude
end
puts "#{image_name} -> #{country + date + name + counter.to_s + File.extname(image_name)}"
File.rename(image_name, File.dirname(image_name) + "/" + country + date + name + counter.to_s + File.extname(image_name))
end
end
end
|