-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimagesort.pl6
executable file
·109 lines (101 loc) · 3.27 KB
/
imagesort.pl6
1
2
3
4
5
6
7
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
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
#!/usr/bin/env perl6
use Inline::Perl5;
use HTTP::UserAgent;
use JSON::Tiny;
use Image::ExifTool:from<Perl5>;
sub getUrl($type, $key)
{
if $type ~~ "osm"
{
return "http://nominatim.openstreetmap.org/reverse?";
}
elsif $type ~~ /"locationiq"/
{
die "API key missing" if ! $key.defined;
return "http://locationiq.org/v1/reverse.php?key=$key&";
}
else
{
die "url source type $type not handled";
}
}
sub getCoords($image)
{
my $exifTool = Image::ExifTool.new;
my $ret = $exifTool.ExtractInfo($image.Str);
if $ret == 1
{
$exifTool.Options(CoordFormat => '%+.6f');
my $lat = $exifTool.GetValue("GPSLatitude");
my $lon = $exifTool.GetValue("GPSLongitude");
#say "[$lat, $lon]";
return ($lat, $lon);
}
else
{
warn "ERROR: " ~ $exifTool.GetValue('Error');
}
return ();
}
sub MAIN(Str :$src! , Str :$dest!, Str :$apikey)
{
die "Source Directory $src not found" if ! $src.IO.d;
die "Destination Directory $dest not found" if ! $dest.IO.d;
my $url = getUrl("locationiq", $apikey);
my $ua = HTTP::UserAgent.new(:useragent<firefox_linux>);
my @files = dir $src;
for @files.kv -> $idx, $file
{
say "[$idx/@files.elems()] $file.basename()";
my ($lat, $lon) = getCoords($file);
# TODO: cache bounding boxes
if $lat.defined && $lon.defined && $lat !~~ "" && $lon !~~ ""
{
# wait few sec b/w each requests (nominatim TOC)
sleep 0.5;
#say $url ~ "format=json&lat=$lat&lon=$lon&zoom=14&addressdetails=1&accept-language=en-US";
my $response = $ua.get($url ~ "format=json&lat=$lat&lon=$lon&zoom=14&addressdetails=1&accept-language=en-US");
if $response.is-success
{
my $respStr = from-json( $response.content );
#say $response.content;
if $respStr{"address"}{"country"}
{
my $lvl2="";
if $respStr{"address"}{"city"}
{
$lvl2 = $respStr{"address"}{"city"};
}
elsif $respStr{"address"}{"town"}
{
$lvl2 = $respStr{"address"}{"town"};
}
elsif $respStr{"address"}{"village"}
{
$lvl2 = $respStr{"address"}{"village"};
}
elsif $respStr{"address"}{"state"}
{
$lvl2 = $respStr{"address"}{"state"};
}
else
{
say "city/village/town not found ===> " ~ $respStr.perl;
}
my $country = $respStr{"address"}{"country"};
say " -> Moving to $dest/$country/$lvl2/$file.basename()";
mkdir "$dest/$country/$lvl2";
move $file, "$dest/$country/$lvl2/$file.basename()";
}
else
{
warn "NO Country ===> " ~ $respStr.perl;
}
}
else
{
warn $response;
}
}
}
}