aboutsummaryrefslogtreecommitdiffstats
path: root/plasma_json/po2json.py
blob: 3b37580855c7d949d71afd9ffc293f975e0549e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import errno, glob, polib, re, os, getopt, sys
from time import strftime

def usage():
    print('\nUsage: python %s [OPTION]' %os.path.basename(sys.argv[0]))
    print('       generate pot catalogs and updates po files for json resources in the specified directory')
    print('Options: -h, --help                              : usage')
    print('         -d <directory>, --directory <directory> : directory with json files')
    sys.exit(2)
try:
    opts, args = getopt.getopt(sys.argv[1:], "hd:", ["help", "directory="])
except getopt.GetoptError:
    usage() # print help information and exit

directory='.'
for o,a in opts:
    if o in ("-h", "--help"):
        usage()
    if o in ("-d", "--directory"):
        directory=a

directory = directory.rstrip('/')

if (directory != '') and (os.path.isdir(directory) == False):
    sys.exit('Specified directory does not exist')

# Find all json files
files = []
for rootdir, dirnames, filenames in os.walk(directory):
    files.extend(glob.glob(rootdir + "/*.json"))

# Define Templates and po directory name
messagetemplate='(?<=\n)(\ *\"Name\".*?\n|\ *\"Description\".*?\n|\ *\"Keywords\".*?\n)'
mpattern=re.compile(messagetemplate,re.DOTALL)
translationtemplate='(?<=\n)(\ *\"Name\[.*?\n|\ *\"Description\[.*?\n|\ *\"Keywords\[.*?\n)'
tpattern=re.compile(translationtemplate,re.DOTALL)
podir = 'po'

# Write POT file
pot = polib.POFile('',check_for_duplicates=True)
potcreationtime = strftime('%Y-%m-%d %H:%M%z')
pot.metadata = {
  'Project-Id-Version': 'Mageia json files translation',
  'Report-Msgid-Bugs-To': 'i18n-discuss@ml.mageia.org',
  'POT-Creation-Date': potcreationtime,
  'PO-Revision-Date': 'YEAR-MO-DA HO:MI+ZONE',
  'Last-Translator': 'FULL NAME <EMAIL@ADDRESS>',
  'Language-Team': 'LANGUAGE <LL@li.org>',
  'MIME-Version': '1.0',
  'Content-Type': 'text/plain; charset=UTF-8',
  'Content-Transfer-Encoding': '8bit',
  }

for langfile in files:
  langfiledir = langfile.replace('.json', '')
  langfilename = langfiledir.rpartition('/')[2]
  # Create localization directories if needed
  try:
    os.makedirs(podir)
  except OSError as e:
    if e.errno != errno.EEXIST:
        raise
  #open json file
  text = open(langfile,"r").read()

  # Parse contents and add them to POT
  for mblock in mpattern.findall(text):
    mblock_stripped = mblock.strip('\n')
    message_comment, message_id = mblock.strip('\n').split(': ')
    message_comment = message_comment.strip('\"')
    message_id = message_id.strip('\"')
    potentry = polib.POEntry(
      msgctxt = message_comment.strip(' \"'),
      msgid = message_id.strip(' \",\n'),
      msgstr = '',
      occurrences=[(langfile,'')]
      )
    if message_id != '':
      try:
        pot.append(potentry)
      except ValueError:
        print('The entry already exists')
pot.save('./po/json.pot')

# Merge translations
for pofile in glob.glob(podir + '/*.po'):
  lang = pofile[:-3].rsplit('/',1)[1]
  pofilename = pofile
  po = polib.pofile(pofilename)
  po.merge(pot)
  po.save(pofilename)

for langfile in files:
  #open json file
  jsonfile = open(langfile,"r")
  text = jsonfile.read()
  jsonfile.close()
  jsonfile = open(langfile,"w")
  for transblock in tpattern.findall(text):
    text = text.replace(transblock, '')
  lines = text.split('\n')

  # Parse PO files
  for pofile in sorted(glob.glob(podir + '/*.po'), reverse = True):
    lang = pofile[:-3].rsplit('/',1)[1]
    pofilename = pofile
    po = polib.pofile(pofilename)
    for entry in po.translated_entries():
      for line in lines:
        if entry.msgid in line:
          indent = line.replace('\"' + entry.msgctxt + '\": \"' + entry.msgid + '\"', '').strip(',')
          origandtranslated = line + '\n' + indent + '\"' + entry.msgctxt + '[' + lang + ']' + '\": \"' + entry.msgstr + '\",'
          text = text.replace(line, origandtranslated)

  # Remove extra commas
  lines = text.split('\n')
  for line in lines:
    if  (line.endswith(',')) and ('}' in lines[lines.index(line) + 1]):
      text = text.replace(line, line[:-1])

  jsonfile.write(text)
  jsonfile.close()