Skip to content

Commit

Permalink
feat: Place unaligned translation at top/bottom of merged unit. resolved
Browse files Browse the repository at this point in the history
  • Loading branch information
bookfere committed Mar 9, 2024
1 parent 9bf9326 commit 2f609df
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 90 deletions.
98 changes: 56 additions & 42 deletions lib/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def delete(self):
def get_content(self, placeholder):
raise NotImplementedError()

def add_translation(self, translation, placeholder, position=None,
lang=None, color=None):
def add_translation(
self, translation, placeholder, position, lang=None, color=None):
raise NotImplementedError()


Expand All @@ -67,8 +67,8 @@ def get_text(self):
def get_content(self, placeholder):
return self.element[2]

def add_translation(self, translation, placeholder, position=None,
lang=None, color=None):
def add_translation(
self, translation, placeholder, position, lang=None, color=None):
if translation is not None:
if position == 'only':
self.element[2] = translation
Expand Down Expand Up @@ -144,13 +144,17 @@ def get_content(self, placeholder):
return trim(''.join(self.element_copy.itertext()))

def _polish_translation(self, translation):
translation = translation.replace('\n', '<br />')
# Condense consecutive letters to a maximum of four.
return re.sub(r'((\w)\2{3})\2*', r'\1', translation)

def add_translation(self, translation, placeholder, position=None,
lang=None, color=None):
def add_translation(
self, translation, placeholder, position, lang=None, color=None):
if translation is None:
if position == 'only':
if position in ('left', 'right'):
self.element.addnext(
self._create_table(position, self.element_copy))
if position in ('only', 'left', 'right'):
self.delete()
return self.element
# Escape the markups (<m id=1 />) to replace escaped markups.
Expand Down Expand Up @@ -184,20 +188,8 @@ def add_translation(self, translation, placeholder, position=None,
self.element.tail = None # Make sure the element has no tail

if position in ('left', 'right'):
# table = self.element.makeelement('table', attrib={'width': '100%'})
table = etree.XML(
'<table xmlns="{}" width="100%"></table>'.format(ns['x']))
tr = etree.SubElement(table, 'tr')
td_left = etree.SubElement(
tr, 'td', attrib={'width': '45%', 'valign': 'top'})
td_left.append(
new_element if position == 'left' else self.element_copy)
etree.SubElement(tr, 'td', attrib={'width': '10%'})
td_right = etree.SubElement(
tr, 'td', attrib={'width': '45%', 'valign': 'top'})
td_right.append(
self.element_copy if position == 'left' else new_element)
self.element.addnext(table)
self.element.addnext(
self._create_table(position, self.element_copy, new_element))
elif position == 'above':
self.element.addprevious(new_element)
else:
Expand All @@ -206,6 +198,26 @@ def add_translation(self, translation, placeholder, position=None,
self.delete()
return new_element

def _create_table(self, position, original, translation=None):
# table = self.element.makeelement('table', attrib={'width': '100%'})
table = etree.XML(
'<table xmlns="{}" width="100%"></table>'.format(ns['x']))
tr = etree.SubElement(table, 'tr')
td_left = etree.SubElement(
tr, 'td', attrib={'width': '45%', 'valign': 'top'})
etree.SubElement(tr, 'td', attrib={'width': '10%'})
td_right = etree.SubElement(
tr, 'td', attrib={'width': '45%', 'valign': 'top'})
if position == 'left':
if translation is not None:
td_left.append(translation)
td_right.append(original)
if position == 'right':
td_left.append(original)
if translation is not None:
td_right.append(translation)
return table


class Extraction:
__version__ = '20230608'
Expand Down Expand Up @@ -313,12 +325,12 @@ def filter_content(self, element):


class ElementHandler:
def __init__(self, placeholder, separator, merge_length=0):
def __init__(self, placeholder, separator, position, merge_length=0):
self.placeholder = placeholder
self.separator = separator
self.position = position
self.merge_length = merge_length

self.position = None
self.color = None
self.lang = None

Expand All @@ -330,9 +342,6 @@ def __init__(self, placeholder, separator, merge_length=0):
def get_merge_length(self):
return self.merge_length

def set_translation_position(self, position):
self.position = position

def set_translation_color(self, color):
self.color = color

Expand Down Expand Up @@ -426,16 +435,24 @@ def align_paragraph(self, paragraph):
translations = translation.strip().split(self.separator)
offset = len(originals) - len(translations)
if offset > 0:
addition = [None] * offset
if self.position == 'below':
translations = addition + translations
else:
# TODO: Merge the original and translation for the left and right.
if self.position in ['left', 'right']:
addition = [None] * offset
translations += addition
else:
merged_translations = '\n\n'.join(translations)
translations = [None] * (len(originals) - 1)
if self.position in ['above']:
translations.insert(0, merged_translations)
else:
translations.append(merged_translations)
elif offset < 0:
translations = translations[:offset]
for original in originals:
if original and original not in self.base_originals:
translations.pop(originals.index(original))
offset = len(originals) - 1
translations = translations[:offset] + [
'\n\n'.join(translations[offset:])]
# for original in originals:
# if original and original not in self.base_originals:
# translations.pop(originals.index(original))
return translations

def add_translations(self, paragraphs):
Expand All @@ -445,8 +462,6 @@ def add_translations(self, paragraphs):
total = len(translations)
count = 0
for eid, element in self.elements.copy().items():
# TODO: Maybe the translation count does not match the elements
# count due to the criteria of the old version has been changed.
if element.ignored or eid >= total:
continue
element.add_translation(
Expand Down Expand Up @@ -498,13 +513,12 @@ def get_page_elements(pages):

def get_element_handler(placeholder, separator):
config = get_config()
handler = ElementHandler(placeholder, separator)
position_alias = {'before': 'above', 'after': 'below'}
position = config.get('translation_position', 'below')
position = position_alias.get(position) or position
handler = ElementHandler(placeholder, separator, position)
if config.get('merge_enabled'):
handler = ElementHandlerMerge(
placeholder, separator, config.get('merge_length'))
position = config.get('translation_position', 'below')
position_alias = {'before': 'above', 'after': 'below'}
handler.set_translation_position(
position_alias.get(position) or position)
placeholder, separator, position, config.get('merge_length'))
handler.set_translation_color(config.get('translation_color'))
return handler
5 changes: 2 additions & 3 deletions lib/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def set_cancel_request(self, cancel_request):

def need_stop(self):
# Cancel the request if there are more than max continuous errors.
return self.translator.max_error_count != 0 and \
return self.translator.max_error_count > 0 and \
self.abort_count >= self.translator.max_error_count

def _translate_text(self, text, retry=0, interval=5):
Expand Down Expand Up @@ -149,8 +149,7 @@ def _translate_text(self, text, retry=0, interval=5):
self.abort_count += 1
message = _(
'Failed to retrieve data from translate engine API.')
retry_exceeded = retry >= self.translator.request_attempt
if retry_exceeded:
if retry >= self.translator.request_attempt:
raise TranslationFailed('{}\n{}'.format(message, str(e)))
retry += 1
interval *= retry
Expand Down
2 changes: 2 additions & 0 deletions page/_layouts/default.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ <h2 class="project-tagline">{{ page.description | default: site.description | de
</header>

<main id="content" class="main-content" role="main">
<p>&hearts; Support Open Source Software: <a href="https://paypal.me/bookfere">Paypal</a> / <a href="https://patreon.com/bookfere">Patreon</a> / <a href="https://bookfere.com/donate">More...</a></p>

{{ content }}

<footer class="site-footer">
Expand Down
Loading

0 comments on commit 2f609df

Please sign in to comment.