forked from rogermolas/csv-localizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv-localizer
executable file
·278 lines (227 loc) · 10.1 KB
/
csv-localizer
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python
import sys, argparse, logging, os, csv
PLATFORM = None
IN_PATH = None
OUT_PATH = None
DELIMITER = None
LANG_KEYS = None # static will change later
# Gather our code in a main() function
def main(args, loglevel):
logging.basicConfig(format="%(message)s", level=loglevel)
PLATFORM = args.platform
IN_PATH = args.input
OUT_PATH = args.output
DELIMITER = args.delimiter
# check DELIMITER
if args.delimiter == None : DELIMITER = ','
print '\n'
logging.info("Start Localizing .... ")
print '\n'
logging.info("------------------------------------")
# check source path
logging.debug("\n")
logging.debug("Validating source path ...")
logging.debug("\n")
if not os.path.exists(IN_PATH):
logging.error('Source path not found, Invalid path.')
logging.debug("\n")
return
logging.debug("Valid source path, finding csv file ...")
logging.debug("\n")
logging.debug("Validating target path ...")
logging.debug("\n")
# check output path
if not os.path.exists(OUT_PATH):
logging.error('Target path not found, Invalid path.')
logging.debug("\n")
return
logging.debug("Valid target path, generating output directory ...")
logging.debug("\n")
# generate output directory
OUTPUT_DIR = os.path.join(OUT_PATH, "output")
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
logging.debug("Output directory generated : %s" % OUTPUT_DIR)
logging.debug("\n")
else:
logging.debug("Using output directory: %s" % OUTPUT_DIR)
logging.debug("\n")
logging.debug("\n")
if PLATFORM == "ios":
logging.debug("Platform : %s" % PLATFORM)
elif PLATFORM == "android":
logging.debug("Platform : %s" % PLATFORM)
elif PLATFORM == "json":
logging.debug("Platform : %s" % PLATFORM)
else:
logging.warn("Invalid platform, platform should be ios, android, json only")
logging.debug("\n")
logging.error('ERROR LOCALIZING.\n')
return
logging.info("Generated output directory: %s" % OUTPUT_DIR)
generate_keys(IN_PATH, OUTPUT_DIR, PLATFORM, DELIMITER)
print '\n'
logging.info("DONE LOCALIZING.\n")
def generate_keys(source_path, output, platform, delimiter):
base_out_dir = output
full_out_paths = None
allwrites = None
for dirname, dirnames, filenames in os.walk(source_path):
for f in filenames:
filename, ext = os.path.splitext(f)
if ext != '.csv':
continue
fullpath = os.path.join(dirname, f)
with open(fullpath, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=delimiter)
# create language key
for i, line in enumerate(reader):
if i == 0:
line.remove(line[0])
LANG_KEYS = line # assign new value to key
# iterate each language
lang_path = ""
for lang in LANG_KEYS:
if platform == "ios":
lang_path = os.path.join(base_out_dir, "{0}.lproj/".format(lang))
if platform == "android":
lang_path = os.path.join(base_out_dir, "values-{0}/".format(lang))
if platform == "json":
lang_path = os.path.join(base_out_dir, "{0}/".format(lang))
# Generate directory per language key
if not os.path.exists(lang_path):
os.makedirs(lang_path)
if platform == "ios":
full_out_paths = [os.path.join(base_out_dir, "{0}.lproj/".format(langKey) + "Localizable.strings") for langKey in LANG_KEYS]
if platform == "android":
full_out_paths = [os.path.join(base_out_dir, "values-{0}/".format(langKey) + "strings.xml") for langKey in LANG_KEYS]
if platform == "json":
full_out_paths = [os.path.join(base_out_dir, "{0}/".format(langKey) + "{0}_message.json".format(langKey)) for langKey in LANG_KEYS]
allwrites = [open(out_path, 'w') for out_path in full_out_paths]
if platform == "ios":
start_localize_ios(source_path, allwrites, LANG_KEYS, delimiter)
if platform == "android":
start_localize_android(source_path, allwrites, LANG_KEYS, delimiter)
if platform == "json":
start_localize_json(source_path, allwrites, LANG_KEYS, delimiter)
# =========================================================================
# ++++++++++++++++++++++++++++++ iOS ++++++++++++++++++++++++++++++++++++++
# =========================================================================
def start_localize_ios(source_path, all_writes, lang_keys, delimiter):
allwrites = all_writes
for dirname, dirnames, filenames in os.walk(source_path):
for f in filenames:
filename, ext = os.path.splitext(f)
if ext != '.csv':
continue
fullpath = os.path.join(dirname, f)
logging.info("Localizing: %s to iOS", filename)
with open(fullpath, 'rb') as csvfile:
[fwrite.write('\n/* {0} */\n'.format(filename)) for fwrite in allwrites]
reader = csv.reader(csvfile, delimiter=delimiter)
iterrows = iter(reader)
next(iterrows) # skip first line (it is header).
for row in iterrows:
row_key = row[0].replace(" ", "")
# comment
if row_key[:2] == '//':
continue
row_values = [row[i+1] for i in range(len(lang_keys))]
# if any row is empty, skip it!
if any([value == "" for value in row_values]):
[fwrite.write('\n') for idx, fwrite in enumerate(allwrites)]
else:
[fwrite.write('"{key}" = "{lang}";\n'.format(key=row_key, lang=row_values[idx]))
for idx, fwrite in enumerate(allwrites)]
[fwrite.close() for fwrite in allwrites]
# =========================================================================
# ++++++++++++++++++++++++++++++ Android ++++++++++++++++++++++++++++++++++
# =========================================================================
def start_localize_android(source_path, all_writes, lang_keys, delimiter):
allwrites = all_writes
[fwrite.write('<?xml version="1.0" encoding="utf-8"?>\n') for fwrite in allwrites]
[fwrite.write('<resources>') for fwrite in allwrites]
for dirname, dirnames, filenames in os.walk(source_path):
for f in filenames:
filename, ext = os.path.splitext(f)
if ext != '.csv':
continue
fullpath = os.path.join(dirname, f)
logging.info("Localizing: %s to Android", filename)
with open(fullpath, 'rb') as csvfile:
[fwrite.write('\n<!-- {0} -->\n'.format(filename)) for fwrite in allwrites]
reader = csv.reader(csvfile, delimiter=delimiter)
iterrows = iter(reader)
next(iterrows) # skip first line (it is header).
for row in iterrows:
row_key = row[0].replace(" ", "")
# comment
if row_key[:2] == '//':
continue
row_values = [row[i+1] for i in range(len(lang_keys))]
# if any row is empty, skip it!
if any([value == "" for value in row_values]):
[fwrite.write('\n') for idx, fwrite in enumerate(allwrites)]
else:
[fwrite.write('\t<string name="{key}">{lang}</string>\n'.format(key=row_key, lang=row_values[idx]))
for idx, fwrite in enumerate(allwrites)]
[fwrite.write('</resources>') for fwrite in allwrites]
[fwrite.close() for fwrite in allwrites]
# =========================================================================
# ++++++++++++++++++++++++++++++ iOS ++++++++++++++++++++++++++++++++++++++
# =========================================================================
def start_localize_json(source_path, all_writes, lang_keys, delimiter):
allwrites = all_writes
[fwrite.write('{') for fwrite in allwrites]
for dirname, dirnames, filenames in os.walk(source_path):
for f in filenames:
filename, ext = os.path.splitext(f)
if ext != '.csv':
continue
fullpath = os.path.join(dirname, f)
logging.info("Localizing: %s to JSON", filename)
current_row = 0
with open(fullpath, 'rb') as csvfile:
[fwrite.write('\n/* {0} */\n'.format(filename)) for fwrite in allwrites]
reader = csv.reader(csvfile, delimiter=delimiter)
iterrows = iter(reader)
next(iterrows) # skip first line (it is header).
list_data = list(iterrows)
for row in list_data:
row_key = row[0].replace(" ", "")
# comment
if row_key[:2] == '//':
continue
row_values = [row[i+1] for i in range(len(lang_keys))]
separator = ", \n"
# check if last row then remove ';'
if current_row == len(list_data) - 1:
separator = "\n"
current_row += 1 # iterate row count
# if any row is empty, skip it!
if any([value == "" for value in row_values]):
[fwrite.write('\n') for idx, fwrite in enumerate(allwrites)]
else:
[fwrite.write('"{key}": "{lang}"{separator}'.format(key=row_key, lang=row_values[idx], separator=separator))
for idx, fwrite in enumerate(allwrites)]
[fwrite.write('}') for fwrite in allwrites]
[fwrite.close() for fwrite in allwrites]
# =========================================================================
# +++++++ Standard boilerplate to call the main() function to begin +++++++
# =========================================================================
parser = argparse.ArgumentParser(description="Locatization commands")
parser.add_argument("-p", help="Specify Platform (iOS, Android)", dest="platform", type=str, required=True)
parser.add_argument("-i", help="Input source, CSV file path", dest="input", type=str, required=True)
parser.add_argument("-o", help="Generated output path for localizable files", dest="output", type=str, required=True)
parser.add_argument("-d", help="Delimiter used as seperation of values in the CSV file (example ':' or ',')", dest="delimiter", type=str, required=False)
parser.add_argument("-v",
"--verbose",
help="increase output verbosity",
action="store_true")
args = parser.parse_args()
# Setup logging
if args.verbose:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
main(args, loglevel)