]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/token_analysis/generic.py
f0de0cca4e28c5f8e2601086153704bc8637f269
[nominatim.git] / nominatim / tokenizer / token_analysis / generic.py
1 """
2 Generic processor for names that creates abbreviation variants.
3 """
4 from collections import defaultdict
5 import itertools
6 import re
7
8 from icu import Transliterator
9 import datrie
10
11 from nominatim.config import flatten_config_list
12 from nominatim.errors import UsageError
13 import nominatim.tokenizer.icu_variants as variants
14
15 ### Configuration section
16
17 def configure(rules, normalization_rules):
18     """ Extract and preprocess the configuration for this module.
19     """
20     return {'variants': _parse_variant_list(rules.get('variants'),
21                                             normalization_rules)}
22
23
24 def _parse_variant_list(rules, normalization_rules):
25     vset = set()
26
27     if rules:
28         rules = flatten_config_list(rules, 'variants')
29
30         vmaker = _VariantMaker(normalization_rules)
31
32         properties = []
33         for section in rules:
34             # Create the property field and deduplicate against existing
35             # instances.
36             props = variants.ICUVariantProperties.from_rules(section)
37             for existing in properties:
38                 if existing == props:
39                     props = existing
40                     break
41             else:
42                 properties.append(props)
43
44             for rule in (section.get('words') or []):
45                 vset.update(vmaker.compute(rule, props))
46
47     return vset
48
49
50 class _VariantMaker:
51     """ Generater for all necessary ICUVariants from a single variant rule.
52
53         All text in rules is normalized to make sure the variants match later.
54     """
55
56     def __init__(self, norm_rules):
57         self.norm = Transliterator.createFromRules("rule_loader_normalization",
58                                                    norm_rules)
59
60
61     def compute(self, rule, props):
62         """ Generator for all ICUVariant tuples from a single variant rule.
63         """
64         parts = re.split(r'(\|)?([=-])>', rule)
65         if len(parts) != 4:
66             raise UsageError("Syntax error in variant rule: " + rule)
67
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(','))
71
72         # If the source should be kept, add a 1:1 replacement
73         if parts[2] == '-':
74             for src in src_terms:
75                 if src:
76                     for froms, tos in _create_variants(*src, src[0], decompose):
77                         yield variants.ICUVariant(froms, tos, props)
78
79         for src, repl in itertools.product(src_terms, repl_terms):
80             if src and repl:
81                 for froms, tos in _create_variants(*src, repl, decompose):
82                     yield variants.ICUVariant(froms, tos, props)
83
84
85     def _parse_variant_word(self, name):
86         name = name.strip()
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))
91         if not norm_name:
92             return None
93
94         return norm_name, match.group(1), match.group(3)
95
96
97 _FLAG_MATCH = {'^': '^ ',
98                '$': ' ^',
99                '': ' '}
100
101
102 def _create_variants(src, preflag, postflag, repl, decompose):
103     if preflag == '~':
104         postfix = _FLAG_MATCH[postflag]
105         # suffix decomposition
106         src = src + postfix
107         repl = repl + postfix
108
109         yield src, repl
110         yield ' ' + src, ' ' + repl
111
112         if decompose:
113             yield src, ' ' + repl
114             yield ' ' + src, repl
115     elif postflag == '~':
116         # prefix decomposition
117         prefix = _FLAG_MATCH[preflag]
118         src = prefix + src
119         repl = prefix + repl
120
121         yield src, repl
122         yield src + ' ', repl + ' '
123
124         if decompose:
125             yield src, repl + ' '
126             yield src + ' ', repl
127     else:
128         prefix = _FLAG_MATCH[preflag]
129         postfix = _FLAG_MATCH[postflag]
130
131         yield prefix + src + postfix, prefix + repl + postfix
132
133
134 ### Analysis section
135
136 def create(norm_rules, trans_rules, config):
137     """ Create a new token analysis instance for this module.
138     """
139     return GenericTokenAnalysis(norm_rules, trans_rules, config['variants'])
140
141
142 class GenericTokenAnalysis:
143     """ Collects the different transformation rules for normalisation of names
144         and provides the functions to apply the transformations.
145     """
146
147     def __init__(self, norm_rules, trans_rules, replacements):
148         self.normalizer = Transliterator.createFromRules("icu_normalization",
149                                                          norm_rules)
150         self.to_ascii = Transliterator.createFromRules("icu_to_ascii",
151                                                        trans_rules +
152                                                        ";[:Space:]+ > ' '")
153         self.search = Transliterator.createFromRules("icu_search",
154                                                      norm_rules + trans_rules)
155
156         # Intermediate reorder by source. Also compute required character set.
157         immediate = defaultdict(list)
158         chars = set()
159         for variant in replacements:
160             if variant.source[-1] == ' ' and variant.replacement[-1] == ' ':
161                 replstr = variant.replacement[:-1]
162             else:
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
170
171
172     def get_normalized(self, name):
173         """ Normalize the given name, i.e. remove all elements not relevant
174             for search.
175         """
176         return self.normalizer.transliterate(name).strip()
177
178     def get_variants_ascii(self, norm_name):
179         """ Compute the spelling variants for the given normalized name
180             and transliterate the result.
181         """
182         baseform = '^ ' + norm_name + ' ^'
183         partials = ['']
184
185         startpos = 0
186         pos = 0
187         force_space = False
188         while pos < len(baseform):
189             full, repl = self.replacements.longest_prefix_item(baseform[pos:],
190                                                                (None, None))
191             if full is not None:
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.
199                     startpos = 0
200                     break
201                 startpos = pos + len(full)
202                 if full[-1] == ' ':
203                     startpos -= 1
204                     force_space = True
205                 pos = startpos
206             else:
207                 pos += 1
208                 force_space = False
209
210         # No variants detected? Fast return.
211         if startpos == 0:
212             trans_name = self.to_ascii.transliterate(norm_name).strip()
213             return [trans_name] if trans_name else []
214
215         return self._compute_result_set(partials, baseform[startpos:])
216
217
218     def _compute_result_set(self, partials, prefix):
219         results = set()
220
221         for variant in partials:
222             vname = variant + prefix
223             trans_name = self.to_ascii.transliterate(vname[1:-1]).strip()
224             if trans_name:
225                 results.add(trans_name)
226
227         return list(results)
228
229
230     def get_search_normalized(self, name):
231         """ Return the normalized version of the name (including transliteration)
232             to be applied at search time.
233         """
234         return self.search.transliterate(' ' + name + ' ').strip()