]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/icu_rule_loader.py
Merge remote-tracking branch 'upstream/master'
[nominatim.git] / nominatim / tokenizer / icu_rule_loader.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 Helper class to create ICU rules from a configuration file.
9 """
10 from typing import Mapping, Any, Dict, Optional
11 import io
12 import json
13 import logging
14
15 from icu import Transliterator
16
17 from nominatim.config import flatten_config_list, Configuration
18 from nominatim.db.properties import set_property, get_property
19 from nominatim.db.connection import Connection
20 from nominatim.errors import UsageError
21 from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
22 from nominatim.tokenizer.icu_token_analysis import ICUTokenAnalysis
23 from nominatim.tokenizer.token_analysis.base import AnalysisModule, Analyzer
24 import nominatim.data.country_info
25
26 LOG = logging.getLogger()
27
28 DBCFG_IMPORT_NORM_RULES = "tokenizer_import_normalisation"
29 DBCFG_IMPORT_TRANS_RULES = "tokenizer_import_transliteration"
30 DBCFG_IMPORT_ANALYSIS_RULES = "tokenizer_import_analysis_rules"
31
32
33 def _get_section(rules: Mapping[str, Any], section: str) -> Any:
34     """ Get the section named 'section' from the rules. If the section does
35         not exist, raise a usage error with a meaningful message.
36     """
37     if section not in rules:
38         LOG.fatal("Section '%s' not found in tokenizer config.", section)
39         raise UsageError("Syntax error in tokenizer configuration file.")
40
41     return rules[section]
42
43
44 class ICURuleLoader:
45     """ Compiler for ICU rules from a tokenizer configuration file.
46     """
47
48     def __init__(self, config: Configuration) -> None:
49         self.config = config
50         rules = config.load_sub_configuration('icu_tokenizer.yaml',
51                                               config='TOKENIZER_CONFIG')
52
53         # Make sure country information is available to analyzers and sanitizers.
54         nominatim.data.country_info.setup_country_config(config)
55
56         self.normalization_rules = self._cfg_to_icu_rules(rules, 'normalization')
57         self.transliteration_rules = self._cfg_to_icu_rules(rules, 'transliteration')
58         self.analysis_rules = _get_section(rules, 'token-analysis')
59         self._setup_analysis()
60
61         # Load optional sanitizer rule set.
62         self.sanitizer_rules = rules.get('sanitizers', [])
63
64
65     def load_config_from_db(self, conn: Connection) -> None:
66         """ Get previously saved parts of the configuration from the
67             database.
68         """
69         rules = get_property(conn, DBCFG_IMPORT_NORM_RULES)
70         if rules is not None:
71             self.normalization_rules = rules
72
73         rules = get_property(conn, DBCFG_IMPORT_TRANS_RULES)
74         if rules is not None:
75             self.transliteration_rules = rules
76
77         rules = get_property(conn, DBCFG_IMPORT_ANALYSIS_RULES)
78         if rules:
79             self.analysis_rules = json.loads(rules)
80         else:
81             self.analysis_rules = []
82         self._setup_analysis()
83
84
85     def save_config_to_db(self, conn: Connection) -> None:
86         """ Save the part of the configuration that cannot be changed into
87             the database.
88         """
89         set_property(conn, DBCFG_IMPORT_NORM_RULES, self.normalization_rules)
90         set_property(conn, DBCFG_IMPORT_TRANS_RULES, self.transliteration_rules)
91         set_property(conn, DBCFG_IMPORT_ANALYSIS_RULES, json.dumps(self.analysis_rules))
92
93
94     def make_sanitizer(self) -> PlaceSanitizer:
95         """ Create a place sanitizer from the configured rules.
96         """
97         return PlaceSanitizer(self.sanitizer_rules, self.config)
98
99
100     def make_token_analysis(self) -> ICUTokenAnalysis:
101         """ Create a token analyser from the reviouly loaded rules.
102         """
103         return ICUTokenAnalysis(self.normalization_rules,
104                                 self.transliteration_rules, self.analysis)
105
106
107     def get_search_rules(self) -> str:
108         """ Return the ICU rules to be used during search.
109             The rules combine normalization and transliteration.
110         """
111         # First apply the normalization rules.
112         rules = io.StringIO()
113         rules.write(self.normalization_rules)
114
115         # Then add transliteration.
116         rules.write(self.transliteration_rules)
117         return rules.getvalue()
118
119
120     def get_normalization_rules(self) -> str:
121         """ Return rules for normalisation of a term.
122         """
123         return self.normalization_rules
124
125
126     def get_transliteration_rules(self) -> str:
127         """ Return the rules for converting a string into its asciii representation.
128         """
129         return self.transliteration_rules
130
131
132     def _setup_analysis(self) -> None:
133         """ Process the rules used for creating the various token analyzers.
134         """
135         self.analysis: Dict[Optional[str], TokenAnalyzerRule]  = {}
136
137         if not isinstance(self.analysis_rules, list):
138             raise UsageError("Configuration section 'token-analysis' must be a list.")
139
140         norm = Transliterator.createFromRules("rule_loader_normalization",
141                                               self.normalization_rules)
142         trans = Transliterator.createFromRules("rule_loader_transliteration",
143                                               self.transliteration_rules)
144
145         for section in self.analysis_rules:
146             name = section.get('id', None)
147             if name in self.analysis:
148                 if name is None:
149                     LOG.fatal("ICU tokenizer configuration has two default token analyzers.")
150                 else:
151                     LOG.fatal("ICU tokenizer configuration has two token "
152                               "analyzers with id '%s'.", name)
153                 raise UsageError("Syntax error in ICU tokenizer config.")
154             self.analysis[name] = TokenAnalyzerRule(section, norm, trans,
155                                                     self.config)
156
157
158     @staticmethod
159     def _cfg_to_icu_rules(rules: Mapping[str, Any], section: str) -> str:
160         """ Load an ICU ruleset from the given section. If the section is a
161             simple string, it is interpreted as a file name and the rules are
162             loaded verbatim from the given file. The filename is expected to be
163             relative to the tokenizer rule file. If the section is a list then
164             each line is assumed to be a rule. All rules are concatenated and returned.
165         """
166         content = _get_section(rules, section)
167
168         if content is None:
169             return ''
170
171         return ';'.join(flatten_config_list(content, section)) + ';'
172
173
174 class TokenAnalyzerRule:
175     """ Factory for a single analysis module. The class saves the configuration
176         and creates a new token analyzer on request.
177     """
178
179     def __init__(self, rules: Mapping[str, Any],
180                  normalizer: Any, transliterator: Any,
181                  config: Configuration) -> None:
182         analyzer_name = _get_section(rules, 'analyzer')
183         if not analyzer_name or not isinstance(analyzer_name, str):
184             raise UsageError("'analyzer' parameter needs to be simple string")
185
186         self._analysis_mod: AnalysisModule = \
187             config.load_plugin_module(analyzer_name, 'nominatim.tokenizer.token_analysis')
188
189         self.config = self._analysis_mod.configure(rules, normalizer,
190                                                    transliterator)
191
192
193     def create(self, normalizer: Any, transliterator: Any) -> Analyzer:
194         """ Create a new analyser instance for the given rule.
195         """
196         return self._analysis_mod.create(normalizer, transliterator, self.config)