]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/api/localization.py
dump params in log view
[nominatim.git] / nominatim / api / localization.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Helper functions for localizing names of results.
9 """
10 from typing import Mapping, List, Optional
11
12 import re
13
14 class Locales:
15     """ Helper class for localization of names.
16
17         It takes a list of language prefixes in their order of preferred
18         usage.
19     """
20
21     def __init__(self, langs: Optional[List[str]] = None):
22         self.languages = langs or []
23         self.name_tags: List[str] = []
24
25         # Build the list of supported tags. It is currently hard-coded.
26         self._add_lang_tags('name')
27         self._add_tags('name', 'brand')
28         self._add_lang_tags('official_name', 'short_name')
29         self._add_tags('official_name', 'short_name', 'ref')
30
31
32     def __bool__(self) -> bool:
33         return len(self.languages) > 0
34
35
36     def _add_tags(self, *tags: str) -> None:
37         for tag in tags:
38             self.name_tags.append(tag)
39             self.name_tags.append(f"_place_{tag}")
40
41
42     def _add_lang_tags(self, *tags: str) -> None:
43         for tag in tags:
44             for lang in self.languages:
45                 self.name_tags.append(f"{tag}:{lang}")
46                 self.name_tags.append(f"_place_{tag}:{lang}")
47
48
49     def display_name(self, names: Optional[Mapping[str, str]]) -> str:
50         """ Return the best matching name from a dictionary of names
51             containing different name variants.
52
53             If 'names' is null or empty, an empty string is returned. If no
54             appropriate localization is found, the first name is returned.
55         """
56         if not names:
57             return ''
58
59         if len(names) > 1:
60             for tag in self.name_tags:
61                 if tag in names:
62                     return names[tag]
63
64         # Nothing? Return any of the other names as a default.
65         return next(iter(names.values()))
66
67
68     @staticmethod
69     def from_accept_languages(langstr: str) -> 'Locales':
70         """ Create a localization object from a language list in the
71             format of HTTP accept-languages header.
72
73             The functions tries to be forgiving of format errors by first splitting
74             the string into comma-separated parts and then parsing each
75             description separately. Badly formatted parts are then ignored.
76         """
77         # split string into languages
78         candidates = []
79         for desc in langstr.split(','):
80             m = re.fullmatch(r'\s*([a-z_-]+)(?:;\s*q\s*=\s*([01](?:\.\d+)?))?\s*',
81                              desc, flags=re.I)
82             if m:
83                 candidates.append((m[1], float(m[2] or 1.0)))
84
85         # sort the results by the weight of each language (preserving order).
86         candidates.sort(reverse=True, key=lambda e: e[1])
87
88         # If a language has a region variant, also add the language without
89         # variant but only if it isn't already in the list to not mess up the weight.
90         languages = []
91         for lid, _ in candidates:
92             languages.append(lid)
93             parts = lid.split('-', 1)
94             if len(parts) > 1 and all(c[0] != parts[0] for c in candidates):
95                 languages.append(parts[0])
96
97         return Locales(languages)