1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2024 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Parser for configuration for variants.
10 from typing import Any, Iterator, Tuple, List, Optional, Set, NamedTuple
11 from collections import defaultdict
15 from ...config import flatten_config_list
16 from ...errors import UsageError
18 class ICUVariant(NamedTuple):
19 """ A single replacement rule for variant creation.
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
30 Returns a tuple containing the replacement set and the list of characters
31 used in the replacements.
33 immediate = defaultdict(list)
34 chars: Set[str] = set()
37 vset: Set[ICUVariant] = set()
38 rules = flatten_config_list(in_rules, 'variants')
40 vmaker = _VariantMaker(normalizer)
43 for rule in (section.get('words') or []):
44 vset.update(vmaker.compute(rule))
46 # Intermediate reorder by source. Also compute required character set.
48 if variant.source[-1] == ' ' and variant.replacement[-1] == ' ':
49 replstr = variant.replacement[:-1]
51 replstr = variant.replacement
52 immediate[variant.source].append(replstr)
53 chars.update(variant.source)
55 return list(immediate.items()), ''.join(chars)
59 """ Generator for all necessary ICUVariants from a single variant rule.
61 All text in rules is normalized to make sure the variants match later.
64 def __init__(self, normalizer: Any) -> None:
65 self.norm = normalizer
68 def compute(self, rule: Any) -> Iterator[ICUVariant]:
69 """ Generator for all ICUVariant tuples from a single variant rule.
71 parts = re.split(r'(\|)?([=-])>', rule)
73 raise UsageError(f"Syntax error in variant rule: {rule}")
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(','))
79 # If the source should be kept, add a 1:1 replacement
83 for froms, tos in _create_variants(*src, src[0], decompose):
84 yield ICUVariant(froms, tos)
86 for src, repl in itertools.product(src_terms, repl_terms):
88 for froms, tos in _create_variants(*src, repl, decompose):
89 yield ICUVariant(froms, tos)
92 def _parse_variant_word(self, name: str) -> Optional[Tuple[str, str, str]]:
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()
101 return norm_name, match.group(1), match.group(3)
104 _FLAG_MATCH = {'^': '^ ',
109 def _create_variants(src: str, preflag: str, postflag: str,
110 repl: str, decompose: bool) -> Iterator[Tuple[str, str]]:
112 postfix = _FLAG_MATCH[postflag]
113 # suffix decomposition
115 repl = repl + postfix
118 yield ' ' + src, ' ' + repl
121 yield src, ' ' + repl
122 yield ' ' + src, repl
123 elif postflag == '~':
124 # prefix decomposition
125 prefix = _FLAG_MATCH[preflag]
130 yield src + ' ', repl + ' '
133 yield src, repl + ' '
134 yield src + ' ', repl
136 prefix = _FLAG_MATCH[preflag]
137 postfix = _FLAG_MATCH[postflag]
139 yield prefix + src + postfix, prefix + repl + postfix