jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750712 )
Change subject: [IMPR] Improve i18n module
......................................................................
[IMPR] Improve i18n module
- add i18n.bundles() function to get all bundle names
- add i18n.known_languages() functions to get all languages with translations
- add i18n._get_bundle function to get the dict from json text
for a language bundle
- add Generator to backports.py
- add bundle tests
Change-Id: I9cb13bb215fadcb340b263748c3c21c115a95e9c
---
M pywikibot/i18n.py
M tests/l10n_tests.py
2 files changed, 67 insertions(+), 9 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index 2dffea9..6dcdda5 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -26,6 +26,7 @@
from collections import abc, defaultdict
from contextlib import suppress
+from pathlib import Path
from textwrap import fill
from typing import Optional, Union
@@ -35,6 +36,7 @@
from pywikibot.backports import (
cache,
Dict,
+ Generator,
Iterable,
Iterator,
List,
@@ -412,6 +414,24 @@
@cache
+def _get_bundle(lang: str, dirname: str) -> Dict[str, str]:
+ """Return json data of certain bundle if exists.
+
+ For internal use, don't use it directly.
+
+ .. versionadded:: 7.0
+ """
+ filename = '{}/{}.json'.format(dirname, lang)
+ try:
+ data = pkgutil.get_data(_messages_package_name, filename)
+ assert data is not None
+ trans_text = data.decode('utf-8')
+ except OSError: # file open can cause several exceptions
+ return {}
+
+ return json.loads(trans_text)
+
+
def _get_translation(lang: str, twtitle: str) -> Optional[str]:
"""
Return message of certain twtitle if exists.
@@ -419,15 +439,7 @@
For internal use, don't use it directly.
"""
message_bundle = twtitle.split('-')[0]
- filename = '{}/{}.json'.format(message_bundle, lang)
- try:
- data = pkgutil.get_data(_messages_package_name, filename)
- assert data is not None
- trans_text = data.decode('utf-8')
- except OSError: # file open can cause several exceptions
- return None
-
- transdict = json.loads(trans_text)
+ transdict = _get_bundle(lang, message_bundle)
return transdict.get(twtitle)
@@ -801,6 +813,34 @@
if lang != 'qqq' and _get_translation(lang, twtitle)]
+def bundles(stem: bool = False) -> Generator[Union[Path, str], None, None]:
+ """A generator which yields message bundle names or its path objects.
+
+ :param stem: yield the Path.stem if True and the Path object otherwise
+
+ .. versionadded:: 7.0
+ """
+ for dirpath in Path(*_messages_package_name.split('.')).iterdir():
+ if dirpath.is_dir() and not dirpath.match('*__'): # ignore cache
+ if stem:
+ yield dirpath.stem
+ else:
+ yield dirpath
+
+
+def known_languages() -> List[str]:
+ """All languages we have localizations for.
+
+ .. versionadded:: 7.0
+ """
+ langs = set()
+ for dirpath in bundles():
+ for fname in dirpath.iterdir():
+ if fname.suffix == '.json':
+ langs.add(fname.stem)
+ return sorted(langs)
+
+
def input(twtitle: str,
parameters: Optional[Mapping[str, int]] = None,
password: bool = False,
diff --git a/tests/l10n_tests.py b/tests/l10n_tests.py
index 04388de..61db833 100644
--- a/tests/l10n_tests.py
+++ b/tests/l10n_tests.py
@@ -114,6 +114,24 @@
self.assertIsNotEmpty(keys)
self.assertIn('en', keys)
+ def test_package_bundles(self):
+ """Test whether package bundles has valid entries."""
+ langs = i18n.known_languages()
+ self.assertIsInstance(langs, list)
+ self.assertIsNotEmpty(langs)
+ for dirname in i18n.bundles(stem=True):
+ for lang in langs:
+ with self.subTest(bundle=dirname, lang=lang):
+ bundle = i18n._get_bundle(lang, dirname)
+ if lang in ('en', 'qqq'):
+ self.assertIsNotEmpty(bundle)
+ for key in bundle.keys():
+ if key == '@metadata':
+ continue
+ self.assertTrue(key.startswith(dirname),
+ '{!r} does not start with {!r}'
+ .format(key, dirname))
+
if __name__ == '__main__': # pragma: no cover
with suppress(SystemExit):
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750712
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I9cb13bb215fadcb340b263748c3c21c115a95e9c
Gerrit-Change-Number: 750712
Gerrit-PatchSet: 6
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Legoktm <legoktm(a)debian.org>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750457 )
Change subject: [i18n] Make pywikibot messages available with site package.
......................................................................
[i18n] Make pywikibot messages available with site package.
There are several predefined messages with Pywikibot.
Use their translations with Pywikibot's site-package too.
- i18n pywikibot messages will be copied to pywikibot/scripts folder
when uploading to pypi to ensure this message are available
- set include_package_data to True in setup.py to ensure the external
i18n files are installed with the package
- use MANIFEST.in to copy the i18n files to the distribution
- remove fallbacks in bot.py, page/__init__.py and pagegenerators.py
- find the package directory with i18n module
- add Natural Languages to classifiers
- update documentation
Bug: T275981
Bug: T57109
Change-Id: I7b36c3d76516e0252b43557b02c70d87954d03d0
---
M CONTENT.rst
A MANIFEST.in
M docs/api_ref/pywikibot.config.rst
M docs/installation.rst
M pywikibot/CONTENT.rst
M pywikibot/bot.py
M pywikibot/i18n.py
M pywikibot/page/__init__.py
M pywikibot/pagegenerators.py
M pywikibot/scripts/__init__.py
M setup.py
11 files changed, 105 insertions(+), 17 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/CONTENT.rst b/CONTENT.rst
index 9e02e4b..e43f649 100644
--- a/CONTENT.rst
+++ b/CONTENT.rst
@@ -20,6 +20,8 @@
+---------------------------+-----------------------------------------------------------+
| LICENSE | Reference to the MIT license |
+---------------------------+-----------------------------------------------------------+
+ | MANIFEST.in | Setup file for package data |
+ +---------------------------+-----------------------------------------------------------+
| pwb.py | Code entry wrapper script (directory mode only) |
+---------------------------+-----------------------------------------------------------+
| README.rst | Short info string used by Pywikibot Nightlies |
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..0952697
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1 @@
+graft pywikibot/scripts/i18n/pywikibot
\ No newline at end of file
diff --git a/docs/api_ref/pywikibot.config.rst b/docs/api_ref/pywikibot.config.rst
index c31852a..f859921 100644
--- a/docs/api_ref/pywikibot.config.rst
+++ b/docs/api_ref/pywikibot.config.rst
@@ -18,6 +18,9 @@
:start-at: # ############# ACCOUNT SETTINGS
:end-before: # #############
+
+.. _user-interface-settings:
+
User Interface Settings
+++++++++++++++++++++++
@@ -39,6 +42,7 @@
:start-at: # ############# LOGFILE SETTINGS
:end-before: # #############
+
.. _external-script-path-settings:
External Script Path Settings
diff --git a/docs/installation.rst b/docs/installation.rst
index b943842..3bff88f 100644
--- a/docs/installation.rst
+++ b/docs/installation.rst
@@ -17,5 +17,26 @@
the site-package. For more settings use :mod:`generate_user_files` script
or refer :mod:`pywikibot.config`.
-.. note::
- Please also see the documentation at :manpage:`Installation`
+.. seealso:: :manpage:`Installation` Manual
+
+
+Internationalisation (i18n)
+---------------------------
+
+Some of the framework input interaction is translated. The user interface
+language to be used can be set as follows:
+
+#. set the `userinterface_lang` in your :ref:`user-config.py<user-interface-settings>` to your preferred language
+#. set environment variable `PYWIKIBOT_USERINTERFACE_LANG` to your preferred language
+#. default is obtained from `locale.getdefaultlocale`
+#. fallback is `'en'` for english if all other options fails
+
+.. note:: The preferred language code must follow ISO 639.
+.. versionadded:: 7.0
+ Added to site-package distribution
+.. seealso::
+ * :manpage:`i18n` Manual
+ * `MediaWiki Language Codes <https://www.mediawiki.org/wiki/Manual:Language#Language_code>`_
+ * :ref:`User Interface Settings<user-interface-settings>`
+ * :py:mod:`pywikibot.i18n`
+
diff --git a/pywikibot/CONTENT.rst b/pywikibot/CONTENT.rst
index 5342f9c..a9eed53 100644
--- a/pywikibot/CONTENT.rst
+++ b/pywikibot/CONTENT.rst
@@ -127,6 +127,8 @@
| version.py | Outputs Pywikibot's revision number, Python's |
| | version and OS used. |
+----------------------------+------------------------------------------------------+
+ | i18n (folder) | Contains i18n translations (site-package only) |
+ +----------------------------+------------------------------------------------------+
+----------------------------+------------------------------------------------------+
diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index d1e3699..aed6458 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -1104,8 +1104,7 @@
def open_webbrowser(page: 'pywikibot.page.BasePage') -> None:
"""Open the web browser displaying the page and wait for input."""
webbrowser.open(page.full_url())
- i18n.input('pywikibot-enter-finished-browser',
- fallback_prompt='Press Enter when finished in browser.')
+ i18n.input('pywikibot-enter-finished-browser')
class _OptionDict(dict):
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index 2dffea9..a4b738f 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -826,3 +826,7 @@
'Unable to load messages package {} for bundle {}'
.format(_messages_package_name, twtitle))
return pywikibot.input(prompt, password)
+
+
+if not messages_available():
+ set_messages_package('pywikibot.scripts.i18n')
diff --git a/pywikibot/page/__init__.py b/pywikibot/page/__init__.py
index 0552e50..3d82922 100644
--- a/pywikibot/page/__init__.py
+++ b/pywikibot/page/__init__.py
@@ -1322,8 +1322,7 @@
if self.exists():
# ensure always get the page text and not to change it.
del self.text
- summary = i18n.twtranslate(self.site, 'pywikibot-touch',
- fallback_prompt='Pywikibot touch edit')
+ summary = i18n.twtranslate(self.site, 'pywikibot-touch')
self.save(summary=summary, watch='nochange',
minor=False, botflag=botflag, force=True,
asynchronous=False, callback=callback,
diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py
index 54653cc..8178e16 100644
--- a/pywikibot/pagegenerators.py
+++ b/pywikibot/pagegenerators.py
@@ -685,9 +685,7 @@
:param category: category name with start parameter
"""
if not category:
- category = i18n.input(
- 'pywikibot-enter-category-name',
- fallback_prompt='Please enter the category name:')
+ category = i18n.input('pywikibot-enter-category-name')
category = category.replace('#', '|')
startfrom = None # type: Optional[str]
@@ -800,10 +798,7 @@
def _handle_filelinks(self, value: str) -> HANDLER_RETURN_TYPE:
"""Handle `-filelinks` argument."""
if not value:
- value = i18n.input(
- 'pywikibot-enter-file-links-processing',
- fallback_prompt='Links to which file page should be '
- 'processed?')
+ value = i18n.input('pywikibot-enter-file-links-processing')
if not value.startswith(self.site.namespace(6) + ':'):
value = 'Image:' + value
file_page = pywikibot.FilePage(self.site, value)
@@ -930,9 +925,7 @@
def _handle_interwiki(self, value: str) -> HANDLER_RETURN_TYPE:
"""Handle `-interwiki` argument."""
if not value:
- value = i18n.input(
- 'pywikibot-enter-page-processing',
- fallback_prompt='Which page should be processed?')
+ value = i18n.input('pywikibot-enter-page-processing')
page = pywikibot.Page(pywikibot.Link(value, self.site))
return InterwikiPageGenerator(page)
diff --git a/pywikibot/scripts/__init__.py b/pywikibot/scripts/__init__.py
index 4836696..03090c6 100644
--- a/pywikibot/scripts/__init__.py
+++ b/pywikibot/scripts/__init__.py
@@ -1,6 +1,7 @@
"""Folder which holds framework scripts.
-When uploading pywikibot to pypi the pwb.py (wrapper script) is copied here.
+When uploading pywikibot to pypi the pwb.py (wrapper script) and
+pywikibot i18n package are copied here.
.. versionadded:: 7.0
"""
diff --git a/setup.py b/setup.py
index e9164ee..840534a 100644
--- a/setup.py
+++ b/setup.py
@@ -6,10 +6,13 @@
- replace the developmental version string in ``pywikibot.__metadata__.py``
by the corresponing final release
+- copy pwb.py to pywikibot/scripts folder
+- copy scripts/i18n/pywikibot folder to pywikibot/scripts/i18n/pywikibot
- create the package with::
python setup.py sdist
+- remove copied files
- push the change to Gerrit and merge it to the repository
- upload the package to PyPy by::
@@ -256,6 +259,7 @@
download_url=metadata.__download_url__,
test_suite='tests.collector',
tests_require=test_deps,
+ include_package_data=True,
entry_points={
'console_scripts': [
'pwb = pywikibot.scripts.pwb:run',
@@ -266,7 +270,65 @@
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
+ 'Natural Language :: Afrikaans',
+ 'Natural Language :: Arabic',
+ 'Natural Language :: Basque',
+ 'Natural Language :: Bengali',
+ 'Natural Language :: Bosnian',
+ 'Natural Language :: Bulgarian',
+ 'Natural Language :: Cantonese',
+ 'Natural Language :: Catalan',
+ 'Natural Language :: Chinese (Simplified)',
+ 'Natural Language :: Chinese (Traditional)',
+ 'Natural Language :: Croatian',
+ 'Natural Language :: Czech',
+ 'Natural Language :: Danish',
+ 'Natural Language :: Dutch',
'Natural Language :: English',
+ 'Natural Language :: Esperanto',
+ 'Natural Language :: Finnish',
+ 'Natural Language :: French',
+ 'Natural Language :: Galician',
+ 'Natural Language :: German',
+ 'Natural Language :: Greek',
+ 'Natural Language :: Hebrew',
+ 'Natural Language :: Hindi',
+ 'Natural Language :: Hungarian',
+ 'Natural Language :: Icelandic',
+ 'Natural Language :: Indonesian',
+ 'Natural Language :: Irish',
+ 'Natural Language :: Italian',
+ 'Natural Language :: Japanese',
+ 'Natural Language :: Javanese',
+ 'Natural Language :: Korean',
+ 'Natural Language :: Latin',
+ 'Natural Language :: Latvian',
+ 'Natural Language :: Lithuanian',
+ 'Natural Language :: Macedonian',
+ 'Natural Language :: Malay',
+ 'Natural Language :: Marathi',
+ 'Natural Language :: Nepali',
+ 'Natural Language :: Norwegian',
+ 'Natural Language :: Panjabi',
+ 'Natural Language :: Persian',
+ 'Natural Language :: Polish',
+ 'Natural Language :: Portuguese',
+ 'Natural Language :: Portuguese (Brazilian)',
+ 'Natural Language :: Romanian',
+ 'Natural Language :: Russian',
+ 'Natural Language :: Serbian',
+ 'Natural Language :: Slovak',
+ 'Natural Language :: Slovenian',
+ 'Natural Language :: Spanish',
+ 'Natural Language :: Swedish',
+ 'Natural Language :: Tamil',
+ 'Natural Language :: Telugu',
+ 'Natural Language :: Thai',
+ 'Natural Language :: Tibetan',
+ 'Natural Language :: Turkish',
+ 'Natural Language :: Ukrainian',
+ 'Natural Language :: Urdu',
+ 'Natural Language :: Vietnamese',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750457
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I7b36c3d76516e0252b43557b02c70d87954d03d0
Gerrit-Change-Number: 750457
Gerrit-PatchSet: 3
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Euglou <eugbot31(a)gmail.com>
Gerrit-Reviewer: Lokal Profil <andre.costa(a)wikimedia.se>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged