-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathadvanced.py
1212 lines (1019 loc) · 46.1 KB
/
advanced.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
from types import MethodType
from calibre.constants import __version__
from .lib.utils import uid, traceback_error
from .lib.config import get_config
from .lib.encodings import encoding_list
from .lib.cache import Paragraph, get_cache
from .lib.translation import get_engine_class, get_translator, get_translation
from .lib.element import get_element_handler
from .lib.conversion import extract_item, extra_formats
from .engines.openai import ChatgptTranslate, ChatgptBatchTranslate
from .engines.custom import CustomTranslate
from . import EbookTranslator
from .components import (
EngineList, Footer, SourceLang, TargetLang, InputFormat, OutputFormat,
AlertMessage, AdvancedTranslationTable, StatusColor, TranslationStatus,
set_shortcut, ChatgptBatchTranslationManager)
try:
from qt.core import (
Qt, QObject, QDialog, QGroupBox, QWidget, QVBoxLayout, QHBoxLayout,
QPlainTextEdit, QPushButton, QSplitter, QLabel, QThread, QLineEdit,
QGridLayout, QProgressBar, pyqtSignal, pyqtSlot, QPixmap, QEvent,
QStackedWidget, QSpacerItem, QTextCursor, QTabWidget, QCheckBox,
QComboBox, QSizePolicy)
except ImportError:
from PyQt5.Qt import (
Qt, QObject, QDialog, QGroupBox, QWidget, QVBoxLayout, QHBoxLayout,
QPlainTextEdit, QPushButton, QSplitter, QLabel, QThread, QLineEdit,
QGridLayout, QProgressBar, pyqtSignal, pyqtSlot, QPixmap, QEvent,
QStackedWidget, QSpacerItem, QTextCursor, QTabWidget, QCheckBox,
QComboBox, QSizePolicy)
load_translations()
class EditorWorker(QObject):
start = pyqtSignal((str,), (str, object))
show = pyqtSignal(str)
finished = pyqtSignal()
def __init__(self):
QObject.__init__(self)
self.start[str].connect(self.show_message)
self.start[str, object].connect(self.show_message)
@pyqtSlot(str)
@pyqtSlot(str, object)
def show_message(self, message, callback=None):
time.sleep(0.01)
self.show.emit(message)
time.sleep(1)
self.show.emit('')
callback and callback()
self.finished.emit()
class PreparationWorker(QObject):
start = pyqtSignal()
progress = pyqtSignal(int)
progress_message = pyqtSignal(str)
progress_detail = pyqtSignal(str)
close = pyqtSignal(int)
finished = pyqtSignal(str)
def __init__(self, engine_class, ebook):
QObject.__init__(self)
self.engine_class = engine_class
self.ebook = ebook
self.on_working = False
self.canceled = False
self.start.connect(self.prepare_ebook_data)
def clean_cache(self, cache):
cache.is_fresh() and cache.destroy()
self.on_working = False
self.close.emit(1)
def set_canceled(self, canceled):
self.canceled = canceled
# def cancel(self):
# return self.thread().isInterruptionRequested()
@pyqtSlot()
def prepare_ebook_data(self):
self.on_working = True
input_path = self.ebook.get_input_path()
element_handler = get_element_handler(
self.engine_class.placeholder, self.engine_class.separator,
self.ebook.target_direction)
merge_length = str(element_handler.get_merge_length())
encoding = ''
if self.ebook.encoding.lower() != 'utf-8':
encoding = self.ebook.encoding.lower()
cache_id = uid(
input_path + self.engine_class.name + self.ebook.target_lang
+ merge_length + encoding)
cache = get_cache(cache_id)
if cache.is_fresh() or not cache.is_persistence():
self.progress_detail.emit(
'Start processing the ebook: %s' % self.ebook.title)
cache.set_info('title', self.ebook.title)
cache.set_info('engine_name', self.engine_class.name)
cache.set_info('target_lang', self.ebook.target_lang)
cache.set_info('merge_length', merge_length)
cache.set_info('plugin_version', EbookTranslator.__version__)
cache.set_info('calibre_version', __version__)
# --------------------------
a = time.time()
# --------------------------
self.progress_message.emit(_('Extracting ebook content...'))
try:
elements = extract_item(
input_path, self.ebook.input_format, self.ebook.encoding,
self.progress_detail.emit)
except Exception:
self.progress_message.emit(
_('Failed to extract ebook content'))
self.progress_detail.emit('\n' + traceback_error())
self.progress.emit(100)
self.clean_cache(cache)
return
if self.canceled:
self.clean_cache(cache)
return
self.progress.emit(30)
b = time.time()
self.progress_detail.emit('extracting timing: %s' % (b - a))
if self.canceled:
self.clean_cache(cache)
return
# --------------------------
self.progress_message.emit(_('Filtering ebook content...'))
original_group = element_handler.prepare_original(elements)
self.progress.emit(80)
c = time.time()
self.progress_detail.emit('filtering timing: %s' % (c - b))
if self.canceled:
self.clean_cache(cache)
return
# --------------------------
self.progress_message.emit(_('Preparing user interface...'))
cache.save(original_group)
self.progress.emit(100)
d = time.time()
self.progress_detail.emit('cache timing: %s' % (d - c))
if self.canceled:
self.clean_cache(cache)
return
else:
self.progress_detail.emit(
'Loading data from cache and preparing user interface...')
time.sleep(0.1)
self.finished.emit(cache_id)
self.on_working = False
class TranslationWorker(QObject):
start = pyqtSignal()
close = pyqtSignal(int)
finished = pyqtSignal()
translate = pyqtSignal(list, bool)
logging = pyqtSignal(str, bool)
# error = pyqtSignal(str, str, str)
streaming = pyqtSignal(object)
callback = pyqtSignal(object)
def __init__(self, engine_class, ebook):
QObject.__init__(self)
self.source_lang = ebook.source_lang
self.target_lang = ebook.target_lang
self.engine_class = engine_class
self.on_working = False
self.canceled = False
self.need_close = False
self.translate.connect(self.translate_paragraphs)
# self.finished.connect(lambda: self.set_canceled(False))
def set_source_lang(self, lang):
self.source_lang = lang
def set_target_lang(self, lang):
self.target_lang = lang
def set_engine_class(self, engine_class):
self.engine_class = engine_class
def set_canceled(self, canceled):
self.canceled = canceled
def cancel_request(self):
return self.canceled
def set_need_close(self, need_close):
self.need_close = need_close
@pyqtSlot(list, bool)
def translate_paragraphs(self, paragraphs=[], fresh=False):
""":fresh: retranslate all paragraphs."""
self.on_working = True
self.start.emit()
translator = get_translator(self.engine_class)
translator.set_source_lang(self.source_lang)
translator.set_target_lang(self.target_lang)
translation = get_translation(translator)
translation.set_fresh(fresh)
translation.set_logging(
lambda text, error=False: self.logging.emit(text, error))
translation.set_streaming(self.streaming.emit)
translation.set_callback(self.callback.emit)
translation.set_cancel_request(self.cancel_request)
translation.handle(paragraphs)
self.on_working = False
self.finished.emit()
if self.need_close:
time.sleep(0.5)
self.close.emit(0)
class CreateTranslationProject(QDialog):
start_translation = pyqtSignal(object)
def __init__(self, parent, ebook):
QDialog.__init__(self, parent)
self.ebook = ebook
layout = QVBoxLayout(self)
self.choose_format = self.layout_format()
self.start_button = QPushButton(_('&Start'))
# self.start_button.setStyleSheet(
# 'padding:0;height:48;font-size:20px;color:royalblue;'
# 'text-transform:uppercase;')
self.start_button.clicked.connect(self.show_advanced)
layout.addWidget(self.choose_format)
layout.addWidget(self.start_button)
def layout_format(self):
engine_class = get_engine_class()
widget = QWidget()
layout = QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
input_group = QGroupBox(_('Input Format'))
input_layout = QGridLayout(input_group)
input_format = InputFormat(self.ebook.files.keys())
input_format.setFixedWidth(150)
input_layout.addWidget(input_format)
layout.addWidget(input_group)
output_group = QGroupBox(_('Output Format'))
output_layout = QGridLayout(output_group)
output_format = OutputFormat()
output_format.setFixedWidth(150)
output_layout.addWidget(output_format)
layout.addWidget(output_group)
source_group = QGroupBox(_('Source Language'))
source_layout = QVBoxLayout(source_group)
source_lang = SourceLang()
source_lang.setFixedWidth(150)
source_layout.addWidget(source_lang)
layout.addWidget(source_group)
target_group = QGroupBox(_('Target Language'))
target_layout = QVBoxLayout(target_group)
target_lang = TargetLang()
target_lang.setFixedWidth(150)
target_layout.addWidget(target_lang)
layout.addWidget(target_group)
source_lang.refresh.emit(
engine_class.lang_codes.get('source'),
engine_class.config.get('source_lang'),
not issubclass(engine_class, CustomTranslate))
target_lang.refresh.emit(
engine_class.lang_codes.get('target'),
engine_class.config.get('target_lang'))
def change_input_format(_format):
self.ebook.set_input_format(_format)
change_input_format(input_format.currentText())
input_format.currentTextChanged.connect(change_input_format)
def change_output_format(_format):
self.ebook.set_output_format(_format)
change_output_format(output_format.currentText())
output_format.currentTextChanged.connect(change_output_format)
def change_source_lang(lang):
self.ebook.set_source_lang(lang)
change_source_lang(source_lang.currentText())
source_lang.currentTextChanged.connect(change_source_lang)
def change_target_lang(lang):
self.ebook.set_target_lang(lang)
change_target_lang(target_lang.currentText())
target_lang.currentTextChanged.connect(change_target_lang)
if self.ebook.input_format in extra_formats.keys():
encoding_group = QGroupBox(_('Encoding'))
encoding_layout = QVBoxLayout(encoding_group)
encoding_select = QComboBox()
encoding_select.setFixedWidth(150)
encoding_select.addItems(encoding_list)
encoding_layout.addWidget(encoding_select)
layout.addWidget(encoding_group)
def change_encoding(encoding):
self.ebook.set_encoding(encoding)
encoding_select.currentTextChanged.connect(change_encoding)
else:
direction_group = QGroupBox(_('Target Directionality'))
direction_layout = QVBoxLayout(direction_group)
direction_list = QComboBox()
direction_list.setFixedWidth(150)
direction_list.addItem(_('Auto'), 'auto')
direction_list.addItem(_('Left to Right'), 'ltr')
direction_list.addItem(_('Right to Left'), 'rtl')
direction_layout.addWidget(direction_list)
layout.addWidget(direction_group)
def change_direction(_index):
_direction = direction_list.itemData(_index)
self.ebook.set_target_direction(_direction)
direction_list.currentIndexChanged.connect(change_direction)
engine_target_lange_codes = engine_class.lang_codes.get('target')
if engine_target_lange_codes is not None and self.ebook.target_lang in engine_target_lange_codes:
target_lang_code = engine_target_lange_codes[self.ebook.target_lang]
direction = engine_class.lang_codes_directionality.get(target_lang_code, 'auto')
index = direction_list.findData(direction)
direction_list.setCurrentIndex(index)
return widget
@pyqtSlot()
def show_advanced(self):
self.done(0)
self.start_translation.emit(self.ebook)
class AdvancedTranslation(QDialog):
paragraph_sig = pyqtSignal(object)
ebook_title = pyqtSignal()
progress_bar = pyqtSignal()
batch_translation = pyqtSignal()
preparation_thread = QThread()
trans_thread = QThread()
editor_thread = QThread()
def __init__(self, parent, icon, worker, ebook):
QDialog.__init__(self, parent)
self.api = parent.current_db.new_api
self.icon = icon
self.worker = worker
self.ebook = ebook
self.config = get_config()
self.alert = AlertMessage(self)
self.footer = Footer()
# self.error = JobError(self)
self.current_engine = get_engine_class()
self.cache = None
self.merge_enabled = False
self.progress_step = 0
self.translate_all = False
self.editor_worker = EditorWorker()
self.editor_worker.moveToThread(self.editor_thread)
self.editor_thread.finished.connect(self.editor_worker.deleteLater)
self.editor_thread.start()
self.trans_worker = TranslationWorker(self.current_engine, self.ebook)
self.trans_worker.close.connect(self.done)
self.trans_worker.moveToThread(self.trans_thread)
self.trans_thread.finished.connect(self.trans_worker.deleteLater)
self.trans_thread.start()
self.preparation_worker = PreparationWorker(
self.current_engine, self.ebook)
self.preparation_worker.close.connect(self.done)
self.preparation_worker.moveToThread(self.preparation_thread)
self.preparation_thread.finished.connect(
self.preparation_worker.deleteLater)
self.preparation_thread.start()
layout = QVBoxLayout(self)
self.waiting = self.layout_progress()
self.stack = QStackedWidget()
self.stack.addWidget(self.waiting)
layout.addWidget(self.stack)
layout.addWidget(self.footer)
def working_status():
self.logging_text.clear()
self.errors_text.clear()
self.trans_worker.start.connect(working_status)
self.trans_worker.logging.connect(
lambda text, error: self.errors_text.appendPlainText(text)
if error else self.logging_text.appendPlainText(text))
def working_finished():
if self.translate_all and not self.trans_worker.cancel_request():
failures = len(self.table.get_selected_paragraphs(True, True))
if failures > 0:
message = _(
'Failed to translate {} paragraph(s), '
'Would you like to retry?')
if self.alert.ask(message.format(failures)) == 'yes':
self.translate_all_paragraphs()
return
else:
self.alert.pop(_('Translation completed.'))
self.trans_worker.set_canceled(False)
self.translate_all = False
self.trans_worker.finished.connect(working_finished)
# self.trans_worker.error.connect(
# lambda title, reason, detail: self.error.show_error(
# title, _('Failed') + ': ' + reason, det_msg=detail))
def prepare_table_layout(cache_id):
self.cache = get_cache(cache_id)
self.merge_enabled = int(self.cache.get_info('merge_length')) > 0
paragraphs = self.cache.all_paragraphs()
if len(paragraphs) < 1:
self.alert.pop(
_('There is no content that needs to be translated.'),
'warning')
self.done(0)
return
self.table = AdvancedTranslationTable(self, paragraphs)
self.panel = self.layout_panel()
self.stack.addWidget(self.panel)
self.stack.setCurrentWidget(self.panel)
self.table.setFocus(Qt.OtherFocusReason)
self.preparation_worker.finished.connect(prepare_table_layout)
self.preparation_worker.start.emit()
def layout_progress(self):
widget = QWidget()
layout = QGridLayout(widget)
try:
cover_image = self.api.cover(self.ebook.id, as_pixmap=True)
except Exception:
cover_image = QPixmap(self.api.cover(self.ebook.id, as_image=True))
if cover_image.isNull():
cover_image = QPixmap(I('default_cover.png'))
mode = getattr(Qt.TransformationMode, 'SmoothTransformation', None) \
or Qt.SmoothTransformation
cover_image = cover_image.scaledToHeight(480, mode)
cover = QLabel()
cover.setAlignment(Qt.AlignCenter)
cover.setPixmap(cover_image)
title = QLabel()
title.setMaximumWidth(cover_image.width())
title.setText(title.fontMetrics().elidedText(
self.ebook.title, Qt.ElideRight, title.width()))
title.setToolTip(self.ebook.title)
progress_bar = QProgressBar()
progress_bar.setFormat('')
progress_bar.setValue(0)
# progress_bar.setFixedWidth(300)
progress_bar.setMinimum(0)
progress_bar.setMaximum(0)
def show_progress(value):
if progress_bar.maximum() == 0:
progress_bar.setMaximum(100)
progress_bar.setValue(value)
self.preparation_worker.progress.connect(show_progress)
label = QLabel(_('Loading ebook data, please wait...'))
label.setAlignment(Qt.AlignCenter)
self.preparation_worker.progress_message.connect(label.setText)
detail = QPlainTextEdit()
detail.setReadOnly(True)
self.preparation_worker.progress_detail.connect(detail.appendPlainText)
layout.addWidget(cover, 0, 0)
layout.addWidget(title, 1, 0)
layout.addItem(QSpacerItem(0, 20), 2, 0, 1, 3)
layout.addWidget(progress_bar, 3, 0)
layout.addWidget(label, 4, 0)
layout.addItem(QSpacerItem(0, 0), 5, 0, 1, 3)
layout.addItem(QSpacerItem(10, 0), 0, 1, 6, 1)
layout.addWidget(detail, 0, 2, 6, 1)
# layout.setRowStretch(0, 1)
layout.setRowStretch(2, 1)
layout.setColumnStretch(2, 1)
# layout.setColumnStretch(2, 1)
return widget
def layout_panel(self):
widget = QWidget()
layout = QVBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
tabs = QTabWidget()
review_index = tabs.addTab(self.layout_review(), _('Review'))
log_index = tabs.addTab(self.layout_log(), _('Log'))
errors_index = tabs.addTab(self.layout_errors(), _('Errors'))
tabs.setStyleSheet('QTabBar::tab {min-width:120px;}')
self.trans_worker.start.connect(
lambda: (self.translate_all or self.table.selected_count() > 1)
and tabs.setCurrentIndex(log_index))
self.trans_worker.finished.connect(
lambda: tabs.setCurrentIndex(
errors_index if self.errors_text.toPlainText()
else review_index))
splitter = QSplitter()
splitter.addWidget(self.layout_table())
splitter.addWidget(tabs)
splitter.setSizes([int(splitter.width() / 2)] * 2)
layout.addWidget(self.layout_control())
layout.addWidget(splitter, 1)
return widget
def layout_filter(self):
widget = QWidget()
layout = QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
categories = QComboBox()
categories.addItem(_('All'), 'all')
if self.merge_enabled:
categories.addItem(_('Non-aligned'), 'non_aligned')
categories.addItem(_('Translated'), 'translated')
categories.addItem(_('Untranslated'), 'untranslated')
content_types = QComboBox()
content_types.addItem(_('Original Text'), 'original_text')
content_types.addItem(_('Original Code'), 'original_code')
content_types.addItem(_('Translation Text'), 'translation_text')
search_input = QLineEdit()
search_input.setPlaceholderText(_('keyword for filtering'))
set_shortcut(
search_input, 'search', search_input.setFocus,
search_input.placeholderText())
reset_button = QPushButton(_('Reset'))
reset_button.setVisible(False)
def filter_table_items(index):
self.table.show_all_rows()
category = categories.itemData(index)
if category == 'non_aligned':
self.table.hide_by_paragraphs(self.table.aligned_paragraphs())
elif category == 'translated':
self.table.hide_by_paragraphs(
self.table.untranslated_paragraphs())
elif category == 'untranslated':
self.table.hide_by_paragraphs(
self.table.translated_paragraphs())
def filter_by_category(index):
reset_button.setVisible(index != 0)
filter_table_items(index)
self.table.show_by_text(
search_input.text(), content_types.currentData())
categories.currentIndexChanged.connect(filter_by_category)
def filter_by_content_type(index):
reset_button.setVisible(index != 0)
filter_table_items(categories.currentIndex())
self.table.show_by_text(
search_input.text(), content_types.itemData(index))
content_types.currentIndexChanged.connect(filter_by_content_type)
def filter_by_keyword(text):
reset_button.setVisible(text != '')
filter_table_items(categories.currentIndex())
self.table.show_by_text(text, content_types.currentData())
search_input.textChanged.connect(filter_by_keyword)
def reset_filter_criteria():
categories.setCurrentIndex(0)
content_types.setCurrentIndex(0)
search_input.clear()
reset_button.setVisible(False)
reset_button.clicked.connect(reset_filter_criteria)
# def reset_filter():
# filter_table_items(categories.currentIndex())
# self.table.show_by_text(search_input.text())
# self.editor_worker.finished.connect(reset_filter)
# self.trans_worker.finished.connect(reset_filter)
layout.addWidget(categories)
layout.addWidget(content_types)
layout.addWidget(search_input)
layout.addWidget(reset_button)
return widget
def layout_table(self):
widget = QWidget()
widget.setSizePolicy(
QSizePolicy.Ignored, QSizePolicy.Preferred)
layout = QVBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
progress_bar = QProgressBar()
progress_bar.setMaximum(100000000)
progress_bar.setVisible(False)
def write_progress():
value = progress_bar.value() + self.progress_step
if value > progress_bar.maximum():
value = progress_bar.maximum()
progress_bar.setValue(value)
self.progress_bar.connect(write_progress)
paragraph_count = QLabel()
non_aligned_paragraph_count = QLabel()
non_aligned_paragraph_count.setVisible(False)
counter = QWidget()
counter_layout = QHBoxLayout(counter)
counter_layout.setContentsMargins(0, 0, 0, 0)
counter_layout.setSpacing(0)
counter_layout.addWidget(paragraph_count)
counter_layout.addWidget(non_aligned_paragraph_count)
counter_layout.addStretch(1)
self.footer.layout().insertWidget(0, counter)
def get_paragraph_count(select_all=True):
item_count = char_count = 0
paragraphs = self.table.get_selected_paragraphs(
select_all=select_all)
for paragraph in paragraphs:
item_count += 1
char_count += len(paragraph.original)
return (item_count, char_count)
all_item_count, all_char_count = get_paragraph_count(True)
def item_selection_changed():
item_count, char_count = get_paragraph_count(False)
total = '%s/%s' % (item_count, all_item_count)
parts = '%s/%s' % (char_count, all_char_count)
paragraph_count.setText(
_('Total items: {}').format(total) + ' · '
+ _('Character count: {}').format(parts))
item_selection_changed()
self.table.itemSelectionChanged.connect(item_selection_changed)
if self.merge_enabled:
non_aligned_paragraph_count.setVisible(True)
def show_none_aligned_count():
non_aligned_paragraph_count.setText(
' · ' + _('Non-aligned items: {}')
.format(self.table.non_aligned_count))
show_none_aligned_count()
self.table.row.connect(show_none_aligned_count)
filter_widget = self.layout_filter()
layout.addWidget(filter_widget)
layout.addWidget(self.table, 1)
layout.addWidget(progress_bar)
layout.addWidget(self.layout_table_control())
def working_start():
if self.translate_all or self.table.selected_count() > 1:
filter_widget.setVisible(False)
progress_bar.setValue(0)
progress_bar.setVisible(True)
counter.setVisible(False)
self.trans_worker.start.connect(working_start)
def working_end():
filter_widget.setVisible(True)
progress_bar.setVisible(False)
counter.setVisible(True)
self.trans_worker.finished.connect(working_end)
return widget
def layout_table_control(self):
action_widget = QWidget()
action_layout = QHBoxLayout(action_widget)
action_layout.setContentsMargins(0, 0, 0, 0)
delete_button = QPushButton(_('Delete'))
delete_button.setToolTip(delete_button.text() + ' [Del]')
batch_translation = QPushButton(
' %s (%s)' % (_('Batch Translation'), _('Beta')))
translate_all = QPushButton(' %s ' % _('Translate All'))
translate_selected = QPushButton(' %s ' % _('Translate Selected'))
delete_button.clicked.connect(self.table.delete_selected_rows)
translate_all.clicked.connect(self.translate_all_paragraphs)
translate_selected.clicked.connect(self.translate_selected_paragraph)
action_layout.addWidget(delete_button)
action_layout.addStretch(1)
action_layout.addWidget(batch_translation)
action_layout.addWidget(translate_all)
action_layout.addWidget(translate_selected)
stop_widget = QWidget()
stop_layout = QHBoxLayout(stop_widget)
stop_layout.setContentsMargins(0, 0, 0, 0)
# stop_layout.addStretch(1)
stop_button = QPushButton(_('Stop'))
stop_layout.addWidget(stop_button)
delete_button.setDisabled(True)
translate_selected.setDisabled(True)
self.batch_translation.connect(
lambda: batch_translation.setVisible(
self.current_engine == ChatgptTranslate))
self.batch_translation.emit()
def start_batch_translation():
translator = get_translator(self.current_engine)
translator.set_source_lang(self.ebook.source_lang)
translator.set_target_lang(self.ebook.target_lang)
batch_translator = ChatgptBatchTranslate(translator)
batch = ChatgptBatchTranslationManager(
batch_translator, self.cache, self.table, self)
batch.exec_()
batch_translation.clicked.connect(start_batch_translation)
def item_selection_changed():
disabled = self.table.selected_count() < 1
delete_button.setDisabled(disabled)
translate_selected.setDisabled(disabled)
item_selection_changed()
self.table.itemSelectionChanged.connect(item_selection_changed)
def stop_translation():
action = self.alert.ask(
_('Are you sure you want to stop the translation progress?'))
if action != 'yes':
return
stop_button.setDisabled(True)
stop_button.setText(_('Stopping...'))
self.trans_worker.set_canceled(True)
stop_button.clicked.connect(stop_translation)
def terminate_finished():
stop_button.setDisabled(False)
stop_button.setText(_('Stop'))
self.paragraph_sig.emit(self.table.current_paragraph())
self.trans_worker.finished.connect(terminate_finished)
stack = QStackedWidget()
stack.addWidget(action_widget)
stack.addWidget(stop_widget)
def working_start():
stack.setCurrentWidget(stop_widget)
action_widget.setDisabled(True)
self.trans_worker.start.connect(working_start)
def working_finished():
stack.setCurrentWidget(action_widget)
action_widget.setDisabled(False)
self.trans_worker.finished.connect(working_finished)
return stack
def layout_control(self):
widget = QWidget()
layout = QHBoxLayout(widget)
layout.setContentsMargins(0, 0, 0, 0)
cache_group = QGroupBox(_('Cache Status'))
cache_layout = QVBoxLayout(cache_group)
cache_status = QLabel(
_('Enabled') if self.cache.is_persistence() else _('Disabled'))
cache_status.setAlignment(Qt.AlignCenter)
cache_status.setStyleSheet(
'border-radius:2px;color:white;background-color:%s;'
% ('green' if self.cache.is_persistence() else 'grey'))
cache_layout.addWidget(cache_status)
engine_group = QGroupBox(_('Translation Engine'))
engine_layout = QVBoxLayout(engine_group)
engine_list = EngineList(self.current_engine.name)
engine_list.setMaximumWidth(150)
engine_layout.addWidget(engine_list)
source_group = QGroupBox(_('Source Language'))
source_layout = QVBoxLayout(source_group)
source_lang = SourceLang()
source_lang.setMaximumWidth(150)
source_layout.addWidget(source_lang)
target_group = QGroupBox(_('Target Language'))
target_layout = QVBoxLayout(target_group)
target_lang = TargetLang()
target_lang.setMaximumWidth(150)
target_layout.addWidget(target_lang)
title_group = QGroupBox(_('Custom Ebook Title'))
title_layout = QHBoxLayout(title_group)
custom_title = QCheckBox()
ebook_title = QLineEdit()
ebook_title.setToolTip(
_('By default, title metadata will be translated.'))
ebook_title.setText(self.ebook.title)
ebook_title.setCursorPosition(0)
ebook_title.setDisabled(True)
title_layout.addWidget(custom_title)
title_layout.addWidget(ebook_title)
def enable_custom_title(checked):
ebook_title.setDisabled(not checked)
self.ebook.set_custom_title(
ebook_title.text() if checked else None)
if checked:
ebook_title.setFocus(Qt.MouseFocusReason)
custom_title.stateChanged.connect(enable_custom_title)
def change_ebook_title():
if ebook_title.text() == '':
ebook_title.undo()
self.ebook.set_custom_title(ebook_title.text())
ebook_title.editingFinished.connect(change_ebook_title)
# if self.config.get('to_library'):
# ebook_title.setDisabled(True)
# ebook_title.setToolTip(_(
# "The ebook's filename is automatically managed by Calibre "
# 'according to metadata since the output path is set to '
# 'Calibre Library.'))
# ebook_title.textChanged.connect(self.ebook.set_custom_title)
output_group = QGroupBox(_('Output Ebook'))
output_layout = QHBoxLayout(output_group)
output_button = QPushButton(_('Output'))
output_format = OutputFormat()
output_layout.addWidget(output_format)
output_layout.addWidget(output_button)
layout.addWidget(cache_group)
layout.addWidget(engine_group)
layout.addWidget(source_group)
layout.addWidget(target_group)
layout.addWidget(title_group, 1)
layout.addWidget(output_group)
source_lang.currentTextChanged.connect(
self.trans_worker.set_source_lang)
target_lang.currentTextChanged.connect(
self.trans_worker.set_target_lang)
def refresh_languages():
source_lang.refresh.emit(
self.current_engine.lang_codes.get('source'),
self.ebook.source_lang,
not isinstance(self.current_engine, CustomTranslate))
target_lang.refresh.emit(
self.current_engine.lang_codes.get('target'),
self.ebook.target_lang)
refresh_languages()
self.ebook.set_source_lang(source_lang.currentText())
def choose_engine(index):
engine_name = engine_list.itemData(index)
self.current_engine = get_engine_class(engine_name)
self.trans_worker.set_engine_class(self.current_engine)
self.batch_translation.emit()
refresh_languages()
engine_list.currentIndexChanged.connect(choose_engine)
output_format.setCurrentText(self.ebook.output_format)
def change_output_format(format):
self.ebook.set_output_format(format)
change_output_format(output_format.currentText())
output_format.currentTextChanged.connect(change_output_format)
if self.ebook.is_extra_format():
output_format.lock_format(self.ebook.input_format)
change_output_format(self.ebook.input_format)
def output_ebook():
if len(self.table.findItems(_('Translated'), Qt.MatchExactly)) < 1:
self.alert.pop(_('The ebook has not been translated yet.'))
return
if self.table.non_aligned_count > 0:
message = _(
'The number of lines in some translation units differs '
'between the original text and the translated text. Are '
'you sure you want to output without checking alignment?')
if self.alert.ask(message) != 'yes':
return
lang_code = self.current_engine.get_iso639_target_code(
self.ebook.target_lang)
self.ebook.set_lang_code(lang_code)
self.worker.translate_ebook(self.ebook, cache_only=True)
self.done(1)
output_button.clicked.connect(output_ebook)
def working_start():
self.translate_all and widget.setVisible(False)
widget.setDisabled(True)
self.trans_worker.start.connect(working_start)
def working_finished():
widget.setVisible(True)
widget.setDisabled(False)
self.trans_worker.finished.connect(working_finished)
return widget
def layout_review(self):
widget = QWidget()
layout = QVBoxLayout(widget)
splitter = QSplitter(Qt.Vertical)
splitter.setContentsMargins(0, 0, 0, 0)
raw_text = QPlainTextEdit()
raw_text.setReadOnly(True)
original_text = QPlainTextEdit()
original_text.setReadOnly(True)
translation_text = QPlainTextEdit()
if self.ebook.target_direction == 'rtl':
translation_text.setLayoutDirection(Qt.RightToLeft)
document = translation_text.document()
option = document.defaultTextOption()
option.setAlignment(Qt.AlignRight)
document.setDefaultTextOption(option)
translation_text.setPlaceholderText(_('No translation yet'))
splitter.addWidget(raw_text)
splitter.addWidget(original_text)
splitter.addWidget(translation_text)
splitter.setSizes([0] + [int(splitter.height() / 2)] * 2)
translation_text.cursorPositionChanged.connect(
translation_text.ensureCursorVisible)
def refresh_translation(paragraph):
# TODO: check - why/how can "paragraph" be None and what should we do in such case?
if paragraph is not None:
raw_text.setPlainText(paragraph.raw.strip())
original_text.setPlainText(paragraph.original.strip())
translation_text.setPlainText(paragraph.translation)
self.paragraph_sig.connect(refresh_translation)
self.trans_worker.start.connect(
lambda: translation_text.setReadOnly(True))
self.trans_worker.finished.connect(
lambda: translation_text.setReadOnly(False))
# default_flag = translation_text.textInteractionFlags()
# def disable_translation_text():
# if self.trans_worker.on_working:
# translation_text.setTextInteractionFlags(Qt.TextEditable)
# end = getattr(QTextCursor.MoveOperation, 'End', None) \
# or QTextCursor.End
# translation_text.moveCursor(end)
# else:
# translation_text.setTextInteractionFlags(default_flag)
# translation_text.cursorPositionChanged.connect(
# disable_translation_text)
def auto_open_close_splitter():
if splitter.sizes()[0] > 0:
sizes = [0] + [int(splitter.height() / 2)] * 2
else:
sizes = [int(splitter.height() / 3)] * 3
splitter.setSizes(sizes)
self.install_widget_event(