Trans_tools/Auto Trans/Translator.py

96 lines
3.0 KiB
Python

# Translates the game using good ol fashioned google translator. Be sure to replace the dialogue code in the translator.
# Also this breaks a tiny bit if the dialogue contains \n, but oh well. I don't want to open that can of worms.
# Also by break I mean that it may leave some text in english, is not that it will implode... I think.
import csv
import os
import re
from colorama import init
from colorama import Fore
from googletrans import Translator
from datetime import datetime, timedelta
translator = Translator()
# For Colorama to work
init()
times = []
def translate(string):
# Split the string by it's tags
tokens = re.findall(r'\b\w+\b|{[^}]*}|\[.*\]|[^\w\s]|\s+', string)
# We encode this bitch up so that google trans doesn't botch the tags
to_restore = []
for idx, token in enumerate(tokens):
if token[0] == "{" or token[0] == "[":
to_restore.append(token)
# Emojis aren't touched by the translator and retain their position 😎
tokens[idx] = "🔠"
encoded_string = "".join(tokens)
# Translate the encoded string
trans = translator.translate(encoded_string, dest='es')
temp = list(trans.text)
# Restore the original tags
for tag in to_restore:
for idx, char in enumerate(temp):
if char == "🔠":
temp[idx] = tag
break
return "".join(temp)
def avrg(nums):
average = sum(nums)/len(nums)
return timedelta(seconds=average)
# Open the input and output CSV files with the utf-8 encoding
with open('original.csv', 'r', encoding='utf-8') as input_file, \
open('trans.csv', 'w', encoding='utf-8',newline='') as output_file:
length = len(input_file.readlines())
# Wacky hacks to calculate the time left
input_file.seek(0)
# Create readers and writers for the input and output files
reader = csv.reader(input_file)
writer = csv.writer(output_file)
# Loop through the rows in the input file
for i, row in enumerate(reader):
start_time = datetime.now().replace(microsecond=0)
try:
# Translate the string
translation = translate(row[0])
#Hope this works for escaping, lol
translation = translation.replace('"',r'\"')
except Exception as e:
print(f'{Fore.RESET}An error occurred: {e}')
# So we know where we left off (Not yet implemented :fangcute:)
writer.writerow([row[0], 'aezakmi'])
break
else:
current_time = datetime.now().replace(microsecond=0)
# Calculate the time taken to translate the current string
time_taken = current_time - start_time
times.append(time_taken.total_seconds())
# Calculate the estimated time remaining to translate the whole file
time_remaining = avrg(times) * (length - i)
print(f'{Fore.RED}Original: {Fore.RESET}{row[0]} | {Fore.GREEN}Translation: {Fore.RESET}{translation.text}{" "*10}\n{Fore.CYAN}Estimated time remaining: {str(time_remaining).split(".")[0]}', end="\r")
writer.writerow([row[0], translation.text])
print(f"\n\n{Fore.YELLOW}FINISHED")