Skip to content

Commit

Permalink
Fixed the bug that cannot save custom engine data properly. fixed yih…
Browse files Browse the repository at this point in the history
  • Loading branch information
bookfere committed Jun 10, 2023
1 parent b31a1b4 commit dd3a155
Show file tree
Hide file tree
Showing 10 changed files with 126 additions and 77 deletions.
6 changes: 6 additions & 0 deletions advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ def __init__(self, ebook, engine_class):
self.engine_class = engine_class
self.start.connect(self.prepare_ebook_data)

def clean_cache(self, cache):
cache.is_fresh() and cache.destroy()

@pyqtSlot()
def prepare_ebook_data(self):
input_path = self.ebook.get_input_path()
Expand All @@ -80,6 +83,7 @@ def prepare_ebook_data(self):
b = time.time()
print('extract: ', b - a)
if self.cancel():
self.clean_cache(cache)
return
# --------------------------
self.progress_message.emit(_('Filtering ebook content...'))
Expand All @@ -88,6 +92,7 @@ def prepare_ebook_data(self):
c = time.time()
print('filter: ', c - b)
if self.cancel():
self.clean_cache(cache)
return
# --------------------------
self.progress_message.emit(_('Preparing user interface...'))
Expand All @@ -96,6 +101,7 @@ def prepare_ebook_data(self):
d = time.time()
print('cache: ', d - c)
if self.cancel():
self.clean_cache(cache)
return

self.finished.emit(cache_id)
Expand Down
124 changes: 78 additions & 46 deletions components/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
import uuid
from types import GeneratorType

from ..utils import sorted_mixed_keys
from ..config import get_config
from ..engines.custom import create_engine_template, load_engine_data
from ..engines import builtin_engines, GoogleFreeTranslate
from .lang import SourceLang, TargetLang
from .alert import AlertMessage
from ..utils import sorted_mixed_keys
from ..engines.custom import get_engine_template, load_engine_data
from ..config import defaults, get_config
from ..engines import builtin_engines


try:
Expand All @@ -23,19 +23,23 @@


class EngineList(QComboBox):
def __init__(self, default=None, parent=None):
QComboBox.__init__(self, parent)
def __init__(self, default=None):
QComboBox.__init__(self)
self.default = default
self.wheelEvent = lambda event: None
self.refresh(default)
self.refresh()

def refresh(self, default=None):
self.clear()
def layout(self):
for engine in builtin_engines:
self.addItem(_(engine.alias), engine.name)
custom_engines = get_config().get('custom_engines')
for name in sorted(custom_engines.keys(), key=sorted_mixed_keys):
self.addItem(name, name)
default and self.setCurrentIndex(self.findData(default))
self.default and self.setCurrentIndex(self.findData(self.default))

def refresh(self):
self.clear()
self.layout()


