]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/sanitizers/clean_postcodes.py
postcodes: strip leading country codes
[nominatim.git] / nominatim / tokenizer / sanitizers / clean_postcodes.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Sanitizer that filters postcodes by their officially allowed pattern.
9
10 Arguments:
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
17                         searchable either.
18 """
19 import re
20
21 from nominatim.errors import UsageError
22 from nominatim.tools import country_info
23
24 class _PostcodeMatcher:
25     """ Matches and formats a postcode according to the format definition.
26     """
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}'")
31
32         pc_pattern = config['pattern'].replace('d', '[0-9]').replace('l', '[A-Z]')
33
34         self.pattern = re.compile(f'(?:{country_code.upper()}[ -]?)?({pc_pattern})')
35
36
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.
40         """
41         normalized = postcode.strip().upper()
42
43         match = self.pattern.fullmatch(normalized)
44
45         return match.group(1) if match else None
46
47
48 class _PostcodeSanitizer:
49
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 = {}
55
56         for ccode, prop in country_info.iterate('postcode'):
57             if prop is False:
58                 self.country_without_postcode.add(ccode)
59             elif isinstance(prop, dict):
60                 self.country_matcher[ccode] = _PostcodeMatcher(ccode, prop)
61             else:
62                 raise UsageError(f"Invalid entry 'postcode' for country '{ccode}'")
63
64
65     def __call__(self, obj):
66         if not obj.address:
67             return
68
69         postcodes = ((i, o) for i, o in enumerate(obj.address) if o.kind == 'postcode')
70
71         for pos, postcode in postcodes:
72             formatted = self.scan(postcode.name, obj.place.country_code)
73
74             if formatted is None:
75                 if self.convert_to_address:
76                     postcode.kind = 'unofficial_postcode'
77                 else:
78                     obj.address.pop(pos)
79             else:
80                 postcode.name = formatted
81
82
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.
87         """
88         if country in self.country_without_postcode:
89             return None
90
91         if country in self.country_matcher:
92             return self.country_matcher[country].normalize(postcode)
93
94         return postcode.upper()
95
96
97
98 def create(config):
99     """ Create a housenumber processing function.
100     """
101
102     return _PostcodeSanitizer(config)