-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget.py
More file actions
370 lines (320 loc) · 12.7 KB
/
widget.py
File metadata and controls
370 lines (320 loc) · 12.7 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
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
# This Python file uses the following encoding: utf-8
import sys
from pathlib import Path
from PySide6.QtCore import QThread, Signal
from PySide6.QtWidgets import (
QApplication,
QComboBox,
QDialog,
QDialogButtonBox,
QFileDialog,
QGridLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QMessageBox,
QPushButton,
QProgressBar,
QVBoxLayout,
QWidget,
)
from PySide6.QtGui import QIcon
from translator import LANG_SOURCE_CODES, LANG_TARGET_CODES, DocumentTranslator
APP_VERSION = "0.0.1"
LANG_SUFFIX_MAP = {"zh-cn": "cn", "en": "en", "fr": "fr", "es": "es"}
LANG_NATIVE_NAMES = {
"auto": "Auto",
"zh-cn": "Chinese",
"en": "English",
"fr": "French",
"es": "Spanish",
}
class TranslationWorker(QThread):
progress_changed = Signal(int)
status_changed = Signal(object)
finished = Signal(str)
failed = Signal(str)
def __init__(
self,
input_file: str,
output_file: str,
state_file: str,
src_lang: str,
dest_lang: str,
) -> None:
super().__init__()
self.input_file = input_file
self.output_file = output_file
self.state_file = state_file
self.src_lang = src_lang
self.dest_lang = dest_lang
def run(self) -> None:
try:
translator = DocumentTranslator(
input_file=self.input_file,
output_file=self.output_file,
state_file=self.state_file,
src_lang=self.src_lang,
dest_lang=self.dest_lang,
)
for progress, status in translator.translate():
self.progress_changed.emit(progress)
self.status_changed.emit(status)
self.finished.emit(self.output_file)
except Exception as exc: # pylint: disable=broad-except
self.failed.emit(str(exc))
class TranslatorWidget(QWidget):
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.setWindowTitle("Translate File Windows")
self._set_window_icon()
self.source_label = QLabel()
self.output_label = QLabel()
self.src_lang_label = QLabel()
self.dest_lang_label = QLabel()
self.input_edit = QLineEdit()
self.output_edit = QLineEdit()
self.output_edit.setReadOnly(True)
self.src_combo = QComboBox()
self.dest_combo = QComboBox()
self.lang_button = QPushButton()
self.select_input_btn = QPushButton("Choose Word file")
self.start_btn = QPushButton("Start")
self.progress_bar = QProgressBar()
self.progress_bar.setRange(0, 100)
self.status_label = QLabel()
self.worker: TranslationWorker | None = None
self._init_lang_options()
self._build_layout()
self._connect_signals()
self._apply_language()
self.setAcceptDrops(True)
def _build_layout(self) -> None:
grid = QGridLayout()
grid.addWidget(self.source_label, 0, 0)
grid.addWidget(self.input_edit, 0, 1)
grid.addWidget(self.select_input_btn, 0, 2)
grid.addWidget(self.output_label, 1, 0)
grid.addWidget(self.output_edit, 1, 1)
grid.addWidget(self.src_lang_label, 2, 0)
grid.addWidget(self.src_combo, 2, 1)
grid.addWidget(self.dest_lang_label, 3, 0)
grid.addWidget(self.dest_combo, 3, 1)
buttons = QHBoxLayout()
buttons.addWidget(self.lang_button)
buttons.addStretch()
buttons.addWidget(self.start_btn)
layout = QVBoxLayout()
layout.addLayout(grid)
layout.addWidget(self.progress_bar)
layout.addWidget(self.status_label)
layout.addLayout(buttons)
self.setLayout(layout)
def _connect_signals(self) -> None:
self.select_input_btn.clicked.connect(self.choose_input)
self.start_btn.clicked.connect(self.start_translation)
self.dest_combo.currentIndexChanged.connect(self._refresh_output_path)
self.lang_button.clicked.connect(self._open_language_dialog)
def choose_input(self) -> None:
file_path, _ = QFileDialog.getOpenFileName(
self, "Choose Word file", "", "Word files (*.docx)"
)
if file_path:
self.input_edit.setText(file_path)
default_output = self._default_output_path(
Path(file_path), self.dest_combo.currentData()
)
self.output_edit.setText(str(default_output))
def start_translation(self) -> None:
input_path = self.input_edit.text().strip()
if not input_path:
self._show_error("Please select a Word file.")
return
self.start_btn.setEnabled(False)
self.status_label.setText("Starting translation...")
self.progress_bar.setValue(0)
src_lang = self.src_combo.currentData()
dest_lang = self.dest_combo.currentData()
if src_lang == dest_lang:
self._show_error("Source and target languages must differ.")
self.start_btn.setEnabled(True)
return
output_path = str(
self._default_output_path(Path(input_path), dest_lang)
)
state_path = str(
self._default_state_path(Path(input_path), src_lang, dest_lang)
)
self.output_edit.setText(output_path)
self.worker = TranslationWorker(
input_path, output_path, state_path, src_lang, dest_lang
)
self.worker.progress_changed.connect(self.progress_bar.setValue)
self.worker.status_changed.connect(self._on_status)
self.worker.finished.connect(self._on_finished)
self.worker.failed.connect(self._on_failed)
self.worker.start()
def _on_finished(self, output_file: str) -> None:
self.start_btn.setEnabled(True)
self.status_label.setText(
"Completed ({src} -> {dest}). Saved to {output}".format(
src=self._lang_name(self.src_combo.currentData()),
dest=self._lang_name(self.dest_combo.currentData()),
output=output_file,
)
)
self.progress_bar.setValue(100)
QMessageBox.information(
self,
"Done",
"Translation completed.\nSaved to:\n{output}".format(output=output_file),
)
def _on_failed(self, message: str) -> None:
self.start_btn.setEnabled(True)
self.status_label.setText(f"Translation failed: {message}")
QMessageBox.critical(self, "Error", f"Translation failed:\n{message}")
def _on_status(self, payload: object) -> None:
if not isinstance(payload, dict):
self.status_label.setText(str(payload))
return
event = payload.get("event")
if event == "skip_empty":
text = "Paragraph {index}/{total}: empty, skipped.".format(
index=payload.get("index"),
total=payload.get("total"),
)
elif event == "translated":
text = "Paragraph {index}/{total}: {src} -> {dest} done.".format(
index=payload.get("index"),
total=payload.get("total"),
src=self._lang_name(payload.get("src")),
dest=self._lang_name(payload.get("dest")),
)
elif event == "completed":
text = "Completed ({src} -> {dest}). Saved to {output}".format(
src=self._lang_name(payload.get("src")),
dest=self._lang_name(payload.get("dest")),
output=payload.get("output"),
)
else:
text = str(payload)
self.status_label.setText(text)
def _show_error(self, message: str) -> None:
QMessageBox.warning(self, "Notice", message)
def dragEnterEvent(self, event) -> None:
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
if urls and urls[0].toLocalFile().lower().endswith(".docx"):
event.acceptProposedAction()
return
event.ignore()
def dropEvent(self, event) -> None:
urls = event.mimeData().urls()
if not urls:
return
file_path = urls[0].toLocalFile()
if not file_path.lower().endswith(".docx"):
self._show_error("Please drop a .docx file.")
return
self.input_edit.setText(file_path)
output_path = self._default_output_path(
Path(file_path), self.dest_combo.currentData()
)
self.output_edit.setText(str(output_path))
@staticmethod
def _default_output_path(input_path: Path, dest_lang: str) -> Path:
suffix_tag = LANG_SUFFIX_MAP.get(dest_lang, dest_lang.replace("-", "_"))
return input_path.with_name(f"{input_path.stem}-{suffix_tag}{input_path.suffix}")
@staticmethod
def _default_state_path(input_path: Path, src_lang: str, dest_lang: str) -> Path:
return input_path.with_suffix(
f".state-{src_lang.replace('-', '_')}-{dest_lang.replace('-', '_')}.json"
)
def _init_lang_options(self) -> None:
self.src_combo.clear()
self.dest_combo.clear()
for code in LANG_SOURCE_CODES:
display = self._lang_name(code)
self.src_combo.addItem(display, code)
for code in LANG_TARGET_CODES:
display = self._lang_name(code)
self.dest_combo.addItem(display, code)
# defaults: auto-detect -> Chinese
self.src_combo.setCurrentIndex(0)
for idx in range(self.dest_combo.count()):
if self.dest_combo.itemData(idx) == "zh-cn":
self.dest_combo.setCurrentIndex(idx)
break
def _refresh_output_path(self) -> None:
# Only auto-update when input already chosen
input_path = self.input_edit.text().strip()
if not input_path:
return
output_path = self._default_output_path(
Path(input_path), self.dest_combo.currentData()
)
self.output_edit.setText(str(output_path))
def _apply_language(self) -> None:
self.setWindowTitle("Translate File Windows")
self.lang_button.setText("Settings")
self.source_label.setText("Source file")
self.output_label.setText("Output file")
self.src_lang_label.setText("Source language")
self.dest_lang_label.setText("Target language")
self.select_input_btn.setText("Choose Word file")
self.start_btn.setText("Start")
self._refresh_lang_labels()
if not self.worker or not self.worker.isRunning():
self.status_label.setText("Ready")
def _set_window_icon(self) -> None:
candidates = [
Path(__file__).resolve().parent / "static" / "favicon.ico",
Path(getattr(sys, "_MEIPASS", Path(__file__).parent)) / "static" / "favicon.ico",
Path(getattr(sys, "_MEIPASS", Path(__file__).parent)) / "favicon.ico",
]
for icon_path in candidates:
if icon_path.exists():
self.setWindowIcon(QIcon(str(icon_path)))
break
def _lang_name(self, code: str) -> str:
return LANG_NATIVE_NAMES.get(code, code)
def _open_language_dialog(self) -> None:
dialog = QDialog(self)
dialog.setWindowTitle("Settings")
layout = QVBoxLayout()
version_label = QLabel(f"Version: {APP_VERSION}")
layout.addWidget(version_label)
site_label = QLabel(
"Author: <a href='https://wuhz.net'>wuhz.net</a>"
)
site_label.setOpenExternalLinks(True)
layout.addWidget(site_label)
lang_label = QLabel("Interface language: English only")
layout.addWidget(lang_label)
buttons = QDialogButtonBox(QDialogButtonBox.Ok)
layout.addWidget(buttons)
dialog.setLayout(layout)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
dialog.exec()
def _refresh_lang_labels(self) -> None:
# Update displayed text for language combos based on current UI language
for combo in (self.src_combo, self.dest_combo):
current_code = combo.currentData()
combo.blockSignals(True)
combo.clear()
codes = LANG_SOURCE_CODES if combo is self.src_combo else LANG_TARGET_CODES
for code in codes:
combo.addItem(self._lang_name(code), code)
# restore selection
for idx in range(combo.count()):
if combo.itemData(idx) == current_code:
combo.setCurrentIndex(idx)
break
combo.blockSignals(False)
if __name__ == "__main__":
app = QApplication([])
window = TranslatorWidget()
window.resize(640, 200)
window.show()
sys.exit(app.exec())