Локализация

Added in version 1.1.

Complementary to translations provided for Sphinx-generated messages such as navigation bars, Sphinx provides mechanisms facilitating the translation of documents. See the Options for internationalization for details on configuration.

../../_images/translation.svg

Workflow visualization of translations in Sphinx. (The figure is created by plantuml.)

Детали локализации Sphinx

gettext [1] является установленным стандартом для интернационализации и локализации. Он просто сопоставляет сообщения в программе с переведенной строкой. Sphinx использует эти средства для полного перевода документов.

Initially project maintainers have to collect all translatable strings (also referred to as messages) to make them known to translators. Sphinx extracts these through invocation of sphinx-build -M gettext.

Каждый элемент в структуре документа (doctree) будет помещен в отдельное сообщение, в результате получается список фрагментов, которые будут равнозначны фрагментам исходного документа хотя большие абзацы будут оставаться столь же крупными. Это дает бесшовные обновления документа обеспечивая контекст для переводчиков в свободной части текста. Задача сопровождающего-разбить абзацы, которые слишком велики, так как нет вменяемого автоматизированного способа сделать это.

После успешного вызова класса MessageCatalogBuilder вы сможете найти набор файлов .pot в выходном каталоге. Они являются перечнем шаблонов и содержат сообщения только на языке оригинала.

Они могут быть предоставлены переводчикам, которые преобразуют их в файлы .po — которые называются каталогами сообщений — содержащими соответствие между оригинальными сообщениями и сообщениями на целевом языке.

gettext compiles them into a binary format known as binary catalogs through msgfmt for efficiency reasons. If you make these files discoverable with locale_dirs for your language, Sphinx will pick them up automatically.

An example: you have a document usage.rst in your Sphinx project. The gettext builder will put its messages into usage.pot. Imagine you have Spanish translations [2] stored in usage.po — for your builds to be translated you need to follow these instructions:

  • Скомпилируйте ваш каталог сообщений (po) в локальную директорию, скажем в locale. Так в результате двоичный каталог должен распологаться по адресу ./locale/es/LC_MESSAGES/usage.mo относительно исходной директории (здесь es является кодом Испанского языка)

    msgfmt "usage.po" -o "locale/es/LC_MESSAGES/usage.mo"
    
  • Установите параметр locale_dirs в ["locale/"].

  • Установите параметр language в es (так же возможно через командную строку -D).

  • Выполните необходимую сборку.

In order to protect against mistakes, a warning is emitted if cross-references in the translated paragraph do not match those from the original. This can be turned off globally using the suppress_warnings configuration variable. Alternatively, to turn it off for one message only, end the message with #noqa like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
risus tortor, luctus id ultrices at. #noqa

