Last active
November 25, 2017 19:53
-
-
Save nitely/60deca44680704a6f28e to your computer and use it in GitHub Desktop.
Django split big locale file into locales for every app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Before running this script: | |
* move all locale folders (en, es, pl, etc) to ./locales, these are the big (original) .po files. | |
* create a locale folder in every app, then run 'django-admin makemessages -l xx' (where xx is every language) | |
* move the project root (the one containing the apps) to ./spirit | |
* run this script | |
* you should get all the django.po translated from the original locale files (those in the ./locales folder) | |
""" | |
if __name__ == '__main__': | |
import polib | |
import os | |
# Parse original locales | |
poss_org = {} | |
for root, dir, files in os.walk("./locales"): | |
if 'django.po' not in files: | |
continue | |
path = os.path.join(root, 'django.po') | |
_, lang = os.path.split(os.path.split(root)[0]) # ../en/LC_MESSAGES | |
poss_org[lang] = polib.pofile(path) | |
# Parse new locales (en) | |
poss = {} | |
for root, dir, files in os.walk("./spirit"): | |
if 'django.po' not in files: | |
continue | |
path = os.path.join(root, 'django.po') | |
_, lang = os.path.split(os.path.split(root)[0]) # ../en/LC_MESSAGES | |
poss[(lang, root)] = polib.pofile(path) | |
# Create new locales | |
metadata = { | |
'Project-Id-Version': 'Spirit', | |
'Report-Msgid-Bugs-To': '', | |
'POT-Creation-Date': '2015-07-25 18:00+0000', | |
'PO-Revision-Date': '2015-07-25 18:00+0000', | |
'Last-Translator': 'Author <[email protected]>', | |
'Language-Team': 'Spirit', | |
'MIME-Version': '1.0', | |
'Content-Type': 'text/plain; charset=utf-8', | |
'Content-Transfer-Encoding': '8bit', | |
} | |
for (lang, root), po in poss.items(): | |
messages = {entry.msgid: entry.msgstr for entry in poss_org[lang] if entry.translated()} # ignore fuzzy | |
po_out = polib.POFile() | |
po_out.metadata = metadata | |
for entry in po: | |
new_entry = polib.POEntry( | |
msgid=entry.msgid, | |
msgstr=messages.get(entry.msgid, "") | |
) | |
po_out.append(new_entry) | |
path = os.path.join(root, 'new_django.po') | |
po_out.save(path) | |
# cleanup | |
for root, dir, files in os.walk("./spirit"): | |
if 'django.po' not in files: | |
continue | |
os.remove(os.path.join(root, 'django.po')) | |
os.rename(os.path.join(root, 'new_django.po'), os.path.join(root, 'django.po')) | |
print("ok") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment