Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/tornado/locale.py: 20%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

223 statements  

1# Copyright 2009 Facebook 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); you may 

4# not use this file except in compliance with the License. You may obtain 

5# a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 

11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 

12# License for the specific language governing permissions and limitations 

13# under the License. 

14 

15"""Translation methods for generating localized strings. 

16 

17To load a locale and generate a translated string:: 

18 

19 user_locale = tornado.locale.get("es_LA") 

20 print(user_locale.translate("Sign out")) 

21 

22`tornado.locale.get()` returns the closest matching locale, not necessarily the 

23specific locale you requested. You can support pluralization with 

24additional arguments to `~Locale.translate()`, e.g.:: 

25 

26 people = [...] 

27 message = user_locale.translate( 

28 "%(list)s is online", "%(list)s are online", len(people)) 

29 print(message % {"list": user_locale.list(people)}) 

30 

31The first string is chosen if ``len(people) == 1``, otherwise the second 

32string is chosen. 

33 

34Applications should call one of `load_translations` (which uses a simple 

35CSV format) or `load_gettext_translations` (which uses the ``.mo`` format 

36supported by `gettext` and related tools). If neither method is called, 

37the `Locale.translate` method will simply return the original string. 

38""" 

39 

40from __future__ import annotations 

41 

42import codecs 

43import csv 

44import datetime 

45import gettext 

46import glob 

47import os 

48import re 

49from collections.abc import Iterable 

50from typing import Any 

51 

52from tornado import escape 

53from tornado._locale_data import LOCALE_NAMES 

54from tornado.log import gen_log 

55 

56_default_locale = "en_US" 

57_translations: dict[str, Any] = {} 

58_supported_locales = frozenset([_default_locale]) 

59_use_gettext = False 

60CONTEXT_SEPARATOR = "\x04" 

61 

62 

63def get(*locale_codes: str) -> Locale: 

64 """Returns the closest match for the given locale codes. 

65 

66 We iterate over all given locale codes in order. If we have a tight 

67 or a loose match for the code (e.g., "en" for "en_US"), we return 

68 the locale. Otherwise we move to the next code in the list. 

69 

70 By default we return ``en_US`` if no translations are found for any of 

71 the specified locales. You can change the default locale with 

72 `set_default_locale()`. 

73 """ 

74 return Locale.get_closest(*locale_codes) 

75 

76 

77def set_default_locale(code: str) -> None: 

78 """Sets the default locale. 

79 

80 The default locale is assumed to be the language used for all strings 

81 in the system. The translations loaded from disk are mappings from 

82 the default locale to the destination locale. Consequently, you don't 

83 need to create a translation file for the default locale. 

84 """ 

85 global _default_locale 

86 global _supported_locales 

87 _default_locale = code 

88 _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) 

89 

90 

91def load_translations(directory: str, encoding: str | None = None) -> None: 

92 """Loads translations from CSV files in a directory. 

93 

94 Translations are strings with optional Python-style named placeholders 

95 (e.g., ``My name is %(name)s``) and their associated translations. 

96 

97 The directory should have translation files of the form ``LOCALE.csv``, 

98 e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, 

99 translation, and an optional plural indicator. Plural indicators should 

100 be one of "plural" or "singular". A given string can have both singular 

101 and plural forms. For example ``%(name)s liked this`` may have a 

102 different verb conjugation depending on whether %(name)s is one 

103 name or a list of names. There should be two rows in the CSV file for 

104 that string, one with plural indicator "singular", and one "plural". 

105 For strings with no verbs that would change on translation, simply 

106 use "unknown" or the empty string (or don't include the column at all). 

107 

108 The file is read using the `csv` module in the default "excel" dialect. 

109 In this format there should not be spaces after the commas. 

110 

111 If no ``encoding`` parameter is given, the encoding will be 

112 detected automatically (among UTF-8 and UTF-16) if the file 

113 contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM 

114 is present. 

115 

116 Example translation ``es_LA.csv``:: 

117 

118 "I love you","Te amo" 

119 "%(name)s liked this","A %(name)s les gustó esto","plural" 

120 "%(name)s liked this","A %(name)s le gustó esto","singular" 

121 

122 .. versionchanged:: 4.3 

123 Added ``encoding`` parameter. Added support for BOM-based encoding 

124 detection, UTF-16, and UTF-8-with-BOM. 

125 """ 

