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:
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)
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, self.normalization_rules)
151 def _cfg_to_icu_rules(rules: Mapping[str, Any], section: str) -> str:
152 """ Load an ICU ruleset from the given section. If the section is a
153 simple string, it is interpreted as a file name and the rules are
154 loaded verbatim from the given file. The filename is expected to be
155 relative to the tokenizer rule file. If the section is a list then
156 each line is assumed to be a rule. All rules are concatenated and returned.
158 content = _get_section(rules, section)
163 return ';'.join(flatten_config_list(content, section)) + ';'
166 class TokenAnalyzerRule:
167 """ Factory for a single analysis module. The class saves the configuration
168 and creates a new token analyzer on request.
171 def __init__(self, rules: Mapping[str, Any], normalization_rules: str) -> None:
172 # Find the analysis module
173 module_name = 'nominatim.tokenizer.token_analysis.' \
174 + _get_section(rules, 'analyzer').replace('-', '_')
175 self._analysis_mod: AnalysisModule = importlib.import_module(module_name)
177 # Load the configuration.
178 self.config = self._analysis_mod.configure(rules, normalization_rules)
180 def create(self, normalizer: Any, transliterator: Any) -> Analyser:
181 """ Create a new analyser instance for the given rule.
183 return self._analysis_mod.create(normalizer, transliterator, self.config)