2 Helper class to create ICU rules from a configuration file.
10 from icu import Transliterator
12 from nominatim.db.properties import set_property, get_property
13 from nominatim.errors import UsageError
14 from nominatim.tokenizer.icu_name_processor import ICUNameProcessor
15 import nominatim.tokenizer.icu_variants as variants
17 LOG = logging.getLogger()
19 DBCFG_IMPORT_NORM_RULES = "tokenizer_import_normalisation"
20 DBCFG_IMPORT_TRANS_RULES = "tokenizer_import_transliteration"
21 DBCFG_IMPORT_ANALYSIS_RULES = "tokenizer_import_analysis_rules"
24 def _flatten_config_list(content):
28 if not isinstance(content, list):
29 raise UsageError("List expected in ICU configuration.")
33 if isinstance(ele, list):
34 output.extend(_flatten_config_list(ele))
42 """ Saves a single variant expansion.
44 An expansion consists of the normalized replacement term and
45 a dicitonary of properties that describe when the expansion applies.
48 def __init__(self, replacement, properties):
49 self.replacement = replacement
50 self.properties = properties or {}
54 """ Compiler for ICU rules from a tokenizer configuration file.
57 def __init__(self, config):
58 rules = config.load_sub_configuration('icu_tokenizer.yaml',
59 config='TOKENIZER_CONFIG')
63 self.normalization_rules = self._cfg_to_icu_rules(rules, 'normalization')
64 self.transliteration_rules = self._cfg_to_icu_rules(rules, 'transliteration')
65 self.analysis_rules = self._get_section(rules, 'variants')
66 self._parse_variant_list()
69 def load_config_from_db(self, conn):
70 """ Get previously saved parts of the configuration from the
73 self.normalization_rules = get_property(conn, DBCFG_IMPORT_NORM_RULES)
74 self.transliteration_rules = get_property(conn, DBCFG_IMPORT_TRANS_RULES)
75 self.analysis_rules = json.loads(get_property(conn, DBCFG_IMPORT_ANALYSIS_RULES))
76 self._parse_variant_list()
79 def save_config_to_db(self, conn):
80 """ Save the part of the configuration that cannot be changed into
83 set_property(conn, DBCFG_IMPORT_NORM_RULES, self.normalization_rules)
84 set_property(conn, DBCFG_IMPORT_TRANS_RULES, self.transliteration_rules)
85 set_property(conn, DBCFG_IMPORT_ANALYSIS_RULES, json.dumps(self.analysis_rules))
88 def make_token_analysis(self):
89 """ Create a token analyser from the reviouly loaded rules.
91 return ICUNameProcessor(self.normalization_rules,
92 self.transliteration_rules,
96 def get_search_rules(self):
97 """ Return the ICU rules to be used during search.
98 The rules combine normalization and transliteration.
100 # First apply the normalization rules.
101 rules = io.StringIO()
102 rules.write(self.normalization_rules)
104 # Then add transliteration.
105 rules.write(self.transliteration_rules)
106 return rules.getvalue()
108 def get_normalization_rules(self):
109 """ Return rules for normalisation of a term.
111 return self.normalization_rules
113 def get_transliteration_rules(self):
114 """ Return the rules for converting a string into its asciii representation.
116 return self.transliteration_rules
118 def get_replacement_pairs(self):
119 """ Return the list of possible compound decompositions with
120 application of abbreviations included.
121 The result is a list of pairs: the first item is the sequence to
122 replace, the second is a list of replacements.
128 def _get_section(rules, section):
129 """ Get the section named 'section' from the rules. If the section does
130 not exist, raise a usage error with a meaningful message.
132 if section not in rules:
133 LOG.fatal("Section '%s' not found in tokenizer config.", section)
134 raise UsageError("Syntax error in tokenizer configuration file.")
136 return rules[section]
139 def _cfg_to_icu_rules(self, rules, section):
140 """ Load an ICU ruleset from the given section. If the section is a
141 simple string, it is interpreted as a file name and the rules are
142 loaded verbatim from the given file. The filename is expected to be
143 relative to the tokenizer rule file. If the section is a list then
144 each line is assumed to be a rule. All rules are concatenated and returned.
146 content = self._get_section(rules, section)
151 return ';'.join(_flatten_config_list(content)) + ';'
154 def _parse_variant_list(self):
155 rules = self.analysis_rules
157 self.variants.clear()
162 rules = _flatten_config_list(rules)
164 vmaker = _VariantMaker(self.normalization_rules)
167 for section in rules:
168 # Create the property field and deduplicate against existing
170 props = variants.ICUVariantProperties.from_rules(section)
171 for existing in properties:
172 if existing == props:
176 properties.append(props)
178 for rule in (section.get('words') or []):
179 self.variants.update(vmaker.compute(rule, props))
183 """ Generater for all necessary ICUVariants from a single variant rule.
185 All text in rules is normalized to make sure the variants match later.
188 def __init__(self, norm_rules):
189 self.norm = Transliterator.createFromRules("rule_loader_normalization",
193 def compute(self, rule, props):
194 """ Generator for all ICUVariant tuples from a single variant rule.
196 parts = re.split(r'(\|)?([=-])>', rule)
198 raise UsageError("Syntax error in variant rule: " + rule)
200 decompose = parts[1] is None
201 src_terms = [self._parse_variant_word(t) for t in parts[0].split(',')]
202 repl_terms = (self.norm.transliterate(t.strip()) for t in parts[3].split(','))
204 # If the source should be kept, add a 1:1 replacement
206 for src in src_terms:
208 for froms, tos in _create_variants(*src, src[0], decompose):
209 yield variants.ICUVariant(froms, tos, props)
211 for src, repl in itertools.product(src_terms, repl_terms):
213 for froms, tos in _create_variants(*src, repl, decompose):
214 yield variants.ICUVariant(froms, tos, props)
217 def _parse_variant_word(self, name):
219 match = re.fullmatch(r'([~^]?)([^~$^]*)([~$]?)', name)
220 if match is None or (match.group(1) == '~' and match.group(3) == '~'):
221 raise UsageError("Invalid variant word descriptor '{}'".format(name))
222 norm_name = self.norm.transliterate(match.group(2))
226 return norm_name, match.group(1), match.group(3)
229 _FLAG_MATCH = {'^': '^ ',
234 def _create_variants(src, preflag, postflag, repl, decompose):
236 postfix = _FLAG_MATCH[postflag]
237 # suffix decomposition
239 repl = repl + postfix
242 yield ' ' + src, ' ' + repl
245 yield src, ' ' + repl
246 yield ' ' + src, repl
247 elif postflag == '~':
248 # prefix decomposition
249 prefix = _FLAG_MATCH[preflag]
254 yield src + ' ', repl + ' '
257 yield src, repl + ' '
258 yield src + ' ', repl
260 prefix = _FLAG_MATCH[preflag]
261 postfix = _FLAG_MATCH[postflag]
263 yield prefix + src + postfix, prefix + repl + postfix