forked from bookfere/Ebook-Translator-Calibre-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translation.py
187 lines (145 loc) · 6.03 KB
/
translation.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
import os
import time
import random
from types import GeneratorType
# from calibre import prepare_string_for_xml as escape
from calibre_plugins.ebook_translator.utils import sep, uid, trim
from calibre_plugins.ebook_translator.config import get_config
from calibre_plugins.ebook_translator.element import ElementHandler
load_translations()
class Translation:
def __init__(self, translator, glossary):
self.translator = translator
self.glossary = glossary
self.merge_length = 0
self.translation_position = None
self.translation_color = None
self.request_attempt = 3
self.request_interval = 5
self.cache = None
self.progress = None
self.log = None
self.need_sleep = False
def set_merge_length(self, length):
self.merge_length = length
def set_translation_position(self, position):
self.translation_position = position
def set_translation_color(self, color):
self.translation_color = color
def set_request_attempt(self, limit):
self.request_attempt = limit
def set_request_interval(self, max):
self.request_interval = max
def set_cache(self, cache):
self.cache = cache
def set_progress(self, progress):
self.progress = progress
def set_log(self, log):
self.log = log
def _progress(self, *args):
if self.progress:
self.progress(*args)
def _log(self, *args, **kwargs):
if self.log:
self.log.info(*args, **kwargs)
def _translate_text(self, text, count=0, interval=5):
try:
return self.translator.translate(text)
except Exception as e:
message = _('Failed to retreive data from translate engine API.')
if count >= self.request_attempt:
raise Exception('{} {}'.format(message, str(e)))
count += 1
interval *= count
self._log(message)
self._log(_('Will retry in {} seconds.').format(interval))
time.sleep(interval)
self._log(_('Retrying ... (timeout is {} seconds).')
.format(int(self.translator.timeout)))
return self._translate_text(text, count, interval)
def _get_translation(self, original):
self._log(_('Original: {}').format(original))
translation = None
paragraph_uid = uid(original)
if self.cache and self.cache.exists():
translation = self.cache.get(paragraph_uid)
if translation is not None:
self._log(_('Translation (Cached): {}').format(translation))
self.need_sleep = False
else:
original = self.glossary.replace(original)
translation = self._translate_text(original)
# TODO: translation monitor display streaming text
if isinstance(translation, GeneratorType):
translation = ''.join(text for text in translation)
# translation = escape(trim(translation))
translation = self.glossary.restore(trim(translation))
self.cache and self.cache.add(paragraph_uid, translation)
self._log(_('Translation: {}').format(translation))
self.need_sleep = True
return translation
# element_handler.add_translation(
# translation, self.translator.get_target_code(),
# self.position, self.color)
def handle(self, elements):
element_handler = ElementHandler(
elements, self.merge_length, self.translator.get_target_code(),
self.translation_position, self.translation_color)
original_group = element_handler.get_original()
count = 0
total = len(original_group)
if total < 1:
raise Exception(_('There is no content need to translate.'))
self._log(sep, _('Start to translate ebook content:'), sep, sep='\n')
self._log(_('Total items: {}').format(total))
process, step = 0.0, 1.0 / total
for original in original_group:
self._log('-' * 30)
count += 1
self._progress(process, _('Translating: {}/{}')
.format(count, total))
element_handler.add_translation(
self._get_translation(original))
process += step
if self.need_sleep and count < total:
time.sleep(random.randint(1, self.request_interval))
element_handler.apply_translation()
self._progress(1, _('Translation completed.'))
self._log(sep, _('Start to convert ebook format:'), sep, sep='\n')
class Glossary:
def __init__(self):
self.glossary = []
def load(self, path):
try:
with open(path, encoding='utf-8') as f:
content = f.read().strip()
except Exception:
raise Exception(_('The specified glossary file does not exist.'))
if not content:
return
for group in content.split(os.linesep*2):
group = group.strip().split(os.linesep)
if len(group) > 2:
continue
if len(group) == 1:
group.append(group[0])
self.glossary.append(group)
def replace(self, text):
for word in self.glossary:
text = text.replace(word[0], 'id_%d' % id(word))
return text
def restore(self, text):
for word in self.glossary:
text = text.replace('id_%d' % id(word), word[1])
return text
def get_translation(translator):
glossary = Glossary()
if get_config('glossary_enabled'):
glossary.load(get_config('glossary_path'))
translation = Translation(translator, glossary)
translation.set_merge_length(get_config('merge_length'))
translation.set_translation_position(get_config('translation_position'))
translation.set_translation_color(get_config('translation_color'))
translation.set_request_attempt(get_config('request_attempt'))
translation.set_request_interval(get_config('request_interval'))
return translation