Coverage for app/backend/src/couchers/i18n/localize.py: 92%

72 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-06-28 16:54 +0000

1""" 

2Defines low-level localization functions for strings, dates, etc. 

3Most code should use the higher-level couchers.i18n.LocalizationContext object. 

4""" 

5 

6import re 

7from collections.abc import Mapping, Sequence 

8from datetime import date, datetime, time, tzinfo 

9from typing import cast 

10 

11import babel 

12import phonenumbers 

13from babel.dates import get_datetime_format, get_timezone_name, match_skeleton, parse_pattern 

14from babel.lists import format_list 

15 

16from couchers.i18n.locales import DEFAULT_LOCALE, get_main_i18next 

17from couchers.resources import get_region_code_iso3166_alpha3_to_alpha2 

18 

19 

20def localize_string(lang: str | None, key: str, *, substitutions: Mapping[str, str | int] | None = None) -> str: 

21 """ 

22 Retrieves a translated string and performs substitutions. 

23 

24 Args: 

25 lang: Language code (e.g., "en", "pt-BR"). If None, defaults to the default fallback language ("en") 

26 key: The key for the string to be looked up. 

27 substitutions: Dictionary of variable substitutions for the string (e.g., {"hours": 24}) 

28 

29 Returns: 

30 The translated string with substitutions applied 

31 """ 

32 return get_main_i18next().localize(key, lang or DEFAULT_LOCALE, substitutions) 

33 

34 

35def localize_list(items: Sequence[str], locale: babel.Locale) -> str: 

36 return format_list(items, locale=locale) 

37 

38 

39def try_localize_language_name_from_iso639(code: str, locale: babel.Locale, standalone: bool = False) -> str | None: 

40 """ 

41 Attempts to localize the name of a language expressed as an ISO639 code. 

42 

43 Args: 

44 code: The ISO639 language code. 

45 locale: The locale to render the language name in. 

46 standalone: The result won't be part of a larger sentence and should be capitalized if the language has capitals. 

47 

48 Returns: 

49 The localized name, or None if no localized name is available. 

50 """ 

51 try: 

52 name = babel.Locale.parse(code).get_language_name(locale) 

53 if name is None: 53 ↛ 54line 53 didn't jump to line 54 because the condition on line 53 was never true

54 return None 

55 if standalone: 

56 # The Unicode CLDR returns a casing that allows embedding in a larger sentence, e.g. "español". 

57 # If we're displaying the language name on its own, capitalize its first letter if applicable. 

58 # An LLM prompt revealed that this holds for all major languages. 

59 # It is a no-op for scripts that don't have capital letters. 

60 name = name[:1].title() + name[1:] 

61 return name 

62 except (ValueError, babel.UnknownLocaleError): 

63 return None 

64 

65 

66def try_localize_region_name_from_iso3166(code: str, locale: babel.Locale) -> str | None: 

67 """ 

68 Gets a region name specified as an ISO3166 alpha2 or alpha3 code, localized in the given locale. 

69 """ 

70 # The Unicode CLDR uses alpha2 codes as keys (all alpha3 codes have a corresponding alpha2 code) 

71 code = get_region_code_iso3166_alpha3_to_alpha2().get(code, code) 

72 region_name: str | None = locale.territories.get(code, None) 

73 return region_name 

74 

75 

76def localize_date( 

77 value: date, locale: babel.Locale, *, abbrev: bool = False, with_year: bool = True, with_day_of_week: bool = False 

78) -> str: 

79 """Formats a time- and timezone-agnostic date for the given locale.""" 

80 pattern = _get_cldr_date_pattern(locale, abbrev=abbrev, with_year=with_year, with_day_of_week=with_day_of_week) 

81 return parse_pattern(pattern).apply(value, locale) 

82 

83 

84def localize_time(value: time, locale: babel.Locale, *, with_seconds: bool = False) -> str: 

85 """Formats a date- and timezone-agnostic time for the given locale.""" 

86 pattern = _get_cldr_time_pattern(locale, with_seconds=with_seconds) 

87 return parse_pattern(pattern).apply(value, locale) 

88 

89 

90def localize_datetime( 

91 value: datetime, 

92 locale: babel.Locale, 

93 *, 

94 abbrev: bool = False, 

95 with_year: bool = True, 

96 with_day_of_week: bool = False, 

97 with_seconds: bool = False, 

98) -> str: 

99 """Formats a date and time for the given locale.""" 

100 # A timezone-unaware datetime is almost certainly a bug, so we don't support it. 

