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
19 class ICUVariant(NamedTuple):
20 """ A single replacement rule for variant creation.
26 def get_variant_config(in_rules: Any,
27 normalizer: Any) -> Tuple[List[Tuple[str, List[str]]], str]:
28 """ Convert the variant definition from the configuration into
31 Returns a tuple containing the replacement set and the list of characters
32 used in the replacements.
34 immediate = defaultdict(list)
35 chars: Set[str] = set()
38 vset: Set[ICUVariant] = set()
39 rules = flatten_config_list(in_rules, 'variants')
41 vmaker = _VariantMaker(normalizer)
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 """ Generator 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, normalizer: Any) -> None:
66 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)
91 def _parse_variant_word(self, name: str) -> Optional[Tuple[str, str, str]]:
93 match = re.fullmatch(r'([~^]?)([^~$^]*)([~$]?)', name)
94 if match is None or (match.group(1) == '~' and match.group(3) == '~'):
95 raise UsageError(f"Invalid variant word descriptor '{name}'")
96 norm_name = self.norm.transliterate(match.group(2)).strip()
100 return norm_name, match.group(1), match.group(3)
103 _FLAG_MATCH = {'^': '^ ',
108 def _create_variants(src: str, preflag: str, postflag: str,
109 repl: str, decompose: bool) -> Iterator[Tuple[str, str]]:
111 postfix = _FLAG_MATCH[postflag]
112 # suffix decomposition
114 repl = repl + postfix
117 yield ' ' + src, ' ' + repl
120 yield src, ' ' + repl
121 yield ' ' + src, repl
122 elif postflag == '~':
123 # prefix decomposition
124 prefix = _FLAG_MATCH[preflag]
129 yield src + ' ', repl + ' '
132 yield src, repl + ' '
133 yield src + ' ', repl
135 prefix = _FLAG_MATCH[preflag]
136 postfix = _FLAG_MATCH[postflag]
138 yield prefix + src + postfix, prefix + repl + postfix