1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Generic processor for names that creates abbreviation variants.
14 from nominatim.errors import UsageError
15 from nominatim.tokenizer.token_analysis.config_variants import get_variant_config
16 from nominatim.tokenizer.token_analysis.generic_mutation import MutationVariantGenerator
18 ### Configuration section
20 def configure(rules, normalization_rules):
21 """ Extract and preprocess the configuration for this module.
25 config['replacements'], config['chars'] = get_variant_config(rules.get('variants'),
27 config['variant_only'] = rules.get('mode', '') == 'variant-only'
29 # parse mutation rules
30 config['mutations'] = []
31 for rule in rules.get('mutations', []):
32 if 'pattern' not in rule:
33 raise UsageError("Missing field 'pattern' in mutation configuration.")
34 if not isinstance(rule['pattern'], str):
35 raise UsageError("Field 'pattern' in mutation configuration "
36 "must be a simple text field.")
37 if 'replacements' not in rule:
38 raise UsageError("Missing field 'replacements' in mutation configuration.")
39 if not isinstance(rule['replacements'], list):
40 raise UsageError("Field 'replacements' in mutation configuration "
41 "must be a list of texts.")
43 config['mutations'].append((rule['pattern'], rule['replacements']))
50 def create(normalizer, transliterator, config):
51 """ Create a new token analysis instance for this module.
53 return GenericTokenAnalysis(normalizer, transliterator, config)
56 class GenericTokenAnalysis:
57 """ Collects the different transformation rules for normalisation of names
58 and provides the functions to apply the transformations.
61 def __init__(self, norm, to_ascii, config):
63 self.to_ascii = to_ascii
64 self.variant_only = config['variant_only']
67 if config['replacements']:
68 self.replacements = datrie.Trie(config['chars'])
69 for src, repllist in config['replacements']:
70 self.replacements[src] = repllist
72 self.replacements = None
74 # set up mutation rules
75 self.mutations = [MutationVariantGenerator(*cfg) for cfg in config['mutations']]
78 def normalize(self, name):
79 """ Return the normalized form of the name. This is the standard form
80 from which possible variants for the name can be derived.
82 return self.norm.transliterate(name).strip()
85 def get_variants_ascii(self, norm_name):
86 """ Compute the spelling variants for the given normalized name
87 and transliterate the result.
89 variants = self._generate_word_variants(norm_name)
91 for mutation in self.mutations:
92 variants = mutation.generate(variants)
94 return [name for name in self._transliterate_unique_list(norm_name, variants) if name]
97 def _transliterate_unique_list(self, norm_name, iterable):
102 for variant in map(str.strip, iterable):
103 if variant not in seen:
105 yield self.to_ascii.transliterate(variant).strip()
108 def _generate_word_variants(self, norm_name):
109 baseform = '^ ' + norm_name + ' ^'
110 baselen = len(baseform)
114 if self.replacements is not None:
118 full, repl = self.replacements.longest_prefix_item(baseform[pos:],
121 done = baseform[startpos:pos]
122 partials = [v + done + r
123 for v, r in itertools.product(partials, repl)
124 if not force_space or r.startswith(' ')]
125 if len(partials) > 128:
126 # If too many variants are produced, they are unlikely
127 # to be helpful. Only use the original term.
130 startpos = pos + len(full)
139 # No variants detected? Fast return.
143 if startpos < baselen:
144 return (part[1:] + baseform[startpos:-1] for part in partials)
146 return (part[1:-1] for part in partials)