gettext.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. """Internationalization and localization support.
  2. This module provides internationalization (I18N) and localization (L10N)
  3. support for your Python programs by providing an interface to the GNU gettext
  4. message catalog library.
  5. I18N refers to the operation by which a program is made aware of multiple
  6. languages. L10N refers to the adaptation of your program, once
  7. internationalized, to the local language and cultural habits.
  8. """
  9. # This module represents the integration of work, contributions, feedback, and
  10. # suggestions from the following people:
  11. #
  12. # Martin von Loewis, who wrote the initial implementation of the underlying
  13. # C-based libintlmodule (later renamed _gettext), along with a skeletal
  14. # gettext.py implementation.
  15. #
  16. # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
  17. # which also included a pure-Python implementation to read .mo files if
  18. # intlmodule wasn't available.
  19. #
  20. # James Henstridge, who also wrote a gettext.py module, which has some
  21. # interesting, but currently unsupported experimental features: the notion of
  22. # a Catalog class and instances, and the ability to add to a catalog file via
  23. # a Python API.
  24. #
  25. # Barry Warsaw integrated these modules, wrote the .install() API and code,
  26. # and conformed all C and Python code to Python's coding standards.
  27. #
  28. # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
  29. # module.
  30. #
  31. # J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
  32. #
  33. # TODO:
  34. # - Lazy loading of .mo files. Currently the entire catalog is loaded into
  35. # memory, but that's probably bad for large translated programs. Instead,
  36. # the lexical sort of original strings in GNU .mo files should be exploited
  37. # to do binary searches and lazy initializations. Or you might want to use
  38. # the undocumented double-hash algorithm for .mo files with hash tables, but
  39. # you'll need to study the GNU gettext code to do this.
  40. #
  41. # - Support Solaris .mo file formats. Unfortunately, we've been unable to
  42. # find this format documented anywhere.
  43. import locale, copy, io, os, re, struct, sys
  44. from errno import ENOENT
  45. __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
  46. 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
  47. 'bind_textdomain_codeset',
  48. 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
  49. 'ldngettext', 'lngettext', 'ngettext',
  50. ]
  51. _default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
  52. def c2py(plural):
  53. """Gets a C expression as used in PO files for plural forms and returns a
  54. Python lambda function that implements an equivalent expression.
  55. """
  56. # Security check, allow only the "n" identifier
  57. import token, tokenize
  58. tokens = tokenize.generate_tokens(io.StringIO(plural).readline)
  59. try:
  60. danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
  61. except tokenize.TokenError:
  62. raise ValueError('plural forms expression error, maybe unbalanced parenthesis')
  63. else:
  64. if danger:
  65. raise ValueError('plural forms expression could be dangerous')
  66. # Replace some C operators by their Python equivalents
  67. plural = plural.replace('&&', ' and ')
  68. plural = plural.replace('||', ' or ')
  69. expr = re.compile(r'\!([^=])')
  70. plural = expr.sub(' not \\1', plural)
  71. # Regular expression and replacement function used to transform
  72. # "a?b:c" to "b if a else c".
  73. expr = re.compile(r'(.*?)\?(.*?):(.*)')
  74. def repl(x):
  75. return "(%s if %s else %s)" % (x.group(2), x.group(1),
  76. expr.sub(repl, x.group(3)))
  77. # Code to transform the plural expression, taking care of parentheses
  78. stack = ['']
  79. for c in plural:
  80. if c == '(':
  81. stack.append('')
  82. elif c == ')':
  83. if len(stack) == 1:
  84. # Actually, we never reach this code, because unbalanced
  85. # parentheses get caught in the security check at the
  86. # beginning.
  87. raise ValueError('unbalanced parenthesis in plural form')
  88. s = expr.sub(repl, stack.pop())
  89. stack[-1] += '(%s)' % s
  90. else:
  91. stack[-1] += c
  92. plural = expr.sub(repl, stack.pop())
  93. return eval('lambda n: int(%s)' % plural)
  94. def _expand_lang(loc):
  95. loc = locale.normalize(loc)
  96. COMPONENT_CODESET = 1 << 0
  97. COMPONENT_TERRITORY = 1 << 1
  98. COMPONENT_MODIFIER = 1 << 2
  99. # split up the locale into its base components
  100. mask = 0
  101. pos = loc.find('@')
  102. if pos >= 0:
  103. modifier = loc[pos:]
  104. loc = loc[:pos]
  105. mask |= COMPONENT_MODIFIER
  106. else:
  107. modifier = ''
  108. pos = loc.find('.')
  109. if pos >= 0:
  110. codeset = loc[pos:]
  111. loc = loc[:pos]
  112. mask |= COMPONENT_CODESET
  113. else:
  114. codeset = ''
  115. pos = loc.find('_')
  116. if pos >= 0:
  117. territory = loc[pos:]
  118. loc = loc[:pos]
  119. mask |= COMPONENT_TERRITORY
  120. else:
  121. territory = ''
  122. language = loc
  123. ret = []
  124. for i in range(mask+1):
  125. if not (i & ~mask): # if all components for this combo exist ...
  126. val = language
  127. if i & COMPONENT_TERRITORY: val += territory
  128. if i & COMPONENT_CODESET: val += codeset
  129. if i & COMPONENT_MODIFIER: val += modifier
  130. ret.append(val)
  131. ret.reverse()
  132. return ret
  133. class NullTranslations:
  134. def __init__(self, fp=None):
  135. self._info = {}
  136. self._charset = None
  137. self._output_charset = None
  138. self._fallback = None
  139. if fp is not None:
  140. self._parse(fp)
  141. def _parse(self, fp):
  142. pass
  143. def add_fallback(self, fallback):
  144. if self._fallback:
  145. self._fallback.add_fallback(fallback)
  146. else:
  147. self._fallback = fallback
  148. def gettext(self, message):
  149. if self._fallback:
  150. return self._fallback.gettext(message)
  151. return message
  152. def lgettext(self, message):
  153. if self._fallback:
  154. return self._fallback.lgettext(message)
  155. return message
  156. def ngettext(self, msgid1, msgid2, n):
  157. if self._fallback:
  158. return self._fallback.ngettext(msgid1, msgid2, n)
  159. if n == 1:
  160. return msgid1
  161. else:
  162. return msgid2
  163. def lngettext(self, msgid1, msgid2, n):
  164. if self._fallback:
  165. return self._fallback.lngettext(msgid1, msgid2, n)
  166. if n == 1:
  167. return msgid1
  168. else:
  169. return msgid2
  170. def info(self):
  171. return self._info
  172. def charset(self):
  173. return self._charset
  174. def output_charset(self):
  175. return self._output_charset
  176. def set_output_charset(self, charset):
  177. self._output_charset = charset
  178. def install(self, names=None):
  179. import builtins
  180. builtins.__dict__['_'] = self.gettext
  181. if hasattr(names, "__contains__"):
  182. if "gettext" in names:
  183. builtins.__dict__['gettext'] = builtins.__dict__['_']
  184. if "ngettext" in names:
  185. builtins.__dict__['ngettext'] = self.ngettext
  186. if "lgettext" in names:
  187. builtins.__dict__['lgettext'] = self.lgettext
  188. if "lngettext" in names:
  189. builtins.__dict__['lngettext'] = self.lngettext
  190. class GNUTranslations(NullTranslations):
  191. # Magic number of .mo files
  192. LE_MAGIC = 0x950412de
  193. BE_MAGIC = 0xde120495
  194. # Acceptable .mo versions
  195. VERSIONS = (0, 1)
  196. def _get_versions(self, version):
  197. """Returns a tuple of major version, minor version"""
  198. return (version >> 16, version & 0xffff)
  199. def _parse(self, fp):
  200. """Override this method to support alternative .mo formats."""
  201. unpack = struct.unpack
  202. filename = getattr(fp, 'name', '')
  203. # Parse the .mo file header, which consists of 5 little endian 32
  204. # bit words.
  205. self._catalog = catalog = {}
  206. self.plural = lambda n: int(n != 1) # germanic plural by default
  207. buf = fp.read()
  208. buflen = len(buf)
  209. # Are we big endian or little endian?
  210. magic = unpack('<I', buf[:4])[0]
  211. if magic == self.LE_MAGIC:
  212. version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
  213. ii = '<II'
  214. elif magic == self.BE_MAGIC:
  215. version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
  216. ii = '>II'
  217. else:
  218. raise OSError(0, 'Bad magic number', filename)
  219. major_version, minor_version = self._get_versions(version)
  220. if major_version not in self.VERSIONS:
  221. raise OSError(0, 'Bad version number ' + str(major_version), filename)
  222. # Now put all messages from the .mo file buffer into the catalog
  223. # dictionary.
  224. for i in range(0, msgcount):
  225. mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
  226. mend = moff + mlen
  227. tlen, toff = unpack(ii, buf[transidx:transidx+8])
  228. tend = toff + tlen
  229. if mend < buflen and tend < buflen:
  230. msg = buf[moff:mend]
  231. tmsg = buf[toff:tend]
  232. else:
  233. raise OSError(0, 'File is corrupt', filename)
  234. # See if we're looking at GNU .mo conventions for metadata
  235. if mlen == 0:
  236. # Catalog description
  237. lastk = None
  238. for b_item in tmsg.split('\n'.encode("ascii")):
  239. item = b_item.decode().strip()
  240. if not item:
  241. continue
  242. k = v = None
  243. if ':' in item:
  244. k, v = item.split(':', 1)
  245. k = k.strip().lower()
  246. v = v.strip()
  247. self._info[k] = v
  248. lastk = k
  249. elif lastk:
  250. self._info[lastk] += '\n' + item
  251. if k == 'content-type':
  252. self._charset = v.split('charset=')[1]
  253. elif k == 'plural-forms':
  254. v = v.split(';')
  255. plural = v[1].split('plural=')[1]
  256. self.plural = c2py(plural)
  257. # Note: we unconditionally convert both msgids and msgstrs to
  258. # Unicode using the character encoding specified in the charset
  259. # parameter of the Content-Type header. The gettext documentation
  260. # strongly encourages msgids to be us-ascii, but some applications
  261. # require alternative encodings (e.g. Zope's ZCML and ZPT). For
  262. # traditional gettext applications, the msgid conversion will
  263. # cause no problems since us-ascii should always be a subset of
  264. # the charset encoding. We may want to fall back to 8-bit msgids
  265. # if the Unicode conversion fails.
  266. charset = self._charset or 'ascii'
  267. if b'\x00' in msg:
  268. # Plural forms
  269. msgid1, msgid2 = msg.split(b'\x00')
  270. tmsg = tmsg.split(b'\x00')
  271. msgid1 = str(msgid1, charset)
  272. for i, x in enumerate(tmsg):
  273. catalog[(msgid1, i)] = str(x, charset)
  274. else:
  275. catalog[str(msg, charset)] = str(tmsg, charset)
  276. # advance to next entry in the seek tables
  277. masteridx += 8
  278. transidx += 8
  279. def lgettext(self, message):
  280. missing = object()
  281. tmsg = self._catalog.get(message, missing)
  282. if tmsg is missing:
  283. if self._fallback:
  284. return self._fallback.lgettext(message)
  285. return message
  286. if self._output_charset:
  287. return tmsg.encode(self._output_charset)
  288. return tmsg.encode(locale.getpreferredencoding())
  289. def lngettext(self, msgid1, msgid2, n):
  290. try:
  291. tmsg = self._catalog[(msgid1, self.plural(n))]
  292. if self._output_charset:
  293. return tmsg.encode(self._output_charset)
  294. return tmsg.encode(locale.getpreferredencoding())
  295. except KeyError:
  296. if self._fallback:
  297. return self._fallback.lngettext(msgid1, msgid2, n)
  298. if n == 1:
  299. return msgid1
  300. else:
  301. return msgid2
  302. def gettext(self, message):
  303. missing = object()
  304. tmsg = self._catalog.get(message, missing)
  305. if tmsg is missing:
  306. if self._fallback:
  307. return self._fallback.gettext(message)
  308. return message
  309. return tmsg
  310. def ngettext(self, msgid1, msgid2, n):
  311. try:
  312. tmsg = self._catalog[(msgid1, self.plural(n))]
  313. except KeyError:
  314. if self._fallback:
  315. return self._fallback.ngettext(msgid1, msgid2, n)
  316. if n == 1:
  317. tmsg = msgid1
  318. else:
  319. tmsg = msgid2
  320. return tmsg
  321. # Locate a .mo file using the gettext strategy
  322. def find(domain, localedir=None, languages=None, all=False):
  323. # Get some reasonable defaults for arguments that were not supplied
  324. if localedir is None:
  325. localedir = _default_localedir
  326. if languages is None:
  327. languages = []
  328. for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
  329. val = os.environ.get(envar)
  330. if val:
  331. languages = val.split(':')
  332. break
  333. if 'C' not in languages:
  334. languages.append('C')
  335. # now normalize and expand the languages
  336. nelangs = []
  337. for lang in languages:
  338. for nelang in _expand_lang(lang):
  339. if nelang not in nelangs:
  340. nelangs.append(nelang)
  341. # select a language
  342. if all:
  343. result = []
  344. else:
  345. result = None
  346. for lang in nelangs:
  347. if lang == 'C':
  348. break
  349. mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
  350. if os.path.exists(mofile):
  351. if all:
  352. result.append(mofile)
  353. else:
  354. return mofile
  355. return result
  356. # a mapping between absolute .mo file path and Translation object
  357. _translations = {}
  358. def translation(domain, localedir=None, languages=None,
  359. class_=None, fallback=False, codeset=None):
  360. if class_ is None:
  361. class_ = GNUTranslations
  362. mofiles = find(domain, localedir, languages, all=True)
  363. if not mofiles:
  364. if fallback:
  365. return NullTranslations()
  366. raise OSError(ENOENT, 'No translation file found for domain', domain)
  367. # Avoid opening, reading, and parsing the .mo file after it's been done
  368. # once.
  369. result = None
  370. for mofile in mofiles:
  371. key = (class_, os.path.abspath(mofile))
  372. t = _translations.get(key)
  373. if t is None:
  374. with open(mofile, 'rb') as fp:
  375. t = _translations.setdefault(key, class_(fp))
  376. # Copy the translation object to allow setting fallbacks and
  377. # output charset. All other instance data is shared with the
  378. # cached object.
  379. t = copy.copy(t)
  380. if codeset:
  381. t.set_output_charset(codeset)
  382. if result is None:
  383. result = t
  384. else:
  385. result.add_fallback(t)
  386. return result
  387. def install(domain, localedir=None, codeset=None, names=None):
  388. t = translation(domain, localedir, fallback=True, codeset=codeset)
  389. t.install(names)
  390. # a mapping b/w domains and locale directories
  391. _localedirs = {}
  392. # a mapping b/w domains and codesets
  393. _localecodesets = {}
  394. # current global domain, `messages' used for compatibility w/ GNU gettext
  395. _current_domain = 'messages'
  396. def textdomain(domain=None):
  397. global _current_domain
  398. if domain is not None:
  399. _current_domain = domain
  400. return _current_domain
  401. def bindtextdomain(domain, localedir=None):
  402. global _localedirs
  403. if localedir is not None:
  404. _localedirs[domain] = localedir
  405. return _localedirs.get(domain, _default_localedir)
  406. def bind_textdomain_codeset(domain, codeset=None):
  407. global _localecodesets
  408. if codeset is not None:
  409. _localecodesets[domain] = codeset
  410. return _localecodesets.get(domain)
  411. def dgettext(domain, message):
  412. try:
  413. t = translation(domain, _localedirs.get(domain, None),
  414. codeset=_localecodesets.get(domain))
  415. except OSError:
  416. return message
  417. return t.gettext(message)
  418. def ldgettext(domain, message):
  419. try:
  420. t = translation(domain, _localedirs.get(domain, None),
  421. codeset=_localecodesets.get(domain))
  422. except OSError:
  423. return message
  424. return t.lgettext(message)
  425. def dngettext(domain, msgid1, msgid2, n):
  426. try:
  427. t = translation(domain, _localedirs.get(domain, None),
  428. codeset=_localecodesets.get(domain))
  429. except OSError:
  430. if n == 1:
  431. return msgid1
  432. else:
  433. return msgid2
  434. return t.ngettext(msgid1, msgid2, n)
  435. def ldngettext(domain, msgid1, msgid2, n):
  436. try:
  437. t = translation(domain, _localedirs.get(domain, None),
  438. codeset=_localecodesets.get(domain))
  439. except OSError:
  440. if n == 1:
  441. return msgid1
  442. else:
  443. return msgid2
  444. return t.lngettext(msgid1, msgid2, n)
  445. def gettext(message):
  446. return dgettext(_current_domain, message)
  447. def lgettext(message):
  448. return ldgettext(_current_domain, message)
  449. def ngettext(msgid1, msgid2, n):
  450. return dngettext(_current_domain, msgid1, msgid2, n)
  451. def lngettext(msgid1, msgid2, n):
  452. return ldngettext(_current_domain, msgid1, msgid2, n)
  453. # dcgettext() has been deemed unnecessary and is not implemented.
  454. # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
  455. # was:
  456. #
  457. # import gettext
  458. # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
  459. # _ = cat.gettext
  460. # print _('Hello World')
  461. # The resulting catalog object currently don't support access through a
  462. # dictionary API, which was supported (but apparently unused) in GNOME
  463. # gettext.
  464. Catalog = translation