2 Generic processor for names that creates abbreviation variants.
 
   4 from collections import defaultdict, namedtuple
 
   8 from icu import Transliterator
 
  11 from nominatim.config import flatten_config_list
 
  12 from nominatim.errors import UsageError
 
  14 ### Configuration section
 
  16 ICUVariant = namedtuple('ICUVariant', ['source', 'replacement'])
 
  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'
 
  30 def _get_variant_config(rules, normalization_rules):
 
  31     """ Convert the variant definition from the configuration into
 
  34     immediate = defaultdict(list)
 
  39         rules = flatten_config_list(rules, 'variants')
 
  41         vmaker = _VariantMaker(normalization_rules)
 
  44             for rule in (section.get('words') or []):
 
  45                 vset.update(vmaker.compute(rule))
 
  47         # Intermediate reorder by source. Also compute required character set.
 
  49             if variant.source[-1] == ' ' and variant.replacement[-1] == ' ':
 
  50                 replstr = variant.replacement[:-1]
 
  52                 replstr = variant.replacement
 
  53             immediate[variant.source].append(replstr)
 
  54             chars.update(variant.source)
 
  56     return list(immediate.items()), ''.join(chars)
 
  60     """ Generater for all necessary ICUVariants from a single variant rule.
 
  62         All text in rules is normalized to make sure the variants match later.
 
  65     def __init__(self, norm_rules):
 
  66         self.norm = Transliterator.createFromRules("rule_loader_normalization",
 
  70     def compute(self, rule):
 
  71         """ Generator for all ICUVariant tuples from a single variant rule.
 
  73         parts = re.split(r'(\|)?([=-])>', rule)
 
  75             raise UsageError("Syntax error in variant rule: " + rule)
 
  77         decompose = parts[1] is None
 
  78         src_terms = [self._parse_variant_word(t) for t in parts[0].split(',')]
 
  79         repl_terms = (self.norm.transliterate(t).strip() for t in parts[3].split(','))
 
  81         # If the source should be kept, add a 1:1 replacement
 
  85                     for froms, tos in _create_variants(*src, src[0], decompose):
 
  86                         yield ICUVariant(froms, tos)
 
  88         for src, repl in itertools.product(src_terms, repl_terms):
 
  90                 for froms, tos in _create_variants(*src, repl, decompose):
 
  91                     yield ICUVariant(froms, tos)
 
  94     def _parse_variant_word(self, name):
 
  96         match = re.fullmatch(r'([~^]?)([^~$^]*)([~$]?)', name)
 
  97         if match is None or (match.group(1) == '~' and match.group(3) == '~'):
 
  98             raise UsageError("Invalid variant word descriptor '{}'".format(name))
 
  99         norm_name = self.norm.transliterate(match.group(2)).strip()
 
 103         return norm_name, match.group(1), match.group(3)
 
 106 _FLAG_MATCH = {'^': '^ ',
 
 111 def _create_variants(src, preflag, postflag, repl, decompose):
 
 113         postfix = _FLAG_MATCH[postflag]
 
 114         # suffix decomposition
 
 116         repl = repl + postfix
 
 119         yield ' ' + src, ' ' + repl
 
 122             yield src, ' ' + repl
 
 123             yield ' ' + src, repl
 
 124     elif postflag == '~':
 
 125         # prefix decomposition
 
 126         prefix = _FLAG_MATCH[preflag]
 
 131         yield src + ' ', repl + ' '
 
 134             yield src, repl + ' '
 
 135             yield src + ' ', repl
 
 137         prefix = _FLAG_MATCH[preflag]
 
 138         postfix = _FLAG_MATCH[postflag]
 
 140         yield prefix + src + postfix, prefix + repl + postfix
 
 145 def create(transliterator, config):
 
 146     """ Create a new token analysis instance for this module.
 
 148     return GenericTokenAnalysis(transliterator, config)
 
 151 class GenericTokenAnalysis:
 
 152     """ Collects the different transformation rules for normalisation of names
 
 153         and provides the functions to apply the transformations.
 
 156     def __init__(self, to_ascii, config):
 
 157         self.to_ascii = to_ascii
 
 158         self.variant_only = config['variant_only']
 
 161         if config['replacements']:
 
 162             self.replacements = datrie.Trie(config['chars'])
 
 163             for src, repllist in config['replacements']:
 
 164                 self.replacements[src] = repllist
 
 166             self.replacements = None
 
 169     def get_variants_ascii(self, norm_name):
 
 170         """ Compute the spelling variants for the given normalized name
 
 171             and transliterate the result.
 
 173         baseform = '^ ' + norm_name + ' ^'
 
 177         if self.replacements is not None:
 
 180             while pos < len(baseform):
 
 181                 full, repl = self.replacements.longest_prefix_item(baseform[pos:],
 
 184                     done = baseform[startpos:pos]
 
 185                     partials = [v + done + r
 
 186                                 for v, r in itertools.product(partials, repl)
 
 187                                 if not force_space or r.startswith(' ')]
 
 188                     if len(partials) > 128:
 
 189                         # If too many variants are produced, they are unlikely
 
 190                         # to be helpful. Only use the original term.
 
 193                     startpos = pos + len(full)
 
 202         # No variants detected? Fast return.
 
 204             if self.variant_only:
 
 207             trans_name = self.to_ascii.transliterate(norm_name).strip()
 
 208             return [trans_name] if trans_name else []
 
 210         return self._compute_result_set(partials, baseform[startpos:],
 
 211                                         norm_name if self.variant_only else '')
 
 214     def _compute_result_set(self, partials, prefix, exclude):
 
 217         for variant in partials:
 
 218             vname = (variant + prefix)[1:-1].strip()
 
 220                 trans_name = self.to_ascii.transliterate(vname).strip()
 
 222                     results.add(trans_name)