1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Sanitizer that filters postcodes by their officially allowed pattern.
11 convert-to-address: If set to 'yes' (the default), then postcodes that do
12 not conform with their country-specific pattern are
13 converted to an address component. That means that
14 the postcode does not take part when computing the
15 postcode centroids of a country but is still searchable.
16 When set to 'no', non-conforming postcodes are not
21 from nominatim.errors import UsageError
22 from nominatim.tools import country_info
24 class _PostcodeMatcher:
25 """ Matches and formats a postcode according to the format definition.
27 def __init__(self, country_code, config):
28 if 'pattern' not in config:
29 raise UsageError("Field 'pattern' required for 'postcode' "
30 f"for country '{country_code}'")
32 pc_pattern = config['pattern'].replace('d', '[0-9]').replace('l', '[A-Z]')
34 self.pattern = re.compile(f'(?:{country_code.upper()}[ -]?)?({pc_pattern})')
37 def normalize(self, postcode):
38 """ Return the normalized version of the postcode. If the given postcode
39 does not correspond to the usage-pattern, return null.
41 normalized = postcode.strip().upper()
43 match = self.pattern.fullmatch(normalized)
45 return match.group(1) if match else None
48 class _PostcodeSanitizer:
50 def __init__(self, config):
51 self.convert_to_address = config.get_bool('convert-to-address', True)
52 # Objects without a country code can't have a postcode per definition.
53 self.country_without_postcode = {None}
54 self.country_matcher = {}
56 for ccode, prop in country_info.iterate('postcode'):
58 self.country_without_postcode.add(ccode)
59 elif isinstance(prop, dict):
60 self.country_matcher[ccode] = _PostcodeMatcher(ccode, prop)
62 raise UsageError(f"Invalid entry 'postcode' for country '{ccode}'")
65 def __call__(self, obj):
69 postcodes = ((i, o) for i, o in enumerate(obj.address) if o.kind == 'postcode')
71 for pos, postcode in postcodes:
72 formatted = self.scan(postcode.name, obj.place.country_code)
75 if self.convert_to_address:
76 postcode.kind = 'unofficial_postcode'
80 postcode.name = formatted
83 def scan(self, postcode, country):
84 """ Check the postcode for correct formatting and return the
85 normalized version. Returns None if the postcode does not
86 correspond to the oficial format of the given country.
88 if country in self.country_without_postcode:
91 if country in self.country_matcher:
92 return self.country_matcher[country].normalize(postcode)
94 return postcode.upper()
99 """ Create a housenumber processing function.
102 return _PostcodeSanitizer(config)