Traducció d'aplicacions PyGObject a diferents idiomes - Part 5


Continuem amb tu la sèrie de programació PyGObject i aquí, en aquesta 5a part, aprendrem a traduir les nostres aplicacions PyGObject a diferents idiomes. Traduir les vostres aplicacions és important si la publiqueu per al món, serà més fàcil d'utilitzar per als usuaris finals perquè no tothom entén l'anglès.

Com funciona el procés de traducció

Podem resumir els passos per traduir qualsevol programa a l'escriptori Linux mitjançant aquests passos:

  1. Extreu les cadenes traduïbles del fitxer Python.
  2. Deseu les cadenes en un fitxer .pot, amb un format que us permet traduir-lo més tard a altres idiomes.
  3. Comença a traduir les cadenes.
  4. Exporta les noves cadenes traduïdes a un fitxer .po que s'utilitzarà automàticament quan es canviï l'idioma del sistema.
  5. Afegiu alguns petits canvis programàtics al fitxer principal de Python i al fitxer .desktop.

I ja està! Després de fer aquests passos, la vostra aplicació estarà preparada per al seu ús per als usuaris finals de tot el món (hauràs de traduir el programa a tots els idiomes del món, però!), Sembla fàcil, no? :-)

Primer, per estalviar una mica de temps, descarregueu els fitxers del projecte des de l'enllaç següent i extreu el fitxer al vostre directori d'inici.

  1. https://copy.com/TjyZAaNgeQ6BB7yn

Obriu el fitxer \setup.py i observeu els canvis que hem fet:

# 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.

Obriu també el fitxer \myprogram i mireu els canvis programàtics que hem fet, tots els canvis s'expliquen als comentaris:

#!/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()

Ara... Comencem a traduir el nostre programa. Primer creeu el fitxer .pot (un fitxer que conté totes les cadenes traduïbles del programa) perquè pugueu
pot començar a traduir amb l'ordre següent:

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

Això crearà el fitxer \myprogram.pot dins de la carpeta \po a la carpeta principal del projecte que conté el codi següent:

# 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 >, 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 >\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 ""

Ara, per començar a traduir les cadenes, creeu un fitxer separat per a cada idioma al qual vulgueu traduir el programa mitjançant els codis d'idiomes \ISO-639-1 dins del \po”, per exemple, si voleu traduir el vostre programa a l'àrab, creeu un fitxer anomenat \ar.po i copieu-ne el contingut des del fitxer \myprogram.pot.

Si voleu traduir el vostre programa a l'alemany, creeu un fitxer \de.po i copieu el contingut del \myprogram.pot” a ell... i així un, heu de crear un fitxer per a cada idioma al qual voleu traduir el vostre programa.

Ara, treballarem amb el fitxer \ar.po, copiarem el contingut del fitxer \myprogram.pot i el posarem dins d'aquest fitxer i editarem el següent:

  1. ALGUN TÍTOL DESCRIPTIU: podeu introduir aquí el títol del vostre projecte si voleu.
  2. ANY DEL TITULAR DELS COPYRIGHTS DEL PAQUET: substituïu-lo per l'any en què heu creat el projecte.
  3. PAQUET: substituïu-lo pel nom del paquet.
  4. PRIMER AUTOR <[email >, ANY: substituïu-lo pel vostre nom real, correu electrònic i l'any en què heu traduït el fitxer.
  5. VERSIÓ DEL PAQUET: substituïu-la per la versió del paquet del fitxer debian/control.
  6. YEAR-MO-DA HO:MI+ZONE: no necessita explicació, pots canviar-ho a la data que vulguis.
  7. NOM COMPLET <[email >: també substituïu-lo pel vostre nom i correu electrònic.
  8. Language-Equip: substituïu-lo pel nom de l'idioma al qual esteu traduint, per exemple, \àrab o \francès.
  9. Idioma: aquí heu d'inserir el codi ISO-639-1 de l'idioma al qual esteu traduint, per exemple, \ar, \fr, \de ..etc, podeu trobar una llista completa aquí.
  10. CHARSET: aquest pas és important, substituïu aquesta cadena per \UTF-8 (sense cometes) que admet la majoria d'idiomes.

Ara comença a traduir! Afegiu la vostra traducció per a cada cadena després de les cometes a \msgstr. Deseu el fitxer i sortiu. Un bon fitxer de traducció per a
La llengua àrab com a exemple hauria de ser així:

# 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 "اضغط عليّ لفتح الطرفية"

No hi ha res més a fer, només cal empaquetar el programa amb l'ordre següent:

$ debuild -us -uc

Ara proveu d'instal·lar el nou paquet creat mitjançant l'ordre següent.

$ sudo dpkg -i myprogram_1.0_all.deb

I canvieu l'idioma del sistema amb el programa \Suport d'idiomes o amb qualsevol altre programa a l'àrab (o l'idioma al qual heu traduït el fitxer):

Després de seleccionar-lo, el vostre programa es traduirà a l'idioma àrab.

Aquí acaba la nostra sèrie sobre la programació de PyGObject per a l'escriptori Linux, per descomptat, hi ha moltes altres coses que podeu aprendre de la referència de l'API de Python GI.

Què en penseu de la sèrie? Ho trobes útil? Has pogut crear la teva primera aplicació seguint aquesta sèrie? Comparteix-nos els teus pensaments!