Ricerca nel sito web

Tradurre le applicazioni PyGObject in diverse lingue – Parte 5


Continuiamo con te la serie di programmazione PyGObject e qui, in questa quinta parte, impareremo come tradurre le nostre applicazioni PyGObject in diversi linguaggi. Tradurre le tue applicazioni è importante se le pubblicherai per il mondo, sarà più facile da usare per gli utenti finali perché non tutti capiscono l'inglese.

Come funziona il processo di traduzione

Possiamo riassumere i passaggi per tradurre qualsiasi programma sul desktop Linux utilizzando questi passaggi:

  1. Estrai le stringhe traducibili dal file Python.
  2. Salva le stringhe in un file .pot che è un formato che ti consente di tradurlo successivamente in altre lingue.
  3. Inizia a tradurre le stringhe.
  4. Esporta le nuove stringhe tradotte in un file .po che verrà utilizzato automaticamente quando verrà cambiata la lingua del sistema.
  5. Aggiungi alcune piccole modifiche programmatiche al file Python principale e al file .desktop.

E questo è tutto! Dopo aver eseguito questi passaggi, la tua applicazione sarà pronta per l'uso per gli utenti finali di tutto il mondo (tuttavia... dovrai tradurre il tuo programma in tutte le lingue del mondo!), Sembra facile, vero? :-)

Innanzitutto, per risparmiare tempo, scarica i file di progetto dal link sottostante ed estrai il file nella tua home directory.

  1. https://copy.com/TjyZAaNgeQ6BB7yn

Apri il file “setup.py” e nota le modifiche che abbiamo apportato:

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.

Apri anche il file “myprogram” e guarda le modifiche programmatiche che abbiamo apportato, tutte le modifiche sono spiegate nei commenti:

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

Ora... iniziamo a tradurre il nostro programma. Per prima cosa crea il file .pot (un file che contiene tutte le stringhe traducibili nel programma) in modo da
può iniziare a tradurre utilizzando il seguente comando:

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

Questo creerà il file “myprogram.pot” all'interno della cartella “po” nella cartella principale del progetto che contiene il seguente codice:

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 ""

Ora per iniziare a tradurre le stringhe... Crea un file separato per ogni lingua in cui vuoi tradurre il tuo programma utilizzando i codici delle lingue "ISO-639-1" all'interno del file "po ", ad esempio, se vuoi tradurre il tuo programma in arabo, crea un file chiamato "ar.po " e copia il contenuto dalla cartella " mioprogramma.pot " al suo interno.

Se vuoi tradurre il tuo programma in tedesco, crea un file "de.po " e copia il contenuto da "myprogram.pot" file in esso... e quindi, devi creare un file per ogni lingua in cui vuoi tradurre il tuo programma.

Ora lavoreremo sul file “ar.po ”, copieremo il contenuto dal file “myprogram.pot ” e lo inseriremo all'interno di quel file e modificheremo quanto segue :

  1. ALCUNI TITOLI DESCRITTIVI: puoi inserire qui il titolo del tuo progetto, se lo desideri.
  2. ANNO DEL TITOLARE DEL COPYRIGHT DEL PACCHETTO: sostituiscilo con l'anno in cui hai creato il progetto.
  3. PACKAGE: sostituiscilo con il nome del pacchetto.
  4. PRIMO AUTORE , ANNO: sostituiscilo con il tuo vero nome, la tua email e l'anno in cui hai tradotto il file.
  5. VERSIONE PACCHETTO: sostituiscilo con la versione del pacchetto dal file debian/control.
  6. YEAR-MO-DA HO:MI+ZONE: non ha bisogno di spiegazioni, puoi cambiarlo con qualsiasi data tu voglia.
  7. NOME COMPLETO : sostituiscilo anche con il tuo nome e la tua email.
  8. Language-Team: sostituiscilo con il nome della lingua in cui stai traducendo, ad esempio "Arabo" o "Francese".
  9. Lingua: qui devi inserire il codice ISO-639-1 della lingua in cui stai traducendo, ad esempio “ar ”, “fr ”, “de ”..etc, puoi trovi un elenco completo qui.
  10. CHARSET: questo passaggio è importante, sostituisci questa stringa con "UTF-8" (senza virgolette) che supporta la maggior parte delle lingue.

Ora inizia a tradurre! Aggiungi la tua traduzione per ogni stringa dopo le virgolette in "msgstr". Salvare il file ed uscire. Un buon file di traduzione per
La lingua araba come esempio dovrebbe assomigliare a questa:

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

Non c'è altro da fare, basta impacchettare il programma utilizzando il seguente comando:

debuild -us -uc

Ora prova ad installare il nuovo pacchetto creato utilizzando il seguente comando.

sudo dpkg -i myprogram_1.0_all.deb

E cambia la lingua del sistema utilizzando il programma "Supporto lingue" o qualsiasi altro programma in arabo (o la lingua in cui hai tradotto il file):

Dopo la selezione, il tuo programma verrà tradotto in lingua araba.

Qui finisce la nostra serie sulla programmazione PyGObject per il desktop Linux, ovviamente ci sono molte altre cose che puoi imparare dalla documentazione ufficiale e dal riferimento API GI Python..

Cosa ne pensi della serie? Lo trovi utile? Sei riuscito a creare la tua prima applicazione seguendo questa serie? Condividici i tuoi pensieri!