-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
358 lines (303 loc) · 13.4 KB
/
main.py
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
import io
import os.path
import sys
import customtkinter as ctk
from customtkinter import *
import tkinter as tk
import re
from pathlib import Path
import argostranslate.translate as at
######Translator
RE_PATTERN = re.compile(r'\[[^"\]]*]|\$[^$]+\$|#[^$]+#|\\n')
REPLACER = '{@}'
def get_loc_code(from_l: bool, pars_arg: str):
locale_codes = {
'en': 'english',
'de': 'german',
'fr': 'french',
'es': 'spanish',
'ru': 'russian',
'zh-cn': 'simp_chinese',
'ko': 'korean'
}
locale = locale_codes.get(pars_arg)
if not locale:
locale = 'english' if from_l else 'german'
return locale
def call(l1:str,l2:str,trans:int,path):
from_language = l1
to_language = l2
from_naming = get_loc_code(True, from_language)
to_naming = get_loc_code(False, to_language)
if trans == 1:
do_translation = True
else:
do_translation = False
target_dir = Path(path)
if not target_dir.exists():
print("The target directory doesn't exist")
raise SystemExit(1)
init(target_dir, do_translation, from_language, to_language, from_naming, to_naming)
def init(target_dir, do_translation, from_language, to_language, from_naming, to_naming):
INPUT_DIR = target_dir
print("INPUT_DIR " + INPUT_DIR.__str__())
totalCount = 0
file: Path
for file in list(INPUT_DIR.rglob("*.yml*")):
filepath = os.path.dirname(os.path.abspath(file))
filename = file.name.split('/')[0]
newfileName = filename.replace(from_naming, to_naming)
# replace text in file
with open(file, 'r', encoding="utf-8") as f_r:
print('----------------------------------------------')
print("current File: " + file.name)
file_data = f_r.readlines()
file_data[0] = file_data[0].replace(from_naming, to_naming)
if do_translation:
translate(file_data, totalCount, from_language, to_language)
tofile(filepath, filename, file_data, from_naming, to_naming)
def tofile(filepath, filename, file_data, from_naming, to_naming):
old_file = os.path.join(filepath, filename)
newfileName = filename.replace(from_naming, to_naming, 1)
new_filepath = filepath.replace(from_naming, to_naming, 1)
new_file = os.path.join(new_filepath, newfileName)
new_path = Path(new_file)
if not os.path.exists(new_filepath):
os.makedirs(new_filepath)
with open(new_path, 'w', encoding="utf-8") as f_r:
f_r.writelines(file_data)
def translate(file_data, totalCount, from_language, to_language):
# basic Translator in work
for i, lines in enumerate(file_data[1:]):
matches = re.findall('"([^"]*)"', lines)
# matches = re.findall(r'"(.*?)"', lines)
if len(matches) == 1 and matches is not None:
tokens = re.findall(RE_PATTERN, matches[0])
match = matches[0]
matches[0] = re.sub(RE_PATTERN, REPLACER, matches[0])
# translate
try:
translation = at.translate(matches[0], to_code=to_language, from_code=from_language)
padded_translation = translation
except TypeError:
translation = matches[0]
padded_translation = matches[0]
print('Error (TypeError) Skipped in: ' + matches[0])
except TimeoutError:
translation = matches[0]
padded_translation = matches[0]
print('Error (TimeOut) Skipped in: ' + matches[0])
except:
translation = matches[0]
padded_translation = matches[0]
print('Unknown Exception - Skipped in' + matches[0])
totalCount += 1
for t in tokens:
padded_translation = padded_translation.replace(REPLACER, t, 1)
file_data[i + 1] = lines.replace("\"" + match + "\"", "\"" + padded_translation + "\"", 1)
# print("line no. #" + str(totalCount)+" was translated", end="")
print("line no. #" + str(totalCount)+" was translated", end="")
print()
##########GUI STUFF
# Language mapping from display names to ISO 639 codes
LANGUAGES = {
"English": "en",
"German": "de",
"French": "fr",
"Spanish": "es",
"Simplified Chinese": "zh",
"Korean": "ko"
}
def list_files(directory):
"""
Prints all files in the given directory and its subdirectories.
"""
found_files = False # Flag to track if any files were found
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith(".yml"):
# print(os.path.join(root, file))
found_files = True
if not found_files:
print("No files found")
return found_files
def redirect_print_to_text_widget(text_widget):
sys.stdout = TextRedirector(text_widget)
class TextRedirector(io.TextIOBase):
def __init__(self, text_widget): # Set a default update interval (in milliseconds)
self.text_widget = text_widget
# self.update_interval = update_interval
# self.buffer = ""
def write(self, text):
# Write to the Text widget
self.text_widget.insert(tk.END, text)
self.text_widget.see(tk.END) # Scroll to the end
# # Write to the Text widget
# self.terminal.insert(tk.END, text)
# self.terminal.see(tk.END) # Scroll to the end
# Write to the standard console
sys.__stdout__.write(text)
# # Append to the buffer
# self.buffer += text
#
# # Check if it's time to update the Text widget
# if len(self.buffer) >= self.update_interval:
# self.text_widget.insert(tk.END, self.buffer)
# self.text_widget.see(tk.END) # Scroll to the end
# self.buffer = "" # Clear the buffer
#
# def flush(self):
# # Flush any remaining content
# if self.buffer:
# self.text_widget.insert(tk.END, self.buffer)
# self.text_widget.see(tk.END) # Scroll to the end
# self.buffer = "" # Clear the buffer
#######
class CTkTerminalWidget(tk.Text):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
# self.config(state=tk.DISABLED) # Disable direct editing
self.bind("<KeyPress>", self.handle_keypress)
self.buffer = ""
def handle_keypress(self, event):
if event.keysym == "Return":
# Handle user input (e.g., execute a command)
user_input = self.buffer.strip()
self.insert(tk.END, f"\n> {user_input}\n")
self.buffer = ""
# Simulate command execution (replace with your actual logic)
self.execute_command(user_input)
# Scroll to the end
self.see(tk.END)
elif event.keysym == "BackSpace":
# Handle backspace (delete last character)
self.buffer = self.buffer[:-1]
else:
self.buffer += event.char
def execute_command(self, command):
# Simulate command execution (replace with your actual logic)
if command.lower() == "hello":
self.insert(tk.END, "Hello, world!\n")
else:
self.insert(tk.END, f"Unknown command: {command}\n")
def flush(self):
pass # No need to flush anything
class TranslatorApp(ctk.CTk):
def __init__(self):
super().__init__()
self.title("CK3 Language Transilator")
self.geometry("600x400") # Set initial window size
# Create widgets
self.path_entry = ctk.CTkEntry(self) # Removed placeholder argument
self.source_lang_combo = ctk.CTkComboBox(self, values=list(LANGUAGES.keys()),command=self._update_target_langs)
self.target_lang_combo = ctk.CTkComboBox(self, values=list(LANGUAGES.keys()),command=self._update_source_langs)
self.translate_button = ctk.CTkButton(self, text="Translate", command=self.translate_text)
self.mode_switch = ctk.CTkSwitch(self,text="☀", command=self.toggle_mode)
# Create a Frame to hold the Text widget and scrollbar
self.frame = ctk.CTkFrame(self)
self.text_widget = tk.Text(self.frame, wrap=tk.WORD, font=("Helvetica", 18))
# self.terminal = CTkTerminalWidget(self.frame, wrap=tk.WORD, font=("Helvetica", 18))
# Create a Scrollbar and link it to the Text widget
self.scrollbar = tk.Scrollbar(self.frame, command=self.text_widget.yview)
# self.scrollbar = tk.Scrollbar(self.frame, command=self.terminal.yview)
# Set initial values
self.source_lang_combo.set("English")
self.target_lang_combo.set("German")
#Both lists on startup
selected_source_lang = self.source_lang_combo.get()
available_target_languages = [lang for lang in LANGUAGES if lang != selected_source_lang]
self.target_lang_combo.configure(values=available_target_languages)
# Get the current target language
target_lang = self.target_lang_combo.get()
# Create a list of languages that are not equal to the target language
source_languages = [language for language in LANGUAGES if language != target_lang]
# Update the values of the source combobox
self.source_lang_combo.configure(values=source_languages)
####
# Pack widgets
self.path_entry.pack(fill="x", padx=20, pady=10)
self.source_lang_combo.pack(fill="x", padx=20, pady=10)
self.target_lang_combo.pack(fill="x", padx=20, pady=10)
self.translate_button.pack(pady=10)
self.mode_switch.pack(pady=10)
self.frame.pack(fill=tk.BOTH, expand=True)
self.text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# self.terminal.pack(side = tk.LEFT, fill=tk.BOTH, expand=True)
self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y,anchor=tk.E)
# Configure resizing behavior
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
# Redirect print output to both the console and the Text widget
# redirect_print_to_text_widget(self.text_widget)
# redirect_print_to_text_widget(self.terminal)
self.text_widget.config(yscrollcommand=self.scrollbar.set)
# self.terminal.config(yscrollcommand=self.scrollbar.set)
####
# Redirect stdout and stderr to the console widget
# sys.stdout = TextRedirector(self.terminal)
# sys.stderr = TextRedirector(self.terminal)
# # Capture and display the output
# for line in process.stdout:
# print(line, end="")
# for line in process.stderr:
# print(line, end="")
# Restore stdout and stderr
# sys.stdout = sys.__stdout__y
# sys.stderr = sys.__stderr__
def _update_target_langs(self,event):
# Get the current source language
source_lang = self.source_lang_combo.get()
# Create a list of languages that are not equal to the source language
target_languages = [language for language in LANGUAGES if language != source_lang]
# Update the values of the target combobox
self.target_lang_combo.configure(values=target_languages)
def _update_source_langs(self,event):
# Get the current target language
target_lang = self.target_lang_combo.get()
# Create a list of languages that are not equal to the target language
source_languages = [language for language in LANGUAGES if language != target_lang]
# Update the values of the source combobox
self.source_lang_combo.configure(values=source_languages)
def translate_text(self):
# self.terminal.insert(tk.END,"jlkajsdlk")
# Get selected languages
source_lang = self.source_lang_combo.get()
target_lang = self.target_lang_combo.get()
# Convert to ISO 639 codes
source_code = LANGUAGES.get(source_lang)
target_code = LANGUAGES.get(target_lang)
print(f"Source language : {source_code}")
self.output(f"Source language : {source_code}")
print(f"Target language : {target_code}")
self.output(f"Target language : {target_code}")
path = self.path_entry.get()
if os.path.exists(path):
print(f"Path to localization : {path} \n\n")
self.output(f"Path to localization : {path} \n\n")
if list_files(path):
# Perform translation based on user input
call(source_code,target_code,1,path)
# self.call(source_code,target_code,1,path)
print("Finished")
self.output("Finished")
else:
print("No valid path was given")
self.output("No valid path was given")
def toggle_mode(self):
# Switch appearance mode (light/dark)
if self.mode_switch.get():
set_appearance_mode("dark")
self.text_widget.configure(bg="black", fg="white")
self.mode_switch.configure(text ="🌙") # Moon symbol
else:
set_appearance_mode("light")
self.text_widget.configure(bg="white", fg="black")
self.mode_switch.configure(text="☀") # Sun symbol
def output(self,text):
# Write to the Text widget
input = text+"\n"
self.text_widget.insert(tk.END, input)
self.text_widget.see(tk.END) # Scroll to the end
if __name__ == "__main__":
app = TranslatorApp()
app.mainloop()