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'
28 config['mutations'] = rules.get('mutations', [])
35 def create(transliterator, config):
36 """ Create a new token analysis instance for this module.
38 return GenericTokenAnalysis(transliterator, config)
41 class GenericTokenAnalysis:
42 """ Collects the different transformation rules for normalisation of names
43 and provides the functions to apply the transformations.
46 def __init__(self, to_ascii, config):
47 self.to_ascii = to_ascii
48 self.variant_only = config['variant_only']
51 if config['replacements']:
52 self.replacements = datrie.Trie(config['chars'])
53 for src, repllist in config['replacements']:
54 self.replacements[src] = repllist
56 self.replacements = None
58 # set up mutation rules
60 for cfg in config['mutations']:
61 if 'pattern' not in cfg:
62 raise UsageError("Missing field 'pattern' in mutation configuration.")
63 if not isinstance(cfg['pattern'], str):
64 raise UsageError("Field 'pattern' in mutation configuration "
65 "must be a simple text field.")
66 if 'replacements' not in cfg:
67 raise UsageError("Missing field 'replacements' in mutation configuration.")
68 if not isinstance(cfg['replacements'], list):
69 raise UsageError("Field 'replacements' in mutation configuration "
70 "must be a list of texts.")
72 self.mutations.append(MutationVariantGenerator(cfg['pattern'],
76 def get_variants_ascii(self, norm_name):
77 """ Compute the spelling variants for the given normalized name
78 and transliterate the result.
80 variants = self._generate_word_variants(norm_name)
82 for mutation in self.mutations:
83 variants = mutation.generate(variants)
85 return [name for name in self._transliterate_unique_list(norm_name, variants) if name]
88 def _transliterate_unique_list(self, norm_name, iterable):
93 for variant in map(str.strip, iterable):
94 if variant not in seen:
96 yield self.to_ascii.transliterate(variant).strip()
99 def _generate_word_variants(self, norm_name):
100 baseform = '^ ' + norm_name + ' ^'
101 baselen = len(baseform)
105 if self.replacements is not None:
109 full, repl = self.replacements.longest_prefix_item(baseform[pos:],
112 done = baseform[startpos:pos]
113 partials = [v + done + r
114 for v, r in itertools.product(partials, repl)
115 if not force_space or r.startswith(' ')]
116 if len(partials) > 128:
117 # If too many variants are produced, they are unlikely
118 # to be helpful. Only use the original term.
121 startpos = pos + len(full)
130 # No variants detected? Fast return.
134 if startpos < baselen:
135 return (part[1:] + baseform[startpos:-1] for part in partials)
137 return (part[1:-1] for part in partials)