]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/token_analysis/config_variants.py
harmonize interface of token analysis module
[nominatim.git] / nominatim / tokenizer / token_analysis / config_variants.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Parser for configuration for variants.
9 """
10 from typing import Any, Iterator, Tuple, List, Optional, Set, NamedTuple
11 from collections import defaultdict
12 import itertools
13 import re
14
15 from nominatim.config import flatten_config_list
16 from nominatim.errors import UsageError
17
18 class ICUVariant(NamedTuple):
19     """ A single replacement rule for variant creation.
20     """
21     source: str
22     replacement: str
23
24
25 def get_variant_config(in_rules: Any,
26                        normalizer: Any) -> Tuple[List[Tuple[str, List[str]]], str]:
27     """ Convert the variant definition from the configuration into
28         replacement sets.
29
30         Returns a tuple containing the replacement set and the list of characters
31         used in the replacements.
32     """
33     immediate = defaultdict(list)
34     chars: Set[str] = set()
35
36     if in_rules:
37         vset: Set[ICUVariant] = set()
38         rules = flatten_config_list(in_rules, 'variants')
39
40         vmaker = _VariantMaker(normalizer)
41
42         for section in rules:
43             for rule in (section.get('words') or []):
44                 vset.update(vmaker.compute(rule))
45
46         # Intermediate reorder by source. Also compute required character set.
47         for variant in vset:
48             if variant.source[-1] == ' ' and variant.replacement[-1] == ' ':
49                 replstr = variant.replacement[:-1]
50             else:
51                 replstr = variant.replacement
52             immediate[variant.source].append(replstr)
53             chars.update(variant.source)
54
55     return list(immediate.items()), ''.join(chars)
56
57
58 class _VariantMaker:
59     """ Generator for all necessary ICUVariants from a single variant rule.
60
61         All text in rules is normalized to make sure the variants match later.
62     """
63
64     def __init__(self, normalizer: Any) -> None:
65         self.norm = normalizer
66
67
68     def compute(self, rule: Any) -> Iterator[ICUVariant]:
69         """ Generator for all ICUVariant tuples from a single variant rule.
70         """
71         parts = re.split(r'(\|)?([=-])>', rule)
72         if len(parts) != 4:
73             raise UsageError(f"Syntax error in variant rule: {rule}")
74
75         decompose = parts[1] is None
76         src_terms = [self._parse_variant_word(t) for t in parts[0].split(',')]
77         repl_terms = (self.norm.transliterate(t).strip() for t in parts[3].split(','))
78
79         # If the source should be kept, add a 1:1 replacement
80         if parts[2] == '-':
81             for src in src_terms:
82                 if src:
83                     for froms, tos in _create_variants(*src, src[0], decompose):
84                         yield ICUVariant(froms, tos)
85
86         for src, repl in itertools.product(src_terms, repl_terms):
87             if src and repl:
88                 for froms, tos in _create_variants(*src, repl, decompose):
89                     yield ICUVariant(froms, tos)
90
91
92     def _parse_variant_word(self, name: str) -> Optional[Tuple[str, str, str]]:
93         name = name.strip()
94         match = re.fullmatch(r'([~^]?)([^~$^]*)([~$]?)', name)
95         if match is None or (match.group(1) == '~' and match.group(3) == '~'):
96             raise UsageError(f"Invalid variant word descriptor '{name}'")
97         norm_name = self.norm.transliterate(match.group(2)).strip()
98         if not norm_name:
99             return None
100
101         return norm_name, match.group(1), match.group(3)
102
103
104 _FLAG_MATCH = {'^': '^ ',
105                '$': ' ^',
106                '': ' '}
107
108
109 def _create_variants(src: str, preflag: str, postflag: str,
110                      repl: str, decompose: bool) -> Iterator[Tuple[str, str]]:
111     if preflag == '~':
112         postfix = _FLAG_MATCH[postflag]
113         # suffix decomposition
114         src = src + postfix
115         repl = repl + postfix
116
117         yield src, repl
118         yield ' ' + src, ' ' + repl
119
120         if decompose:
121             yield src, ' ' + repl
122             yield ' ' + src, repl
123     elif postflag == '~':
124         # prefix decomposition
125         prefix = _FLAG_MATCH[preflag]
126         src = prefix + src
127         repl = prefix + repl
128
129         yield src, repl
130         yield src + ' ', repl + ' '
131
132         if decompose:
133             yield src, repl + ' '
134             yield src + ' ', repl
135     else:
136         prefix = _FLAG_MATCH[preflag]
137         postfix = _FLAG_MATCH[postflag]
138
139         yield prefix + src + postfix, prefix + repl + postfix