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