Skip to content

Commit

Permalink
Release 1.7.1
Browse files Browse the repository at this point in the history
1. 新增清除翻译缓存功能
2. 修复一些问题
  • Loading branch information
huaiyinfeilong committed Jun 5, 2023
1 parent b93ac96 commit d3c1eeb
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 76 deletions.
7 changes: 6 additions & 1 deletion addon/doc/zh_CN/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,14 @@

## 升级日志

### Version 1.7.1

* 设置中增加“清除缓存”功能,可对翻译历史缓存数据进行清除。
* 修复一些问题。

### Version 1.7

* 增加翻译历史缓存以提高性能
* 增加翻译历史缓存以提高性能

### Version 1.6

Expand Down
73 changes: 54 additions & 19 deletions addon/globalPlugins/baiduTranslation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@
from .translators import BaiduTranslator
from .languages import get_language_list
from .cacheData import CacheDataFile
from .exceptions import TranslationException
from logHandler import log


# 翻译缓存数据文件路径
TRANSLATION_CACHE_DATA_FILENAME = cacheFilename = os.path.abspath(os.path.join(
os.path.dirname(__file__), "../../../..", "baiduTranslation.cache-data"))


addonHandler.initTranslation()

Expand Down Expand Up @@ -87,6 +95,24 @@ def makeSettings(self, sizer):
enabled = not self.usingShareKeyCheckBox.IsChecked()
self.myAppIdTextCtrl.Enable(enabled)
self.myAppSecretTextCtrl.Enable(enabled)
# 清除缓存按钮
# Translators: Label for the clear cache button
self.labelForClearCacheButton = _("Clear cache (current item count: {})")
cacheFile = CacheDataFile()
cacheFile.loadDataFile(TRANSLATION_CACHE_DATA_FILENAME)
label = f"{_(self.labelForClearCacheButton)}".format(cacheFile.getItemCount())
log.info(f"标签={label}")
self.clearCacheButton = helper.addItem(
wx.Button(self, label=label)
)
self.clearCacheButton.Bind(wx.EVT_BUTTON, self.onClearCacheButtonClick)

def onClearCacheButtonClick(self, event):
cacheFile = CacheDataFile()
cacheFile.loadDataFile(TRANSLATION_CACHE_DATA_FILENAME)
cacheFile.clear()
label = f"{_(self.labelForClearCacheButton)}".format(cacheFile.getItemCount())
self.clearCacheButton.SetLabel(label)


def onUsingShareKeyCheckBoxChange(self, event):
Expand Down Expand Up @@ -125,9 +151,7 @@ def __init__(self):
super(globalPluginHandler.GlobalPlugin, self).__init__()
# 翻译历史缓存数据夹在,用以加速相同内容的翻译
self._cacheFile = CacheDataFile()
cacheFilename = os.path.abspath(os.path.join(
os.path.dirname(__file__), "../../../..", "baiduTranslation.cache-data"))
self._cacheFile.loadDataFile(cacheFilename)
self._cacheFile.loadDataFile(TRANSLATION_CACHE_DATA_FILENAME)
# 翻译结果缓存,用以翻译结果拷贝,当拷贝成功后此缓存将被清空
self._translationResult = ""
# 是否拷贝翻译结果标志
Expand Down Expand Up @@ -158,14 +182,12 @@ def __del__(self):
self._speak = None

def terminate(self):
# 保存翻译历史缓存数据
self._cacheFile.saveCacheDataFile()
gui.settingsDialogs.NVDASettingsDialog.categoryClasses.remove(TranslationSettingsPanel)

@scriptHandler.script(
category=CATEGORY_NAME,
# Translators: Translate what you just heard
description=_("Translate what you just heard"),
# Translators: Translate what you just heard, double click to copy translation results to the clipboard
description=_("Translate what you just heard, double click to copy translation results to the clipboard"),
gesture="kb:NVDA+W")
def script_translate(self, gesture):
repeatCount = scriptHandler.getLastScriptRepeatCount()
Expand All @@ -180,10 +202,10 @@ def script_translate(self, gesture):
to_language = config.conf["baiduTranslation"]["to"]
self._translate(from_language, to_language, self._data)

# Translators: Reverse translate what you just heard
# Translators: Reverse translate what you just heard, double click to copy translation results to the clipboard
@scriptHandler.script(
category=CATEGORY_NAME,
description=_("Reverse translate what you just heard"),
description=_("Reverse translate what you just heard, double click to copy translation results to the clipboard"),
gesture="kb:NVDA+SHIFT+W")
def script_reverseTranslate(self, gesture):
repeatCount = scriptHandler.getLastScriptRepeatCount()
Expand Down Expand Up @@ -216,8 +238,8 @@ def script_switchAutomaticTranslationMode(self, gesture):

@scriptHandler.script(
category=CATEGORY_NAME,
# Translators: Translate the content in the clipboard
description=_("Translate the content in the clipboard"),
# Translators: Translate the content in the clipboard, double click to copy translation results to the clipboard
description=_("Translate the content in the clipboard, double click to copy translation results to the clipboard"),
gesture="kb:NVDA+CONTROL+W")
def script_clipboardTranslation(self, gesture):
repeatCount = scriptHandler.getLastScriptRepeatCount()
Expand All @@ -228,8 +250,8 @@ def script_clipboardTranslation(self, gesture):

