Skip to content

Commit

Permalink
支持本地词典
Browse files Browse the repository at this point in the history
  • Loading branch information
xxNull-lsk committed Oct 10, 2021
1 parent 00e4a2d commit 9f25a4e
Show file tree
Hide file tree
Showing 12 changed files with 503 additions and 60 deletions.
17 changes: 15 additions & 2 deletions src/UI/clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@
from PyQt5.QtWidgets import QVBoxLayout, QLabel, QApplication, QWidget

from src.UI.result import ResultWindow
from src.backend.stardict import StartDict
from src.backend.youdao import YouDaoFanYi
from src.setting import setting


class TipWindow(QWidget):
last_text = ""

def __init__(self, youdao: YouDaoFanYi):
def __init__(self, youdao: YouDaoFanYi, star_dict: StartDict):
super().__init__()
self.star_dict = star_dict
self.setMinimumSize(QSize(360, 280))
self.clipboard = QApplication.clipboard()
self.clipboard.dataChanged.connect(self.on_data_changed)
Expand Down Expand Up @@ -51,14 +54,24 @@ def on_data_changed(self):
return
self.last_text = ""
is_word, result = self.youdao.translate(data)
print(json.dumps(result, indent=4, ensure_ascii=False))
if is_word:
succeed = self.result.show_word_result(result)
self.label_src.setText(data)
self.label_src.show()
else:
succeed = self.result.show_text_result(result)
self.label_src.hide()
res = self.star_dict.translate_word(data)
for k in res.keys():
if res[k] == '':
continue
count = len(setting.dicts_for_clipboard)
if count < 1:
continue
if k in setting.dicts_for_clipboard\
or (count == 1 and setting.dicts_for_clipboard[0] == "*"):
self.result.add_word_result(k, res[k])
succeed = True
if succeed:
self.show()

Expand Down
174 changes: 174 additions & 0 deletions src/UI/download_dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import os
import threading

import requests
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QDialog, QVBoxLayout, \
QTableWidget, QHeaderView, QAbstractItemView, QTableView, QTableWidgetItem, QPushButton, QProgressBar
from pystardict import Dictionary

from src import setting
from src.UI.util import create_line, create_widget_with_layout
from src.backend.stardict import StartDict


class MyPushButton(QPushButton):
d: Dictionary = None


class DownloadDialog(QDialog):
signal_reload_dict = pyqtSignal()
signal_change_progress = pyqtSignal(int, int)
dicts = {
"朗道英汉字典5.0": {
"url": "http://download.huzheng.org/zh_CN/stardict-langdao-ec-gb-2.4.2.tar.bz2",
"count": 435468,
"size": "9.1M"
},
"朗道汉英字典5.0": {
"url": "http://download.huzheng.org/zh_CN/stardict-langdao-ce-gb-2.4.2.tar.bz2",
"count": 405719,
"size": "7.8M"
},
"懒虫简明英汉词典": {
"url": "http://download.huzheng.org/zh_CN/stardict-lazyworm-ec-2.4.2.tar.bz2",
"count": 452185,
"size": "10M"
},
"懒虫简明汉英词典": {
"url": "http://download.huzheng.org/zh_CN/stardict-lazyworm-ce-2.4.2.tar.bz2",
"count": 119592,
"size": "1.7M"
},
"新世纪英汉科技大词典": {
"url": "http://download.huzheng.org/zh_CN/stardict-ncce-ec-2.4.2.tar.bz2",
"count": 626953,
"size": "10.4M"
},
"新世纪汉英科技大词典": {
"url": "http://download.huzheng.org/zh_CN/stardict-ncce-ce-2.4.2.tar.bz2",
"count": 621241,
"size": "10.6M"
},
"计算机词汇": {
"url": "http://download.huzheng.org/zh_CN/stardict-kdic-computer-gb-2.4.2.tar.bz2",
"count": 6131,
"size": "683K"
},
"新华字典": {
"url": "http://download.huzheng.org/zh_CN/stardict-xhzd-2.4.2.tar.bz2",
"count": 74025,
"size": "8.9M"
},
"汉语成语词典": {
"url": "http://download.huzheng.org/zh_CN/stardict-hanyuchengyucidian_fix-2.4.2.tar.bz2",
"count": 13305,
"size": "2.8M"
},
}

def __init__(self, parent, star_dict: StartDict):
super().__init__(parent)
self.setWindowTitle("下载离线词典")
self.star_dict = star_dict
self.star_dict.signal_load_dict_finish.connect(self.init_dict)
self.signal_reload_dict.connect(self.init_dict)
self.signal_change_progress.connect(self.on_progress)
self.setMinimumHeight(520)
self.setMinimumWidth(760)
self.list_dicts = QTableWidget()
self.list_dicts.setRowCount(len(self.dicts.keys()))
self.list_dicts.setColumnCount(4)
self.list_dicts.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.list_dicts.setEditTriggers(QTableView.NoEditTriggers)
self.list_dicts.setSelectionMode(QAbstractItemView.SingleSelection)
self.list_dicts.setSelectionBehavior(QAbstractItemView.SelectRows)

self.can_download = True
self.btn_cancel_download = QPushButton("取消")
self.btn_cancel_download.clicked.connect(self.on_cancel_download)
self.btn_cancel_download.hide()

self.progress = QProgressBar()
self.progress.hide()
vbox = QVBoxLayout()
vbox.addWidget(self.list_dicts)
vbox.addItem(create_line([self.progress, self.btn_cancel_download]))
self.setLayout(vbox)

