-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n
executable file
·491 lines (390 loc) · 17 KB
/
i18n
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#!/usr/bin/env python3
import argparse
from io import StringIO
import json
import os
from pathlib import Path
import re
import sys
from typing import Dict, List
from googletrans import Translator
import jinja2
import yaml
from settings import (
INDENT,
TOP_DIR,
HELP_MESSAGE,
CHARACTER_CODE,
EXPORT_FILE_NAME,
FIRST_COLUMN_NAME,
TABLE_TEMPLATE_PATH,
)
RED = "\033[1;31m"
CYAN = "\033[1;36m"
WHITE = "\033[1;37m"
NO_COLOR = "\033[0m"
class LanguageSegmenter:
"""Segment translation files by language
Variables:
languages (list): Target languages
base_data (dict): Base translation data
segmented_data (dict): Segmented translation data
breadcrumb_list (list): Breadcrumb list
"""
languages = []
base_data = {}
segmented_data = {}
breadcrumb_list = []
def __init__(self, languages: List[str], import_file_name: str) -> None:
"""Initialization. Acquisition of translation data and storage in class variables.
Args:
languages (List[str]): Selection of the language described in the yaml file
import_file_name (str): Used to read yaml file
"""
self.languages = languages
self.string_table = ''
LanguageSegmenter.languages = self.languages
# Reads and assigns translation files
with open(import_file_name, 'r', encoding=CHARACTER_CODE) as translation_file:
LanguageSegmenter.base_data = yaml.safe_load(translation_file)
def __call__(self) -> None:
"""Segment translation files and create/store breadcrumb lists"""
# Segment the translation data from the given Languages into their respective languages
[self.Processer(language) for language in self.languages]
# Also create a breadcrumb list from the translation data
self.BreadcrumbListGenerator(self.languages[0])
def write_segmented_data(self, directory: str) -> None:
"""Create directory and write files for segmented translation files
Args:
directory (str): Top directory for directory creation and file writing
"""
for language in self.languages:
locales_path = os.path.join(directory, language)
os.makedirs(locales_path, exist_ok=True)
with open(os.path.join(locales_path, EXPORT_FILE_NAME), 'w') as translation_file:
json.dump(
fp=translation_file,
obj=LanguageSegmenter.segmented_data[language],
indent=INDENT,
ensure_ascii=False,
)
def _get_value(self, data: Dict[str, any], path: str, language: str) -> any:
"""Retrieve hierarchical data data from a path
Args:
data (Dict[str, any]): Data traced by the path
path (str): Paths connected by dots
language (str): Language to be retrieved from data
Returns:
any: It is the type of data for the translation.
"""
for key in path.split('.'):
data = data[key]
return data[language]
def generate_table(self) -> None:
"""Create a table from the segmented translation data"""
table_data = {}
io = StringIO()
for path in LanguageSegmenter.breadcrumb_list:
table_data[path] = {}
for language in self.languages:
data = segmenter._get_value(
path=path,
data=LanguageSegmenter.base_data,
language=language,
)
json.dump(obj=data, fp=io, indent=INDENT, ensure_ascii=False)
string_data = io.getvalue()
table_data[path][language] = string_data
io.truncate(0)
io.seek(0)
io.close()
data_for_template = {
"languages": self.languages,
"columns": [FIRST_COLUMN_NAME] + self.languages,
"data": table_data,
}
environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(TOP_DIR, encoding=CHARACTER_CODE)
)
template = environment.get_template(TABLE_TEMPLATE_PATH)
html_table = template.render(data_for_template)
self.string_table = html_table
def output_table(self) -> None:
"""Output a table."""
print(self.string_table)
def write_table(self, file_name: str) -> None:
"""Writing to a table file.
Args:
file_name (str): File name for writing the table
"""
with open(file_name, 'w', encoding=CHARACTER_CODE) as f:
f.write(self.string_table)
class Processer:
"""Processing class for segmenting translation data"""
def __init__(self, language: str):
"""Initialize variables and segment translation data.
Args:
language (str): Target language
"""
self.language = language
self.result = {} # Stores data only in the language of the argument
self.before_key = '' # Variables for error output. Often contains the last key.
self.before_than_before = '' # The key before the last one is entered.
self.error_count = 0
self._segmenter(LanguageSegmenter.base_data)
LanguageSegmenter.segmented_data[self.language] = self.result
if self.error_count > 0:
sys.exit(self.error_count)
def _error(self, message: str) -> None:
"""Methods for colored error output
Args:
message (str): Error message
"""
print("%sERROR%s: %s%s" % (RED, WHITE, message, NO_COLOR), file=sys.stderr)
def _segmenter(self, translation_data: Dict[str, any]) -> Dict[str, any]:
"""Methods to segment translation data by specific language
Args:
translation_data (Dict[str, any]): Target translation data
Returns:
Dict[str, any]: It is the type of data for the translation.
"""
element = {}
try:
for key, value in translation_data.items():
if self.language in value:
element[key] = value[self.language]
continue
if key not in LanguageSegmenter.languages:
self.before_key = key
element[key] = self._segmenter(value)
self.result = element
return element
except AttributeError: # Output missing elements in a particular language
if self.before_key != self.before_than_before:
error_message = 'The %s"%s"%s element of %s"%s"%s is missing.' % (
CYAN, self.before_key, WHITE, CYAN, self.language, WHITE,
)
self._error(error_message)
self.before_than_before = self.before_key
self.error_count += 1
class BreadcrumbListGenerator:
"""Classes for creating breadcrumb lists"""
def __init__(self, base_language: str) -> None:
"""Initialize variables and create a breadcrumb list.
Args:
base_language (str): Reference language
"""
self.base_language = base_language
self._generate_breadcrumb_list(LanguageSegmenter.base_data)
def _generate_breadcrumb_list(self, data: Dict[str, any], parent: str = None) -> None:
"""Methods for creating breadcrumb lists
Args:
data (Dict[str, any]): Each element
parent (str, optional): Previous paths. Defaults to None.
"""
for key, value in data.items():
if self.base_language in value:
path = key if parent is None else "%s.%s" % (parent, key)
LanguageSegmenter.breadcrumb_list.append(path)
continue
path = key if parent is None else "%s.%s" % (parent, key)
self._generate_breadcrumb_list(value, parent=path)
class ReverseGenerator:
"""Reverse generated class from Json file"""
def __init__(
self,
file_name: str,
directory: str,
addtional_language: str = None,
automatic_translation: bool = None,
) -> None:
"""Initialize variables.
Args:
addtional_language (str, optional): Language to be added. Defaults to None.
file_name (str): Translation file name
directory (str): Directory containing translation files
"""
self.directory = directory
self.file_name = file_name
self.addtional_language = addtional_language
self.automatic_translation = False if not automatic_translation else True
self.generated_data = ''
def __call__(self) -> None:
"""Call method"""
self._reverse_generation()
def _generate_data(self) -> any:
"""Combine each translation data into a single array
Returns:
any: Returns base path and summarized data
"""
directory_path = Path(self.directory)
translation_file_paths = list(directory_path.glob("**/%s" % self.file_name))
languages = []
base_count = 0
base_paths = []
path_and_element_array = []
for translation_file_path in translation_file_paths:
language = str(translation_file_path).split('/')[-2]
languages.append(language)
with open(translation_file_path, 'r', encoding=CHARACTER_CODE) as translation_file:
translation_data = json.load(translation_file)
data_splitter = self.DataSplitter(translation_data)
path_and_element = data_splitter()
io = StringIO()
for path, element in path_and_element:
json.dump(obj=element, fp=io, indent=4, ensure_ascii=False)
string_element = io.getvalue()
path = "%s.%s" % (path, language)
path_and_element_array.append((path, string_element))
if base_count == 0:
base_paths.append(path)
io.truncate(0)
io.seek(0)
base_count += 1
return (base_paths, path_and_element_array)
def _sort(self) -> List[tuple]:
"""Methods to sort languages so that they are grouped into their respective elements
Returns:
List[tuple]: Sorted data
"""
translator = Translator()
sorted_path_and_element = []
base_paths, path_and_element_array = self._generate_data()
for base_path in base_paths:
for path, element in path_and_element_array:
if path.split('.')[:-1] != base_path.split('.')[:-1]:
continue
sorted_path_and_element.append((path, element))
if not self.addtional_language:
continue
if base_path == path:
splited_element = element.split('\n')
for line in splited_element:
match = re.search(r'"(.*)"', line)
if match is None:
continue
string_to_be_replaced = match.group(1)
# TODO: Add a process to exclude paths you do not want translated
if self.automatic_translation:
translated_data = translator.translate(
text=string_to_be_replaced,
dest=self.addtional_language,
).text
element = element.replace(string_to_be_replaced, translated_data)
else:
element = element.replace(string_to_be_replaced, '')
path = "%s.%s" % ('.'.join(path.split('.')[:-1]), self.addtional_language)
sorted_path_and_element.append((path, element))
return sorted_path_and_element
def _reverse_generation(self) -> None:
"""Methods for reverse generation"""
sorted_path_and_element = self._sort()
before = []
for string_breadcrumb_list, element_value in sorted_path_and_element:
breadcrumb_list = string_breadcrumb_list.split('.')
same_paths = list(set(before) & set(breadcrumb_list))
same_path_indexes = [breadcrumb_list.index(same_path) for same_path in same_paths]
for index, path in enumerate(breadcrumb_list):
if index in same_path_indexes:
continue
string_indent = index * (' ' * INDENT)
if (len(breadcrumb_list) - 1) == index:
element_value = element_value.replace('\n', "\n%s" % string_indent)
self.generated_data += "%s%s: %s\n" % (string_indent, path, element_value)
continue
self.generated_data += "%s%s:\n" % (string_indent, path)
before = breadcrumb_list
def write(self, file_name: str) -> None:
"""Write method for reverse-generated files
Args:
file_name (str): File name for writing
"""
with open(file_name, 'w', encoding=CHARACTER_CODE) as f:
f.write(self.generated_data)
class DataSplitter:
"""Class that performs data partitioning"""
def __init__(self, data: any) -> None:
"""Initialize variables.
Args:
data (any): Translation data
"""
self.data = data
self.paths = []
def splitter(self, data: any, parent: str) -> None:
"""Methods for splitting
Args:
data (any): Each element
parent (str): Previous paths
"""
for key, value in data.items():
path = "%s.%s" % (parent, key) if parent else key
if isinstance(value, dict):
self.splitter(value, path)
else:
self.paths.append([path, value])
def __call__(self) -> None:
"""Split data"""
self.splitter(self.data, '')
return self.paths
if __name__ == "__main__":
# Help Command
if sys.argv[1] == "help":
print(HELP_MESSAGE)
sys.exit(0)
# TODO: Add description and help
parser = argparse.ArgumentParser(description='')
subparsers = parser.add_subparsers()
# Segment Command
segment = subparsers.add_parser("segment", help='')
segment.add_argument("--file", "-f", type=str, help='')
segment.add_argument("--output", "-o", type=str, help='')
segment.add_argument("--languages", "-l", type=str, nargs='+', help='')
segment.set_defaults(handler=LanguageSegmenter)
# Reverse Generation Command
revgene = subparsers.add_parser("revgene", help='')
revgene.add_argument("--file", "-f", type=str, help='')
revgene.add_argument("--output", "-o", type=str, help='')
revgene.add_argument("--directory", "-d", type=str, help='')
revgene.add_argument("--addtional_language", "-al", type=str, help='')
revgene.add_argument("--automatic_translation", "-at", action="store_true", help='')
revgene.set_defaults(handler=RecursionError)
# Table Command
table = subparsers.add_parser("table", help='')
table.add_argument("--file", "-f", type=str, help='')
table.add_argument("--output", "-o", type=str, help='')
table.add_argument("--show", "-s", action="store_true", help='')
table.add_argument("--languages", "-l", type=str, nargs='+', help='')
table.set_defaults(handler=LanguageSegmenter)
args = parser.parse_args()
if not hasattr(args, "handler"):
print(HELP_MESSAGE)
exit(1)
# Segment Command
if sys.argv[1] == "segment":
segmenter = LanguageSegmenter(languages=args.languages, import_file_name=args.file)
segmenter()
if args.output:
segmenter.write_segmented_data(directory=args.output)
exit(0)
# Reverse Generation Command
if sys.argv[1] == "revgene":
reverse_generator = ReverseGenerator(
file_name=args.file,
directory=args.directory,
addtional_language=args.addtional_language,
automatic_translation=args.automatic_translation,
)
reverse_generator()
if args.output:
reverse_generator.write(args.output)
exit(0)
# Table Command
if sys.argv[1] == "table":
segmenter = LanguageSegmenter(languages=args.languages, import_file_name=args.file)
segmenter()
segmenter.generate_table()
if args.show:
segmenter.output_table()
if args.output:
segmenter.write_table(file_name=args.output)
exit(0)