2 Helper class to create ICU rules from a configuration file.
10 from icu import Transliterator
12 from nominatim.config import flatten_config_list
13 from nominatim.db.properties import set_property, get_property
14 from nominatim.errors import UsageError
15 from nominatim.tokenizer.icu_name_processor import ICUNameProcessor
16 from nominatim.tokenizer.place_sanitizer import PlaceSanitizer
17 import nominatim.tokenizer.icu_variants as variants
19 LOG = logging.getLogger()
21 DBCFG_IMPORT_NORM_RULES = "tokenizer_import_normalisation"
22 DBCFG_IMPORT_TRANS_RULES = "tokenizer_import_transliteration"
23 DBCFG_IMPORT_ANALYSIS_RULES = "tokenizer_import_analysis_rules"
27 """ Saves a single variant expansion.
29 An expansion consists of the normalized replacement term and
30 a dicitonary of properties that describe when the expansion applies.
33 def __init__(self, replacement, properties):
34 self.replacement = replacement
35 self.properties = properties or {}
39 """ Compiler for ICU rules from a tokenizer configuration file.
42 def __init__(self, config):
43 rules = config.load_sub_configuration('icu_tokenizer.yaml',
44 config='TOKENIZER_CONFIG')
48 self.normalization_rules = self._cfg_to_icu_rules(rules, 'normalization')
49 self.transliteration_rules = self._cfg_to_icu_rules(rules, 'transliteration')
50 self.analysis_rules = self._get_section(rules, 'variants')
51 self._parse_variant_list()
53 # Load optional sanitizer rule set.
54 self.sanitizer_rules = rules.get('sanitizers', [])
57 def load_config_from_db(self, conn):
58 """ Get previously saved parts of the configuration from the
61 self.normalization_rules = get_property(conn, DBCFG_IMPORT_NORM_RULES)
62 self.transliteration_rules = get_property(conn, DBCFG_IMPORT_TRANS_RULES)
63 self.analysis_rules = json.loads(get_property(conn, DBCFG_IMPORT_ANALYSIS_RULES))
64 self._parse_variant_list()
67 def save_config_to_db(self, conn):
68 """ Save the part of the configuration that cannot be changed into
71 set_property(conn, DBCFG_IMPORT_NORM_RULES, self.normalization_rules)
72 set_property(conn, DBCFG_IMPORT_TRANS_RULES, self.transliteration_rules)
73 set_property(conn, DBCFG_IMPORT_ANALYSIS_RULES, json.dumps(self.analysis_rules))
76 def make_sanitizer(self):
77 """ Create a place sanitizer from the configured rules.
79 return PlaceSanitizer(self.sanitizer_rules)
82 def make_token_analysis(self):
83 """ Create a token analyser from the reviouly loaded rules.
85 return ICUNameProcessor(self.normalization_rules,
86 self.transliteration_rules,
90 def get_search_rules(self):
91 """ Return the ICU rules to be used during search.
92 The rules combine normalization and transliteration.
94 # First apply the normalization rules.
96 rules.write(self.normalization_rules)
98 # Then add transliteration.
99 rules.write(self.transliteration_rules)
100 return rules.getvalue()
102 def get_normalization_rules(self):
103 """ Return rules for normalisation of a term.
105 return self.normalization_rules
107 def get_transliteration_rules(self):
108 """ Return the rules for converting a string into its asciii representation.
110 return self.transliteration_rules
112 def get_replacement_pairs(self):
113 """ Return the list of possible compound decompositions with
114 application of abbreviations included.
115 The result is a list of pairs: the first item is the sequence to
116 replace, the second is a list of replacements.
122 def _get_section(rules, section):
123 """ Get the section named 'section' from the rules. If the section does
124 not exist, raise a usage error with a meaningful message.
126 if section not in rules:
127 LOG.fatal("Section '%s' not found in tokenizer config.", section)
128 raise UsageError("Syntax error in tokenizer configuration file.")
130 return rules[section]
133 def _cfg_to_icu_rules(self, rules, section):
134 """ Load an ICU ruleset from the given section. If the section is a
135 simple string, it is interpreted as a file name and the rules are
136 loaded verbatim from the given file. The filename is expected to be
137 relative to the tokenizer rule file. If the section is a list then
138 each line is assumed to be a rule. All rules are concatenated and returned.
140 content = self._get_section(rules, section)
145 return ';'.join(flatten_config_list(content, section)) + ';'
148 def _parse_variant_list(self):
149 rules = self.analysis_rules
151 self.variants.clear()
156 rules = flatten_config_list(rules, 'variants')
158 vmaker = _VariantMaker(self.normalization_rules)
161 for section in rules:
162 # Create the property field and deduplicate against existing
164 props = variants.ICUVariantProperties.from_rules(section)
165 for existing in properties:
166 if existing == props:
170 properties.append(props)
172 for rule in (section.get('words') or []):
173 self.variants.update(vmaker.compute(rule, props))
177 """ Generater for all necessary ICUVariants from a single variant rule.
179 All text in rules is normalized to make sure the variants match later.
182 def __init__(self, norm_rules):
183 self.norm = Transliterator.createFromRules("rule_loader_normalization",
187 def compute(self, rule, props):
188 """ Generator for all ICUVariant tuples from a single variant rule.
190 parts = re.split(r'(\|)?([=-])>', rule)
192 raise UsageError("Syntax error in variant rule: " + rule)
194 decompose = parts[1] is None
195 src_terms = [self._parse_variant_word(t) for t in parts[0].split(',')]
196 repl_terms = (self.norm.transliterate(t.strip()) for t in parts[3].split(','))
198 # If the source should be kept, add a 1:1 replacement
200 for src in src_terms:
202 for froms, tos in _create_variants(*src, src[0], decompose):
203 yield variants.ICUVariant(froms, tos, props)
205 for src, repl in itertools.product(src_terms, repl_terms):
207 for froms, tos in _create_variants(*src, repl, decompose):
208 yield variants.ICUVariant(froms, tos, props)
211 def _parse_variant_word(self, name):
213 match = re.fullmatch(r'([~^]?)([^~$^]*)([~$]?)', name)
214 if match is None or (match.group(1) == '~' and match.group(3) == '~'):
215 raise UsageError("Invalid variant word descriptor '{}'".format(name))
216 norm_name = self.norm.transliterate(match.group(2))
220 return norm_name, match.group(1), match.group(3)
223 _FLAG_MATCH = {'^': '^ ',
228 def _create_variants(src, preflag, postflag, repl, decompose):
230 postfix = _FLAG_MATCH[postflag]
231 # suffix decomposition
233 repl = repl + postfix
236 yield ' ' + src, ' ' + repl
239 yield src, ' ' + repl
240 yield ' ' + src, repl
241 elif postflag == '~':
242 # prefix decomposition
243 prefix = _FLAG_MATCH[preflag]
248 yield src + ' ', repl + ' '
251 yield src, repl + ' '
252 yield src + ' ', repl
254 prefix = _FLAG_MATCH[preflag]
255 postfix = _FLAG_MATCH[postflag]
257 yield prefix + src + postfix, prefix + repl + postfix