126 global _translations 

127 global _supported_locales 

128 _translations = {} 

129 for path in os.listdir(directory): 

130 if not path.endswith(".csv"): 

131 continue 

132 locale, extension = path.split(".") 

133 if not re.match("[a-z]+(_[A-Z]+)?$", locale): 

134 gen_log.error( 

135 "Unrecognized locale %r (path: %s)", 

136 locale, 

137 os.path.join(directory, path), 

138 ) 

139 continue 

140 full_path = os.path.join(directory, path) 

141 if encoding is None: 

142 # Try to autodetect encoding based on the BOM. 

143 with open(full_path, "rb") as bf: 

144 data = bf.read(len(codecs.BOM_UTF16_LE)) 

145 if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): 

146 encoding = "utf-16" 

147 else: 

148 # utf-8-sig is "utf-8 with optional BOM". It's discouraged 

149 # in most cases but is common with CSV files because Excel 

150 # cannot read utf-8 files without a BOM. 

151 encoding = "utf-8-sig" 

152 # python 3: csv.reader requires a file open in text mode. 

153 # Specify an encoding to avoid dependence on $LANG environment variable. 

154 with open(full_path, encoding=encoding) as f: 

155 _translations[locale] = {} 

156 for i, row in enumerate(csv.reader(f)): 

157 if not row or len(row) < 2: 

158 continue 

159 row = [escape.to_unicode(c).strip() for c in row] 

160 english, translation = row[:2] 

161 if len(row) > 2: 

162 plural = row[2] or "unknown" 

163 else: 

164 plural = "unknown" 

165 if plural not in ("plural", "singular", "unknown"): 

166 gen_log.error( 

167 "Unrecognized plural indicator %r in %s line %d", 

168 plural, 

169 path, 

170 i + 1, 

171 ) 

172 continue 

173 _translations[locale].setdefault(plural, {})[english] = translation 

174 _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) 

175 gen_log.debug("Supported locales: %s", sorted(_supported_locales)) 

176 

177 

178def load_gettext_translations(directory: str, domain: str) -> None: 

179 """Loads translations from `gettext`'s locale tree 

180 

181 Locale tree is similar to system's ``/usr/share/locale``, like:: 

182 

183 {directory}/{lang}/LC_MESSAGES/{domain}.mo 

184 

185 Three steps are required to have your app translated: 

186 

187 1. Generate POT translation file:: 

188 

189 xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc 

190 

191 2. Merge against existing POT file:: 

192 

193 msgmerge old.po mydomain.po > new.po 

194 

195 3. Compile:: 

196 

197 msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo 

198 """ 

199 global _translations 

200 global _supported_locales 

201 global _use_gettext 

202 _translations = {} 

203 

204 for filename in glob.glob( 

205 os.path.join(directory, "*", "LC_MESSAGES", domain + ".mo") 

206 ): 

207 lang = os.path.basename(os.path.dirname(os.path.dirname(filename))) 

208 try: 

209 _translations[lang] = gettext.translation( 

210 domain, directory, languages=[lang] 

211 ) 

212 except Exception as e: 

213 gen_log.error("Cannot load translation for '%s': %s", lang, str(e)) 

214 continue 

215 _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) 

216 _use_gettext = True 

217 gen_log.debug("Supported locales: %s", sorted(_supported_locales)) 

218 

219 

220def get_supported_locales() -> Iterable[str]: 

221 """Returns a list of all the supported locale codes.""" 

222 return _supported_locales 

223 

224 

225class Locale: 

226 """Object representing a locale. 

227 

228 After calling one of `load_translations` or `load_gettext_translations`, 

229 call `get` or `get_closest` to get a Locale object. 

230 """ 

231 

232 _cache: dict[str, Locale] = {} 

