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