File Coverage

File:script/bi-geocode
Coverage:59.5%

linestmtbrancondsubtimecode
1#!/usr/bin/env perl
2# bi-geocode -- geocode-cache warming CLI for Database::BI
3#
4# Opens a dataset spec, geocodes every distinct value of the named column
5# (or of several, --col repeated, joined with ", ": an address, then its country),
6# with --text added to the end of each place ("Virginia, USA"),
7# and writes the resolved coordinates into the shared geocode cache in
8# models.json.  Subsequent map views for the same dataset serve from the
9# cache without making any geocoder requests.
10#
11# Places are looked up in Geo::Coder::Free's local data first, then on
12# OpenStreetMap (Nominatim) at one a second, with no limit on how many: the
13# map page asks Nominatim for at most map_geocode_online_max places, and this
14# script is how the rest are found.  --offline keeps every lookup local.
15#
16# The script is idempotent: a second run against the same column with a
17# warm cache resolves zero additional places (and says so).
18#
19# Usage:
20#   bi-geocode --spec <l-spec> --col <column> [--col <column> ...]
21#              [--text <text>] [--data-dir <dir>] [--model-dir <dir>]
22#              [--openaddr <path>] [--region <CC>]
23#              [--offline] [--online-max <n>]
24#              [--dry-run] [--verbose]
25#
26# Exit codes:  0 = ok
27#              1 = column not found or no records loaded
28#              2 = bad arguments / data source unavailable
29#
30# Suitable for cron:
31#   0 2 * * * cd /opt/myapp && ./script/bi-geocode \
32#       --spec table:customers --col city --region US --verbose
33
34
10
10
10
14106
8
108
use strict;
35
10
10
10
8
3
152
use warnings;
36
37
10
10
10
807
2954
364
use FindBin qw($Bin);
38
10
10
10
824
1741
19
use lib "$Bin/../lib";
39
40
10
10
10
2124
29038
11
use Getopt::Long qw(GetOptions :config no_ignore_case);
41
10
10
10
637
6
62
use File::Spec;
42
10
10
10
1165
554880
186
use Mojo::JSON qw(decode_json encode_json);
43
10
10
10
1248
77483
128
use Mojo::File;
44
10
10
10
1095
28
187
use Database::BI::Util qw(iso8601_utc);
45
10
10
10
885
5
643
use Database::BI::I18N ();
46
47# Messages in the language the locale names: LANG=en_US.UTF-8 is American
48# English, anything else British (CGI::Lingua chooses).
49
10
214976
$Database::BI::I18N::LANGUAGE = Database::BI::I18N::from_locale();
50
51# ---------------------------------------------------------------------------
52# Parse arguments
53# ---------------------------------------------------------------------------
54
55
10
101
my @opt_cols;
56
10
11
my ($opt_spec, $opt_data_dir, $opt_model_dir,
57        $opt_openaddr, $opt_region, $opt_dry_run, $opt_verbose, $opt_help,
58        $opt_offline, $opt_online_max, $opt_text);
59
60GetOptions(
61        'spec|s=s'       => \$opt_spec,
62        'col|c=s'        => \@opt_cols,
63        'text|t=s'       => \$opt_text,
64        'data-dir|d=s'   => \$opt_data_dir,
65        'model-dir|m=s'  => \$opt_model_dir,
66        'openaddr|o=s'   => \$opt_openaddr,
67        'region|r=s'     => \$opt_region,
68        'offline'        => \$opt_offline,
69        'online-max=i'   => \$opt_online_max,
70        'dry-run|n'      => \$opt_dry_run,
71        'verbose|v'      => \$opt_verbose,
72        'help|h'         => \$opt_help,
73
10
0
0
44
0
0
) or do { _usage(); exit 2 };
74
75
10
0
0
6004
0
0
if ($opt_help) { _usage(); exit 0 }
76
77
10
18
if (defined($opt_online_max) && $opt_online_max < 1) {
78
0
0
        warn "bi-geocode: --online-max must be a positive whole number\n";
79
0
0
        exit 2;
80}
81
82
10
24
unless (defined $opt_spec && length $opt_spec) {
83
0
0
        warn "bi-geocode: --spec <l-spec> is required\n";
84
0
0
        exit 2;
85}
86
10
11
9
12
@opt_cols = grep { length } @opt_cols;
87
10
11
unless (@opt_cols) {
88
2
19
        warn "bi-geocode: --col <column> is required\n";
89
2
46
        exit 2;
90}
91
92
8
1836
require Database::BI::Model::Geocode;
93
94# The same tidying as the map page's "Add to each place" (loc_text=), so the
95# places cached here are the ones the map asks for.
96
8
21
my ($place_text) = Database::BI::Model::Geocode->place_text($opt_text);
97
8
10
unless (defined $place_text) {
98
10
10
10
11
4
280485
        no warnings qw(once);
99
2
4
        warn "bi-geocode: --text is added to the end of each place: one line of at most ",
100                $Database::BI::Model::Geocode::PLACE_TEXT_MAX, " characters\n";
101
2
68
        exit 2;
102}
103
104
6
14
my $data_dir  = $opt_data_dir  // 'data';
105
6
7
my $model_dir = $opt_model_dir // '.bi';
106
107# ---------------------------------------------------------------------------
108# Load the data source
109# ---------------------------------------------------------------------------
110
111
6
1743
require Database::BI::Model::DataSource;
112
113# table:<name>/<table> and path:<file>#<table> name one table of a file.
114
6
10
my ($table, $path, $url, $internal);
115
6
18
if ($opt_spec =~ /\Atable:(.+)\z/) {
116
0
0
        $table = $1;
117
0
0
        ($table, $internal) = ($1, $2) if $table =~ m{\A([^/]+)/(.+)\z};
118} elsif ($opt_spec =~ /\Apath:(.+)\z/) {
119
6
10
        require Database::BI::Model::DataSource;
120
6
30
        ($path, $internal) = Database::BI::Model::DataSource::split_path($1);
121} elsif ($opt_spec =~ /\Aurl:(.+)\z/) {
122
0
0
        $url = $1;
123} else {
124
0
0
        warn "bi-geocode: spec must start with table:, path:, or url:\n";
125
0
0
        exit 2;
126}
127
128
6
18
my $source = eval {
129
6
31
        if (defined $table) {
130
0
0
                Database::BI::Model::DataSource->new(
131                        table     => $table,
132                        directory => $data_dir,
133                        defined $internal ? (internal_table => $internal) : (),
134                );
135        } elsif (defined $path) {
136                # As the map page opens it: the table is the file's name without its
137                # extension, in the directory the file really is in.
138
6
44
                my $f = Mojo::File->new($path)->realpath;
139
6
232
                (my $stem = $f->basename) =~ s/\.[^.]+\z//;
140
6
230
                Database::BI::Model::DataSource->new(
141                        table     => $stem,
142                        directory => $f->dirname->to_string,
143                        defined $internal ? (internal_table => $internal) : (),
144                );
145        } else {
146
0
0
                Database::BI::Model::DataSource->new(url => $url);
147        }
148};
149
6
22
if ($@ || !defined $source) {
150
0
0
        (my $e = $@ // 'unknown error') =~ s/ at \S+ line \d+\.?\n?$//;
151
0
0
        warn "bi-geocode: could not open data source: $e\n";
152
0
0
        exit 2;
153}
154
155
6
6
5
18
my $records = eval { $source->fetch_all };
156
6
38
if ($@ || !defined $records || !@$records) {
157
0
0
        (my $e = $@ // '') =~ s/ at \S+ line \d+\.?\n?$//;
158
0
0
        warn "bi-geocode: no records loaded" . ($e ? ": $e" : '') . "\n";
159
0
0
        exit 1;
160}
161
162# Validate the columns
163
6
0
17
0
my $columns = $source->columns // [ keys %{ $records->[0] } ];
164
6
24
6
20
my %col_set = map { $_ => 1 } @$columns;
165
6
13
for my $col (@opt_cols) {
166
8
11
        next if $col_set{$col};
167
1
11
        warn "bi-geocode: column \"$col\" not found in dataset\n";
168
1
3
        warn "  available: " . join(', ', sort keys %col_set) . "\n";
169
1
9
        exit 1;
170}
171
172
5
11
_log("Loaded %d records from %s", scalar @$records, $opt_spec);
173
174# ---------------------------------------------------------------------------
175# Load models / geocode cache
176# ---------------------------------------------------------------------------
177
178
5
28
my $models_file = Mojo::File->new($model_dir, 'models.json');
179
5
42
my $models = {};
180
5
89
if (-f $models_file) {
181
0
0
0
0
        eval { $models = decode_json($models_file->slurp) };
182
0
0
        warn "bi-geocode: could not read models.json: $@\n" if $@;
183}
184
185# Several columns are one place, their cells joined with ", ", then --text, as
186# on the map page.
187
5
58
my ($places, $opt_col) = Database::BI::Model::Geocode->place_rows($records, \@opt_cols, $place_text);
188
5
12
_log("Each place ends \", %s\"", $place_text) if length $place_text;
189
190
5
6
my $cache_spec = $opt_spec . '|loc=' . $opt_col;
191
5
9
my $legacy  = Database::BI::Model::Geocode->cache_from_models($models, $cache_spec);
192
5
12
my $shared  = Database::BI::Model::Geocode->shared_cache_from_models($models);
193
5
5
my %cache   = (%$legacy, %$shared);
194
195
5
5
my %args;
196
5
6
$args{openaddr}   = $opt_openaddr if defined $opt_openaddr && length $opt_openaddr;
197# The same Geo::Coder::List cache the map page uses: Geocode->new chooses its
198# directory (Object::Configure, CACHEDIR, CACHE_DIR, cache_dir in
199# database_bi.conf, then <model-dir>/geocode-cache).  With --dry-run nothing is
200# kept, the chain's cache included.
201
5
5
if ($opt_dry_run) {
202
5
13
        $args{cache} = {};
203} else {
204
0
0
        Mojo::File->new($model_dir)->make_path;
205
0
0
        $args{model_dir} = $model_dir;
206}
207
5
12
$args{online}     = $opt_offline ? 0 : 1;
208
5
6
$args{online_max} = $opt_online_max if defined $opt_online_max;
209
210
5
14
my $geocode = Database::BI::Model::Geocode->new(%args);
211
212
5
3
my %opts;
213
5
7
$opts{cache} = \%cache;
214# No cap for the warming script: every row could name a different place, so
215# the number of rows is a cap nothing reaches.  (Geocode refuses max => 0.)
216
5
32
$opts{max}   = scalar(@$records) || 1;
217
5
12
if (defined $opt_region && $opt_region =~ /\A[A-Za-z]{2}\z/) {
218
0
0
        $opts{region} = $opt_region;
219}
220
221# ---------------------------------------------------------------------------
222# Resolve
223# ---------------------------------------------------------------------------
224
225
5
5
my $t0 = time;
226
5
15
my $result = $geocode->resolve_column($places, $opt_col, %opts);
227
5
28
my $elapsed = time - $t0;
228
229
5
6
my $counts   = $result->{counts};
230
5
2
my $messages = $result->{messages};
231
232_log("Resolved %d/%d distinct places in %ds",
233
5
25
        $counts->{resolved} // 0, $counts->{distinct} // 0, $elapsed);
234_log("  cache hits: %d  new: %d  of them online: %d  unresolved: %d  left for later: %d",
235        $counts->{cached} // 0, $counts->{attempted} // 0, $counts->{online} // 0,
236
5
32
        $counts->{unresolved} // 0, $counts->{not_attempted} // 0);
237
238
5
5
for my $msg (@$messages) {
239
10
19
        _log("  [%s] %s", $msg->{key} // 'info', $msg->{text} // '');
240}
241
242# ---------------------------------------------------------------------------
243# Persist
244# ---------------------------------------------------------------------------
245
246
5
5
if ($opt_dry_run) {
247
5
6
        _log("Dry run: cache not written.");
248
5
72
        exit 0;
249}
250
251
0
0
if ($counts->{attempted} // 0) {
252
0
0
        my $backend = $result->{backend};
253        my $updated = Database::BI::Model::Geocode->models_with_shared_cache(
254                $models, $result->{cache},
255
0
0
                (defined($backend) ? (backend => $backend) : ()),
256                built => iso8601_utc(),
257        );
258
259
0
0
        eval {
260
0
0
                Mojo::File->new($model_dir)->make_path;
261
0
0
                my $tmp = Mojo::File->new($models_file . '.tmp');
262
0
0
                $tmp->spurt(encode_json($updated));
263
0
0
                rename $tmp->to_string, $models_file->to_string
264                        or die "rename failed: $!\n";
265        };
266
0
0
        if ($@) {
267
0
0
                (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
268
0
0
                warn "bi-geocode: could not write models.json: $e\n";
269
0
0
                exit 2;
270        }
271
0
0
        _log("Cache written to %s", $models_file->to_string);
272} else {
273
0
0
        _log("Nothing new to write (all places already cached).");
274}
275
276
0
0
exit 0;
277
278# ---------------------------------------------------------------------------
279# Helpers
280# ---------------------------------------------------------------------------
281
282sub _log {
283
32
15
        return unless $opt_verbose;
284
32
24
        my ($fmt, @args) = @_;
285
32
91
        printf STDERR "$fmt\n", @args;
286}
287
288sub _usage {
289
0
        print STDERR <<'USAGE';
290Usage: bi-geocode --spec <l-spec> --col <column> [--col <column> ...] [options]
291
292Required:
293  --spec, -s <spec>     Dataset spec: table:<name>, path:</abs/path>, url:<url>
294  --col,  -c <column>   Column holding place names to geocode; repeat it for a
295                        place across columns, joined with ", " in that order
296                        (--col Address --col Country)
297
298Options:
299  --text,      -t <text>  Text added to the end of each place, after ", ", as
300                          the map's "Add to each place" (--text 'Virginia, USA')
301  --data-dir,  -d <dir>   Data directory (default: data)
302  --model-dir, -m <dir>   Model store directory (default: .bi)
303  --openaddr,  -o <path>  Path to an OpenAddresses data directory for Geo::Coder::Free
304  --region,    -r <CC>    ISO 3166-1 alpha-2 region hint (e.g. US, GB)
305  --offline               Look places up in the local data only, never on
306                          OpenStreetMap
307  --online-max <n>        Look up at most <n> places on OpenStreetMap
308                          (default: no limit; it is asked once a second)
309  --dry-run,   -n         Resolve but do not write the cache
310  --verbose,   -v         Print progress to STDERR
311  --help,      -h         Show this message
312
313Exit codes:
314  0 = success
315  1 = column not found or no records
316  2 = bad arguments or data source error
317USAGE
318}
319