2 Generic processor for names that creates abbreviation variants.
4 from collections import defaultdict
8 from icu import Transliterator
11 from nominatim.config import flatten_config_list
12 from nominatim.errors import UsageError
13 import nominatim.tokenizer.icu_variants as variants
15 ### Configuration section
17 def configure(rules, normalization_rules):
18 """ Extract and preprocess the configuration for this module.
20 return {'variants': _parse_variant_list(rules.get('variants'),
24 def _parse_variant_list(rules, normalization_rules):
28 rules = flatten_config_list(rules, 'variants')
30 vmaker = _VariantMaker(normalization_rules)
34 # Create the property field and deduplicate against existing
36 props = variants.ICUVariantProperties.from_rules(section)
37 for existing in properties:
42 properties.append(props)
44 for rule in (section.get('words') or []):
45 vset.update(vmaker.compute(rule, props))
51 """ Generater for all necessary ICUVariants from a single variant rule.
53 All text in rules is normalized to make sure the variants match later.
56 def __init__(self, norm_rules):
57 self.norm = Transliterator.createFromRules("rule_loader_normalization",
61 def compute(self, rule, props):
62 """ Generator for all ICUVariant tuples from a single variant rule.
64 parts = re.split(r'(\|)?([=-])>', rule)
66 raise UsageError("Syntax error in variant rule: " + rule)
68 decompose = parts[1] is None
69 src_terms = [self._parse_variant_word(t) for t in parts[0].split(',')]
70 repl_terms = (self.norm.transliterate(t.strip()) for t in parts[3].split(','))
72 # If the source should be kept, add a 1:1 replacement
76 for froms, tos in _create_variants(*src, src[0], decompose):
77 yield variants.ICUVariant(froms, tos, props)
79 for src, repl in itertools.product(src_terms, repl_terms):
81 for froms, tos in _create_variants(*src, repl, decompose):
82 yield variants.ICUVariant(froms, tos, props)
85 def _parse_variant_word(self, name):
87 match = re.fullmatch(r'([~^]?)([^~$^]*)([~$]?)', name)
88 if match is None or (match.group(1) == '~' and match.group(3) == '~'):
89 raise UsageError("Invalid variant word descriptor '{}'".format(name))
90 norm_name = self.norm.transliterate(match.group(2))
94 return norm_name, match.group(1), match.group(3)
97 _FLAG_MATCH = {'^': '^ ',
102 def _create_variants(src, preflag, postflag, repl, decompose):
104 postfix = _FLAG_MATCH[postflag]
105 # suffix decomposition
107 repl = repl + postfix
110 yield ' ' + src, ' ' + repl
113 yield src, ' ' + repl
114 yield ' ' + src, repl
115 elif postflag == '~':
116 # prefix decomposition
117 prefix = _FLAG_MATCH[preflag]
122 yield src + ' ', repl + ' '
125 yield src, repl + ' '
126 yield src + ' ', repl
128 prefix = _FLAG_MATCH[preflag]
129 postfix = _FLAG_MATCH[postflag]
131 yield prefix + src + postfix, prefix + repl + postfix
136 def create(norm_rules, trans_rules, config):
137 """ Create a new token analysis instance for this module.
139 return GenericTokenAnalysis(norm_rules, trans_rules, config['variants'])
142 class GenericTokenAnalysis:
143 """ Collects the different transformation rules for normalisation of names
144 and provides the functions to apply the transformations.
147 def __init__(self, norm_rules, trans_rules, replacements):
148 self.normalizer = Transliterator.createFromRules("icu_normalization",
150 self.to_ascii = Transliterator.createFromRules("icu_to_ascii",
153 self.search = Transliterator.createFromRules("icu_search",
154 norm_rules + trans_rules)
156 # Intermediate reorder by source. Also compute required character set.
157 immediate = defaultdict(list)
159 for variant in replacements:
160 if variant.source[-1] == ' ' and variant.replacement[-1] == ' ':
161 replstr = variant.replacement[:-1]
163 replstr = variant.replacement
164 immediate[variant.source].append(replstr)
165 chars.update(variant.source)
166 # Then copy to datrie
167 self.replacements = datrie.Trie(''.join(chars))
168 for src, repllist in immediate.items():
169 self.replacements[src] = repllist
172 def get_normalized(self, name):
173 """ Normalize the given name, i.e. remove all elements not relevant
176 return self.normalizer.transliterate(name).strip()
178 def get_variants_ascii(self, norm_name):
179 """ Compute the spelling variants for the given normalized name
180 and transliterate the result.
182 baseform = '^ ' + norm_name + ' ^'
188 while pos < len(baseform):
189 full, repl = self.replacements.longest_prefix_item(baseform[pos:],
192 done = baseform[startpos:pos]
193 partials = [v + done + r
194 for v, r in itertools.product(partials, repl)
195 if not force_space or r.startswith(' ')]
196 if len(partials) > 128:
197 # If too many variants are produced, they are unlikely
198 # to be helpful. Only use the original term.
201 startpos = pos + len(full)
210 # No variants detected? Fast return.
212 trans_name = self.to_ascii.transliterate(norm_name).strip()
213 return [trans_name] if trans_name else []
215 return self._compute_result_set(partials, baseform[startpos:])
218 def _compute_result_set(self, partials, prefix):
221 for variant in partials:
222 vname = variant + prefix
223 trans_name = self.to_ascii.transliterate(vname[1:-1]).strip()
225 results.add(trans_name)
230 def get_search_normalized(self, name):
231 """ Return the normalized version of the name (including transliteration)
232 to be applied at search time.
234 return self.search.transliterate(' ' + name + ' ').strip()