Skip to content

Commit 491a08b

Browse files
committed
fix:禁用/启用文本对调;错误使用异步,改为多线程
1 parent 11073e3 commit 491a08b

3 files changed

Lines changed: 61 additions & 38 deletions

File tree

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@
2323
- 💎 **词典翻译**:翻译单个词语(或短语)时,首选调用词典翻译,直接查询本地词典,包含690000个单词或短语(基于[ECDICT](https://github.com/skywind3000/ECDICT))。
2424
- 🧠 **离线翻译**:翻译段落或句子时,集成深度学习翻译引擎(基于 [Argos Translate](https://github.com/argosopentech/argos-translate))。
2525
- 🐧 **腾讯翻译**:翻译段落或句子时,假如联网,还能调用腾讯翻译(每月500万字免费,含标点),自动优化翻译结果。
26-
- 💨 **中文改写英文**:选中一段可编辑的中文文本,按下快捷键,就可以直接将其改为英文,并且剪贴板同步修改。假如要用英文关键词搜索资料,非常方便。
26+
- 💨 **中文改写英文**:选中一段可编辑的中文文本,按下快捷键,就可以直接将其改为英文,并且剪贴板同步修改。假如要用英文关键词搜索、回帖,非常方便。
27+
28+
\* *使用教程及快捷键配置见`config.ini`,如不习惯可自行修改*
2729

2830
## ✅ 推荐使用的场景或用户
2931

@@ -32,13 +34,12 @@
3234
- 需要阅读技术文档的工程师、程序员等。
3335
- 中文 ➝ 英文的一般质量翻译。
3436
- 内网电脑使用的场景。
35-
- 习惯使用快捷键的用户。
3637

3738
## ❌ 不推荐使用的场景或用户
3839

3940
- 中文 ➝ 英文的SCI写作级超高质量翻译(通常使用聊天机器人)。
4041
- 英文 ➝ 非中文 翻译(本人只使用中文)。
41-
- 排斥使用快捷键的用户,因为部分功能只能使用快捷键
42+
- 排斥使用快捷键的用户,部分功能只能快捷键触发
4243

4344
## 💻 系统兼容
4445

main.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def __init__(self, raw_text, position: QRect = None, parent=None):
9090
trans.set_ui(self)
9191
# 初始化标志变量,用于记录当前文本是否可复制
9292
self.text_selectable = False
93-
93+
self.priority_level = 5
9494

9595
def setup_ui(self):
9696
self.setAttribute(Qt.WA_TranslucentBackground)
@@ -138,7 +138,12 @@ def setup_ui(self):
138138
self.move(mouse_pos + QPoint(-8, -8))
139139
self.update()
140140

141-
def update_result(self, trans_result):
141+
def update_result(self, trans_result, priority_level = 3):
142+
# 离线翻译的优先度为3,腾讯翻译为2,词典翻译为1,优先度越低越优先采用
143+
if self.priority_level > priority_level:
144+
self.priority_level = priority_level
145+
else:
146+
return
142147
self.trans_text = trans_result
143148
if len(self.trans_text) > 30:
144149
self.content.setAlignment(Qt.AlignLeft)
@@ -374,11 +379,11 @@ def on_hotkey_stoptrans(self):
374379
if self.stop_trans:
375380
self.clipboard.dataChanged.disconnect(self.clipboard_changed_triggered.emit)
376381
self.clipboard_changed_triggered.disconnect(self.clipboard_changed_trans)
377-
self.action_stoptrans.setText(f"禁用复制翻译{config.get('DEFAULT', 'stoptrans_triggered_hotkey')})")
382+
self.action_stoptrans.setText(f"启用复制翻译{config.get('DEFAULT', 'stoptrans_triggered_hotkey')})")
378383
else:
379384
self.clipboard.dataChanged.connect(self.clipboard_changed_triggered.emit)
380385
self.clipboard_changed_triggered.connect(self.clipboard_changed_trans)
381-
self.action_stoptrans.setText(f"启用复制翻译{config.get('DEFAULT', 'stoptrans_triggered_hotkey')})")
386+
self.action_stoptrans.setText(f"禁用复制翻译{config.get('DEFAULT', 'stoptrans_triggered_hotkey')})")
382387
self.stop_trans = not self.stop_trans
383388

384389
# 将选中的中文转为英文快捷键,并原地粘贴,并修改剪切板

translator/translate.py

Lines changed: 48 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,25 @@
11
import configparser
22
import concurrent.futures
3-
from typing import List
3+
from typing import List, Callable
44
from . import ecdict, tencent, argos
5+
from threading import Thread
56

7+
class ResultThread(Thread):
8+
def __init__(self, func, args):
9+
super().__init__()
10+
self.func = func
11+
self.args = args
12+
self.result = None
13+
14+
def run(self):
15+
# 在线程启动时执行传入的函数,并保存结果
16+
self.result = self.func(*self.args)
17+
18+
def join(self):
19+
# 等待线程执行完毕,并返回结果
20+
super().join()
21+
return self.result
22+
623
# 太长或太短,或英文占比没有达到60%,都不翻译
724
def is_translation_needed(text, target = "zh") -> bool:
825
total_chars = len(text)
@@ -21,10 +38,24 @@ def is_translation_needed(text, target = "zh") -> bool:
2138
return percentage <= 0.4
2239

2340
def data_cleaning(text: str) -> List[str]:
24-
texts = text.split("\n\n")
25-
for (idt, text) in enumerate(texts):
26-
texts[idt] = text.replace("\n", " ").strip("' \"[](){}")
27-
return texts
41+
fragments = text.split("\n\n")
42+
for (idt, text) in enumerate(fragments):
43+
fragments[idt] = text.replace("\n", " ").strip("' \"[](){}")
44+
return fragments
45+
46+
def super_translater(translate: Callable[[str], str], fragments: List[str],
47+
callback: Callable[[str, int], None], priority_level: int):
48+
threads: List[ResultThread] = []
49+
for fragment in fragments:
50+
threads.append(ResultThread(func=translate, args=(fragment,)))
51+
for thread in threads:
52+
thread.start()
53+
results = []
54+
for thread in threads:
55+
results.append(thread.join())
56+
result = "\n\n".join(results).strip()
57+
if result and not result.isascii():
58+
callback(result, priority_level)
2859

2960
class Translator():
3061
def __init__(self):
@@ -37,8 +68,8 @@ def __init__(self):
3768
def set_ui(self, ui):
3869
self.ui = ui
3970

40-
def notify(self, text: str):
41-
self.ui.update_result(text)
71+
def notify(self, text: str, priority_level: int):
72+
self.ui.update_result(text, priority_level)
4273

4374
# 翻译英文段落、单词为中文,结果为空表明不满足翻译要求
4475
def translate(self, text) -> bool:
@@ -47,30 +78,16 @@ def translate(self, text) -> bool:
4778
text_list = data_cleaning(text)
4879
if len(text_list) == 1:
4980
if trans_result := self.ecdict_trans.translate(text_list[0]):
50-
self.notify(trans_result)
81+
self.notify(trans_result, 1)
5182
return True
52-
with concurrent.futures.ThreadPoolExecutor() as executor:
53-
futures_online = []
54-
futures_local = []
55-
for t in text_list:
56-
future = executor.submit(self.tencent_trans.translate, t)
57-
futures_online.append(future)
58-
for t in text_list:
59-
future = executor.submit(self.argos_trans.translate, t)
60-
futures_local.append(future)
61-
online_result = ""
62-
local_result = ""
63-
for future in futures_local:
64-
r = future.result()
65-
local_result += r + "\n\n"
66-
local_result = local_result.strip()
67-
self.notify(local_result)
68-
for future in futures_online:
69-
r = future.result()
70-
online_result += r + "\n\n"
71-
online_result = online_result.strip()
72-
if not online_result.isascii():
73-
self.notify(online_result)
74-
return True
7583

84+
local_thread = ResultThread(func=super_translater,
85+
args=(self.argos_trans.translate, text_list, self.notify, 3))
86+
tencent_thread = ResultThread(func=super_translater,
87+
args=(self.tencent_trans.translate, text_list, self.notify, 2))
88+
local_thread.start()
89+
tencent_thread.start()
90+
local_thread.join()
91+
tencent_thread.join()
92+
return True
7693

0 commit comments

Comments
 (0)