233 

234 @classmethod 

235 def get_closest(cls, *locale_codes: str) -> Locale: 

236 """Returns the closest match for the given locale code.""" 

237 for code in locale_codes: 

238 if not code: 

239 continue 

240 code = code.replace("-", "_") 

241 parts = code.split("_") 

242 if len(parts) > 2: 

243 continue 

244 elif len(parts) == 2: 

245 code = parts[0].lower() + "_" + parts[1].upper() 

246 if code in _supported_locales: 

247 return cls.get(code) 

248 if parts[0].lower() in _supported_locales: 

249 return cls.get(parts[0].lower()) 

250 return cls.get(_default_locale) 

251 

252 @classmethod 

253 def get(cls, code: str) -> Locale: 

254 """Returns the Locale for the given locale code. 

255 

256 If it is not supported, we raise an exception. 

257 """ 

258 if code not in cls._cache: 

259 assert code in _supported_locales 

260 translations = _translations.get(code, None) 

261 if translations is None: 

262 locale: Locale = CSVLocale(code, {}) 

263 elif _use_gettext: 

264 locale = GettextLocale(code, translations) 

265 else: 

266 locale = CSVLocale(code, translations) 

267 cls._cache[code] = locale 

268 return cls._cache[code] 

269 

270 def __init__(self, code: str) -> None: 

271 self.code = code 

272 self.name = LOCALE_NAMES.get(code, {}).get("name", "Unknown") 

273 self.rtl = False 

274 for prefix in ["fa", "ar", "he"]: 

275 if self.code.startswith(prefix): 

276 self.rtl = True 

277 break 

278 

279 # Initialize strings for date formatting 

280 _ = self.translate 

281 self._months = [ 

282 _("January"), 

283 _("February"), 

284 _("March"), 

285 _("April"), 

286 _("May"), 

287 _("June"), 

288 _("July"), 

289 _("August"), 

290 _("September"), 

291 _("October"), 

292 _("November"), 

293 _("December"), 

294 ] 

295 self._weekdays = [ 

296 _("Monday"), 

297 _("Tuesday"), 

298 _("Wednesday"), 

299 _("Thursday"), 

300 _("Friday"), 

301 _("Saturday"), 

302 _("Sunday"), 

303 ] 

304 

305 def translate( 

306 self, 

307 message: str, 

308 plural_message: str | None = None, 

309 count: int | None = None, 

310 ) -> str: 

311 """Returns the translation for the given message for this locale. 

312 

313 If ``plural_message`` is given, you must also provide 

314 ``count``. We return ``plural_message`` when ``count != 1``, 

315 and we return the singular form for the given message when 

316 ``count == 1``. 

317 """ 

318 raise NotImplementedError() 

319 

320 def pgettext( 

321 self, 

322 context: str, 

323 message: str, 

324 plural_message: str | None = None, 

325 count: int | None = None, 

326 ) -> str: 

327 raise NotImplementedError() 

328 

329 def format_date( 

330 self, 

331 date: int | float | datetime.datetime, 

332 gmt_offset: int = 0, 

333 relative: bool = True, 

334 shorter: bool = False, 

335 full_format: bool = False, 

336 ) -> str: 

337 """Formats the given date. 

338 

339 By default, we return a relative time (e.g., "2 minutes ago"). You 

340 can return an absolute date string with ``relative=False``. 

341 

342 You can force a full format date ("July 10, 1980") with 

343 ``full_format=True``. 

344 

345 This method is primarily intended for dates in the past. 

346 For dates in the future, we fall back to full format. 

347 

348 .. versionchanged:: 6.4 

349 Aware `datetime.datetime` objects are now supported (naive 

350 datetimes are still assumed to be UTC). 

351 """ 

352 if isinstance(date, (int, float)): 

353 date = datetime.datetime.fromtimestamp(date, datetime.UTC) 

354 if date.tzinfo is None: 

355 date = date.replace(tzinfo=datetime.UTC) 

356 now = datetime.datetime.now(datetime.UTC) 

357 if date > now: 

