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 rules = rules.get('variants')
21 immediate = defaultdict(list)
26 rules = flatten_config_list(rules, 'variants')
28 vmaker = _VariantMaker(normalization_rules)
32 # Create the property field and deduplicate against existing
34 props = variants.ICUVariantProperties.from_rules(section)
35 for existing in properties:
40 properties.append(props)
42 for rule in (section.get('words') or []):
43 vset.update(vmaker.compute(rule, props))
45 # Intermediate reorder by source. Also compute required character set.
47 if variant.source[-1] == ' ' and variant.replacement[-1] == ' ':
48 replstr = variant.replacement[:-1]
50 replstr = variant.replacement
51 immediate[variant.source].append(replstr)
52 chars.update(variant.source)
54 return {'replacements': list(immediate.items()),
55 'chars': ''.join(chars)}
59 """ Generater for all necessary ICUVariants from a single variant rule.
61 All text in rules is normalized to make sure the variants match later.
64 def __init__(self, norm_rules):
65 self.norm = Transliterator.createFromRules("rule_loader_normalization",
69 def compute(self, rule, props):
70 """ Generator for all ICUVariant tuples from a single variant rule.
72 parts = re.split(r'(\|)?([=-])>', rule)
74 raise UsageError("Syntax error in variant rule: " + rule)
76 decompose = parts[1] is None
77 src_terms = [self._parse_variant_word(t) for t in parts[0].split(',')]
78 repl_terms = (self.norm.transliterate(t.strip()) for t in parts[3].split(','))
80 # If the source should be kept, add a 1:1 replacement
84 for froms, tos in _create_variants(*src, src[0], decompose):
85 yield variants.ICUVariant(froms, tos, props)
87 for src, repl in itertools.product(src_terms, repl_terms):
89 for froms, tos in _create_variants(*src, repl, decompose):
90 yield variants.ICUVariant(froms, tos, props)
93 def _parse_variant_word(self, name):
95 match = re.fullmatch(r'([~^]?)([^~$^]*)([~$]?)', name)
96 if match is None or (match.group(1) == '~' and match.group(3) == '~'):
97 raise UsageError("Invalid variant word descriptor '{}'".format(name))
98 norm_name = self.norm.transliterate(match.group(2))
102 return norm_name, match.group(1), match.group(3)
105 _FLAG_MATCH = {'^': '^ ',
110 def _create_variants(src, preflag, postflag, repl, decompose):
112 postfix = _FLAG_MATCH[postflag]
113 # suffix decomposition
115 repl = repl + postfix
118 yield ' ' + src, ' ' + repl
121 yield src, ' ' + repl
122 yield ' ' + src, repl
123 elif postflag == '~':
124 # prefix decomposition
125 prefix = _FLAG_MATCH[preflag]
130 yield src + ' ', repl + ' '
133 yield src, repl + ' '
134 yield src + ' ', repl
136 prefix = _FLAG_MATCH[preflag]
137 postfix = _FLAG_MATCH[postflag]
139 yield prefix + src + postfix, prefix + repl + postfix
144 def create(norm_rules, trans_rules, config):
145 """ Create a new token analysis instance for this module.
147 return GenericTokenAnalysis(norm_rules, trans_rules, config)
150 class GenericTokenAnalysis:
151 """ Collects the different transformation rules for normalisation of names
152 and provides the functions to apply the transformations.
155 def __init__(self, norm_rules, trans_rules, config):
156 self.normalizer = Transliterator.createFromRules("icu_normalization",
158 self.to_ascii = Transliterator.createFromRules("icu_to_ascii",
161 self.search = Transliterator.createFromRules("icu_search",
162 norm_rules + trans_rules)
165 self.replacements = datrie.Trie(config['chars'])
166 for src, repllist in config['replacements']:
167 self.replacements[src] = repllist
170 def get_normalized(self, name):
171 """ Normalize the given name, i.e. remove all elements not relevant
174 return self.normalizer.transliterate(name).strip()
176 def get_variants_ascii(self, norm_name):
177 """ Compute the spelling variants for the given normalized name
178 and transliterate the result.
180 baseform = '^ ' + norm_name + ' ^'
186 while pos < len(baseform):
187 full, repl = self.replacements.longest_prefix_item(baseform[pos:],
190 done = baseform[startpos:pos]
191 partials = [v + done + r
192 for v, r in itertools.product(partials, repl)
193 if not force_space or r.startswith(' ')]
194 if len(partials) > 128:
195 # If too many variants are produced, they are unlikely
196 # to be helpful. Only use the original term.
199 startpos = pos + len(full)
208 # No variants detected? Fast return.
210 trans_name = self.to_ascii.transliterate(norm_name).strip()
211 return [trans_name] if trans_name else []
213 return self._compute_result_set(partials, baseform[startpos:])
216 def _compute_result_set(self, partials, prefix):
219 for variant in partials:
220 vname = variant + prefix
221 trans_name = self.to_ascii.transliterate(vname[1:-1]).strip()
223 results.add(trans_name)
228 def get_search_normalized(self, name):
229 """ Return the normalized version of the name (including transliteration)
230 to be applied at search time.
232 return self.search.transliterate(' ' + name + ' ').strip()