class EngineWorker(QObject):
Expand Down Expand Up @@ -175,13 +179,18 @@ def done(self, result):
class ManageCustomEngine(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.config = get_config()
self.parent = parent
self.config = parent.config
self.alert = AlertMessage(self)

self.custom_engines = self.config.get('custom_engines').copy()
self.engine_config = self.config.get('engine_preferences').copy()
self.default_name = self.config.get('translate_engine')

self.setWindowTitle(_('Custom Translation Engine'))
self.setModal(True)
self.setMinimumWidth(600)
self.layout()
# self.show()

def layout(self):
layout = QGridLayout(self)
Expand All @@ -191,44 +200,42 @@ def layout(self):
custom_engine_data = QPlainTextEdit()
custom_engine_data.setMinimumHeight(400)
custom_clear = QPushButton(_('Clear'))
custom_reset = QPushButton(_('Reset'))
custom_restore = QPushButton(_('Restore'))
custom_verify = QPushButton(_('Verify'))
custom_save = QPushButton(_('Save'))
layout.addWidget(custom_list, 0, 0, 1, 3)
layout.addWidget(custom_add, 0, 3)
layout.addWidget(custom_del, 0, 4)
layout.addWidget(custom_engine_data, 1, 0, 1, 5)
layout.addWidget(custom_clear, 2, 0)
layout.addWidget(custom_reset, 2, 1)
layout.addWidget(custom_restore, 2, 1)
layout.addItem(QSpacerItem(0, 0), 2, 2)
layout.addWidget(custom_verify, 2, 3)
layout.addWidget(custom_save, 2, 4)
layout.setColumnStretch(2, 1)

custom_engines = self.config.get('custom_engines').copy()
default_engine = defaults.get('translate_engine')
current_engine = self.config.get('translate_engine')
engine_preferences = self.config.get('engine_preferences')

def refresh_list():
custom_list.clear()
for name in sorted(custom_engines.keys(), key=sorted_mixed_keys):
custom_list.addItem(name)
engines = sorted(self.custom_engines.keys(), key=sorted_mixed_keys)
for engine in engines:
custom_list.addItem(engine)
refresh_list()
custom_list.setCurrentText(current_engine)
index = custom_list.findText(self.default_name)
custom_list.setCurrentIndex(index if index != -1 else 0)

def add_data():
name = 'New Engine - %s' % uuid.uuid4().hex[:5]
data = get_engine_template(name)
template = create_engine_template(name)
custom_list.addItem(name)
custom_list.setCurrentText(name)
custom_engine_data.setPlainText(data)
custom_engines[name] = data
custom_engine_data.setPlainText(template)
self.custom_engines[name] = template

def reset_data(text=None):
content = custom_engines.get(text or custom_list.currentText())
def restore_data(name=None):
name = name or custom_list.currentText()
content = self.custom_engines.get(name)
custom_engine_data.setPlainText(content)
reset_data()
restore_data()

def verify_data():
valid, data = load_engine_data(custom_engine_data.toPlainText())
Expand All @@ -238,45 +245,70 @@ def verify_data():

def save_data():
current_name = custom_list.currentText()
if not current_name:
self.config.update(
translate_engine=default_engine, custom_engines={})
if not current_name: # If all engine was deleted
self.default_name = GoogleFreeTranslate.name
else:
# Validate the custom engine data
raw_data = custom_engine_data.toPlainText()
valid, data = load_engine_data(raw_data)
if not valid:
return self.alert.pop(data, 'warning')
# Check if the engine name exists
new_name = data.get('name')
if current_name.lower() != new_name.lower():
exist_names = [name.lower() for name in custom_engines]
if new_name.lower() != current_name.lower():
exist_names = [
name.lower() for name in self.custom_engines]
if new_name.lower() in exist_names:
return self.alert.pop(
_('The engine name is already in use.'), 'warning')
del custom_engines[current_name]
custom_engines[new_name] = raw_data
self.config.update(custom_engines=custom_engines)
# Refresh custom engine data
if self.default_name == current_name:
self.default_name = new_name
if current_name in self.engine_config:
data = self.engine_config.pop(current_name)
self.engine_config[new_name] = data
del self.custom_engines[current_name]
self.custom_engines[new_name] = raw_data
# Refresh the custom engine list
refresh_list()
custom_list.setCurrentText(new_name)
# Update the custom engine
self.config.update(custom_engines=self.custom_engines)
self.config.update(engine_preferences=self.engine_config)
self.config.update(translate_engine=self.default_name)
self.config.commit()
self.alert.pop(_('The setting has been saved.'))
# self.done(0)

def delete_data():
if custom_list.count() < 1:
return self.alert.pop(_('No custom engine to delete.'))
current_index = custom_list.currentIndex()
current_name = custom_list.itemText(current_index)
del custom_engines[current_name]
if current_name in self.custom_engines:
del self.custom_engines[current_name]
if current_name in self.engine_config:
del self.engine_config[current_name]
if current_name == self.default_name:
self.default_name = GoogleFreeTranslate.name
custom_list.removeItem(current_index)
if current_name == current_engine:
self.config.update(translate_engine=default_engine)
if current_name in engine_preferences:
del engine_preferences[current_name]

custom_list.currentTextChanged.connect(reset_data)
def disable_save_button():
disabled = custom_list.count() < 1
custom_del.setDisabled(disabled)
custom_clear.setDisabled(disabled)
custom_restore.setDisabled(disabled)
custom_verify.setDisabled(disabled)
custom_save.setDisabled(disabled)
disable_save_button()

custom_list.currentTextChanged.connect(disable_save_button)
custom_list.currentTextChanged.connect(restore_data)
custom_add.clicked.connect(add_data)
custom_del.clicked.connect(delete_data)
custom_clear.clicked.connect(custom_engine_data.clear)
custom_reset.clicked.connect(reset_data)
custom_restore.clicked.connect(restore_data)
custom_verify.clicked.connect(verify_data)
custom_save.clicked.connect(save_data)

def done(self, result):
QDialog.done(self, result)
self.parent.raise_()
self.parent.activateWindow()
2 changes: 1 addition & 1 deletion engines/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
load_translations()


def get_engine_template(name):
def create_engine_template(name):
return """{
"name": "%s",
"languages": {
Expand Down
41 changes: 25 additions & 16 deletions setting.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
import os.path
from subprocess import Popen

from .components import (
layout_info, AlertMessage, TargetLang, SourceLang, EngineList,
EngineTester, get_divider, ManageCustomEngine, InputFormat, OutputFormat)
from .config import get_config
from .utils import css, is_proxy_availiable
from .cache import TranslationCache
from .translation import get_engine_class
from .components import (
layout_info, AlertMessage, TargetLang, SourceLang, EngineList,
EngineTester, get_divider, ManageCustomEngine, InputFormat, OutputFormat)
from .engines import builtin_engines


try:
Expand Down Expand Up @@ -40,12 +41,10 @@ class TranslationSetting(QDialog):
def __init__(self, plugin, parent, icon):
QDialog.__init__(self, parent)
self.plugin = plugin
self.gui = parent
self.icon = icon
self.alert = AlertMessage(self)

self.config = get_config()
# self.config.refresh()
self.current_engine = get_engine_class()

self.main_layout()
Expand Down Expand Up @@ -373,7 +372,7 @@ def layout_engine(self):
# Translate Engine
engine_group = QGroupBox(_('Translation Engine'))
engine_layout = QHBoxLayout(engine_group)
engine_list = EngineList()
engine_list = EngineList(self.current_engine.name)
engine_test = QPushButton(_('Test'))
manage_engine = QPushButton(_('Custom'))
engine_layout.addWidget(engine_list, 1)
Expand Down Expand Up @@ -505,11 +504,9 @@ def change_sampling_method(button):

def choose_default_engine(index):
engine_name = engine_list.itemData(index)
self.config.update(translate_engine=engine_name)
if self.current_engine.name != engine_name:
self.config.update(translate_engine=engine_name)
self.current_engine = get_engine_class(engine_name)
# show api key setting
self.set_api_keys()
# refresh preferred language
source_lang = self.current_engine.config.get('source_lang')
self.source_lang.refresh.emit(
Expand All @@ -518,18 +515,23 @@ def choose_default_engine(index):
target_lang = self.current_engine.config.get('target_lang')
self.target_lang.refresh.emit(
self.current_engine.lang_codes.get('target'), target_lang)
# show prompt setting
show_chatgpt_preferences()
self.set_api_keys() # show api key setting
show_chatgpt_preferences() # show prompt setting
choose_default_engine(engine_list.findData(self.current_engine.name))
engine_list.currentIndexChanged.connect(choose_default_engine)

default_index = engine_list.findData(self.current_engine.name)
engine_list.setCurrentIndex(default_index)
choose_default_engine(default_index)
def refresh_engine_list():
"""Prevent engine list auto intercept the text changed signal."""
engine_list.currentIndexChanged.disconnect(choose_default_engine)
engine_list.refresh()
index = engine_list.findData(self.config.get('translate_engine'))
choose_default_engine(index)
engine_list.setCurrentIndex(index)
engine_list.currentIndexChanged.connect(choose_default_engine)

def manage_custom_translation_engine():
manager = ManageCustomEngine(self)
manager.finished.connect(
lambda: engine_list.refresh(self.current_engine.name))
manager.finished.connect(refresh_engine_list)
manager.show()
manage_engine.clicked.connect(manage_custom_translation_engine)

Expand Down Expand Up @@ -847,6 +849,13 @@ def update_engine_config(self):
# Do not update directly as you may get default preferences!
engine_config = self.config.get('engine_preferences').copy()
engine_config.update({self.current_engine.name: config})
# Cleanup unused engine preferences
engine_names = [engine.name for engine in builtin_engines]
engine_names += self.config.get('custom_engines').keys()
for name in engine_config.copy():
if name not in engine_names:
engine_config.pop(name)
# Update modified engine preferences
self.config.update(engine_preferences=engine_config)
self.config.commit()
self.alert.pop(_('The setting has been saved.'))
Expand Down
21 changes: 11 additions & 10 deletions translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,18 +173,19 @@ def process_translation(paragraph):

def get_engine_class(engine_name=None):
config = get_config()
engine_name = engine_name or config.get('translate_engine')
engines = {engine.name: engine for engine in builtin_engines}
engine_name = engine_name or config.get('translate_engine') \
or GoogleFreeTranslate.name
engine_class = engines.get(engine_name) or CustomTranslate
if engine_class.is_custom():
engine_data = config.get('custom_engines.%s' % engine_name)
if engine_data is not None:
engine_data = json.loads(engine_data)
engine_class.set_engine_data(engine_data)
custom_engines = config.get('custom_engines')
if engine_name in engines:
engine_class = engines.get(engine_name)
elif engine_name in custom_engines:
engine_class = CustomTranslate
engine_data = json.loads(custom_engines.get(engine_name))
engine_class.set_engine_data(engine_data)
else:
engine_config = config.get('engine_preferences.%s' % engine_class.name)
engine_config and engine_class.set_config(engine_config)
engine_class = GoogleFreeTranslate
engine_config = config.get('engine_preferences.%s' % engine_class.name)
engine_config and engine_class.set_config(engine_config)
return engine_class


Expand Down
2 changes: 1 addition & 1 deletion translations/es.po
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ msgstr "Agregar"
msgid "Clear"
msgstr "Limpiar"

msgid "Reset"
msgid "Restore"
msgstr "Restablecer"

msgid "Verify"
Expand Down
Loading

0 comments on commit dd3a155

Please sign in to comment.