1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Helper class to create ICU rules from a configuration file.
10 from typing import Mapping, Any, Dict, Optional
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
24 LOG = logging.getLogger()
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"
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.
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.")
43 """ Compiler for ICU rules from a tokenizer configuration file.
46 def __init__(self, config: Configuration) -> None:
48 rules = config.load_sub_configuration('icu_tokenizer.yaml',
49 config='TOKENIZER_CONFIG')
51 # Make sure country information is available to analyzers and sanitizers.
52 nominatim.data.country_info.setup_country_config(config)
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()
59 # Load optional sanitizer rule set.
60 self.sanitizer_rules = rules.get('sanitizers', [])
63 def load_config_from_db(self, conn: Connection) -> None:
64 """ Get previously saved parts of the configuration from the
67 rules = get_property(conn, DBCFG_IMPORT_NORM_RULES)
69 self.normalization_rules = rules
71 rules = get_property(conn, DBCFG_IMPORT_TRANS_RULES)
73 self.transliteration_rules = rules
75 rules = get_property(conn, DBCFG_IMPORT_ANALYSIS_RULES)
77 self.analysis_rules = json.loads(rules)
79 self.analysis_rules = []
80 self._setup_analysis()
83 def save_config_to_db(self, conn: Connection) -> None:
84 """ Save the part of the configuration that cannot be changed into
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))
92 def make_sanitizer(self) -> PlaceSanitizer:
93 """ Create a place sanitizer from the configured rules.
95 return PlaceSanitizer(self.sanitizer_rules, self.config)
98 def make_token_analysis(self) -> ICUTokenAnalysis:
99 """ Create a token analyser from the reviouly loaded rules.
101 return ICUTokenAnalysis(self.normalization_rules,
102 self.transliteration_rules, self.analysis)
105 def get_search_rules(self) -> str:
106 """ Return the ICU rules to be used during search.
107 The rules combine normalization and transliteration.
109 # First apply the normalization rules.
110 rules = io.StringIO()
111 rules.write(self.normalization_rules)
113 # Then add transliteration.
114 rules.write(self.transliteration_rules)
115 return rules.getvalue()
118 def get_normalization_rules(self) -> str:
119 """ Return rules for normalisation of a term.
121 return self.normalization_rules
124 def get_transliteration_rules(self) -> str:
125 """ Return the rules for converting a string into its asciii representation.
127 return self.transliteration_rules
130 def _setup_analysis(self) -> None:
131 """ Process the rules used for creating the various token analyzers.
133 self.analysis: Dict[Optional[str], TokenAnalyzerRule] = {}
135 if not isinstance(self.analysis_rules, list):
136 raise UsageError("Configuration section 'token-analysis' must be a list.")
138 for section in self.analysis_rules:
139 name = section.get('id', None)
140 if name in self.analysis:
142 LOG.fatal("ICU tokenizer configuration has two default token analyzers.")
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,
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.
160 content = _get_section(rules, section)
165 return ';'.join(flatten_config_list(content, section)) + ';'
168 class TokenAnalyzerRule:
169 """ Factory for a single analysis module. The class saves the configuration
170 and creates a new token analyzer on request.
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")
179 self._analysis_mod: AnalysisModule = \
180 config.load_plugin_module(analyzer_name, 'nominatim.tokenizer.token_analysis')
182 self.config = self._analysis_mod.configure(rules, normalization_rules)
185 def create(self, normalizer: Any, transliterator: Any) -> Analyser:
186 """ Create a new analyser instance for the given rule.
188 return self._analysis_mod.create(normalizer, transliterator, self.config)