1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2024 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 icu import Transliterator
17 from nominatim_core.config import flatten_config_list, Configuration
18 from nominatim_core.db.properties import set_property, get_property
19 from nominatim_core.db.connection import Connection
20 from nominatim_core.errors import UsageError
21 from .place_sanitizer import PlaceSanitizer
22 from .icu_token_analysis import ICUTokenAnalysis
23 from .token_analysis.base import AnalysisModule, Analyzer
24 from ..data import country_info
26 LOG = logging.getLogger()
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"
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.
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.")
45 """ Compiler for ICU rules from a tokenizer configuration file.
48 def __init__(self, config: Configuration) -> None:
50 rules = config.load_sub_configuration('icu_tokenizer.yaml',
51 config='TOKENIZER_CONFIG')
53 # Make sure country information is available to analyzers and sanitizers.
54 country_info.setup_country_config(config)
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()
61 # Load optional sanitizer rule set.
62 self.sanitizer_rules = rules.get('sanitizers', [])
65 def load_config_from_db(self, conn: Connection) -> None:
66 """ Get previously saved parts of the configuration from the
69 rules = get_property(conn, DBCFG_IMPORT_NORM_RULES)
71 self.normalization_rules = rules
73 rules = get_property(conn, DBCFG_IMPORT_TRANS_RULES)
75 self.transliteration_rules = rules
77 rules = get_property(conn, DBCFG_IMPORT_ANALYSIS_RULES)
79 self.analysis_rules = json.loads(rules)
81 self.analysis_rules = []
82 self._setup_analysis()
85 def save_config_to_db(self, conn: Connection) -> None:
86 """ Save the part of the configuration that cannot be changed into
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))
94 def make_sanitizer(self) -> PlaceSanitizer:
95 """ Create a place sanitizer from the configured rules.
97 return PlaceSanitizer(self.sanitizer_rules, self.config)
100 def make_token_analysis(self) -> ICUTokenAnalysis:
101 """ Create a token analyser from the reviouly loaded rules.
103 return ICUTokenAnalysis(self.normalization_rules,
104 self.transliteration_rules, self.analysis)
107 def get_search_rules(self) -> str:
108 """ Return the ICU rules to be used during search.
109 The rules combine normalization and transliteration.
111 # First apply the normalization rules.
112 rules = io.StringIO()
113 rules.write(self.normalization_rules)
115 # Then add transliteration.
116 rules.write(self.transliteration_rules)
117 return rules.getvalue()
120 def get_normalization_rules(self) -> str:
121 """ Return rules for normalisation of a term.
123 return self.normalization_rules
126 def get_transliteration_rules(self) -> str:
127 """ Return the rules for converting a string into its asciii representation.
129 return self.transliteration_rules
132 def _setup_analysis(self) -> None:
133 """ Process the rules used for creating the various token analyzers.
135 self.analysis: Dict[Optional[str], TokenAnalyzerRule] = {}
137 if not isinstance(self.analysis_rules, list):
138 raise UsageError("Configuration section 'token-analysis' must be a list.")
140 norm = Transliterator.createFromRules("rule_loader_normalization",
141 self.normalization_rules)
142 trans = Transliterator.createFromRules("rule_loader_transliteration",
143 self.transliteration_rules)
145 for section in self.analysis_rules:
146 name = section.get('id', None)
147 if name in self.analysis:
149 LOG.fatal("ICU tokenizer configuration has two default token analyzers.")
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,
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.
166 content = _get_section(rules, section)
171 return ';'.join(flatten_config_list(content, section)) + ';'
174 class TokenAnalyzerRule:
175 """ Factory for a single analysis module. The class saves the configuration
176 and creates a new token analyzer on request.
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")
186 self._analysis_mod: AnalysisModule = \
187 config.load_plugin_module(analyzer_name, 'nominatim_db.tokenizer.token_analysis')
189 self.config = self._analysis_mod.configure(rules, normalizer,
193 def create(self, normalizer: Any, transliterator: Any) -> Analyzer:
194 """ Create a new analyser instance for the given rule.
196 return self._analysis_mod.create(normalizer, transliterator, self.config)