]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/place_sanitizer.py
c7dfd1ba5d34f4f55fe946bae421237c5e74cbe8
[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 from typing import Optional, List, Mapping, Sequence, Callable, Any, Tuple
12
13 from nominatim.errors import UsageError
14 from nominatim.config import Configuration
15 from nominatim.tokenizer.sanitizers.config import SanitizerConfig
16 from nominatim.tokenizer.sanitizers.base import SanitizerHandler, ProcessInfo, PlaceName
17 from nominatim.data.place_info import PlaceInfo
18
19
20 class PlaceSanitizer:
21     """ Controller class which applies sanitizer functions on the place
22         names and address before they are used by the token analysers.
23     """
24
25     def __init__(self, rules: Optional[Sequence[Mapping[str, Any]]],
26                  config: Configuration) -> None:
27         self.handlers: List[Callable[[ProcessInfo], None]] = []
28
29         if rules:
30             for func in rules:
31                 if 'step' not in func:
32                     raise UsageError("Sanitizer rule is missing the 'step' attribute.")
33                 if not isinstance(func['step'], str):
34                     raise UsageError("'step' attribute must be a simple string.")
35
36                 module: SanitizerHandler = \
37                     config.load_plugin_module(func['step'], 'nominatim.tokenizer.sanitizers')
38
39                 self.handlers.append(module.create(SanitizerConfig(func)))
40
41
42     def process_names(self, place: PlaceInfo) -> Tuple[List[PlaceName], List[PlaceName]]:
43         """ Extract a sanitized list of names and address parts from the
44             given place. The function returns a tuple
45             (list of names, list of address names)
46         """
47         obj = ProcessInfo(place)
48
49         for func in self.handlers:
50             func(obj)
51
52         return obj.names, obj.address