Recherche de site Web

Traduction d’applications PyGObject dans différentes langues - Partie 5


Nous poursuivons avec vous la série de programmation PyGObject et ici, dans cette 5ème partie, nous allons apprendre à traduire nos applications PyGObject dans différentes langues. La traduction de vos applications est importante si vous voulez les publier pour le monde entier, ce sera plus convivial pour les utilisateurs finaux car tout le monde ne comprend pas l’anglais.

Comment fonctionne le processus de traduction

Nous pouvons résumer les étapes de la traduction de n’importe quel programme sous le bureau Linux en suivant ces étapes :

  1. Extrayez les chaînes traduisibles du fichier Python.
  2. Enregistrez les chaînes dans un fichier .pot qui est un format qui vous permet de les traduire ultérieurement dans d’autres langues.
  3. Commencez à traduire les chaînes.
  4. Exportez les nouvelles chaînes traduites dans un fichier .po qui sera automatiquement utilisé lorsque la langue du système sera modifiée.
  5. Ajoutez quelques petites modifications programmatiques au fichier Python principal et au fichier .desktop.

Et c’est tout ! Après avoir effectué ces étapes, votre application sera prête à être utilisée par les utilisateurs finaux du monde entier (will.. Vous devez traduire votre programme dans toutes les langues du monde, cependant !), Cela semble facile, n’est-ce pas ? :-)

Tout d’abord, pour gagner du temps, téléchargez les fichiers de projet à partir du lien ci-dessous et extrayez le fichier dans votre répertoire personnel.

  1. https://copy.com/TjyZAaNgeQ6BB7yn

Ouvrez le fichier « setup.py " et remarquez les modifications que nous avons apportées :

# Here we imported the 'setup' module which allows us to install Python scripts to the local system beside performing some other tasks, you can find the documentation here: https://docs.python.org/2/distutils/apiref.html
from distutils.core import setup

Those modules will help us in creating the translation files for the program automatically.
from subprocess import call
from glob import glob
from os.path import splitext, split

DON'T FOTGET TO REPLACE 'myprogram' WITH THE NAME OF YOUR PROGRAM IN EVERY FILE IN THIS PROJECT.

data_files = [ ("lib/myprogram", ["ui.glade"]), # This is going to install the "ui.glade" file under the /usr/lib/myprogram path.
                     ("share/applications", ["myprogram.desktop"]) ] 

This code does everything needed for creating the translation files, first it will look for all the .po files inside the po folder, then it will define the default path for where to install the translation files (.mo) on the local system, then it's going to create the directory on the local system for the translation files of our program and finally it's going to convert all the .po files into .mo files using the "msgfmt" command.
po_files = glob("po/*.po")
for po_file in po_files:
  lang = splitext(split(po_file)[1])[0]
  mo_path = "locale/{}/LC_MESSAGES/myprogram.mo".format(lang)
Make locale directories
  call("mkdir -p locale/{}/LC_MESSAGES/".format(lang), shell=True)
Generate mo files
  call("msgfmt {} -o {}".format(po_file, mo_path), shell=True)
  locales = map(lambda i: ('share/'+i, [i+'/myprogram.mo', ]), glob('locale/*/LC_MESSAGES'))

Here, the installer will automatically add the .mo files to the data files to install them later.
  data_files.extend(locales)

setup(name = "myprogram", # Name of the program.
      version = "1.0", # Version of the program.
      description = "An easy-to-use web interface to create & share pastes easily", # You don't need any help here.
      author = "TecMint", # Nor here.
      author_email = "[email ",# Nor here :D
      url = "http://example.com", # If you have a website for you program.. put it here.
      license='GPLv3', # The license of the program.
      scripts=['myprogram'], # This is the name of the main Python script file, in our case it's "myprogram", it's the file that we added under the "myprogram" folder.

Here you can choose where do you want to install your files on the local system, the "myprogram" file will be automatically installed in its correct place later, so you have only to choose where do you want to install the optional files that you shape with the Python script
      data_files=data_files) # And this is going to install the .desktop file under the /usr/share/applications folder, all the folder are automatically installed under the /usr folder in your root partition, you don't need to add "/usr/ to the path.

Ouvrez également le fichier « myprogram » et voyez les modifications programmatiques que nous avons effectuées, toutes les modifications sont expliquées dans les commentaires :

#!/usr/bin/python 
-*- coding: utf-8 -*- 

