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 ..config import flatten_config_list, Configuration
18 from ..db.properties import set_property, get_property
19 from ..db.connection import Connection
20 from ..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', [])
64 def load_config_from_db(self, conn: Connection) -> None:
65 """ Get previously saved parts of the configuration from the
68 rules = get_property(conn, DBCFG_IMPORT_NORM_RULES)
70 self.normalization_rules = rules
72 rules = get_property(conn, DBCFG_IMPORT_TRANS_RULES)
74 self.transliteration_rules = rules
76 rules = get_property(conn, DBCFG_IMPORT_ANALYSIS_RULES)
78 self.analysis_rules = json.loads(rules)
80 self.analysis_rules = []
81 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))
91 def make_sanitizer(self) -> PlaceSanitizer:
92 """ Create a place sanitizer from the configured rules.
94 return PlaceSanitizer(self.sanitizer_rules, self.config)
96 def make_token_analysis(self) -> ICUTokenAnalysis:
97 """ Create a token analyser from the reviouly loaded rules.
99 return ICUTokenAnalysis(self.normalization_rules,
100 self.transliteration_rules, self.analysis)
102 def get_search_rules(self) -> str:
103 """ Return the ICU rules to be used during search.
104 The rules combine normalization and transliteration.
106 # First apply the normalization rules.
107 rules = io.StringIO()
108 rules.write(self.normalization_rules)
110 # Then add transliteration.
111 rules.write(self.transliteration_rules)
112 return rules.getvalue()
114 def get_normalization_rules(self) -> str:
115 """ Return rules for normalisation of a term.
117 return self.normalization_rules
119 def get_transliteration_rules(self) -> str:
120 """ Return the rules for converting a string into its asciii representation.
122 return self.transliteration_rules
124 def _setup_analysis(self) -> None:
125 """ Process the rules used for creating the various token analyzers.
127 self.analysis: Dict[Optional[str], TokenAnalyzerRule] = {}
129 if not isinstance(self.analysis_rules, list):
130 raise UsageError("Configuration section 'token-analysis' must be a list.")
132 norm = Transliterator.createFromRules("rule_loader_normalization",
133 self.normalization_rules)
134 trans = Transliterator.createFromRules("rule_loader_transliteration",
135 self.transliteration_rules)
137 for section in self.analysis_rules:
138 name = section.get('id', None)
139 if name in self.analysis:
141 LOG.fatal("ICU tokenizer configuration has two default token analyzers.")
143 LOG.fatal("ICU tokenizer configuration has two token "
144 "analyzers with id '%s'.", name)
145 raise UsageError("Syntax error in ICU tokenizer config.")
146 self.analysis[name] = TokenAnalyzerRule(section, norm, trans,
150 def _cfg_to_icu_rules(rules: Mapping[str, Any], section: str) -> str:
151 """ Load an ICU ruleset from the given section. If the section is a
152 simple string, it is interpreted as a file name and the rules are
153 loaded verbatim from the given file. The filename is expected to be
154 relative to the tokenizer rule file. If the section is a list then
155 each line is assumed to be a rule. All rules are concatenated and returned.
157 content = _get_section(rules, section)
162 return ';'.join(flatten_config_list(content, section)) + ';'
165 class TokenAnalyzerRule:
166 """ Factory for a single analysis module. The class saves the configuration
167 and creates a new token analyzer on request.
170 def __init__(self, rules: Mapping[str, Any],
171 normalizer: Any, transliterator: Any,
172 config: Configuration) -> None:
173 analyzer_name = _get_section(rules, 'analyzer')
174 if not analyzer_name or not isinstance(analyzer_name, str):
175 raise UsageError("'analyzer' parameter needs to be simple string")
177 self._analysis_mod: AnalysisModule = \
178 config.load_plugin_module(analyzer_name, 'nominatim_db.tokenizer.token_analysis')
180 self.config = self._analysis_mod.configure(rules, normalizer,
183 def create(self, normalizer: Any, transliterator: Any) -> Analyzer:
184 """ Create a new analyser instance for the given rule.
186 return self._analysis_mod.create(normalizer, transliterator, self.config)