-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFolder Translator.py
More file actions
80 lines (69 loc) · 2.6 KB
/
Folder Translator.py
File metadata and controls
80 lines (69 loc) · 2.6 KB
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
import os, re, asyncio, threading
import tkinter as tk
from tkinter import filedialog
from googletrans import Translator
SRC = "ja"
DST = "en"
translator = Translator()
skip_flag = False # global skip flag
def safe_filename(s):
s = re.sub(r'[\/:*?"<>|]', '_', s)
s = re.sub(r'\s+', ' ', s).strip()
return s or "untitled"
def skip_file():
global skip_flag
skip_flag = True
async def translate_file(path, status_label, idx, total):
global skip_flag
if skip_flag:
skip_flag = False
status_label.config(text=f"Skipped {os.path.basename(path)}")
await asyncio.sleep(0.1)
return
fname = os.path.basename(path)
root_dir = os.path.dirname(path)
name, ext = os.path.splitext(fname)
try:
result = await translator.translate(name, src=SRC, dest=DST)
translated = result.text
except Exception:
translated = name
new_name = safe_filename(translated)[:100] + ext # truncate long names
new_path = os.path.join(root_dir, new_name)
if os.path.exists(new_path):
base, e = os.path.splitext(new_name)
i = 1
while os.path.exists(os.path.join(root_dir, f"{base} ({i}){e}")):
i += 1
new_path = os.path.join(root_dir, f"{base} ({i}){e}")
if os.path.exists(path):
os.rename(path, new_path)
status_label.config(text=f"Processing {idx}/{total}: {fname}")
await asyncio.sleep(0.05)
async def translate_folder(folder, status_label):
files = []
for root, dirs, fs in os.walk(folder):
for f in fs:
files.append(os.path.join(root, f))
total = len(files)
for idx, path in enumerate(files, 1):
await translate_file(path, status_label, idx, total)
status_label.config(text="Complete!")
status_label.update()
await asyncio.sleep(2)
status_label.config(text="Choose folder")
def start_translation(status_label):
folder = filedialog.askdirectory()
if folder:
threading.Thread(target=lambda: asyncio.run(translate_folder(folder, status_label)), daemon=True).start()
# GUI
root = tk.Tk()
root.title("Folder Translator (Google)")
root.geometry("500x150")
status_label = tk.Label(root, text="Choose folder", anchor='center')
status_label.pack(expand=True, fill='both')
btn_translate = tk.Button(root, text="Select Folder and Translate", command=lambda: start_translation(status_label))
btn_translate.pack(expand=True, fill='both')
btn_skip = tk.Button(root, text="Skip Current File", command=skip_file)
btn_skip.pack(expand=True, fill='both')
root.mainloop()