Django Translation Files - Integrating legacy translations into .po files

Viewed 191

I have a legacy/non-django application where I have translation files that are in a different format from Django/gettext .po files. I would like to use all the strings in my Django application, but I would also like to continue using them in the existing application.

The format of the current system is:

  1. Every language has it's own file. (ie. en.txt, de.txt, fr.txt)
  2. Each line has a string translated in to it's own language
  3. When a string is used in application, the line number that matches that string is first found in en.txt and the same line is returned from the target language. So if the string was "hello world" and on line 5 of en.txt, the function would return line 5 of de.txt which would be "hallo welt".

What is the best way to use the old translation files within Django?

Here are a few ideas I've thought of

  1. Override the gettext system in Django to return my own translations
  2. Create my own template tags to handle translation
  3. Create a script to create .po files from the .txt files
1 Answers

For #1, I decided that overriding the internal Django TranslationCatalog was possible but appears undocumented and subject to change in the future. For example, if you wanted to add/override a translation, you could do the following:

from django.utils import translation

translation._trans._translations['de']._catalog._catalogs[1]['Hello World'] = 'Hallo Welt'

For #2, this would work just fine, but I would have to reimplement many of the features of the Django translation system if Django changed it's internal data structures.

For #3, this seemed the most viable since it would allow me to keep using the old text files, but have a script process them whenever something changed. Below is the generic version of what I created for us:

lans_dir = 'path/to/lans/files/'
lan_array = ['bg','ca','cs','da','de','el','en','es','fi','fr','hr','hu','it','ja','ko','nl','no','pb','pl','pt','ro','ru','sk','sr','sv','tr','tw','uk','zh']
lan_dict = {}

for lan_code in lan_array:
    line_list = []
    lan_file_name = os.path.join(lans_dir,f'{lan_code}.txt')
    with open(lan_file_name) as file_in:
        for line in file_in:
            line_strip = line.strip()
            line_list.append(line_strip)
    lan_dict[lan_code] = line_list

en_lines = lan_dict['en']
for lan_code in lan_array:
    path = os.path.join(f'locale/{lan_code}/LC_MESSAGES/django.po')
    with open(path, 'wt', encoding='utf-8') as file_out:
        for line_number, line in enumerate(lan_dict[lan_code]):
            file_out.write(f"#: en.txt:{line_number + 1}\n")
            file_out.write(f"msgid \"{en_line}\"\n")
            file_out.write(f"msgstr \"{line}\"\n\n")
Related