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.tokenizer.token_analysis.config_variants import get_variant_config
16 ### Configuration section
18 def configure(rules, normalization_rules):
19 """ Extract and preprocess the configuration for this module.
23 config['replacements'], config['chars'] = get_variant_config(rules.get('variants'),
25 config['variant_only'] = rules.get('mode', '') == 'variant-only'
32 def create(transliterator, config):
33 """ Create a new token analysis instance for this module.
35 return GenericTokenAnalysis(transliterator, config)
38 class GenericTokenAnalysis:
39 """ Collects the different transformation rules for normalisation of names
40 and provides the functions to apply the transformations.
43 def __init__(self, to_ascii, config):
44 self.to_ascii = to_ascii
45 self.variant_only = config['variant_only']
48 if config['replacements']:
49 self.replacements = datrie.Trie(config['chars'])
50 for src, repllist in config['replacements']:
51 self.replacements[src] = repllist
53 self.replacements = None
56 def get_variants_ascii(self, norm_name):
57 """ Compute the spelling variants for the given normalized name
58 and transliterate the result.
61 for variant in self._generate_word_variants(norm_name):
62 if not self.variant_only or variant.strip() != norm_name:
63 trans_name = self.to_ascii.transliterate(variant).strip()
65 results.add(trans_name)
70 def _generate_word_variants(self, norm_name):
71 baseform = '^ ' + norm_name + ' ^'
72 baselen = len(baseform)
76 if self.replacements is not None:
80 full, repl = self.replacements.longest_prefix_item(baseform[pos:],
83 done = baseform[startpos:pos]
84 partials = [v + done + r
85 for v, r in itertools.product(partials, repl)
86 if not force_space or r.startswith(' ')]
87 if len(partials) > 128:
88 # If too many variants are produced, they are unlikely
89 # to be helpful. Only use the original term.
92 startpos = pos + len(full)
101 # No variants detected? Fast return.
105 if startpos < baselen:
106 return (part[1:] + baseform[startpos:-1] for part in partials)
108 return (part[1:-1] for part in partials)