]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/place_sanitizer.py
Merge pull request #2562 from lonvia/copyright-headers
[nominatim.git] / nominatim / tokenizer / place_sanitizer.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 Handler for cleaning name and address tags in place information before it
9 is handed to the token analysis.
10 """
11 import importlib
12
13 from nominatim.errors import UsageError
14
15 class PlaceName:
16     """ A searchable name for a place together with properties.
17         Every name object saves the name proper and two basic properties:
18         * 'kind' describes the name of the OSM key used without any suffixes
19           (i.e. the part after the colon removed)
20         * 'suffix' contains the suffix of the OSM tag, if any. The suffix
21           is the part of the key after the first colon.
22         In addition to that, the name may have arbitrary additional attributes.
23         Which attributes are used, depends on the token analyser.
24     """
25
26     def __init__(self, name, kind, suffix):
27         self.name = name
28         self.kind = kind
29         self.suffix = suffix
30         self.attr = {}
31
32
33     def __repr__(self):
34         return f"PlaceName(name='{self.name}',kind='{self.kind}',suffix='{self.suffix}')"
35
36
37     def clone(self, name=None, kind=None, suffix=None, attr=None):
38         """ Create a deep copy of the place name, optionally with the
39             given parameters replaced. In the attribute list only the given
40             keys are updated. The list is not replaced completely.
41             In particular, the function cannot to be used to remove an
42             attribute from a place name.
43         """
44         newobj = PlaceName(name or self.name,
45                            kind or self.kind,
46                            suffix or self.suffix)
47
48         newobj.attr.update(self.attr)
49         if attr:
50             newobj.attr.update(attr)
51
52         return newobj
53
54
55     def set_attr(self, key, value):
56         """ Add the given property to the name. If the property was already
57             set, then the value is overwritten.
58         """
59         self.attr[key] = value
60
61
62     def get_attr(self, key, default=None):
63         """ Return the given property or the value of 'default' if it
64             is not set.
65         """
66         return self.attr.get(key, default)
67
68
69     def has_attr(self, key):
70         """ Check if the given attribute is set.
71         """
72         return key in self.attr
73
74
75 class _ProcessInfo:
76     """ Container class for information handed into to handler functions.
77         The 'names' and 'address' members are mutable. A handler must change
78         them by either modifying the lists place or replacing the old content
79         with a new list.
80     """
81
82     def __init__(self, place):
83         self.place = place
84         self.names = self._convert_name_dict(place.name)
85         self.address = self._convert_name_dict(place.address)
86
87
88     @staticmethod
89     def _convert_name_dict(names):
90         """ Convert a dictionary of names into a list of PlaceNames.
91             The dictionary key is split into the primary part of the key
92             and the suffix (the part after an optional colon).
93         """
94         out = []
95
96         if names:
97             for key, value in names.items():
98                 parts = key.split(':', 1)
99                 out.append(PlaceName(value.strip(),
100                                      parts[0].strip(),
101                                      parts[1].strip() if len(parts) > 1 else None))
102
103         return out
104
105
106 class PlaceSanitizer:
107     """ Controller class which applies sanitizer functions on the place
108         names and address before they are used by the token analysers.
109     """
110
111     def __init__(self, rules):
112         self.handlers = []
113
114         if rules:
115             for func in rules:
116                 if 'step' not in func:
117                     raise UsageError("Sanitizer rule is missing the 'step' attribute.")
118                 module_name = 'nominatim.tokenizer.sanitizers.' + func['step'].replace('-', '_')
119                 handler_module = importlib.import_module(module_name)
120                 self.handlers.append(handler_module.create(func))
121
122
123     def process_names(self, place):
124         """ Extract a sanitized list of names and address parts from the
125             given place. The function returns a tuple
126             (list of names, list of address names)
127         """
128         obj = _ProcessInfo(place)
129
130         for func in self.handlers:
131             func(obj)
132
133         return obj.names, obj.address