@scriptHandler.script(
category=CATEGORY_NAME,
# Translators: Reverse translate the content in the clipboard
description=_("Reverse translate the content in the clipboard"),
# Translators: Reverse translate the content in the clipboard, double click to copy translation results to the clipboard
description=_("Reverse translate the content in the clipboard, double click to copy translation results to the clipboard"),
gesture="kb:NVDA+CONTROL+SHIFT+W")
def script_clipboardReverseTranslation(self, gesture):
repeatCount = scriptHandler.getLastScriptRepeatCount()
Expand All @@ -253,14 +275,23 @@ def clipboard_translation(self, reverse=False):
self._translate(to_language, from_language, self._data)

def _onResult(self, fromLanguage, toLanguage, source, target):
if target is not None:
if isinstance(target, TranslationException):
self._speak([str(target)])
self._copyFlag = False
self._translationResult = ""
return
if target:
self._speak([target])
self._cacheFile.addCacheItem(fromLanguage, toLanguage, source, target)
if self._copyFlag is True:
api.copyToClip(target)
self._speak([target])
# 拷贝完成清空缓存并重置拷贝标志
self._translationResult = ""
self._copyFlag = False
else:
self._translationResult = target


def speak(self, sequence, *args, **kwargs):
self._data = ""
Expand Down Expand Up @@ -290,11 +321,16 @@ def _playSound(self, reverse_translate=False):
nvwave.playWaveFile(sound_filename)

def _copyTranslationResultToClipboard(self):
if self._translationResult != "":
api.copyToClip(self._translationResult)
self._translationResult = ""
else:
if _translator.isRunning():
self._copyFlag = True
else:
self._copyFlag = False
if self._translationResult:
api.copyToClip(self._translationResult)
self._speak([self._translationResult])
self._translationResult = ""
else:
self._speak([_("No translation results available for replication")])

def _translate(self, fromLanguage, toLanguage, text):
if not text:
Expand All @@ -304,4 +340,3 @@ def _translate(self, fromLanguage, toLanguage, text):
_translator.translate(fromLanguage, toLanguage, text, self._onResult)
else:
self._onResult(fromLanguage, toLanguage, text, result)
self._translationResult = result
15 changes: 12 additions & 3 deletions addon/globalPlugins/baiduTranslation/cacheData.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ class CacheDataFile(object):
针对翻译结果数据进行缓存,避免相同重复内容的频繁请求,加速翻译速度和优化翻译API请求数量
"""

# 翻译数据缓存,默认数量10000"""
_maxCacheCount = 10000
# 翻译缓存数据,字典类型,key为原文,value为译文
_cacheData = {}
# 缓存数据文件路径
Expand All @@ -27,7 +25,7 @@ def loadDataFile(self, filename):
self._cacheData = {}

# 保存缓存数据文件
def saveCacheDataFile(self):
def _saveCacheDataFile(self):
if not self._filename:
return
data = json.dumps(self._cacheData)
Expand All @@ -38,8 +36,19 @@ def saveCacheDataFile(self):
def addCacheItem(self, fromLanguage, toLanguage, source, target):
key = f"[{fromLanguage}>{toLanguage}]{source}"
self._cacheData[key] = target
self._saveCacheDataFile()

# 获取缓存项目
def getCacheItem(self, fromLanguage, toLanguage, source):
key = f"[{fromLanguage}>{toLanguage}]{source}"
return self._cacheData.get(key)


# 获取缓存条目数量
def getItemCount(self):
return len(self._cacheData)

# 清除缓存
def clear(self):
self._cacheData = {}
self._saveCacheDataFile()
16 changes: 16 additions & 0 deletions addon/globalPlugins/baiduTranslation/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# coding=utf-8

import addonHandler


addonHandler.initTranslation()


class TranslationException(Exception):
def __init__(self, message):
self.message = message

def __str__(self):
# Translators: Translation failed
translationFailed = _("Translation failed: ")
return f"{_(translationFailed)}{self.message}"
12 changes: 8 additions & 4 deletions addon/globalPlugins/baiduTranslation/translators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import time
import hashlib
import addonHandler
from .exceptions import TranslationException

# 初始化翻译引擎
addonHandler.initTranslation()
Expand Down Expand Up @@ -41,7 +42,7 @@ def translate(self, from_language, to_language, text, on_result):
self._on_result = on_result
self._thread = threading.Thread(target=self.run)
if self._thread:
self._thread.start()
self ._thread.start()

def run(self):
salt = str(int(time.time()))
Expand Down Expand Up @@ -96,9 +97,12 @@ def run(self):
message = errorDescription.get(errorCode)
if message is None:
message = f"{data.get('error_msg')}, error code={errorCode}"
# Translators: Translation failed message
failedMessage = _("Translation failed: ")
result = f"{_(failedMessage)}{_(message)}"
result = TranslationException(message)
else:
result = "\n".join([r.get("dst") for r in data.get("trans_result")])
self._on_result(from_language, to_language, text, result)

def isRunning(self):
if self._thread and self._thread.is_alive():
return True
return False
Loading

0 comments on commit d3c1eeb

Please sign in to comment.