(Write \#noqa in case you want to have «#noqa» literally in the text. This does not apply to code blocks, where #noqa is ignored because code blocks do not contain references anyway.)

Added in version 4.5: The #noqa mechanism.

Перевод через sphinx-intl

Краткое руководство

sphinx-intl is a useful tool to work with Sphinx translation flow. This section describe an easy way to translate with sphinx-intl.

  1. Install sphinx-intl.

    $ pip install sphinx-intl
    
  2. Add configurations to conf.py.

    locale_dirs = ['locale/']   # path is example but recommended.
    gettext_compact = False     # optional.
    

    This case-study assumes that BUILDDIR is set to _build, locale_dirs is set to locale/ and gettext_compact is set to False (the Sphinx document is already configured as such).

  3. Extract translatable messages into pot files.

    $ make gettext
    

    The generated pot files will be placed in the _build/gettext directory.

  4. Generate po files.

    We’ll use the pot files generated in the above step.

    $ sphinx-intl update -p _build/gettext -l de -l ja
    

    Once completed, the generated po files will be placed in the below directories:

    • ./locale/de/LC_MESSAGES/

    • ./locale/ja/LC_MESSAGES/

  5. Translate po files.

    As noted above, these are located in the ./locale/<lang>/LC_MESSAGES directory. An example of one such file, from Sphinx, builders.po, is given below.

    # a5600c3d2e3d48fc8c261ea0284db79b
    #: ../../builders.rst:4
    msgid "Available builders"
    msgstr "<FILL HERE BY TARGET LANGUAGE>"
    

    В другом случае, если msgid содержит многострочный текст содержащий синтаксические конструкции reStructuredText:

    # 302558364e1d41c69b3277277e34b184
    #: ../../builders.rst:9
    msgid ""
    "These are the built-in Sphinx builders. More builders can be added by "
    ":ref:`extensions <extensions>`."
    msgstr ""
    "FILL HERE BY TARGET LANGUAGE FILL HERE BY TARGET LANGUAGE FILL HERE "
    "BY TARGET LANGUAGE :ref:`EXTENSIONS <extensions>` FILL HERE."
    

    Пожалуйста будьте осторожны и не ломайте конструкции reST. Большинство po-редакторов поможет вам в этом.

  6. Build translated document.

    You need a language parameter in conf.py or you may also specify the parameter on the command line.

    For BSD/GNU make, run:

    $ make -e SPHINXOPTS="-D language='de'" html
    

    For Windows cmd.exe, run:

    > set SPHINXOPTS=-D language=de
    > .\make.bat html
    

    For PowerShell, run:

    > Set-Item env:SPHINXOPTS "-D language=de"
    > .\make.bat html
    

Поздравляем! Теперь ваша переведенная документация находится в каталоге _build/html.

Added in version 1.3: sphinx-build that is invoked by make command will build po files into mo files.

If you are using 1.2.x or earlier, please invoke sphinx-intl build command before make command.

Перевод

Обновите ваши po-файлы из новых файлов pot

If a document is updated, it is necessary to generate updated pot files and to apply differences to translated po files. In order to apply the updates from a pot file to the po file, use the sphinx-intl update command.

$ sphinx-intl update -p _build/gettext

Использование сервиса Transifex для работы в команде

Transifex один из нескольких сервисов предоставляющих возможность совместной работы над переводами через web-интерфейс. Он имеет прекрасный Python-подобный клиент командной строки облегчающий получение и отправку переводов.

  1. Install transifex-client.

    Выполните команду tx для загрузки ваших ресурсов (файлов pot).

    $ pip install transifex-client
    
  2. Create your Transifex account and create new project for your document.

    Currently, Transifex does not allow for a translation project to have more than one version of the document, so you’d better include a version number in your project name.

    Например:

    ID проекта:

    sphinx-document-test_1_0

    URL проекта:

    https://www.transifex.com/projects/p/sphinx-document-test_1_0/

  3. Create config files for tx command.

    Этот процесс создаст .tx/config в текущей директории, а так же файл ~/.transifexrc содержащий информацию для авторизации.

    $ tx init
    Creating .tx folder...
    Transifex instance [https://www.transifex.com]:
    ...
    Please enter your transifex username: <transifex-username>
    Password: <transifex-password>
    ...
    Done.
    
  4. Upload pot files to Transifex service.

    Зарегистрируйте файлы pot в файле .tx/config:

    $ cd /your/document/root
    $ sphinx-intl update-txconfig-resources --pot-dir _build/locale \
      --transifex-project-name sphinx-document-test_1_0
    

    и загрузите файлы pot:

    $ tx push -s
    Pushing translations for resource sphinx-document-test_1_0.builders:
    Pushing source file (locale/pot/builders.pot)
    Resource does not exist.  Creating...
    ...
    Done.
    
  5. Forward the translation on Transifex.

  6. Pull translated po files and make translated HTML.

    Get translated catalogs and build mo files. For example, to build mo files for German (de):

    $ cd /your/document/root
    $ tx pull -l de
    Pulling translations for resource sphinx-document-test_1_0.builders (...)
     -> de: locale/de/LC_MESSAGES/builders.po
    ...
    Done.
    

    Invoke make html (for BSD/GNU make):

    $ make -e SPHINXOPTS="-D language='de'" html
    

И всё!

Совет

Локальный перевод и перевод на Transifex

If you want to push all language’s po files, you can be done by using tx push -t command. Watch out! This operation overwrites translations in Transifex.

Другими словами, если вы обновили каждый из файлов на сервисе и локальные po-файлы, может потребоваться много времени и сил чтобы объединить их.

Using Weblate service for team translation

Read more in Weblate’s documentation.

Участие в переводе справочной информации Sphinx

Рекомендованным способом для новых переводчиков справочной информации Sphinx, является участие в команде переводчиков на Transifex.

There is a sphinx translation page for Sphinx (master) documentation.

  1. Login to Transifex service.

  2. Перейдите на страницу переводов sphinx.

  3. Кликните Запрос языка и заполните форму.

  4. Wait acceptance by Transifex sphinx translation maintainers.

  5. (After acceptance) Translate on Transifex.

Detail is here: https://docs.transifex.com/getting-started-1/translators

Translation progress and statistics

Added in version 7.1.0.

During the rendering process, Sphinx marks each translatable node with a translated attribute, indicating if a translation was found for the text in that node.

The translation_progress_classes configuration value can be used to add a class to each element, depending on the value of the translated attribute.

The |translation progress| substitution can be used to display the percentage of nodes that have been translated on a per-document basis.

Сноски