358 if relative and (date - now).total_seconds() < 60: 

359 # Due to click skew, things are some things slightly 

360 # in the future. Round timestamps in the immediate 

361 # future down to now in relative mode. 

362 date = now 

363 else: 

364 # Otherwise, future dates always use the full format. 

365 full_format = True 

366 local_date = date - datetime.timedelta(minutes=gmt_offset) 

367 local_now = now - datetime.timedelta(minutes=gmt_offset) 

368 local_yesterday = local_now - datetime.timedelta(hours=24) 

369 difference = now - date 

370 seconds = difference.seconds 

371 days = difference.days 

372 

373 _ = self.translate 

374 format = None 

375 if not full_format: 

376 if relative and days == 0: 

377 if seconds < 50: 

378 return _("1 second ago", "%(seconds)d seconds ago", seconds) % { 

379 "seconds": seconds 

380 } 

381 

382 if seconds < 50 * 60: 

383 minutes = round(seconds / 60.0) 

384 return _("1 minute ago", "%(minutes)d minutes ago", minutes) % { 

385 "minutes": minutes 

386 } 

387 

388 hours = round(seconds / (60.0 * 60)) 

389 return _("1 hour ago", "%(hours)d hours ago", hours) % {"hours": hours} 

390 

391 if days == 0: 

392 format = _("%(time)s") 

393 elif days == 1 and local_date.day == local_yesterday.day and relative: 

394 format = _("yesterday") if shorter else _("yesterday at %(time)s") 

395 elif days < 5: 

396 format = _("%(weekday)s") if shorter else _("%(weekday)s at %(time)s") 

397 elif days < 334: # 11mo, since confusing for same month last year 

398 format = ( 

399 _("%(month_name)s %(day)s") 

400 if shorter 

401 else _("%(month_name)s %(day)s at %(time)s") 

402 ) 

403 

404 if format is None: 

405 format = ( 

406 _("%(month_name)s %(day)s, %(year)s") 

407 if shorter 

408 else _("%(month_name)s %(day)s, %(year)s at %(time)s") 

409 ) 

410 

411 tfhour_clock = self.code not in ("en", "en_US", "zh_CN") 

412 if tfhour_clock: 

413 str_time = "%d:%02d" % (local_date.hour, local_date.minute) 

414 elif self.code == "zh_CN": 

415 str_time = "%s%d:%02d" % ( 

416 ("\u4e0a\u5348", "\u4e0b\u5348")[local_date.hour >= 12], 

417 local_date.hour % 12 or 12, 

418 local_date.minute, 

419 ) 

420 else: 

421 str_time = "%d:%02d %s" % ( 

422 local_date.hour % 12 or 12, 

423 local_date.minute, 

424 ("am", "pm")[local_date.hour >= 12], 

425 ) 

426 

427 return format % { 

428 "month_name": self._months[local_date.month - 1], 

429 "weekday": self._weekdays[local_date.weekday()], 

430 "day": str(local_date.day), 

431 "year": str(local_date.year), 

432 "time": str_time, 

433 } 

434 

435 def format_day( 

436 self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True 

437 ) -> str: 

438 """Formats the given date as a day of week. 

439 

440 Example: "Monday, January 22". You can remove the day of week with 

441 ``dow=False``. 

442 """ 

443 local_date = date - datetime.timedelta(minutes=gmt_offset) 

444 _ = self.translate 

445 if dow: 

446 return _("%(weekday)s, %(month_name)s %(day)s") % { 

447 "month_name": self._months[local_date.month - 1], 

448 "weekday": self._weekdays[local_date.weekday()], 

449 "day": str(local_date.day), 

450 } 

451 else: 

452 return _("%(month_name)s %(day)s") % { 

453 "month_name": self._months[local_date.month - 1], 

454 "day": str(local_date.day), 

455 } 

456 

457 def list(self, parts: Any) -> str: 

458 """Returns a comma-separated list for the given list of parts. 

459 

460 The format is, e.g., "A, B and C", "A and B" or just "A" for lists 

461 of size 1. 

462 """ 

463 _ = self.translate 

464 if len(parts) == 0: 

465 return "" 

466 if len(parts) == 1: 

467 return parts[0] 

468 comma = " \u0648 " if self.code.startswith("fa") else ", " 

469 return _("%(commas)s and %(last)s") % { 

470 "commas": comma.join(parts[:-1]), 

471 "last": parts[len(parts) - 1], 

472 } 

473 

474 def friendly_number(self, value: int) -> str: 

475 """Returns a comma-separated number for the given integer.""" 

476 if self.code not in ("en", "en_US"): 

477 return str(value) 

478 s = str(value) 

479 parts = [] 

480 while s: 

481 parts.append(s[-3:]) 

482 s = s[:-3] 

483 return ",".join(reversed(parts)) 

484 

485 

486class CSVLocale(Locale): 

487 """Locale implementation using tornado's CSV translation format.""" 

488 

489 def __init__(self, code: str, translations: dict[str, dict[str, str]]) -> None: 

490 self.translations = translations 

491 super().__init__(code) 

492 

493 def translate( 

494 self, 

495 message: str, 

496 plural_message: str | None = None, 

497 count: int | None = None, 

498 ) -> str: 

499 if plural_message is not None: 

500 assert count is not None 

501 if count != 1: 

502 message = plural_message 

503 message_dict = self.translations.get("plural", {}) 

504 else: 

505 message_dict = self.translations.get("singular", {}) 

506 else: 

507 message_dict = self.translations.get("unknown", {}) 

508 return message_dict.get(message, message) 

509 

510 def pgettext( 

511 self, 

512 context: str, 

513 message: str, 

514 plural_message: str | None = None, 

515 count: int | None = None, 

516 ) -> str: 

517 if self.translations: 

518 gen_log.warning("pgettext is not supported by CSVLocale") 

519 return self.translate(message, plural_message, count) 

520 

521 

522class GettextLocale(Locale): 

523 """Locale implementation using the `gettext` module.""" 

524 

525 def __init__(self, code: str, translations: gettext.NullTranslations) -> None: 

526 self.ngettext = translations.ngettext 

527 self.gettext = translations.gettext 

528 # self.gettext must exist before __init__ is called, since it 

529 # calls into self.translate 

530 super().__init__(code) 

531 

532 def translate( 

533 self, 

534 message: str, 

535 plural_message: str | None = None, 

536 count: int | None = None, 

537 ) -> str: 

538 if plural_message is not None: 

539 assert count is not None 

540 return self.ngettext(message, plural_message, count) 

541 else: 

542 return self.gettext(message) 

543 

544 def pgettext( 

545 self, 

546 context: str, 

547 message: str, 

548 plural_message: str | None = None, 

549 count: int | None = None, 

550 ) -> str: 

551 """Allows to set context for translation, accepts plural forms. 

552 

553 Usage example:: 

554 

555 pgettext("law", "right") 

556 pgettext("good", "right") 

557 

558 Plural message example:: 

559 

560 pgettext("organization", "club", "clubs", len(clubs)) 

561 pgettext("stick", "club", "clubs", len(clubs)) 

562 

563 To generate POT file with context, add following options to step 1 

564 of `load_gettext_translations` sequence:: 

565 

566 xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3 

567 

568 .. versionadded:: 4.2 

569 """ 

570 if plural_message is not None: 

571 assert count is not None 

572 msgs_with_ctxt = ( 

573 f"{context}{CONTEXT_SEPARATOR}{message}", 

574 f"{context}{CONTEXT_SEPARATOR}{plural_message}", 

575 count, 

576 ) 

577 result = self.ngettext(*msgs_with_ctxt) 

578 if CONTEXT_SEPARATOR in result: 

579 # Translation not found 

580 result = self.ngettext(message, plural_message, count) 

581 return result 

582 else: 

583 msg_with_ctxt = f"{context}{CONTEXT_SEPARATOR}{message}" 

584 result = self.gettext(msg_with_ctxt) 

585 if CONTEXT_SEPARATOR in result: 

586 # Translation not found 

587 result = message 

588 return result