]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/sanitizers/clean_postcodes.py
initial postcode cleaner for simple patterns
[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         self.pattern = re.compile(config['pattern'].replace('d', '[0-9]')
33                                                    .replace('l', '[A-Z]'))
34
35
36     def normalize(self, postcode):
37         """ Return the normalized version of the postcode. If the given postcode
38             does not correspond to the usage-pattern, return null.
39         """
40         normalized = postcode.strip().upper()
41
42         return normalized if self.pattern.fullmatch(normalized) else None
43
44
45 class _PostcodeSanitizer:
46
47     def __init__(self, config):
48         self.convert_to_address = config.get_bool('convert-to-address', True)
49         # Objects without a country code can't have a postcode per definition.
50         self.country_without_postcode = {None}
51         self.country_matcher = {}
52
53         for ccode, prop in country_info.iterate('postcode'):
54             if prop is False:
55                 self.country_without_postcode.add(ccode)
56             elif isinstance(prop, dict):
57                 self.country_matcher[ccode] = _PostcodeMatcher(ccode, prop)
58             else:
59                 raise UsageError(f"Invalid entry 'postcode' for country '{ccode}'")
60
61
62     def __call__(self, obj):
63         if not obj.address:
64             return
65
66         postcodes = ((i, o) for i, o in enumerate(obj.address) if o.kind == 'postcode')
67
68         for pos, postcode in postcodes:
69             formatted = self.scan(postcode.name, obj.place.country_code)
70
71             if formatted is None:
72                 if self.convert_to_address:
73                     postcode.kind = 'unofficial_postcode'
74                 else:
75                     obj.address.pop(pos)
76             else:
77                 postcode.name = formatted
78
79
80     def scan(self, postcode, country):
81         """ Check the postcode for correct formatting and return the
82             normalized version. Returns None if the postcode does not
83             correspond to the oficial format of the given country.
84         """
85         if country in self.country_without_postcode:
86             return None
87
88         if country in self.country_matcher:
89             return self.country_matcher[country].normalize(postcode)
90
91         return postcode.upper()
92
93
94
95 def create(config):
96     """ Create a housenumber processing function.
97     """
98
99     return _PostcodeSanitizer(config)