self.init_dict()

def init_dict(self):
self.list_dicts.clear()
self.list_dicts.setHorizontalHeaderLabels(['名称', '词汇数量', '大小', '管理'])
for i, k in enumerate(self.dicts.keys()):
self.list_dicts.setRowHeight(i, 64)
info = self.dicts[k]
self.list_dicts.setItem(i, 0, QTableWidgetItem(k))
self.list_dicts.setItem(i, 1, QTableWidgetItem(str(info["count"])))
self.list_dicts.setItem(i, 2, QTableWidgetItem(info["size"]))
if not self.star_dict.exist(k):
btn_add = MyPushButton("下载")
btn_add.d = self.dicts[k]
btn_add.clicked.connect(self.on_download)
self.list_dicts.setCellWidget(i, 3, create_widget_with_layout(create_line([btn_add])))

for d in self.star_dict.dists:
d: Dictionary
if d.ifo.bookname in self.dicts.keys():
continue
i = self.list_dicts.rowCount()
self.list_dicts.setRowHeight(i, 64)
self.list_dicts.setItem(i, 0, QTableWidgetItem(d.ifo.bookname))
self.list_dicts.setItem(i, 1, QTableWidgetItem(str(d.ifo.wordcount)))
self.list_dicts.setItem(i, 2, QTableWidgetItem(str(d.ifo.idxfilesize)))
if self.progress:
self.progress.hide()
if self.btn_cancel_download:
self.btn_cancel_download.hide()

def on_download(self):
sender = self.sender()
sender: MyPushButton
self.can_download = True
self.progress.setValue(0)
self.progress.show()
self.btn_cancel_download.show()
self.btn_cancel_download.setEnabled(not self.can_download)
# download dict may be use very long time, so do it in a thread
t = threading.Thread(target=self.do_download, args=(sender.d["url"], ))
t.start()

def on_progress(self, curr, total):
self.progress.setMaximum(total)
self.progress.setValue(curr)

def do_download(self, url):
path = "{}/tmp".format(setting.setting_folder)
if not os.path.exists(path):
os.makedirs(path)
filename = os.path.split(url)[-1]
f = open(os.path.join(path, filename), "w+b")
with requests.get(url, stream=True) as r:
filesize = r.headers["Content-Length"]
chunk_size = 128
total = int(filesize) // chunk_size
self.signal_change_progress.emit(0, total)
curr = 1
for chunk in r.iter_content(chunk_size):
if not self.can_download:
break
f.write(chunk)
if curr <= total:
self.signal_change_progress.emit(curr, total)
curr += 1
f.close()
if self.can_download:
os.system("tar -xf {} -C {}".format(os.path.join(path, filename), setting.setting.star_dict_folder))
self.star_dict.load()
self.signal_reload_dict.emit()
os.remove(os.path.join(path, filename))

def on_cancel_download(self):
self.can_download = False
self.btn_cancel_download.setEnabled(not self.can_download)
12 changes: 8 additions & 4 deletions src/UI/find_word.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@


class FindWord(QWidget):
def __init__(self, youdao: YouDaoFanYi, parent=None):
def __init__(self, youdao: YouDaoFanYi, star_dict: StartDict, parent=None):
super().__init__(parent)

self.star_dict = StartDict(setting.star_dict_folder, True)
self.star_dict = star_dict
self.youdao = youdao
self.edit_word = QLineEdit()
self.edit_word.setPlaceholderText("搜索单词")
Expand Down Expand Up @@ -44,4 +43,9 @@ def on_find(self):
for k in res.keys():
if res[k] == '':
continue
self.result.add_word_result(k, res[k])
count = len(setting.dicts_for_query)
if count < 1:
continue
if k in setting.dicts_for_query\
or (count == 1 and setting.dicts_for_query[0] == "*"):
self.result.add_word_result(k, res[k])
14 changes: 11 additions & 3 deletions src/UI/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@

class ResultWindow(QWidget):
last_text = ""
css = '<style type="text/css">\n' \
'div.title {\n' \
' color: rgb(120, 120, 120);\n' \
' font-size: 12px;\n' \
'}\n' \
'</style>'

def __init__(self, parent):
super().__init__(parent)
Expand Down Expand Up @@ -92,7 +98,7 @@ def show_word_result(self, result):
if res != '':
res += "<br>"
res += "&nbsp;&nbsp;&nbsp;&nbsp;{}".format(self.plan2html(item))
res = "<h5>有道词典</h5><hr/>" + res
res = self.css + "<div class=\"title\">有道词典</div><p>" + res + "</p>"
if 'ukspeach' in result and result['ukspeach'] != '':
self.media_player_uk.setMedia(
QMediaContent(QUrl(YouDaoFanYi.voice_addr(result['ukspeach'])))
Expand Down Expand Up @@ -128,10 +134,12 @@ def plan2html(v: str):

def add_word_result(self, k, v: str):
html = self.edit_res.toHtml()
if self.css not in html:
html += self.css
if "<br>" not in v and '<br/>' not in v:
v = v.replace('\n', '<br>')
v = v.replace(' ', '&nbsp;')
v = v.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;')
self.edit_res.setHtml("{}"
"<h5>{}</h5><hr/>"
"&nbsp;&nbsp;&nbsp;&nbsp;<div>{}</div>".format(html, k, v))
"<div class=\"title\">{}</div>"
"<p>{}</p>".format(html, k, v))
Loading

0 comments on commit 9f25a4e

Please sign in to comment.