forked from bookfere/Ebook-Translator-Calibre-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvanced.py
More file actions
2312 lines (2030 loc) · 94.3 KB
/
Copy pathadvanced.py
File metadata and controls
2312 lines (2030 loc) · 94.3 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
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 qt.core import ( # type: ignore
Qt, QObject, QDialog, QGroupBox, QWidget, QVBoxLayout, QHBoxLayout,
QPlainTextEdit, QPushButton, QSplitter, QLabel, QThread, QLineEdit,
QGridLayout, QProgressBar, pyqtSignal, pyqtSlot, QPixmap, QEvent,
QStackedWidget, QSpacerItem, QTabWidget, QCheckBox,
QComboBox, QSizePolicy, QTextCursor, QMenu, QAction)
from calibre.constants import __version__ # type: ignore
from calibre.gui2 import I # type: ignore
from calibre.utils.localization import _ # type: ignore
from . import EbookTranslator
from .lib.utils import 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.anthropic import ClaudeTranslate
from .engines.custom import CustomTranslate
from .components import (
EngineList, Footer, SourceLang, TargetLang, InputFormat, OutputFormat,
AlertMessage, AdvancedTranslationTable, StatusColor, TranslationStatus,
set_shortcut, ChatgptBatchTranslationManager)
from .components.editor import CodeEditor
load_translations() # type: ignore
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('')
if callback is not None:
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.current_engine = engine_class
self.ebook = ebook
self.on_working = False
self.canceled = False
self.start.connect(self.prepare_ebook_data)
def clean_cache(self, cache):
if cache.is_fresh():
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.current_engine.placeholder, self.current_engine.separator,
self.ebook.target_direction)
from .lib.utils import get_cache_id
merge_length = element_handler.get_merge_length()
cache_id = get_cache_id(input_path, self.current_engine.name, self.ebook.target_lang,
merge_length, self.ebook.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.current_engine.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)
consistency = pyqtSignal(list)
consistency_completed = pyqtSignal()
consistency_glossary = pyqtSignal(list)
consistency_glossary_completed = pyqtSignal(int)
agreement = pyqtSignal(list)
agreement_completed = pyqtSignal(int)
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.current_engine = engine_class
self.on_working = False
self.canceled = False
self.need_close = False
# The Translation Brief (a dict) is held here in-memory after
# build, and also persisted to cache via `translation_brief`
# info key. Drafting reads it from whichever source is
# populated and pins it on the translator via
# `translator.translation_brief = ...`.
self.brief = None
# Cache reference, set externally by the dialog after the
# cache is constructed. Used by the auto-trigger to fetch
# all paragraphs for brief building, and to persist a
# newly-built brief.
self.cache = None
self.translate.connect(self.translate_paragraphs)
self.consistency.connect(self.run_consistency_pass)
self.consistency_glossary.connect(
self.run_consistency_pass_glossary)
self.agreement.connect(self.run_agreement_pass)
# 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.current_engine = 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
def _auto_build_brief(self, translator, log):
"""Auto-build a Translation Brief from all source paragraphs
in the cache, before per-paragraph translation begins. This
runs the full three-turn pipeline (build → language review →
logic review) — same flow as the manual 'Build Brief' button,
but with quieter logging suitable for an in-line preparation
step.
Returns the brief dict on success, or None if the build
failed for any reason. The caller persists the brief to
cache via `cache.set_info('translation_brief', ...)`.
"""
from .lib.translation import Translation as _Translation
all_paragraphs = self.cache.all_paragraphs()
if not all_paragraphs:
return None
log('═' * 50)
log(_('Auto-building Translation Brief before drafting...'))
log(_('(First translation in this book — building a '
'reference document with canonical names, character '
'profiles with gender, and recurring terminology so '
'subsequent paragraph translations stay consistent. '
'This takes ~2-3 minutes once per book; afterwards the '
'brief is cached and reused on every subsequent '
'translate.)'))
patterns = _Translation._IDENTIFYING_PATTERNS
items = []
stripped = 0
for i, p in enumerate(all_paragraphs):
text = (p.original or '').strip()
if not text:
continue
if any(pat.search(text) for pat in patterns):
stripped += 1
continue
items.append({'index': i, 'text': text})
if not items:
log(_('No source paragraphs available for brief '
'building.'), True)
return None
log(_('Source: {} eligible blocks (stripped {} '
'identifying paragraphs).').format(
len(items), stripped))
try:
brief = translator.build_translation_brief(
items,
on_progress=log,
cancel_request=self.cancel_request)
except Exception as e:
log(_('Brief build failed: {}').format(str(e)), True)
log(traceback_error(), True)
return None
if brief is None:
log(_('Brief build returned no usable result; '
'proceeding without brief.'), True)
return None
# Quieter summary than the manual-button path.
chars = brief.get('characters') or []
terms = brief.get('terminology') or []
log(_('Brief built: {} character(s), {} term(s).').format(
len(chars), len(terms)))
log('═' * 50)
return brief
def _auto_agreement_pass(self, translator, log):
"""Run the Agreement Pass over every paragraph in the cache
immediately after drafting completes. Fixes are stored as a
separate cache key (agreement_pass_fixes) and applied at
export time — raw paragraph translations in the cache are
never modified. In-memory paragraph objects are mutated for
table display only.
"""
import json as _json
paragraphs = self.cache.all_paragraphs() or []
items = []
for i, p in enumerate(paragraphs):
t = (getattr(p, 'translation', None) or '').strip()
if t:
items.append({'index': i,
'translation': p.translation})
if not items:
return
log('═' * 50)
log(_('Running post-translation Agreement Pass...'))
result = translator.agreement_review(
items, self.brief, on_progress=log,
cancel_request=self.cancel_request)
fixes = result.get('fixes') or []
unfixable = result.get('unfixable') or []
considered = result.get('considered', 0)
applied_fixes = []
char_index = {}
for c in (self.brief.get('characters') or []):
if isinstance(c, dict) and c.get('id'):
char_index[c['id']] = c
for f in fixes:
idx = f.get('block_index')
old_str = f.get('old_str') or ''
new_str = f.get('new_str') or ''
if (not isinstance(idx, int)
or idx < 0 or idx >= len(paragraphs)
or not old_str or old_str == new_str):
continue
p = paragraphs[idx]
t = getattr(p, 'translation', None) or ''
if t.count(old_str) != 1:
continue
# Mutate in-memory only — for table display.
# Raw translation in cache is preserved.
p.translation = t.replace(old_str, new_str, 1)
applied_fixes.append(f)
try:
self.callback.emit(p)
except Exception:
pass
cid = f.get('character_id') or ''
cname = (char_index.get(cid, {}).get('canonical_name')
if cid else '') or cid or '—'
kind = f.get('kind') or 'other'
log(' ✓ block_{} [{}] {} — {!r} → {!r}'.format(
idx, kind, cname, old_str, new_str))
if unfixable:
log(_('Rejected (uniqueness failed): {}').format(
len(unfixable)))
log(_('Agreement Pass: reviewed {} character-mentioning '
'paragraph(s); {} fix(es) will be applied at '
'export.').format(considered, len(applied_fixes)))
try:
self.cache.set_info(
'agreement_pass_fixes',
_json.dumps(applied_fixes, ensure_ascii=False))
from datetime import datetime
ts = datetime.now().strftime('%Y-%m-%d %H:%M')
self.cache.set_info('last_agreement_pass', ts)
except Exception:
pass
try:
self.agreement_completed.emit(len(applied_fixes))
except Exception:
pass
@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.current_engine)
translator.set_source_lang(self.source_lang)
translator.set_target_lang(self.target_lang)
import json as _json
log = lambda text, error=False: self.logging.emit(text, error)
# ── Auto-trigger Translation Brief build ──────────────────
# If no brief exists yet AND the engine supports brief
# building AND the user hasn't opted out via setting AND we
# have access to cached source paragraphs, build a brief
# before drafting starts. The brief is the difference
# between "translate each paragraph in isolation" and
# "translate with full canonical-name and gender awareness."
if (self.brief is None
and hasattr(translator, 'build_translation_brief')
and getattr(translator, 'enable_translation_brief',
False)
and self.cache is not None):
try:
brief = self._auto_build_brief(translator, log)
if brief is not None:
self.brief = brief
try:
self.cache.set_info(
'translation_brief',
_json.dumps(brief, ensure_ascii=False))
except Exception:
pass
except Exception as e:
log(_('Auto-brief build failed: {} — proceeding '
'without brief.').format(str(e)), True)
# Pin the brief on the translator so engines that support
# brief-aware drafting can inject it into their per-paragraph
# system prompt. Strip review-pipeline metadata (the
# _review_*_changes keys) before injecting — those are build-
# time artifacts, not part of the brief's reference content.
if (self.brief is not None
and getattr(translator, 'enable_translation_brief',
False)):
brief_for_drafting = {
k: v for k, v in self.brief.items()
if not (isinstance(k, str) and k.startswith('_review_'))}
translator.translation_brief = brief_for_drafting
translation = get_translation(translator)
translation.set_fresh(fresh)
translation.set_cache(self.cache)
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)
# ── Auto-trigger Agreement Pass ────────────────────────────
# Once drafting is complete, run a post-translation
# Agreement Pass to fix residual gender/number/pronoun drift
# against the brief's canonical morphology. Gated on the
# same setting that gates the manual button — disabling the
# setting suppresses both the button and this auto-run.
# Cancellation, missing brief, or unsupported engine all
# silently skip (logged, non-fatal).
if (not self.cancel_request()
and self.brief is not None
and self.cache is not None
and getattr(translator, 'supports_agreement_review',
False)
and getattr(translator, 'enable_agreement_pass',
False)
and hasattr(translator, 'agreement_review')
and not self.cache.get_info('agreement_pass_fixes')):
try:
self._auto_agreement_pass(translator, log)
except Exception as e:
log(_('Auto Agreement Pass failed: {}').format(
str(e)), True)
self.on_working = False
self.finished.emit()
if self.need_close:
time.sleep(0.5)
self.close.emit(0)
@pyqtSlot(list)
def run_consistency_pass(self, paragraphs=[]):
"""Phase 0 (validation spike): the 'Consistency Pass' button
is temporarily repurposed to trigger Translation Brief
construction. The brief is logged for inspection — no
persistence to cache yet, no apply phase. Once Phase 0
validates that brief construction works on real copyrighted
material, this slot will be replaced by separate prep /
terminology / agreement slots in Phase 1.
"""
import json as _json
from .lib.translation import Translation as _Translation
self.on_working = True
self.start.emit()
translator = get_translator(self.current_engine)
translator.set_source_lang(self.source_lang)
translator.set_target_lang(self.target_lang)
log = lambda text, error=False: self.logging.emit(text, error)
if not hasattr(translator, 'build_translation_brief'):
log(_('Brief building is not supported by this engine '
'(currently Claude only).'), True)
self.on_working = False
self.finished.emit()
return
try:
# Build items from SOURCE text (not translation). The
# brief is a pre-translation reference document.
patterns = _Translation._IDENTIFYING_PATTERNS
items = []
stripped = 0
for i, p in enumerate(paragraphs):
text = (p.original or '').strip()
if not text:
continue
if any(pat.search(text) for pat in patterns):
stripped += 1
continue
items.append({'index': i, 'text': text})
log('═' * 50)
log(_('Building Translation Brief...'))
log(_('Source language: {} → Target language: {}')
.format(self.source_lang, self.target_lang))
log(_('Eligible source blocks: {} (stripped {} '
'identifying paragraphs)')
.format(len(items), stripped))
if not items:
log(_('No eligible source paragraphs to analyze.'),
True)
return
brief = translator.build_translation_brief(
items, on_progress=log,
cancel_request=self.cancel_request)
log('═' * 50)
if brief is None:
log(_('Brief build returned no usable result. '
'See raw response above for diagnosis.'), True)
return
# Surface the review change lists (if any) before the
# final brief dump so the user can see what each critic
# caught and what was applied.
language_changes = brief.pop(
'_review_language_changes', None) \
if isinstance(brief, dict) else None
logic_changes = brief.pop(
'_review_logic_changes', None) \
if isinstance(brief, dict) else None
# Backwards compat with earlier single-review key.
legacy_changes = brief.pop('_review_change_list', None) \
if isinstance(brief, dict) else None
if legacy_changes is not None and language_changes is None:
language_changes = legacy_changes
log(_('Refined brief (post-review). Dumping JSON to log:'))
log(_json.dumps(brief, ensure_ascii=False, indent=2))
def _dump_changes(label, changes):
if changes is None:
return
log('─' * 50)
if changes:
log(_('{} review found {} issue(s):').format(
label, len(changes)))
for issue in changes:
cat = issue.get('category', '')
path = issue.get('field_path', '')
cur = issue.get('current', '')
sug = issue.get('suggested', '')
reason = issue.get('reason', '')
log(' [{}] {}: {!r} → {!r} — {}'.format(
cat, path, cur, sug, reason))
else:
log(_('{} review found no issues.').format(label))
_dump_changes(_('Language'), language_changes)
_dump_changes(_('Logic'), logic_changes)
# Surface a quick-scan summary alongside the JSON.
log('─' * 50)
summary = brief.get('source_summary') or {}
themes = summary.get('themes') or []
central = summary.get('central_conflict', '')
if themes:
log(_('Themes: {}').format(', '.join(themes)))
if central:
log(_('Central conflict: {}').format(central))
chars = brief.get('characters') or []
terms = brief.get('terminology') or []
char_index = {c.get('id', ''): c for c in chars if c.get('id')}
log(_('Summary: {} character(s), {} term(s).')
.format(len(chars), len(terms)))
for c in chars:
cid = c.get('id', '')
name = c.get('canonical_name', '')
src = c.get('source_name', '')
gender = c.get('gender', '')
role = c.get('role', '')
mentions = c.get('mention_count')
first = c.get('first_occurrence_index')
meta_bits = []
if mentions is not None:
meta_bits.append('×{}'.format(mentions))
if first is not None:
meta_bits.append('first@block_{}'.format(first))
meta = ' [' + ', '.join(meta_bits) + ']' if meta_bits else ''
log(' • [{}] {} ({} ← {}) — {}{}'.format(
cid, name, gender, src, role, meta))
# Show relationships using canonical names where ids
# resolve, ids otherwise.
for rel in (c.get('relationships') or []):
to_id = rel.get('to_id', '')
rtype = rel.get('type', '')
target = char_index.get(to_id)
target_label = (target.get('canonical_name', to_id)
if target else to_id)
log(' ↳ {} → {}'.format(rtype, target_label))
for t in terms:
tid = t.get('id', '')
canon = t.get('canonical', '')
src = t.get('source_form', '')
ttype = t.get('type', '')
dnt = t.get('do_not_translate', False)
mentions = t.get('mention_count')
first = t.get('first_occurrence_index')
meta_bits = []
if dnt:
meta_bits.append('DNT')
if mentions is not None:
meta_bits.append('×{}'.format(mentions))
if first is not None:
meta_bits.append('first@block_{}'.format(first))
meta = ' [' + ', '.join(meta_bits) + ']' if meta_bits else ''
log(' · [{}] {} ({}) ← {}{}'.format(
tid, canon, ttype, src, meta))
# Phase 1a spike: hold the brief in-memory on the worker
# so subsequent translate_paragraphs calls in the same
# session can pin it on the translator. The dialog's
# consistency_completed handler will also persist it to
# cache so it survives plugin reloads.
self.brief = brief
self.consistency_completed.emit()
except Exception as e:
log(_('Brief build failed: {}').format(str(e)), True)
log(traceback_error(), True)
finally:
self.on_working = False
self.finished.emit()
@pyqtSlot(list)
def run_consistency_pass_glossary(self, paragraphs=[]):
"""Manually rebuild the Consistency Pass glossary from the
current translated paragraphs and store it in cache. Does NOT
modify paragraph translations — substitutions are applied at
export time only."""
import json as _json
self.on_working = True
self.start.emit()
translator = get_translator(self.current_engine)
translator.set_source_lang(self.source_lang)
translator.set_target_lang(self.target_lang)
log = lambda text, error=False: self.logging.emit(text, error)
if not hasattr(translator, 'consistency_review'):
log(_('Consistency Pass is not supported by this '
'engine.'), True)
self.on_working = False
self.finished.emit()
return
try:
items = []
for i, p in enumerate(paragraphs):
t = (getattr(p, 'translation', None) or '').strip()
if t:
items.append({'index': i,
'translation': p.translation})
if not items:
log(_('No translated paragraphs to review.'), True)
return
log('═' * 50)
log(_('Running Consistency Pass...'))
log(_('Reviewing {} translated paragraph(s).')
.format(len(items)))
review = translator.consistency_review(
items, on_progress=log,
cancel_request=self.cancel_request)
glossary = (review.get('glossary') or []
if isinstance(review, dict) else [])
log('─' * 50)
log(_('Consistency Pass: {} glossary entry(s).')
.format(len(glossary)))
for g in glossary:
canonical = g.get('canonical', '')
variants = g.get('variants') or []
if variants:
log(' {} ← [{}]'.format(
canonical, ', '.join(variants)))
if self.cache is not None and glossary:
self.cache.set_info(
'consistency_pass_glossary',
_json.dumps(glossary, ensure_ascii=False))
try:
from datetime import datetime
self.cache.set_info(
'last_consistency_pass_glossary',
datetime.now().strftime('%Y-%m-%d %H:%M'))
except Exception:
pass
log('═' * 50)
log(_('Consistency Pass complete: glossary cached for '
'export ({} entries).').format(len(glossary)))
self.consistency_glossary_completed.emit(len(glossary))
except Exception as e:
log(_('Consistency Pass failed: {}').format(str(e)), True)
log(traceback_error(), True)
finally:
self.on_working = False
self.finished.emit()
@pyqtSlot(list)
def run_agreement_pass(self, paragraphs=[]):
"""Run an Agreement Pass over the translated paragraphs:
scan for residual gender/number/pronoun drift against the
canonical character morphology in the brief, request fixes
from the engine, validate single-occurrence uniqueness, and
apply the validated fixes back to the cache.
Requires a brief to be present (the canonical morphology
source). Skips silently with a log message if absent.
"""
import json as _json
self.on_working = True
self.start.emit()
translator = get_translator(self.current_engine)
translator.set_source_lang(self.source_lang)
translator.set_target_lang(self.target_lang)
log = lambda text, error=False: self.logging.emit(text, error)
if not getattr(translator, 'supports_agreement_review', False) \
or not hasattr(translator, 'agreement_review'):
log(_('Agreement Pass is not supported by this engine '
'(currently Claude only).'), True)
self.on_working = False
self.finished.emit()
return
# Rehydrate brief: prefer the in-memory copy, fall back to
# the persisted one in cache.
brief = self.brief
if brief is None and self.cache is not None:
try:
brief_json = self.cache.get_info('translation_brief')
if brief_json:
brief = _json.loads(brief_json)
except Exception:
brief = None
if not brief:
log(_('Agreement Pass requires a Translation Brief. '
'Click "Build Brief" first (or run a translation '
'with auto-brief enabled).'), True)
self.on_working = False
self.finished.emit()
return
try:
log('═' * 50)
log(_('Running Agreement Pass...'))
log(_('Target language: {}').format(self.target_lang))
# Items use the paragraphs' indices in the supplied list
# — these match the block_N indices the engine emits in
# its fixes. Caller passes all_paragraphs() so indices
# are stable across the book.
items = []
for i, p in enumerate(paragraphs):
t = (getattr(p, 'translation', None) or '').strip()
if not t:
continue
items.append({
'index': i,
'translation': p.translation,
})
log(_('Translated paragraphs available: {}/{}.').format(
len(items), len(paragraphs)))
if not items:
log(_('No translated paragraphs to review.'), True)
return
result = translator.agreement_review(
items, brief, on_progress=log,
cancel_request=self.cancel_request)
fixes = result.get('fixes') or []
unfixable = result.get('unfixable') or []
considered = result.get('considered', 0)
log('─' * 50)
log(_('Agreement Pass: reviewed {} paragraph(s) that '
'mention named characters; {} fix(es) validated, '
'{} rejected by uniqueness check.').format(
considered, len(fixes), len(unfixable)))
applied_fixes = []
char_index = {}
for c in (brief.get('characters') or []):
if isinstance(c, dict) and c.get('id'):
char_index[c['id']] = c
for f in fixes:
idx = f.get('block_index')
old_str = f.get('old_str') or ''
new_str = f.get('new_str') or ''
if (not isinstance(idx, int)
or idx < 0 or idx >= len(paragraphs)
or not old_str or old_str == new_str):
continue
p = paragraphs[idx]
t = getattr(p, 'translation', None) or ''
if t.count(old_str) != 1:
continue
# Mutate in-memory only — for table display.
# Raw translation in cache is preserved.
p.translation = t.replace(old_str, new_str, 1)
applied_fixes.append(f)
# Surface to the table so the user sees the change.
try:
self.callback.emit(p)
except Exception:
pass
cid = f.get('character_id') or ''
cname = (char_index.get(cid, {}).get('canonical_name')
if cid else '') or cid or '—'
kind = f.get('kind') or 'other'
log(' ✓ block_{} [{}] {} — {!r} → {!r} ({})'.format(
idx, kind, cname, old_str, new_str,
f.get('reason') or ''))
if unfixable:
log('─' * 50)
log(_('Rejected (uniqueness failed) — surfaced for '
'inspection:'))
for u in unfixable:
log(' ✗ block_{}: {!r} → {!r} — {}'.format(
u.get('block_index', '?'),
u.get('old_str', ''),
u.get('new_str', ''),
u.get('reason', '')))
# Persist fixes as a separate cache key — applied at
# export time, not baked into paragraph translations.
if self.cache is not None:
try:
self.cache.set_info(
'agreement_pass_fixes',
_json.dumps(applied_fixes, ensure_ascii=False))
except Exception:
pass
log('═' * 50)
log(_('Agreement Pass complete: {} fix(es) queued for '
'export.').format(len(applied_fixes)))
self.agreement_completed.emit(len(applied_fixes))
except Exception as e:
log(_('Agreement Pass failed: {}').format(str(e)), True)
log(traceback_error(), True)
finally:
self.on_working = False
self.finished.emit()
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 = QGridLayout(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, 0, 0, 1, 3)
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, 0, 3, 1, 3)
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, 1, 0, 1, 2)
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, 1, 2, 1, 2)
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)
if self.ebook.is_extra_format():
output_format.lock_format(self.ebook.input_format)
change_output_format(self.ebook.input_format)
else:
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)
self.ebook.set_lang_code(
engine_class.get_iso639_target_code(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, 1, 4, 1, 2)
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, 1, 4, 1, 2)
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.get_lang_directionality(
target_lang_code)
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()
def __init__(self, plugin, parent, worker, ebook):
QDialog.__init__(self, parent)
self.ui_settings = plugin.ui_settings
self.api = parent.current_db.new_api
self.worker = worker
self.ebook = ebook