101 assert value.tzinfo is not None, "Cannot localize a timezone-unaware datetime." 

102 

103 pattern = _combine_cldr_date_time_patterns( 

104 locale, 

105 _get_cldr_date_pattern(locale, abbrev=abbrev, with_year=with_year, with_day_of_week=with_day_of_week), 

106 _get_cldr_time_pattern(locale, with_seconds=with_seconds), 

107 ) 

108 return parse_pattern(pattern).apply(value, locale) 

109 

110 

111def _get_cldr_date_pattern( 

112 locale: babel.Locale, *, abbrev: bool = False, with_year: bool = True, with_day_of_week: bool = False 

113) -> str: 

114 # First build a Unicode CLDR datetime pattern skeleton, which is locale and order-agnostic, 

115 # and only indicates the components we're interested in formatting. 

116 # This is similar to Intl.DateTimeFormat in Javascript. 

117 # See https://cldr.unicode.org/translation/date-time/date-time-symbols. 

118 requested_skeleton = "" 

119 

120 if with_year: 

121 requested_skeleton += "y" 

122 requested_skeleton += "MMM" if abbrev else "MMMM" 

123 requested_skeleton += "d" 

124 if with_day_of_week: 

125 requested_skeleton += "EEE" if abbrev else "EEEE" 

126 

127 # Next, match that skeleton to a similar locale-supported skeleton, 

128 # which allows us to lower it to a datetime pattern (locale and order-specific). 

129 matched_skeleton = match_skeleton(requested_skeleton, options=locale.datetime_skeletons) 

130 if not matched_skeleton: 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true

131 raise ValueError(f"Locale {locale.english_name} has no matching datetime skeleton for '{requested_skeleton}'") 

132 

133 pattern: str = locale.datetime_skeletons[matched_skeleton].pattern 

134 

135 # By CLDR rules, skeleton matching might return a pattern with abbreviations where 

136 # we asked for non-abbreviated forms, in which case we can update the returned pattern. 

137 if not abbrev: 

138 # Abbreviated to non-abbreviated month (MMM = abbreviated) 

139 pattern = re.sub(r"(?<!M)MMM(?!M)", "MMMM", pattern) 

140 if with_day_of_week: 

141 # Abbreviated to non-abbreviated day of week (E = EEE = abbreviated) 

142 pattern = re.sub(r"(?<!E)E{1,3}(?!E)", "EEEE", pattern) 

143 

144 return pattern 

145 

146 

147def _get_cldr_time_pattern(locale: babel.Locale, *, with_seconds: bool = False) -> str: 

148 # Use a reference format pattern to figure out if it's using 24h clock 

149 reference_time_pattern: str = locale.time_formats["medium"].pattern 

150 

151 # Remove literals like 'of' 

152 reference_time_pattern = re.sub("'[^']*'", "", reference_time_pattern) 

153 

154 # Extract only the hours, minutes and am/pm patterns. 

155 requested_skeleton = re.sub("[^hHkKma]+", "", reference_time_pattern) 

156 if with_seconds: 

157 requested_skeleton += "ss" 

158 

159 # Next, match that skeleton to a similar locale-supported skeleton, 

160 # which allows us to lower it to a datetime pattern (locale and order-specific). 

161 matched_skeleton = match_skeleton(requested_skeleton, options=locale.datetime_skeletons) 

162 if not matched_skeleton: 162 ↛ 163line 162 didn't jump to line 163 because the condition on line 162 was never true

163 raise ValueError(f"Locale {locale.english_name} has no matching datetime skeleton for '{requested_skeleton}'") 

164 

165 return cast(str, locale.datetime_skeletons[matched_skeleton].pattern) # "pattern" is Any-typed 

166 

167 

168def _combine_cldr_date_time_patterns(locale: babel.Locale, date_pattern: str, time_pattern: str) -> str: 

169 # get_datetime_format's return value is statically mistyped 

170 combining_format = cast(str, get_datetime_format(locale=locale)) 

171 

172 # CLDR defines {0} to be the time and {1} to be the date 

173 return combining_format.replace("{1}", date_pattern).replace("{0}", time_pattern) 

174 

175 

176def localize_timezone(timezone: tzinfo, locale: babel.Locale, *, short: bool = False) -> str: 

177 return get_timezone_name(timezone, width="short" if short else "long", locale=locale) 

178 

179 

180def format_phone_number(value: str) -> str: 

181 """Formats a phone number from E.164 format to the international format.""" 

182 return phonenumbers.format_number(phonenumbers.parse(value), phonenumbers.PhoneNumberFormat.INTERNATIONAL)