## Replace your name and email.
My Name <[email >

## Here you must add the license of the file, replace "MyProgram" with your program name.
License:
   MyProgram is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
#
   MyProgram is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
#
   You should have received a copy of the GNU General Public License
   along with MyProgram.  If not, see <http://www.gnu.org/licenses/>.

from gi.repository import Gtk 
import os, gettext, locale

## This is the programmatic change that you need to add to the Python file, just replace "myprogram" with the name of your program. The "locale" and "gettext" modules will take care about the rest of the operation.
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain('myprogram', '/usr/share/locale')
gettext.textdomain('myprogram')
_ = gettext.gettext
gettext.install("myprogram", "/usr/share/locale")

class Handler: 
  
  def openterminal(self, button): 
    ## When the user clicks on the first button, the terminal will be opened.
    os.system("x-terminal-emulator ")
  
  def closeprogram(self, button):
    Gtk.main_quit()
    
Nothing new here.. We just imported the 'ui.glade' file. 
builder = Gtk.Builder() 
builder.add_from_file("/usr/lib/myprogram/ui.glade") 
builder.connect_signals(Handler()) 

label = builder.get_object("label1")
Here's another small change, instead of setting the text to ("Welcome to my Test program!") we must add a "_" char before it in order to allow the responsible scripts about the translation process to recognize that it's a translatable string.
label.set_text(_("Welcome to my Test program !"))

button = builder.get_object("button2")
And here's the same thing.. You must do this for all the texts in your program, elsewhere, they won't be translated.
button.set_label(_("Click on me to open the Terminal"))


window = builder.get_object("window1") 
window.connect("delete-event", Gtk.main_quit)
window.show_all() 
Gtk.main()

Maintenant.. Commençons à traduire notre programme. Tout d’abord, créez le fichier .pot (un fichier qui contient toutes les chaînes traduisibles dans le programme) afin que
puisse commencer à traduire à l’aide de la commande suivante :

$ cd myprogram
xgettext --language=Python --keyword=_ -o po/myprogram.pot myprogram

Cela va créer le fichier « myprogram.pot » à l’intérieur du dossier « po » dans le dossier principal du projet qui contient le code suivant :

# SOME DESCRIPTIVE TITLE.
Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
This file is distributed under the same license as the PACKAGE package.
FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2014-12-29 21:28+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email >\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

#: myprogram:48
msgid "Welcome to my Test program !"
msgstr ""

#: myprogram:52
msgid "Click on me to open the Terminal"
msgstr ""

Maintenant, pour commencer à traduire les chaînes.. Créez un fichier séparé pour chaque langue dans laquelle vous souhaitez traduire votre programme en utilisant les codes de langues « ISO-639-1 » dans le dossier « po », par exemple, si vous souhaitez traduire votre programme en arabe, créez un fichier appelé « ar.po » et copiez le contenu du fichier « myprogram.pot » dans celui-ci.

Si vous souhaitez traduire votre programme en allemand, créez un fichier « de.po » et copiez le contenu du fichier « myprogram.pot » dans celui-ci. Et donc, vous devez créer un fichier pour chaque langue dans laquelle vous souhaitez traduire votre programme.

Maintenant, nous allons travailler sur le fichier « ar.po », copier le contenu du fichier « myprogram.pot » et le mettre à l’intérieur de ce fichier et modifier ce qui suit :

  1. TITRE DESCRIPTIF : vous pouvez entrer le titre de votre projet ici si vous le souhaitez.
  2. ANNÉE DU DÉTENTEUR DES DROITS D’AUTEUR DU PAQUET : REMPLACEZ-LE PAR L’ANNÉE DE CRÉATION DU PROJET.
  3. PACKAGE : remplacez-le par le nom du package.
  4. PREMIER AUTEUR <EMAIL@ADDRESS>, ANNÉE : remplacez-le par votre vrai nom, votre adresse e-mail et l’année où vous avez traduit le fichier.
  5. VERSION DU PAQUET : REMPLACEZ-LE PAR LA VERSION DU PAQUET DU FICHIER DEBIAN/CONTROL.
  6. YEAR-MO-DA HO :MI+ZONE : n’a pas besoin d’explication, vous pouvez le changer à n’importe quelle date que vous voulez.
  7. NOM COMPLET <EMAIL@ADDRESS> : remplacez-le également par votre nom et votre adresse e-mail.
  8. Language-Team : remplacez-le par le nom de la langue vers laquelle vous traduisez, par exemple « Arabe » ou « Français ».
  9. Langue : ici, vous devez insérer le code ISO-639-1 de la langue vers laquelle vous traduisez, par exemple « ar « , « fr « , « de « .. etc., vous pouvez trouver une liste complète ici.
  10. CHARSET : cette étape est importante, remplacez cette chaîne par « UTF-8 » (sans les guillemets) qui supporte la plupart des langues.

Maintenant, commencez à traduire ! Ajoutez votre traduction pour chaque chaîne après les guillemets dans « msgstr « . Enregistrez le fichier et quittez. Un bon fichier de traduction pour la langue arabe
par exemple devrait ressembler à ceci :

# My Program
Copyright (C) 2014
This file is distributed under the same license as the myprogram package.
Hanny Helal <[email <, 2014.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2014-12-29 21:28+0200\n"
"PO-Revision-Date: 2014-12-29 22:28+0200\n"
"Last-Translator: M.Hanny Sabbagh <hannysabbagh<@hotmail.com<\n"
"Language-Team: Arabic <[email <\n"
"Language: ar\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: myprogram:48
msgid "Welcome to my Test program !"
msgstr "أهلًا بك إلى برنامجي الاختباري!"

#: myprogram:52
msgid "Click on me to open the Terminal"
msgstr "اضغط عليّ لفتح الطرفية"

Il n’y a plus rien à faire, il suffit d’empaqueter le programme à l’aide de la commande suivante :

$ debuild -us -uc

Essayez maintenant d’installer le nouveau paquet créé à l’aide de la commande suivante.

$ sudo dpkg -i myprogram_1.0_all.deb

Et changez la langue du système à l’aide du programme « Language Support » ou à l’aide de n’importe quel autre programme en arabe (ou dans la langue dans laquelle vous avez traduit votre fichier) :

Après avoir sélectionné, votre programme sera traduit en langue arabe.

Ici se termine notre série sur la programmation PyGObject pour le bureau Linux, bien sûr, il y a beaucoup d’autres choses que vous pouvez apprendre de la documentation officielle et de la référence de l’API Python GI.

Que pensez-vous de la série ? Le trouvez-vous utile ? Avez-vous pu créer votre première application en suivant cette série ? Faites-nous part de vos réflexions !

Articles connexes: