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