]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/token_analysis/generic.py
c904d87d4eb18e15143b12935891955930dd5113
[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(trans_rules, config):
135     """ Create a new token analysis instance for this module.
136     """
137     return GenericTokenAnalysis(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, to_ascii, config):
146         self.to_ascii = to_ascii
147
148         # Set up datrie
149         self.replacements = datrie.Trie(config['chars'])
150         for src, repllist in config['replacements']:
151             self.replacements[src] = repllist
152
153
154     def get_variants_ascii(self, norm_name):
155         """ Compute the spelling variants for the given normalized name
156             and transliterate the result.
157         """
158         baseform = '^ ' + norm_name + ' ^'
159         partials = ['']
160
161         startpos = 0
162         pos = 0
163         force_space = False
164         while pos < len(baseform):
165             full, repl = self.replacements.longest_prefix_item(baseform[pos:],
166                                                                (None, None))
167             if full is not None:
168                 done = baseform[startpos:pos]
169                 partials = [v + done + r
170                             for v, r in itertools.product(partials, repl)
171                             if not force_space or r.startswith(' ')]
172                 if len(partials) > 128:
173                     # If too many variants are produced, they are unlikely
174                     # to be helpful. Only use the original term.
175                     startpos = 0
176                     break
177                 startpos = pos + len(full)
178                 if full[-1] == ' ':
179                     startpos -= 1
180                     force_space = True
181                 pos = startpos
182             else:
183                 pos += 1
184                 force_space = False
185
186         # No variants detected? Fast return.
187         if startpos == 0:
188             trans_name = self.to_ascii.transliterate(norm_name).strip()
189             return [trans_name] if trans_name else []
190
191         return self._compute_result_set(partials, baseform[startpos:])
192
193
194     def _compute_result_set(self, partials, prefix):
195         results = set()
196
197         for variant in partials:
198             vname = variant + prefix
199             trans_name = self.to_ascii.transliterate(vname[1:-1]).strip()
200             if trans_name:
201                 results.add(trans_name)
202
203         return list(results)