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
16 from nominatim.config import flatten_config_list, Configuration
17 from nominatim.db.properties import set_property, get_property
18 from nominatim.db.connection import Connection
19 from nominatim.errors import UsageError
20 from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
21 from nominatim.tokenizer.icu_token_analysis import ICUTokenAnalysis
22 from nominatim.tokenizer.token_analysis.base import AnalysisModule, Analyser
23 import nominatim.data.country_info
25 LOG = logging.getLogger()
27 DBCFG_IMPORT_NORM_RULES = "tokenizer_import_normalisation"
28 DBCFG_IMPORT_TRANS_RULES = "tokenizer_import_transliteration"
29 DBCFG_IMPORT_ANALYSIS_RULES = "tokenizer_import_analysis_rules"
32 def _get_section(rules: Mapping[str, Any], section: str) -> Any:
33 """ Get the section named 'section' from the rules. If the section does
34 not exist, raise a usage error with a meaningful message.
36 if section not in rules:
37 LOG.fatal("Section '%s' not found in tokenizer config.", section)
38 raise UsageError("Syntax error in tokenizer configuration file.")
44 """ Compiler for ICU rules from a tokenizer configuration file.
47 def __init__(self, config: Configuration) -> None:
49 rules = config.load_sub_configuration('icu_tokenizer.yaml',
50 config='TOKENIZER_CONFIG')
52 # Make sure country information is available to analyzers and sanitizers.
53 nominatim.data.country_info.setup_country_config(config)
55 self.normalization_rules = self._cfg_to_icu_rules(rules, 'normalization')
56 self.transliteration_rules = self._cfg_to_icu_rules(rules, 'transliteration')
57 self.analysis_rules = _get_section(rules, 'token-analysis')
58 self._setup_analysis()
60 # Load optional sanitizer rule set.
61 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()
84 def save_config_to_db(self, conn: Connection) -> None:
85 """ Save the part of the configuration that cannot be changed into
88 set_property(conn, DBCFG_IMPORT_NORM_RULES, self.normalization_rules)
89 set_property(conn, DBCFG_IMPORT_TRANS_RULES, self.transliteration_rules)
90 set_property(conn, DBCFG_IMPORT_ANALYSIS_RULES, json.dumps(self.analysis_rules))
93 def make_sanitizer(self) -> PlaceSanitizer:
94 """ Create a place sanitizer from the configured rules.
96 return PlaceSanitizer(self.sanitizer_rules, self.config)
99 def make_token_analysis(self) -> ICUTokenAnalysis:
100 """ Create a token analyser from the reviouly loaded rules.
102 return ICUTokenAnalysis(self.normalization_rules,
103 self.transliteration_rules, self.analysis)
106 def get_search_rules(self) -> str:
107 """ Return the ICU rules to be used during search.
108 The rules combine normalization and transliteration.
110 # First apply the normalization rules.
111 rules = io.StringIO()
112 rules.write(self.normalization_rules)
114 # Then add transliteration.
115 rules.write(self.transliteration_rules)
116 return rules.getvalue()
119 def get_normalization_rules(self) -> str:
120 """ Return rules for normalisation of a term.
122 return self.normalization_rules
125 def get_transliteration_rules(self) -> str:
126 """ Return the rules for converting a string into its asciii representation.
128 return self.transliteration_rules
131 def _setup_analysis(self) -> None:
132 """ Process the rules used for creating the various token analyzers.
134 self.analysis: Dict[Optional[str], TokenAnalyzerRule] = {}
136 if not isinstance(self.analysis_rules, list):
137 raise UsageError("Configuration section 'token-analysis' must be a list.")
139 for section in self.analysis_rules:
140 name = section.get('id', None)
141 if name in self.analysis:
143 LOG.fatal("ICU tokenizer configuration has two default token analyzers.")
145 LOG.fatal("ICU tokenizer configuration has two token "
146 "analyzers with id '%s'.", name)
147 raise UsageError("Syntax error in ICU tokenizer config.")
148 self.analysis[name] = TokenAnalyzerRule(section, self.normalization_rules)
152 def _cfg_to_icu_rules(rules: Mapping[str, Any], section: str) -> str:
153 """ Load an ICU ruleset from the given section. If the section is a
154 simple string, it is interpreted as a file name and the rules are
155 loaded verbatim from the given file. The filename is expected to be
156 relative to the tokenizer rule file. If the section is a list then
157 each line is assumed to be a rule. All rules are concatenated and returned.
159 content = _get_section(rules, section)
164 return ';'.join(flatten_config_list(content, section)) + ';'
167 class TokenAnalyzerRule:
168 """ Factory for a single analysis module. The class saves the configuration
169 and creates a new token analyzer on request.
172 def __init__(self, rules: Mapping[str, Any], normalization_rules: str) -> None:
173 # Find the analysis module
174 module_name = 'nominatim.tokenizer.token_analysis.' \
175 + _get_section(rules, 'analyzer').replace('-', '_')
176 self._analysis_mod: AnalysisModule = importlib.import_module(module_name)
178 # Load the configuration.
179 self.config = self._analysis_mod.configure(rules, normalization_rules)
181 def create(self, normalizer: Any, transliterator: Any) -> Analyser:
182 """ Create a new analyser instance for the given rule.
184 return self._analysis_mod.create(normalizer, transliterator, self.config)