1#   Type: Python 3 script
2# Author: Steven Sun <stevenlele@outlook.com>
3#   Date: Feb 28, 2020
4#  Notes: Put "Language.csv" and "Language_parsed.csv" in this folder
5#         and run the script. It converts the parsed file back into the
6#         original CSV, and generates a single language file for testing.
7
8import csv
9import sys
10import os
11
12#################################
13######### Configuration #########
14
15# edit the filename if the CSV file is placed elsewhere
16language_file = 'Language.csv'
17translated_file = 'Language_parsed.csv'
18
19# output filename
20output_file = 'Language_translated.csv'
21
22######### Configuration #########
23#################################
24
25csv.register_dialect('MediaInfo', delimiter=';')
26
27if not os.path.exists(language_file):
28    print('Error: Language.csv file does not exist!')
29    sys.exit(1)
30
31if not os.path.exists(translated_file):
32    print('Error: Translated file does not exist!')
33    sys.exit(1)
34
35output_rows = []
36output_lang_rows = []
37translated_rows = []
38
39with open(translated_file, 'r', encoding='utf_8') as f:
40    reader = csv.reader(f)
41
42    header = next(reader)
43    lang_code = header[2]
44    for row in reader:
45        key = row[0]
46        translated = row[2]
47        translated_rows.append((key, translated))
48
49with open(language_file, 'r', encoding='utf_8') as f:
50    reader = csv.reader(f, dialect='MediaInfo')
51
52    header = next(reader)
53    index_lang = header.index(lang_code)
54    output_rows.append(header)
55    output_lang_rows.append([header[0], header[index_lang]])
56
57    for row in reader:
58        key = row[0]
59        translated_row = translated_rows.pop(0)
60        if key != translated_row[0]:
61            print(f'Error: Key "{key}" does not match the translated file "{translated_rows[0][0]}".')
62            print('Please check whether you have changed the translated file or not.')
63            sys.exit(1)
64        translated_string = translated_row[1]
65        if translated_string.startswith('"') and translated_string.endswith('"'):
66            translated_string = translated_string.strip('"')
67        new_row = row
68        new_row[index_lang] = translated_string
69        output_rows.append(new_row)
70        output_lang_rows.append([key, translated_string])
71
72with open(output_file, 'w', encoding='utf_8', newline='') as f:
73    writer = csv.writer(f, dialect='MediaInfo')
74    writer.writerows(output_rows)
75
76with open(f'{lang_code}.csv', 'w', encoding='utf_8', newline='') as f:
77    writer = csv.writer(f, dialect='MediaInfo')
78    writer.writerows(output_lang_rows)
79
80print('Info: Compile completed!')
81