| 1 | package Geo::Address::Formatter; | ||
| 2 | $Geo::Address::Formatter::VERSION = '1.994'; | ||
| 3 | # ABSTRACT: take structured address data and format it according to the various global/country rules | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | use feature qw(say); | ||
| 8 | use Clone qw(clone); | ||
| 9 | use Data::Dumper; | ||
| 10 | $Data::Dumper::Sortkeys = 1; | ||
| 11 | use File::Basename qw(dirname); | ||
| 12 | use File::Find::Rule; | ||
| 13 | use Ref::Util qw(is_hashref); | ||
| 14 | use Scalar::Util qw(looks_like_number); | ||
| 15 | use Text::Hogan::Compiler; | ||
| 16 | use Try::Catch; | ||
| 17 | use YAML::XS qw(LoadFile); | ||
| 18 | use utf8; | ||
| 19 | |||
| 20 | my $THC = Text::Hogan::Compiler->new; | ||
| 21 | |||
| 22 | # optional params | ||
| 23 | my $show_warnings = 1; | ||
| 24 | my $debug = 0; | ||
| 25 | my $only_address = 0; | ||
| 26 | |||
| 27 | |||
| 28 | sub new { | ||
| 29 | my ($class, %params) = @_; | ||
| 30 | |||
| 31 | my $self = {}; | ||
| 32 | my $conf_path = $params{conf_path} || die "no conf_path set"; | ||
| 33 | |||
| 34 | # optional params | ||
| 35 | if ( defined($params{no_warnings}) && ($params{no_warnings})){ | ||
| 36 | $show_warnings = 0; | ||
| 37 | } | ||
| 38 | $only_address = (defined($params{only_address}) && $params{only_address}) // 0; | ||
| 39 | $debug = (defined($params{debug}) && $params{debug}) // 0; | ||
| 40 | |||
| 41 | $self->{final_components} = undef; | ||
| 42 | bless($self, $class); | ||
| 43 | |||
| 44 | say STDERR "************* in Geo::Address::Formatter::new ***" if ($debug); | ||
| 45 | |||
| 46 | if ($self->_read_configuration($conf_path)){ | ||
| 47 | return $self; | ||
| 48 | } | ||
| 49 | die 'unable to read configuration'; | ||
| 50 | } | ||
| 51 | |||
| 52 | sub _read_configuration { | ||
| 53 | my $self = shift; | ||
| 54 | my $path = shift; | ||
| 55 | |||
| 56 | return if (! -e $path); | ||
| 57 | |||
| 58 | my @a_filenames = File::Find::Rule->file()->name('*.yaml')->in($path . '/countries'); | ||
| 59 | |||
| 60 | $self->{templates} = {}; | ||
| 61 | $self->{component_aliases} = {}; | ||
| 62 | $self->{component2type} = {}; | ||
| 63 | $self->{ordered_components} = []; | ||
| 64 | |||
| 65 | # read the config file(s) | ||
| 66 | my $loaded = 0; | ||
| 67 | foreach my $filename (sort @a_filenames) { | ||
| 68 | try { | ||
| 69 | my $rh_templates = LoadFile($filename); | ||
| 70 | |||
| 71 | # if file 00-default.yaml defines 'DE' (Germany) and | ||
| 72 | # file 01-germany.yaml does as well, then the second | ||
| 73 | # occurance of the key overwrites the first. | ||
| 74 | foreach (keys %$rh_templates) { | ||
| 75 | $self->{templates}{$_} = $rh_templates->{$_}; | ||
| 76 | } | ||
| 77 | $loaded = 1; | ||
| 78 | } catch { | ||
| 79 | warn "error parsing country configuration in $filename: $_"; | ||
| 80 | }; | ||
| 81 | } | ||
| 82 | return if ($loaded == 0); | ||
| 83 | |||
| 84 | # see if we can load the components | ||
| 85 | try { | ||
| 86 | say STDERR "loading components" if ($debug); | ||
| 87 | my @c = LoadFile($path . '/components.yaml'); | ||
| 88 | |||
| 89 | if ($debug){ | ||
| 90 | say STDERR Dumper \@c; | ||
| 91 | } | ||
| 92 | |||
| 93 | foreach my $rh_c (@c) { | ||
| 94 | if (defined($rh_c->{name})){ | ||
| 95 | if (defined($rh_c->{aliases})){ | ||
| 96 | $self->{component_aliases}{$rh_c->{name}} = $rh_c->{aliases}; | ||
| 97 | } else { | ||
| 98 | $self->{component_aliases}{$rh_c->{name}} = []; | ||
| 99 | } | ||
| 100 | } | ||
| 101 | } | ||
| 102 | |||
| 103 | foreach my $rh_c (@c) { | ||
| 104 | push(@{$self->{ordered_components}}, $rh_c->{name}); | ||
| 105 | $self->{component2type}->{$rh_c->{name}} = $rh_c->{name}; | ||
| 106 | |||
| 107 | if (defined($rh_c->{aliases})) { | ||
| 108 | foreach my $alias (@{$rh_c->{aliases}}) { | ||
| 109 | push(@{$self->{ordered_components}}, $alias); | ||
| 110 | $self->{component2type}->{$alias} = $rh_c->{name}; | ||
| 111 | } | ||
| 112 | } | ||
| 113 | } | ||
| 114 | if ($debug){ | ||
| 115 | say STDERR 'component_aliases'; | ||
| 116 | say STDERR Dumper $self->{component_aliases}; | ||
| 117 | say STDERR 'ordered_components'; | ||
| 118 | say STDERR Dumper $self->{ordered_components}; | ||
| 119 | say STDERR 'component2type'; | ||
| 120 | say STDERR Dumper $self->{component2type}; | ||
| 121 | } | ||
| 122 | } catch { | ||
| 123 | warn "error parsing component configuration: $_"; | ||
| 124 | }; | ||
| 125 | |||
| 126 | # get the county and state codes and country2lang conf | ||
| 127 | my @conf_files = qw(county_codes state_codes country2lang); | ||
| 128 | foreach my $cfile (@conf_files) { | ||
| 129 | $self->{$cfile} = {}; | ||
| 130 | my $yfile = $path . '/' . $cfile . '.yaml'; | ||
| 131 | if (-e $yfile) { | ||
| 132 | try { | ||
| 133 | $self->{$cfile} = LoadFile($yfile); | ||
| 134 | } catch { | ||
| 135 | warn "error parsing $cfile configuration: $_"; | ||
| 136 | }; | ||
| 137 | } | ||
| 138 | } | ||
| 139 | |||
| 140 | # get the abbreviations | ||
| 141 | my @abbrv_filenames = File::Find::Rule->file()->name('*.yaml')->in($path . '/abbreviations'); | ||
| 142 | |||
| 143 | # read the config files | ||
| 144 | foreach my $abbrv_file (@abbrv_filenames) { | ||
| 145 | try { | ||
| 146 | if ($abbrv_file =~ m/\/(\w\w)\.yaml$/) { | ||
| 147 | my $lang = $1; # two letter lang code like 'en' | ||
| 148 | my $rh_c = LoadFile($abbrv_file); | ||
| 149 | $self->{abbreviations}->{$lang} = $rh_c; | ||
| 150 | } | ||
| 151 | } catch { | ||
| 152 | warn "error parsing abbrv configuration in $abbrv_file: $_"; | ||
| 153 | }; | ||
| 154 | } | ||
| 155 | #say Dumper $self->{abbreviations}; | ||
| 156 | #say Dumper $self->{country2lang}; | ||
| 157 | return 1; | ||
| 158 | } | ||
| 159 | |||
| 160 | |||
| 161 | sub final_components { | ||
| 162 | my $self = shift; | ||
| 163 | if (defined($self->{final_components})) { | ||
| 164 | return $self->{final_components}; | ||
| 165 | } | ||
| 166 | warn 'final_components not yet set' if ($show_warnings); | ||
| 167 | return; | ||
| 168 | } | ||
| 169 | |||
| 170 | |||
| 171 | sub format_address { | ||
| 172 | my $self = shift; | ||
| 173 | my $rh_components = clone(shift) || return; | ||
| 174 | my $rh_options = shift || {}; | ||
| 175 | |||
| 176 | # 1. make sure empty at the beginning | ||
| 177 | $self->{final_components} = undef; | ||
| 178 | |||
| 179 | if ($debug){ | ||
| 180 | say STDERR "*** in format_address ***"; | ||
| 181 | say STDERR Dumper $rh_options; | ||
| 182 | say STDERR Dumper $rh_components; | ||
| 183 | } | ||
| 184 | |||
| 185 | # 2. deal with the options | ||
| 186 | |||
| 187 | # 2a. which country format will we use? | ||
| 188 | # might have been specified in options | ||
| 189 | # otherwise look at components | ||
| 190 | my $cc = $rh_options->{country} | ||
| 191 | || $self->_determine_country_code($rh_components) | ||
| 192 | || ''; | ||
| 193 | |||
| 194 | if ($cc) { | ||
| 195 | $rh_components->{country_code} = $cc; | ||
| 196 | $self->_set_district_alias($cc); | ||
| 197 | } | ||
| 198 | |||
| 199 | # 2b. should we abbreviate? | ||
| 200 | my $abbrv = $rh_options->{abbreviate} // 0; | ||
| 201 | |||
| 202 | # 2c. was only_address set at the formatting level | ||
| 203 | my $oa = $only_address; | ||
| 204 | if (defined($rh_options->{only_address})){ | ||
| 205 | $oa = $rh_options->{only_address}; | ||
| 206 | } | ||
| 207 | |||
| 208 | if ($debug){ | ||
| 209 | say STDERR "component_aliases"; | ||
| 210 | say STDERR Dumper $self->{component_aliases}; | ||
| 211 | } | ||
| 212 | |||
| 213 | # done with the options | ||
| 214 | |||
| 215 | # 3. set the aliases, unless this would overwrite something | ||
| 216 | # need to do this in the right order (as defined in the components file) | ||
| 217 | # For example: | ||
| 218 | # both 'city_district' and 'suburb' are aliases of 'neighbourhood' | ||
| 219 | # so which one should we use if both are present? | ||
| 220 | # We should use the one defined first in the list | ||
| 221 | |||
| 222 | my $rhh_p2a; | ||
| 223 | foreach my $c (keys %$rh_components){ | ||
| 224 | |||
| 225 | # might not need an alias as it is a primary type | ||
| 226 | next if (defined($self->{component_aliases}{$c})); | ||
| 227 | |||
| 228 | # it is not a primary type | ||
| 229 | # is there an alias? | ||
| 230 | if (defined($self->{component2type}{$c})){ | ||
| 231 | my $ptype = $self->{component2type}{$c}; | ||
| 232 | # but is it already set? | ||
| 233 | if (! defined($rh_components->{$ptype}) ){ | ||
| 234 | # no, we will set it later | ||
| 235 | $rhh_p2a->{$ptype}{$c} = 1; | ||
| 236 | |||
| 237 | } | ||
| 238 | } | ||
| 239 | } | ||
| 240 | |||
| 241 | # now we know which primary types have aliases | ||
| 242 | foreach my $ptype (keys %$rhh_p2a){ | ||
| 243 | # is there more than one? | ||
| 244 | my @aliases = keys %{$rhh_p2a->{$ptype}}; | ||
| 245 | if (scalar @aliases == 1){ | ||
| 246 | $rh_components->{$ptype} = $rh_components->{$aliases[0]}; | ||
| 247 | next; # we are done with this ptype | ||
| 248 | } | ||
| 249 | |||
| 250 | # if there is more than one we need to go through the list | ||
| 251 | # so we do them in the right order | ||
| 252 | foreach my $c (@{$self->{component_aliases}->{$ptype}}){ | ||
| 253 | if (defined($rh_components->{$c})){ | ||
| 254 | $rh_components->{$ptype} = $rh_components->{$c}; | ||
| 255 | last; # we are done with this ptype | ||
| 256 | } | ||
| 257 | } | ||
| 258 | } | ||
| 259 | |||
| 260 | if ($debug){ | ||
| 261 | say STDERR "after component_aliases applied"; | ||
| 262 | say STDERR Dumper $rh_components; | ||
| 263 | } | ||
| 264 | |||
| 265 | # 4. deal wtih terrible inputs | ||
| 266 | $self->_sanity_cleaning($rh_components); | ||
| 267 | if ($debug){ | ||
| 268 | say STDERR "after sanity_cleaning applied"; | ||
| 269 | say STDERR Dumper $rh_components; | ||
| 270 | } | ||
| 271 | |||
| 272 | # 5. determine the template | ||
| 273 | my $template_text; | ||
| 274 | my $rh_config = $self->{templates}{uc($cc)} || $self->{templates}{default}; | ||
| 275 | |||
| 276 | if (defined($rh_options->{address_template})) { | ||
| 277 | $template_text = $rh_options->{address_template}; | ||
| 278 | } | ||
| 279 | else { | ||
| 280 | |||
| 281 | if (defined($rh_config->{address_template})) { | ||
| 282 | $template_text = $rh_config->{address_template}; | ||
| 283 | } elsif (defined($self->{templates}{default}{address_template})) { | ||
| 284 | $template_text = $self->{templates}{default}{address_template}; | ||
| 285 | } | ||
| 286 | |||
| 287 | # do we have the minimal components for an address? | ||
| 288 | # or should we instead use the fallback template? | ||
| 289 | if (!$self->_minimal_components($rh_components)) { | ||
| 290 | say STDERR "using fallback" if ($debug); | ||
| 291 | if (defined($rh_config->{fallback_template})) { | ||
| 292 | $template_text = $rh_config->{fallback_template}; | ||
| 293 | } elsif (defined($self->{templates}{default}{fallback_template})) { | ||
| 294 | $template_text = $self->{templates}{default}{fallback_template}; | ||
| 295 | } | ||
| 296 | # no fallback | ||
| 297 | } | ||
| 298 | |||
| 299 | } | ||
| 300 | |||
| 301 | say STDERR 'template text: ' . $template_text if ($debug); | ||
| 302 | |||
| 303 | # 6. clean up the components, possibly add codes | ||
| 304 | $self->_fix_country($rh_components); | ||
| 305 | if ($debug){ | ||
| 306 | say STDERR "after fix_country"; | ||
| 307 | say STDERR Dumper $rh_components; | ||
| 308 | } | ||
| 309 | |||
| 310 | $self->_apply_replacements($rh_components, $rh_config->{replace}); | ||
| 311 | if ($debug){ | ||
| 312 | say STDERR "after applying_replacements applied"; | ||
| 313 | say STDERR Dumper $rh_components; | ||
| 314 | } | ||
| 315 | $self->_add_state_code($rh_components); | ||
| 316 | $self->_add_county_code($rh_components); | ||
| 317 | if ($debug){ | ||
| 318 | say STDERR "after adding codes"; | ||
| 319 | say STDERR Dumper $rh_components; | ||
| 320 | } | ||
| 321 | |||
| 322 | # 7. add the attention, if needed | ||
| 323 | if ($debug){ | ||
| 324 | say STDERR "object level only_address: $only_address"; | ||
| 325 | say STDERR "formatting level only_address: $oa"; | ||
| 326 | } | ||
| 327 | |||
| 328 | if ($oa){ | ||
| 329 | if ($debug){ | ||
| 330 | say STDERR "not looking for unknown_components"; | ||
| 331 | say STDERR "only_address was specified"; | ||
| 332 | } | ||
| 333 | } | ||
| 334 | else { | ||
| 335 | my $ra_unknown = $self->_find_unknown_components($rh_components); | ||
| 336 | if ($debug){ | ||
| 337 | say STDERR "unknown_components:"; | ||
| 338 | say STDERR Dumper $ra_unknown; | ||
| 339 | } | ||
| 340 | if (scalar(@$ra_unknown)){ | ||
| 341 | $rh_components->{attention} = | ||
| 342 | join(', ', map { $rh_components->{$_} } @$ra_unknown); | ||
| 343 | if ($debug){ | ||
| 344 | say STDERR "putting unknown_components in 'attention'"; | ||
| 345 | } | ||
| 346 | } | ||
| 347 | } | ||
| 348 | |||
| 349 | # 8. abbreviate, if needed | ||
| 350 | if ($abbrv) { | ||
| 351 | $rh_components = $self->_abbreviate($rh_components); | ||
| 352 | } | ||
| 353 | |||
| 354 | # 9. prepare the template | ||
| 355 | $template_text = $self->_replace_template_lambdas($template_text); | ||
| 356 | |||
| 357 | # 10. compiled the template | ||
| 358 | my $compiled_template = | ||
| 359 | $THC->compile($template_text, {'numeric_string_as_string' => 1}); | ||
| 360 | |||
| 361 | if ($debug){ | ||
| 362 | say STDERR "before _render_template"; | ||
| 363 | say STDERR Dumper $rh_components; | ||
| 364 | say STDERR "template: "; | ||
| 365 | say STDERR Dumper $compiled_template; | ||
| 366 | } | ||
| 367 | |||
| 368 | # 11. render the template | ||
| 369 | my $text = $self->_render_template($compiled_template, $rh_components); | ||
| 370 | if ($debug){ | ||
| 371 | say STDERR "text after _render_template $text"; | ||
| 372 | } | ||
| 373 | |||
| 374 | # 11. postformatting | ||
| 375 | $text = $self->_postformat($text, $rh_config->{postformat_replace}); | ||
| 376 | |||
| 377 | # 12. clean again | ||
| 378 | $text = $self->_clean($text); | ||
| 379 | |||
| 380 | # 13. set final components | ||
| 381 | $self->{final_components} = $rh_components; | ||
| 382 | |||
| 383 | # all done | ||
| 384 | return $text; | ||
| 385 | } | ||
| 386 | |||
| 387 | # remove duplicates ("Berlin, Berlin"), do replacements and similar | ||
| 388 | sub _postformat { | ||
| 389 | my $self = shift; | ||
| 390 | my $text = shift; | ||
| 391 | my $raa_rules = shift; | ||
| 392 | |||
| 393 | if ($debug){ | ||
| 394 | say STDERR "entering _postformat: $text" | ||
| 395 | } | ||
| 396 | |||
| 397 | # remove duplicates | ||
| 398 | my @before_pieces = split(/, /, $text); | ||
| 399 | my %seen; | ||
| 400 | my @after_pieces; | ||
| 401 | foreach my $piece (@before_pieces) { | ||
| 402 | $piece =~ s/^\s+//g; | ||
| 403 | $seen{$piece}++; | ||
| 404 | if (lc($piece) ne 'new york') { | ||
| 405 | next if ($seen{$piece} > 1); | ||
| 406 | } | ||
| 407 | push(@after_pieces, $piece); | ||
| 408 | } | ||
| 409 | $text = join(', ', @after_pieces); | ||
| 410 | |||
| 411 | # do any country specific rules | ||
| 412 | foreach my $ra_fromto (@$raa_rules) { | ||
| 413 | try { | ||
| 414 | my $regexp = qr/$ra_fromto->[0]/; | ||
| 415 | my $replacement = $ra_fromto->[1]; | ||
| 416 | |||
| 417 | # ultra hack to do substitution | ||
| 418 | # limited to $1 and $2, should really be a while loop | ||
| 419 | # doing every substitution | ||
| 420 | |||
| 421 | if ($replacement =~ m/\$\d/) { | ||
| 422 | if ($text =~ m/$regexp/) { | ||
| 423 | my $tmp1 = $1; | ||
| 424 | my $tmp2 = $2; | ||
| 425 | my $tmp3 = $3; | ||
| 426 | $replacement =~ s/\$1/$tmp1/; | ||
| 427 | $replacement =~ s/\$2/$tmp2/; | ||
| 428 | $replacement =~ s/\$3/$tmp3/; | ||
| 429 | } | ||
| 430 | } | ||
| 431 | $text =~ s/$regexp/$replacement/; | ||
| 432 | } catch { | ||
| 433 | warn "invalid replacement: " . join(', ', @$ra_fromto); | ||
| 434 | }; | ||
| 435 | } | ||
| 436 | return $text; | ||
| 437 | } | ||
| 438 | |||
| 439 | sub _sanity_cleaning { | ||
| 440 | my $self = shift; | ||
| 441 | my $rh_components = shift || return; | ||
| 442 | |||
| 443 | # catch insane postcodes | ||
| 444 | if (defined($rh_components->{'postcode'})) { | ||
| 445 | if (length($rh_components->{'postcode'}) > 20) { | ||
| 446 | delete $rh_components->{'postcode'}; | ||
| 447 | } elsif ($rh_components->{'postcode'} =~ m/\d+;\d+/) { | ||
| 448 | # sometimes OSM has postcode ranges | ||
| 449 | delete $rh_components->{'postcode'}; | ||
| 450 | } elsif ($rh_components->{'postcode'} =~ m/^(\d{5}),\d{5}/) { | ||
| 451 | $rh_components->{'postcode'} = $1; | ||
| 452 | } | ||
| 453 | } | ||
| 454 | |||
| 455 | # remove things that might be empty | ||
| 456 | foreach my $c (keys %$rh_components) { | ||
| 457 | # catch empty values | ||
| 458 | if (!defined($rh_components->{$c})) { | ||
| 459 | delete $rh_components->{$c}; | ||
| 460 | } | ||
| 461 | # no chars | ||
| 462 | elsif ($rh_components->{$c} !~ m/\w/) { | ||
| 463 | delete $rh_components->{$c}; | ||
| 464 | } | ||
| 465 | # catch values containing URLs | ||
| 466 | elsif ($rh_components->{$c} =~ m|https?://|) { | ||
| 467 | delete $rh_components->{$c}; | ||
| 468 | } | ||
| 469 | } | ||
| 470 | return; | ||
| 471 | } | ||
| 472 | |||
| 473 | sub _minimal_components { | ||
| 474 | my $self = shift; | ||
| 475 | my $rh_components = shift || return; | ||
| 476 | my @required_components = qw(road postcode); #FIXME - should be in conf | ||
| 477 | my $missing = 0; # number of required components missing | ||
| 478 | |||
| 479 | my $minimal_threshold = 2; | ||
| 480 | foreach my $c (@required_components) { | ||
| 481 | $missing++ if (!defined($rh_components->{$c})); | ||
| 482 | return 0 if ($missing == $minimal_threshold); | ||
| 483 | } | ||
| 484 | return 1; | ||
| 485 | } | ||
| 486 | |||
| 487 | my %valid_replacement_components = ('state' => 1,); | ||
| 488 | |||
| 489 | # determines which country code to use | ||
| 490 | # may also override other configuration if we are dealing with | ||
| 491 | # a dependent territory | ||
| 492 | sub _determine_country_code { | ||
| 493 | my $self = shift; | ||
| 494 | my $rh_components = shift || return; | ||
| 495 | |||
| 496 | # FIXME - validate it is a valid country | ||
| 497 | return if (!defined($rh_components->{country_code})); | ||
| 498 | |||
| 499 | if (my $cc = lc($rh_components->{country_code})) { | ||
| 500 | |||
| 501 | # is it two letters long? | ||
| 502 | return if ($cc !~ m/^[a-z][a-z]$/); | ||
| 503 | return 'GB' if ($cc eq 'uk'); | ||
| 504 | |||
| 505 | $cc = uc($cc); | ||
| 506 | |||
| 507 | # check if the configuration tells us to use | ||
| 508 | # the configuration of another country | ||
| 509 | # used in cases of dependent territories like | ||
| 510 | # American Samoa (AS) and Puerto Rico (PR) | ||
| 511 | if ( defined($self->{templates}{$cc}) | ||
| 512 | && defined($self->{templates}{$cc}{use_country})) | ||
| 513 | { | ||
| 514 | my $old_cc = $cc; | ||
| 515 | $cc = $self->{templates}{$cc}{use_country}; | ||
| 516 | if (defined($self->{templates}{$old_cc}{change_country})) { | ||
| 517 | |||
| 518 | my $new_country = $self->{templates}{$old_cc}{change_country}; | ||
| 519 | if ($new_country =~ m/\$(\w*)/) { | ||
| 520 | my $component = $1; | ||
| 521 | if (defined($rh_components->{$component})) { | ||
| 522 | $new_country =~ s/\$$component/$rh_components->{$component}/; | ||
| 523 | } else { | ||
| 524 | $new_country =~ s/\$$component//; | ||
| 525 | } | ||
| 526 | } | ||
| 527 | $rh_components->{country} = $new_country; | ||
| 528 | } | ||
| 529 | if (defined($self->{templates}{$old_cc}{add_component})) { | ||
| 530 | my $tmp = $self->{templates}{$old_cc}{add_component}; | ||
| 531 | my ($k, $v) = split(/=/, $tmp); | ||
| 532 | # check whitelist of valid replacement components | ||
| 533 | if (defined($valid_replacement_components{$k})) { | ||
| 534 | $rh_components->{$k} = $v; | ||
| 535 | } | ||
| 536 | } | ||
| 537 | } | ||
| 538 | |||
| 539 | if ($cc eq 'NL') { | ||
| 540 | if (defined($rh_components->{state})) { | ||
| 541 | if ($rh_components->{state} eq 'Curaçao') { | ||
| 542 | $cc = 'CW'; | ||
| 543 | $rh_components->{country} = 'Curaçao'; | ||
| 544 | } elsif ($rh_components->{state} =~ m/^sint maarten/i) { | ||
| 545 | $cc = 'SX'; | ||
| 546 | $rh_components->{country} = 'Sint Maarten'; | ||
| 547 | } elsif ($rh_components->{state} =~ m/^Aruba/i) { | ||
| 548 | $cc = 'AW'; | ||
| 549 | $rh_components->{country} = 'Aruba'; | ||
| 550 | } | ||
| 551 | } | ||
| 552 | } | ||
| 553 | return $cc; | ||
| 554 | } | ||
| 555 | return; | ||
| 556 | } | ||
| 557 | |||
| 558 | # hacks for bad country data | ||
| 559 | sub _fix_country { | ||
| 560 | my $self = shift; | ||
| 561 | my $rh_components = shift || return; | ||
| 562 | |||
| 563 | # is the country a number? | ||
| 564 | # if so, and there is a state, use state as country | ||
| 565 | if (defined($rh_components->{country})) { | ||
| 566 | if (looks_like_number($rh_components->{country})) { | ||
| 567 | if (defined($rh_components->{state})) { | ||
| 568 | $rh_components->{country} = $rh_components->{state}; | ||
| 569 | delete $rh_components->{state}; | ||
| 570 | } | ||
| 571 | } | ||
| 572 | } | ||
| 573 | return; | ||
| 574 | } | ||
| 575 | |||
| 576 | # sets and returns a state code | ||
| 577 | # note may also set other values in some odd edge cases | ||
| 578 | sub _add_state_code { | ||
| 579 | my $self = shift; | ||
| 580 | my $rh_components = shift; | ||
| 581 | return $self->_add_code('state', $rh_components); | ||
| 582 | } | ||
| 583 | |||
| 584 | sub _add_county_code { | ||
| 585 | my $self = shift; | ||
| 586 | my $rh_components = shift; | ||
| 587 | return $self->_add_code('county', $rh_components); | ||
| 588 | } | ||
| 589 | |||
| 590 | sub _add_code { | ||
| 591 | my $self = shift; | ||
| 592 | my $keyname = shift // return; | ||
| 593 | my $rh_components = shift; | ||
| 594 | return if !$rh_components->{country_code}; # do we know country? | ||
| 595 | return if !$rh_components->{$keyname}; # do we know state/county? | ||
| 596 | |||
| 597 | my $code = $keyname . '_code'; | ||
| 598 | |||
| 599 | if (defined($rh_components->{$code})) { # do we already have code? | ||
| 600 | # but could have situation | ||
| 601 | # where code and long name are | ||
| 602 | # the same which we want to correct | ||
| 603 | if ($rh_components->{$code} ne $rh_components->{$keyname}) { | ||
| 604 | return; | ||
| 605 | } | ||
| 606 | } | ||
| 607 | |||
| 608 | # ensure country_code is uppercase as we use it as conf key | ||
| 609 | $rh_components->{country_code} = uc($rh_components->{country_code}); | ||
| 610 | my $cc = $rh_components->{country_code}; | ||
| 611 | |||
| 612 | if (my $mapping = $self->{$code . 's'}{$cc}) { | ||
| 613 | |||
| 614 | my $name = $rh_components->{$keyname}; | ||
| 615 | my $uc_name = uc($name); | ||
| 616 | |||
| 617 | LOCCODE: foreach my $abbrv (keys %$mapping) { | ||
| 618 | |||
| 619 | my @confnames; # can have multiple names for the place | ||
| 620 | # for example in different languages | ||
| 621 | |||
| 622 | if (is_hashref($mapping->{$abbrv})) { | ||
| 623 | push(@confnames, values %{$mapping->{$abbrv}}); | ||
| 624 | } else { | ||
| 625 | push(@confnames, $mapping->{$abbrv}); | ||
| 626 | } | ||
| 627 | |||
| 628 | foreach my $confname (@confnames) { | ||
| 629 | if ($uc_name eq uc($confname)) { | ||
| 630 | $rh_components->{$code} = $abbrv; | ||
| 631 | last LOCCODE; | ||
| 632 | } | ||
| 633 | # perhaps instead of passing in a name, we passed in a code | ||
| 634 | # example: state => 'NC' | ||
| 635 | # we want to turn that into | ||
| 636 | # state => 'North Carolina' | ||
| 637 | # state_code => 'NC' | ||
| 638 | # | ||
| 639 | if ($uc_name eq $abbrv) { | ||
| 640 | $rh_components->{$keyname} = $confname; | ||
| 641 | $rh_components->{$code} = $abbrv; | ||
| 642 | last LOCCODE; | ||
| 643 | } | ||
| 644 | } | ||
| 645 | } | ||
| 646 | # didn't find a valid code or name | ||
| 647 | |||
| 648 | # try again for odd variants like "United States Virgin Islands" | ||
| 649 | if ($keyname eq 'state') { | ||
| 650 | if (!defined($rh_components->{state_code})) { | ||
| 651 | if ($cc eq 'US') { | ||
| 652 | if ($rh_components->{state} =~ m/^united states/i) { | ||
| 653 | my $state = $rh_components->{state}; | ||
| 654 | $state =~ s/^United States/US/i; | ||
| 655 | foreach my $k (keys %$mapping) { | ||
| 656 | if (uc($state) eq uc($k)) { | ||
| 657 | $rh_components->{state_code} = $mapping->{$k}; | ||
| 658 | last; | ||
| 659 | } | ||
| 660 | } | ||
| 661 | } | ||
| 662 | if ($rh_components->{state} =~ m/^washington,? d\.?c\.?/i) { | ||
| 663 | $rh_components->{state_code} = 'DC'; | ||
| 664 | $rh_components->{state} = 'District of Columbia'; | ||
| 665 | $rh_components->{city} = 'Washington'; | ||
| 666 | } | ||
| 667 | } | ||
| 668 | } | ||
| 669 | } | ||
| 670 | } | ||
| 671 | return $rh_components->{$code}; | ||
| 672 | } | ||
| 673 | |||
| 674 | sub _apply_replacements { | ||
| 675 | my $self = shift; | ||
| 676 | my $rh_components = shift; | ||
| 677 | my $raa_rules = shift; | ||
| 678 | |||
| 679 | if ($debug){ | ||
| 680 | say STDERR "in _apply_replacements"; | ||
| 681 | say STDERR Dumper $raa_rules; | ||
| 682 | } | ||
| 683 | |||
| 684 | foreach my $component (keys %$rh_components) { | ||
| 685 | foreach my $ra_fromto (@$raa_rules) { | ||
| 686 | try { | ||
| 687 | # do key specific replacement | ||
| 688 | if ($ra_fromto->[0] =~ m/^$component=/) { | ||
| 689 | my $from = $ra_fromto->[0]; | ||
| 690 | $from =~ s/^$component=//; | ||
| 691 | if ($rh_components->{$component} eq $from) { | ||
| 692 | $rh_components->{$component} = $ra_fromto->[1]; | ||
| 693 | } | ||
| 694 | } else { | ||
| 695 | my $regexp = qr/$ra_fromto->[0]/; | ||
| 696 | $rh_components->{$component} =~ s/$regexp/$ra_fromto->[1]/; | ||
| 697 | } | ||
| 698 | } catch { | ||
| 699 | warn "invalid replacement: " . join(', ', @$ra_fromto); | ||
| 700 | }; | ||
| 701 | } | ||
| 702 | } | ||
| 703 | return $rh_components; | ||
| 704 | } | ||
| 705 | |||
| 706 | sub _abbreviate { | ||
| 707 | my $self = shift; | ||
| 708 | my $rh_comp = shift // return; | ||
| 709 | |||
| 710 | # do we know the country? | ||
| 711 | if (!defined($rh_comp->{country_code})) { | ||
| 712 | if ($show_warnings){ | ||
| 713 | my $error_msg = 'no country_code, unable to abbreviate'; | ||
| 714 | if (defined($rh_comp->{country})) { | ||
| 715 | $error_msg .= ' - country: ' . $rh_comp->{country}; | ||
| 716 | } | ||
| 717 | warn $error_msg | ||
| 718 | } | ||
| 719 | return; | ||
| 720 | } | ||
| 721 | |||
| 722 | # do we have abbreviations for this country? | ||
| 723 | my $cc = uc($rh_comp->{country_code}); | ||
| 724 | |||
| 725 | # 1. which languages? | ||
| 726 | if (defined($self->{country2lang}{$cc})) { | ||
| 727 | |||
| 728 | my @langs = split(/,/, $self->{country2lang}{$cc}); | ||
| 729 | |||
| 730 | foreach my $lang (@langs) { | ||
| 731 | # do we have abbrv for this lang? | ||
| 732 | if (defined($self->{abbreviations}->{$lang})) { | ||
| 733 | |||
| 734 | my $rh_abbr = $self->{abbreviations}->{$lang}; | ||
| 735 | foreach my $comp_name (keys %$rh_abbr) { | ||
| 736 | next if (!defined($rh_comp->{$comp_name})); | ||
| 737 | foreach my $long (keys %{$rh_abbr->{$comp_name}}) { | ||
| 738 | my $short = $rh_abbr->{$comp_name}->{$long}; | ||
| 739 | $rh_comp->{$comp_name} =~ s/\b$long\b/$short/; | ||
| 740 | } | ||
| 741 | } | ||
| 742 | } else { | ||
| 743 | #warn "no abbreviations defined for lang $lang"; | ||
| 744 | } | ||
| 745 | } | ||
| 746 | } | ||
| 747 | |||
| 748 | return $rh_comp; | ||
| 749 | } | ||
| 750 | |||
| 751 | # " abc,,def , ghi " => 'abc, def, ghi' | ||
| 752 | sub _clean { | ||
| 753 | my $self = shift; | ||
| 754 | my $out = shift // return; | ||
| 755 | if ($debug){ | ||
| 756 | say STDERR "entering _clean \n$out"; | ||
| 757 | } | ||
| 758 | |||
| 759 | $out =~ s/\'\;/'/g; | ||
| 760 | |||
| 761 | $out =~ s/[\},\s]+$//; | ||
| 762 | $out =~ s/^[,\s]+//; | ||
| 763 | |||
| 764 | $out =~ s/^- //; # line starting with dash due to a parameter missing | ||
| 765 | |||
| 766 | $out =~ s/,\s*,/, /g; # multiple commas to one | ||
| 767 | $out =~ s/\h+,\h+/, /g; # one horiz whitespace behind comma | ||
| 768 | $out =~ s/\h\h+/ /g; # multiple horiz whitespace to one | ||
| 769 | $out =~ s/\h\n/\n/g; # horiz whitespace, newline to newline | ||
| 770 | $out =~ s/\n,/\n/g; # newline comma to just newline | ||
| 771 | $out =~ s/,,+/,/g; # multiple commas to one | ||
| 772 | $out =~ s/,\n/\n/g; # comma newline to just newline | ||
| 773 | $out =~ s/\n\h+/\n/g; # newline plus space to newline | ||
| 774 | $out =~ s/\n\n+/\n/g; # multiple newline to one | ||
| 775 | |||
| 776 | # final dedupe across and within lines | ||
| 777 | my @before_pieces = split(/\n/, $out); | ||
| 778 | my %seen_lines; | ||
| 779 | my @after_pieces; | ||
| 780 | foreach my $line (@before_pieces) { | ||
| 781 | $line =~ s/^\h+//g; | ||
| 782 | $line =~ s/\h+$//g; | ||
| 783 | $seen_lines{$line}++; | ||
| 784 | next if ($seen_lines{$line} > 1); | ||
| 785 | # now dedupe within the line | ||
| 786 | my @before_words = split(/,/, $line); | ||
| 787 | my %seen_words; | ||
| 788 | my @after_words; | ||
| 789 | foreach my $w (@before_words) { | ||
| 790 | $w =~ s/^\h+//g; | ||
| 791 | $w =~ s/\h+$//g; | ||
| 792 | if (lc($w) ne 'new york') { | ||
| 793 | $seen_words{$w}++; | ||
| 794 | } | ||
| 795 | next if ((defined($seen_words{$w})) && ($seen_words{$w} > 1)); | ||
| 796 | push(@after_words, $w); | ||
| 797 | } | ||
| 798 | $line = join(', ', @after_words); | ||
| 799 | push(@after_pieces, $line); | ||
| 800 | } | ||
| 801 | $out = join("\n", @after_pieces); | ||
| 802 | |||
| 803 | $out =~ s/^\s+//; # remove leading whitespace | ||
| 804 | $out =~ s/\s+$//; # remove end whitespace | ||
| 805 | |||
| 806 | $out .= "\n"; # add final newline | ||
| 807 | return $out; # we are done | ||
| 808 | } | ||
| 809 | |||
| 810 | sub _render_template { | ||
| 811 | my $self = shift; | ||
| 812 | my $thtemplate = shift; | ||
| 813 | my $components = shift; | ||
| 814 | |||
| 815 | # Mustache calls it context | ||
| 816 | my $context = clone($components); | ||
| 817 | say STDERR 'context: ' . Dumper $context if ($debug); | ||
| 818 | my $output = $thtemplate->render($context); | ||
| 819 | |||
| 820 | $output = $self->_evaluate_template_lamdas($output); | ||
| 821 | |||
| 822 | say STDERR "in _render before _clean: $output" if ($debug); | ||
| 823 | $output = $self->_clean($output); | ||
| 824 | |||
| 825 | # is it empty? | ||
| 826 | # if yes and there is only one component then just use that one | ||
| 827 | if ($output !~ m/\w/) { | ||
| 828 | my @comps = sort keys %$components; | ||
| 829 | if (scalar(@comps) == 1) { | ||
| 830 | foreach my $k (@comps) { | ||
| 831 | $output = $components->{$k}; | ||
| 832 | } | ||
| 833 | } # FIXME what if more than one? | ||
| 834 | } | ||
| 835 | return $output; | ||
| 836 | } | ||
| 837 | |||
| 838 | # Text::Hogan apparently caches lambdas when rendering templates. In the past | ||
| 839 | # we needed our lambda 'first', example | ||
| 840 | # {{#first}} {{{city}}} || {{{town}}} {{/first}} | ||
| 841 | # to evaluate the componentes. Whenever the lambda was called with different | ||
| 842 | # component values it consumed memory. Now replace with a simpler implementation | ||
| 843 | # | ||
| 844 | sub _replace_template_lambdas { | ||
| 845 | my $self = shift; | ||
| 846 | my $template_text = shift; | ||
| 847 | $template_text =~ s!\Q{{#first}}\E(.+?)\Q{{/first}}\E!FIRSTSTART${1}FIRSTEND!g; | ||
| 848 | return $template_text; | ||
| 849 | } | ||
| 850 | |||
| 851 | # We only use a lambda named 'first' | ||
| 852 | sub _evaluate_template_lamdas { | ||
| 853 | my $self = shift; | ||
| 854 | my $text = shift; | ||
| 855 | $text =~ s!FIRSTSTART\s*(.+?)\s*FIRSTEND!_select_first($1)!seg; | ||
| 856 | return $text; | ||
| 857 | } | ||
| 858 | |||
| 859 | # '|| val1 || || val3' => 'val1' | ||
| 860 | sub _select_first { | ||
| 861 | my $text = shift; | ||
| 862 | my @a_parts = grep { length($_) } split(/\s*\|\|\s*/, $text); | ||
| 863 | return scalar(@a_parts) ? $a_parts[0] : ''; | ||
| 864 | } | ||
| 865 | |||
| 866 | my %small_district = ( | ||
| 867 | 'br' => 1, | ||
| 868 | 'cr' => 1, | ||
| 869 | 'es' => 1, | ||
| 870 | 'ni' => 1, | ||
| 871 | 'py' => 1, | ||
| 872 | 'ro' => 1, | ||
| 873 | 'tg' => 1, | ||
| 874 | 'tm' => 1, | ||
| 875 | 'xk' => 1, | ||
| 876 | ); | ||
| 877 | |||
| 878 | # correct the alias for "district" | ||
| 879 | # in OSM some countries use district to mean "city_district" | ||
| 880 | # others to mean "state_district" | ||
| 881 | sub _set_district_alias { | ||
| 882 | my $self = shift; | ||
| 883 | my $cc = shift; | ||
| 884 | |||
| 885 | my $oldalias; | ||
| 886 | if (defined($small_district{$cc})){ | ||
| 887 | $self->{component2type}{district} = 'neighbourhood'; | ||
| 888 | $oldalias = 'state_district'; | ||
| 889 | |||
| 890 | # add to the neighbourhood alias list | ||
| 891 | # though of course we are just sticking it at the end | ||
| 892 | push(@{$self->{component_aliases}{'neighbourhood'}}, 'district'); | ||
| 893 | |||
| 894 | } else { | ||
| 895 | # set 'district' to be type 'state_district' | ||
| 896 | $self->{component2type}{district} = 'state_district'; | ||
| 897 | $oldalias = 'neighbourhood'; | ||
| 898 | |||
| 899 | # add to the state_district alias list | ||
| 900 | push(@{$self->{component_aliases}{'state_district'}}, 'district'); | ||
| 901 | } | ||
| 902 | |||
| 903 | # remove from the old alias list | ||
| 904 | my @temp = grep { $_ ne 'district' } @{$self->{component_aliases}{$oldalias}}; | ||
| 905 | $self->{component_aliases}{$oldalias} = \@temp; | ||
| 906 | |||
| 907 | return; | ||
| 908 | } | ||
| 909 | |||
| 910 | |||
| 911 | # returns [] | ||
| 912 | sub _find_unknown_components { | ||
| 913 | my $self = shift; | ||
| 914 | my $rh_components = shift; | ||
| 915 | |||
| 916 | my %h_known = map { $_ => 1 } @{$self->{ordered_components}}; | ||
| 917 | my @a_unknown = grep { !exists($h_known{$_}) } sort keys %$rh_components; | ||
| 918 | |||
| 919 | return \@a_unknown; | ||
| 920 | } | ||
| 921 | |||
| 922 | 1; | ||
| 923 | |||
| 924 | __END__ | ||
| 925 | |||
| 926 | =pod | ||
| 927 | |||
| 928 | =encoding UTF-8 | ||
| 929 | |||
| 930 | =head1 NAME | ||
| 931 | |||
| 932 | Geo::Address::Formatter - take structured address data and format it according to the various global/country rules | ||
| 933 | |||
| 934 | =head1 VERSION | ||
| 935 | |||
| 936 | version 1.994 | ||
| 937 | |||
| 938 | =head1 SYNOPSIS | ||
| 939 | |||
| 940 | # | ||
| 941 | # get the templates (or use your own) | ||
| 942 | # git clone git@github.com:OpenCageData/address-formatting.git | ||
| 943 | # | ||
| 944 | my $GAF = Geo::Address::Formatter->new( conf_path => '/path/to/templates' ); | ||
| 945 | |||
| 946 | my $components = { ... } | ||
| 947 | my $text = $GAF->format_address($components, { country => 'FR' } ); | ||
| 948 | my $rh_final_components = $GAF->final_components(); | ||
| 949 | # | ||
| 950 | # or if we want shorter output | ||
| 951 | # | ||
| 952 | my $short_text = $GAF->format_address($components, { country => 'FR', abbreviate => 1, }); | ||
| 953 | |||
| 954 | =head2 new | ||
| 955 | |||
| 956 | my $GAF = Geo::Address::Formatter->new( conf_path => '/path/to/templates' ); | ||
| 957 | |||
| 958 | Returns one instance. The I<conf_path> is required. | ||
| 959 | |||
| 960 | Optional parameters are: | ||
| 961 | |||
| 962 | I<debug>: prints tons of debugging info for use in development. | ||
| 963 | |||
| 964 | I<no_warnings>: turns off a few warnings if configuration is not optimal. | ||
| 965 | |||
| 966 | I<only_address>: formatted will only contain known components (will not include POI names like). Note, can be overridden with optional param to format_address method. | ||
| 967 | |||
| 968 | =head2 final_components | ||
| 969 | |||
| 970 | my $rh_components = $GAF->final_components(); | ||
| 971 | |||
| 972 | returns a reference to a hash of the final components that are set at the | ||
| 973 | completion of B<format_address>. Warns if called before they have been set | ||
| 974 | (unless I<no_warnings> was set at object creation). | ||
| 975 | |||
| 976 | =head2 format_address | ||
| 977 | |||
| 978 | my $text = $GAF->format_address(\%components, \%options ); | ||
| 979 | |||
| 980 | Given a structures address (hashref) and options (hashref) returns a | ||
| 981 | formatted address. | ||
| 982 | |||
| 983 | Possible options are: | ||
| 984 | |||
| 985 | 'abbreviate', if supplied common abbreviations are applied | ||
| 986 | to the resulting output. | ||
| 987 | |||
| 988 | 'address_template', a mustache format template to be used instead of the template | ||
| 989 | defined in the configuration | ||
| 990 | |||
| 991 | 'country', which should be an uppercase ISO 3166-1:alpha-2 code | ||
| 992 | e.g. 'GB' for Great Britain, 'DE' for Germany, etc. | ||
| 993 | If ommited we try to find the country in the address components. | ||
| 994 | |||
| 995 | 'only_address', same as only_address global option but set at formatting level | ||
| 996 | |||
| 997 | =head1 DESCRIPTION | ||
| 998 | |||
| 999 | You have a structured postal address (hash) and need to convert it into a | ||
| 1000 | readable address based on the format of the address country. | ||
| 1001 | |||
| 1002 | For example, you have: | ||
| 1003 | |||
| 1004 | { | ||
| 1005 | house_number => 12, | ||
| 1006 | street => 'Avenue Road', | ||
| 1007 | postcode => 45678, | ||
| 1008 | city => 'Deville' | ||
| 1009 | } | ||
| 1010 | |||
| 1011 | you need: | ||
| 1012 | |||
| 1013 | Great Britain: 12 Avenue Road, Deville 45678 | ||
| 1014 | France: 12 Avenue Road, 45678 Deville | ||
| 1015 | Germany: Avenue Road 12, 45678 Deville | ||
| 1016 | Latvia: Avenue Road 12, Deville, 45678 | ||
| 1017 | |||
| 1018 | It gets more complicated with 200+ countries and territories and dozens more | ||
| 1019 | address components to consider. | ||
| 1020 | |||
| 1021 | This module comes with a minimal configuration to run tests. Instead of | ||
| 1022 | developing your own configuration please use (and contribute to) | ||
| 1023 | those in https://github.com/OpenCageData/address-formatting | ||
| 1024 | which includes test cases. | ||
| 1025 | |||
| 1026 | Together we can address the world! | ||
| 1027 | |||
| 1028 | =head1 AUTHOR | ||
| 1029 | |||
| 1030 | Ed Freyfogle | ||
| 1031 | |||
| 1032 | =head1 COPYRIGHT AND LICENSE | ||
| 1033 | |||
| 1034 | This software is copyright (c) 2023 by Opencage GmbH. | ||
| 1035 | |||
| 1036 | This is free software; you can redistribute it and/or modify it under | ||
| 1037 | the same terms as the Perl 5 programming language system itself. | ||
| 1038 | |||
| 1039 | =cut |