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 Helper functions for localizing names of results.
10 from typing import Mapping, List, Optional
16 """ Helper class for localization of names.
18 It takes a list of language prefixes in their order of preferred
22 def __init__(self, langs: Optional[List[str]] = None):
23 self.languages = langs or []
24 self.name_tags: List[str] = []
26 # Build the list of supported tags. It is currently hard-coded.
27 self._add_lang_tags('name')
28 self._add_tags('name', 'brand')
29 self._add_lang_tags('official_name', 'short_name')
30 self._add_tags('official_name', 'short_name', 'ref')
32 def __bool__(self) -> bool:
33 return len(self.languages) > 0
35 def _add_tags(self, *tags: str) -> None:
37 self.name_tags.append(tag)
38 self.name_tags.append(f"_place_{tag}")
40 def _add_lang_tags(self, *tags: str) -> None:
42 for lang in self.languages:
43 self.name_tags.append(f"{tag}:{lang}")
44 self.name_tags.append(f"_place_{tag}:{lang}")
46 def display_name(self, names: Optional[Mapping[str, str]]) -> str:
47 """ Return the best matching name from a dictionary of names
48 containing different name variants.
50 If 'names' is null or empty, an empty string is returned. If no
51 appropriate localization is found, the first name is returned.
57 for tag in self.name_tags:
61 # Nothing? Return any of the other names as a default.
62 return next(iter(names.values()))
65 def from_accept_languages(langstr: str) -> 'Locales':
66 """ Create a localization object from a language list in the
67 format of HTTP accept-languages header.
69 The functions tries to be forgiving of format errors by first splitting
70 the string into comma-separated parts and then parsing each
71 description separately. Badly formatted parts are then ignored.
73 # split string into languages
75 for desc in langstr.split(','):
76 m = re.fullmatch(r'\s*([a-z_-]+)(?:;\s*q\s*=\s*([01](?:\.\d+)?))?\s*',
79 candidates.append((m[1], float(m[2] or 1.0)))
81 # sort the results by the weight of each language (preserving order).
82 candidates.sort(reverse=True, key=lambda e: e[1])
84 # If a language has a region variant, also add the language without
85 # variant but only if it isn't already in the list to not mess up the weight.
87 for lid, _ in candidates:
89 parts = lid.split('-', 1)
90 if len(parts) > 1 and all(c[0] != parts[0] for c in candidates):
91 languages.append(parts[0])
93 return Locales(languages)