From 022e1553fb41b2fe7a87316b42ace79c2c857e14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=81=8D=E5=85=AE=E6=83=9A=E5=85=AE?= <101191390+HIllya51@users.noreply.github.com> Date: Thu, 16 May 2024 01:36:03 +0800 Subject: [PATCH] update --- .../LunaTranslator/LunaTranslator.py | 22 +- .../LunaTranslator/cishu/cishubase.py | 41 ++ LunaTranslator/LunaTranslator/cishu/edict.py | 8 +- LunaTranslator/LunaTranslator/cishu/edict2.py | 8 +- LunaTranslator/LunaTranslator/cishu/goo.py | 3 +- .../LunaTranslator/cishu/linggesi.py | 21 +- .../LunaTranslator/cishu/mojidict.py | 4 +- LunaTranslator/LunaTranslator/cishu/weblio.py | 3 +- .../LunaTranslator/cishu/xiaoxueguan.py | 9 +- LunaTranslator/LunaTranslator/cishu/youdao.py | 3 +- .../LunaTranslator/gui/dialog_savedgame.py | 1 + .../LunaTranslator/gui/selecthook.py | 2 +- .../LunaTranslator/gui/settingpage_cishu.py | 150 +++---- .../LunaTranslator/gui/settingpage_ocr.py | 1 - .../LunaTranslator/gui/showocrimage.py | 2 + LunaTranslator/LunaTranslator/gui/showword.py | 368 +++++++++++------- .../LunaTranslator/gui/translatorUI.py | 33 +- .../LunaTranslator/gui/usefulwidget.py | 6 +- .../LunaTranslator/hiraparse/basehira.py | 59 +++ .../LunaTranslator/hiraparse/latin.py | 9 +- .../LunaTranslator/hiraparse/mecab.py | 14 +- .../LunaTranslator/hiraparse/mojinlt.py | 12 +- .../LunaTranslator/textsource/texthook.py | 8 +- .../LunaTranslator/translator/baidu_dev.py | 18 +- .../translator/basetranslator_dev.py | 29 +- .../LunaTranslator/translator/dev_baidu_ai.py | 28 -- LunaTranslator/files/anki/back.html | 33 +- LunaTranslator/files/anki/front.html | 16 +- .../files/defaultconfig/config.json | 170 ++++++-- .../files/defaultconfig/static_data.json | 1 + LunaTranslator/files/lang/ar.json | 2 - LunaTranslator/files/lang/cht.json | 2 - LunaTranslator/files/lang/en.json | 2 - LunaTranslator/files/lang/es.json | 2 - LunaTranslator/files/lang/fr.json | 2 - LunaTranslator/files/lang/it.json | 2 - LunaTranslator/files/lang/ja.json | 2 - LunaTranslator/files/lang/ko.json | 2 - LunaTranslator/files/lang/pl.json | 2 - LunaTranslator/files/lang/ru.json | 2 - LunaTranslator/files/lang/th.json | 2 - LunaTranslator/files/lang/tr.json | 2 - LunaTranslator/files/lang/uk.json | 2 - LunaTranslator/files/lang/vi.json | 2 - LunaTranslator/files/lang/zh.json | 2 - plugins/CMakeLists.txt | 4 +- 46 files changed, 658 insertions(+), 458 deletions(-) create mode 100644 LunaTranslator/LunaTranslator/cishu/cishubase.py create mode 100644 LunaTranslator/LunaTranslator/hiraparse/basehira.py delete mode 100644 LunaTranslator/LunaTranslator/translator/dev_baidu_ai.py diff --git a/LunaTranslator/LunaTranslator/LunaTranslator.py b/LunaTranslator/LunaTranslator/LunaTranslator.py index f6a14b92..b2aa6e02 100644 --- a/LunaTranslator/LunaTranslator/LunaTranslator.py +++ b/LunaTranslator/LunaTranslator/LunaTranslator.py @@ -492,12 +492,13 @@ class MAINUI: == False ): continue - _hira = importlib.import_module("hiraparse." + name).hira + _hira = importlib.import_module("hiraparse." + name) + _hira = getattr(_hira, name) break try: if _hira: - self.hira_ = _hira() + self.hira_ = _hira(name) else: self.hira_ = None except: @@ -583,22 +584,7 @@ class MAINUI: except: return - class cishuwrapper: - def __init__(self, _type) -> None: - self._ = _type() - - @threader - def search(self, sentence): - try: - res = self._.search(sentence) - if res is None or res == "": - return - self.callback(res) - except: - pass - - _ = cishuwrapper(aclass) - return _ + return aclass(type_) def onwindowloadautohook(self): textsourceusing = globalconfig["sourcestatus2"]["texthook"]["use"] diff --git a/LunaTranslator/LunaTranslator/cishu/cishubase.py b/LunaTranslator/LunaTranslator/cishu/cishubase.py new file mode 100644 index 00000000..4793f1a5 --- /dev/null +++ b/LunaTranslator/LunaTranslator/cishu/cishubase.py @@ -0,0 +1,41 @@ +from myutils.config import globalconfig +from myutils.wrapper import threader + + +class cishubase: + def init(self): + pass + + def search(self, word): + return word + + def __init__(self, typename) -> None: + self.typename = typename + self.callback = print + self.needinit = True + try: + self.init() + self.needinit = False + except: + pass + + @threader + def safesearch(self, sentence): + try: + if self.needinit: + self.init() + self.needinit = False + try: + res = self.search(sentence) + except: + self.needinit = True + + if res is None or res == "": + return + self.callback(res) + except: + pass + + @property + def config(self): + return globalconfig["cishu"][self.typename]["args"] diff --git a/LunaTranslator/LunaTranslator/cishu/edict.py b/LunaTranslator/LunaTranslator/cishu/edict.py index a91bacb8..50032c6a 100644 --- a/LunaTranslator/LunaTranslator/cishu/edict.py +++ b/LunaTranslator/LunaTranslator/cishu/edict.py @@ -1,14 +1,14 @@ -from myutils.config import globalconfig import sqlite3, os import winsharedutils, re from myutils.utils import argsort, autosql +from cishu.cishubase import cishubase -class edict: - def __init__(self): +class edict(cishubase): + def init(self): self.sql = None try: - path = globalconfig["cishu"]["edict"]["path"] + path = self.config["path"] if os.path.exists(path): self.sql = autosql(sqlite3.connect(path, check_same_thread=False)) except: diff --git a/LunaTranslator/LunaTranslator/cishu/edict2.py b/LunaTranslator/LunaTranslator/cishu/edict2.py index 6dc65603..9da10afc 100644 --- a/LunaTranslator/LunaTranslator/cishu/edict2.py +++ b/LunaTranslator/LunaTranslator/cishu/edict2.py @@ -1,15 +1,15 @@ -from myutils.config import globalconfig import winsharedutils, os import re from myutils.utils import argsort from traceback import print_exc +from cishu.cishubase import cishubase -class edict2: - def __init__(self): +class edict2(cishubase): + def init(self): self.sql = None try: - path = globalconfig["cishu"]["edict2"]["path"] + path = self.config["path"] if os.path.exists(path): with open(path, "r", encoding="euc-jp") as ff: _ = ff.read() diff --git a/LunaTranslator/LunaTranslator/cishu/goo.py b/LunaTranslator/LunaTranslator/cishu/goo.py index 3af25d91..581cb1bf 100644 --- a/LunaTranslator/LunaTranslator/cishu/goo.py +++ b/LunaTranslator/LunaTranslator/cishu/goo.py @@ -2,9 +2,10 @@ import requests from urllib.parse import quote import re from myutils.proxy import getproxy +from cishu.cishubase import cishubase -class goo: +class goo(cishubase): def search(self, word): url = "https://dictionary.goo.ne.jp/srch/all/{}/m1u/".format(quote(word)) diff --git a/LunaTranslator/LunaTranslator/cishu/linggesi.py b/LunaTranslator/LunaTranslator/cishu/linggesi.py index 08a88738..65f38609 100644 --- a/LunaTranslator/LunaTranslator/cishu/linggesi.py +++ b/LunaTranslator/LunaTranslator/cishu/linggesi.py @@ -1,35 +1,28 @@ -from myutils.config import globalconfig from myutils.utils import autosql import sqlite3 import winsharedutils import os +from cishu.cishubase import cishubase -class linggesi: - def __init__(self): +class linggesi(cishubase): + def init(self): self.sql = None try: if ( - os.path.exists( - os.path.join(globalconfig["cishu"]["linggesi"]["path"], "ja-zh.db") - ) - == False - or os.path.exists( - os.path.join( - globalconfig["cishu"]["linggesi"]["path"], "ja-zh-gbk.db" - ) - ) + os.path.exists(os.path.join(self.config["path"], "ja-zh.db")) == False + or os.path.exists(os.path.join(self.config["path"], "ja-zh-gbk.db")) == False ): return self.sql = autosql( sqlite3.connect( - os.path.join(globalconfig["cishu"]["linggesi"]["path"], "ja-zh.db"), + os.path.join(self.config["path"], "ja-zh.db"), check_same_thread=False, ) ) self.sql2 = sqlite3.connect( - os.path.join(globalconfig["cishu"]["linggesi"]["path"], "ja-zh-gbk.db"), + os.path.join(self.config["path"], "ja-zh-gbk.db"), check_same_thread=False, ) except: diff --git a/LunaTranslator/LunaTranslator/cishu/mojidict.py b/LunaTranslator/LunaTranslator/cishu/mojidict.py index 1e8cf939..b480fb66 100644 --- a/LunaTranslator/LunaTranslator/cishu/mojidict.py +++ b/LunaTranslator/LunaTranslator/cishu/mojidict.py @@ -1,8 +1,10 @@ import requests from myutils.proxy import getproxy +from cishu.cishubase import cishubase -class mojidict: + +class mojidict(cishubase): def search(self, word): try: response = requests.post( diff --git a/LunaTranslator/LunaTranslator/cishu/weblio.py b/LunaTranslator/LunaTranslator/cishu/weblio.py index ff6044e4..262916ca 100644 --- a/LunaTranslator/LunaTranslator/cishu/weblio.py +++ b/LunaTranslator/LunaTranslator/cishu/weblio.py @@ -1,11 +1,12 @@ import requests from urllib.parse import quote +from cishu.cishubase import cishubase from myutils.proxy import getproxy import re -class weblio: +class weblio(cishubase): def search(self, word): url = "https://www.weblio.jp/content/" + quote(word) diff --git a/LunaTranslator/LunaTranslator/cishu/xiaoxueguan.py b/LunaTranslator/LunaTranslator/cishu/xiaoxueguan.py index bcaa7917..f23c69c6 100644 --- a/LunaTranslator/LunaTranslator/cishu/xiaoxueguan.py +++ b/LunaTranslator/LunaTranslator/cishu/xiaoxueguan.py @@ -1,14 +1,15 @@ -from myutils.config import globalconfig import sqlite3, os import winsharedutils from myutils.utils import argsort, autosql +from cishu.cishubase import cishubase -class xiaoxueguan: - def __init__(self): + +class xiaoxueguan(cishubase): + def init(self): self.sql = None try: - path = globalconfig["cishu"]["xiaoxueguan"]["path"] + path = self.config["path"] if os.path.exists(path): self.sql = autosql(sqlite3.connect(path, check_same_thread=False)) except: diff --git a/LunaTranslator/LunaTranslator/cishu/youdao.py b/LunaTranslator/LunaTranslator/cishu/youdao.py index 7b1d05f7..c4dd6e43 100644 --- a/LunaTranslator/LunaTranslator/cishu/youdao.py +++ b/LunaTranslator/LunaTranslator/cishu/youdao.py @@ -3,9 +3,10 @@ import requests from urllib.parse import quote import re from myutils.proxy import getproxy +from cishu.cishubase import cishubase -class youdao: +class youdao(cishubase): @property def srclang(self): diff --git a/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py b/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py index d60ba3d4..ddf9de26 100644 --- a/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py +++ b/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py @@ -310,6 +310,7 @@ class tagitem(QWidget): super().__init__() tagLayout = QHBoxLayout() tagLayout.setContentsMargins(0, 0, 0, 0) + tagLayout.setSpacing(0) self._type = _type key = (tag, _type, refdata) self.setLayout(tagLayout) diff --git a/LunaTranslator/LunaTranslator/gui/selecthook.py b/LunaTranslator/LunaTranslator/gui/selecthook.py index f7ba0ad6..3efcae91 100644 --- a/LunaTranslator/LunaTranslator/gui/selecthook.py +++ b/LunaTranslator/LunaTranslator/gui/selecthook.py @@ -520,7 +520,7 @@ class hookselect(closeashidewindow): savehook_new_data[gobject.baseobject.textsource.pname][ "hooktypeasname" ].__setitem__, - json.dumps(key), + json.dumps(gobject.baseobject.textsource.serialkey(key)), ), ), ) diff --git a/LunaTranslator/LunaTranslator/gui/settingpage_cishu.py b/LunaTranslator/LunaTranslator/gui/settingpage_cishu.py index 7b20f26b..d945c42d 100644 --- a/LunaTranslator/LunaTranslator/gui/settingpage_cishu.py +++ b/LunaTranslator/LunaTranslator/gui/settingpage_cishu.py @@ -1,6 +1,6 @@ import functools, os from myutils.config import globalconfig, _TRL -from gui.inputdialog import getsomepath1, autoinitdialog +from gui.inputdialog import autoinitdialog, autoinitdialog_items from gui.usefulwidget import ( getcolorbutton, yuitsu_switch, @@ -18,83 +18,54 @@ def gethiragrid(self): grids = [] i = 0 - self.ocrswitchs = {} + self.hiraswitchs = {} line = [] for name in globalconfig["hirasetting"]: _f = "./LunaTranslator/hiraparse/{}.py".format(name) if os.path.exists(_f) == False: continue - - line += [ - ((globalconfig["hirasetting"][name]["name"]), 5), - getsimpleswitch( - globalconfig["hirasetting"][name], - "use", - parent=self, - name=name, + if "args" in globalconfig["hirasetting"][name]: + items = autoinitdialog_items(globalconfig["hirasetting"][name]) + _3 = getcolorbutton( + globalconfig, + "", callback=functools.partial( - yuitsu_switch, + autoinitdialog, self, - globalconfig["hirasetting"], - "hiraswitchs", - name, - gobject.baseobject.starthira, + globalconfig["hirasetting"][name]["name"], + 800, + items, ), - pair="hiraswitchs", - ), - ] - items = [] - for key in globalconfig["hirasetting"][name]: - if key == "path": - items.append( - { - "t": "file", - "l": globalconfig["hirasetting"][name]["name"], - "d": globalconfig["hirasetting"][name], - "k": "path", - "dir": True, - } - ) - elif key == "token": - items.append( - { - "t": "lineedit", - "l": globalconfig["hirasetting"][name]["token_name"], - "d": globalconfig["hirasetting"][name], - "k": "token", - } - ) - elif key == "codec": - items.append( - { - "t": "combo", - "l": "codec", - "d": globalconfig["hirasetting"][name], - "k": "codec", - "list": ["utf8", "shiftjis"], - } - ) - if len(items): - items.append({"t": "okcancel", "callback": gobject.baseobject.starthira}) - line += [ - getcolorbutton( - globalconfig, - "", - callback=functools.partial( - autoinitdialog, - self, - globalconfig["hirasetting"][name]["name"], - 800, - items, - ), - icon="fa.gear", - constcolor="#FF69B4", - ) - ] + icon="fa.gear", + constcolor="#FF69B4", + ) else: - line += [""] + _3 = "" + + line += [ + ((globalconfig["hirasetting"][name]["name"]), 6), + ( + getsimpleswitch( + globalconfig["hirasetting"][name], + "use", + name=name, + parent=self, + callback=functools.partial( + yuitsu_switch, + self, + globalconfig["hirasetting"], + "hiraswitchs", + name, + gobject.baseobject.starthira, + ), + pair="hiraswitchs", + ), + 1, + ), + _3, + ] if i % 3 == 2: grids.append(line) line = [] @@ -112,7 +83,7 @@ def setTabcishu_l(self): [ [("分词&假名分析器", 10)], [ - ("日语注音方案", 5), + ("日语注音方案", 6), ( getsimplecombobox( _TRL(["平假名", "片假名", "罗马音"]), @@ -128,7 +99,7 @@ def setTabcishu_l(self): [], [], [ - ("点击单词查词", 5), + ("点击单词查词", 6), (getsimpleswitch(globalconfig, "usesearchword"), 1), getcolorbutton( globalconfig, @@ -138,11 +109,11 @@ def setTabcishu_l(self): constcolor="#FF69B4", ), "", - ("点击单词复制", 5), + ("点击单词复制", 6), (getsimpleswitch(globalconfig, "usecopyword"), 1), ], [ - ("使用原型查询", 5), + ("使用原型查询", 6), (getsimpleswitch(globalconfig, "usewordorigin"), 1), ], [], @@ -156,33 +127,28 @@ def setTabcishu_l(self): _f = "./LunaTranslator/cishu/{}.py".format(cishu) if os.path.exists(_f) == False: continue + + items = autoinitdialog_items(globalconfig["cishu"][cishu]) + line += [ - (globalconfig["cishu"][cishu]["name"], 5), + (globalconfig["cishu"][cishu]["name"], 6), getsimpleswitch( globalconfig["cishu"][cishu], "use", callback=functools.partial(gobject.baseobject.startxiaoxueguan, cishu), ), - ( - getcolorbutton( - globalconfig, - "", - callback=functools.partial( - getsomepath1, - self, - globalconfig["cishu"][cishu]["name"], - globalconfig["cishu"][cishu], - "path", - globalconfig["cishu"][cishu]["name"], - functools.partial(gobject.baseobject.startxiaoxueguan, cishu), - globalconfig["cishu"][cishu]["isdir"], - globalconfig["cishu"][cishu]["filter"], - ), - icon="fa.gear", - constcolor="#FF69B4", - ) - if "path" in globalconfig["cishu"][cishu] - else "" + getcolorbutton( + globalconfig, + "", + callback=functools.partial( + autoinitdialog, + self, + globalconfig["cishu"][cishu]["name"], + 800, + items, + ), + icon="fa.gear", + constcolor="#FF69B4", ), ] diff --git a/LunaTranslator/LunaTranslator/gui/settingpage_ocr.py b/LunaTranslator/LunaTranslator/gui/settingpage_ocr.py index 062b25e1..c0cc5b3f 100644 --- a/LunaTranslator/LunaTranslator/gui/settingpage_ocr.py +++ b/LunaTranslator/LunaTranslator/gui/settingpage_ocr.py @@ -16,7 +16,6 @@ def getocrgrid(self): grids = [] i = 0 - lendict = len(list(globalconfig["ocr"].keys())) self.ocrswitchs = {} line = [] diff --git a/LunaTranslator/LunaTranslator/gui/showocrimage.py b/LunaTranslator/LunaTranslator/gui/showocrimage.py index 1055117e..8cbec6e0 100644 --- a/LunaTranslator/LunaTranslator/gui/showocrimage.py +++ b/LunaTranslator/LunaTranslator/gui/showocrimage.py @@ -65,4 +65,6 @@ class showocrimage(closeashidewindow): self.originimage = originimage self.img1 = QPixmap.fromImage(originimage) self.img2 = QPixmap.fromImage(solved) + self.img1.setDevicePixelRatio(self.devicePixelRatioF()) + self.img2.setDevicePixelRatio(self.devicePixelRatioF()) self.showimg() diff --git a/LunaTranslator/LunaTranslator/gui/showword.py b/LunaTranslator/LunaTranslator/gui/showword.py index 723adc97..c8bc066b 100644 --- a/LunaTranslator/LunaTranslator/gui/showword.py +++ b/LunaTranslator/LunaTranslator/gui/showword.py @@ -1,4 +1,3 @@ -from PyQt5.QtCore import Qt from PyQt5.QtWidgets import ( QWidget, QHBoxLayout, @@ -7,24 +6,21 @@ from PyQt5.QtWidgets import ( QLineEdit, QPlainTextEdit, QFormLayout, - QAction, QSizePolicy, - QStylePainter, - QStyleOptionTab, - QStyle, QPushButton, QTextEdit, - QTabWidget,QFileDialog, + QTabWidget, + QFileDialog, QTabBar, QLabel, ) +from PyQt5.QtGui import QPixmap, QImage from traceback import print_exc import requests, json -from PyQt5.QtCore import Qt, pyqtSignal -from PyQt5.QtGui import QCursor -import qtawesome, functools, os, re, base64 -import threading, gobject, uuid -from myutils.config import globalconfig, _TR, _TRL, static_data +from PyQt5.QtCore import pyqtSignal, Qt +import qtawesome, functools, os, base64 +import gobject, uuid +from myutils.config import globalconfig, _TR, static_data import myutils.ankiconnect as anki from gui.usefulwidget import ( closeashidewindow, @@ -33,8 +29,8 @@ from gui.usefulwidget import ( getboxlayout, getspinbox, getlineedit, - saveposwindow, - getsimpleswitch,getcolorbutton, + getsimpleswitch, + getcolorbutton, tabadd_lazy, ) from myutils.wrapper import threader @@ -42,16 +38,22 @@ from myutils.ocrutil import imageCut, ocr_run from gui.rangeselect import rangeselct_function -class AnkiWindow(closeashidewindow): +class AnkiWindow(QWidget): setcurrenttext = pyqtSignal(str) __ocrsettext = pyqtSignal(str) refreshhtml = pyqtSignal() def langdu(self): if gobject.baseobject.reader: - self.audiopath.setText(gobject.baseobject.reader.syncttstofile( - self.wordedit.text() - )) + self.audiopath.setText( + gobject.baseobject.reader.syncttstofile(self.currentword) + ) + + def langdu2(self): + if gobject.baseobject.reader: + self.audiopath_sentence.setText( + gobject.baseobject.reader.syncttstofile(self.example.toPlainText()) + ) @threader def asyncocr(self, fname): @@ -63,20 +65,26 @@ class AnkiWindow(closeashidewindow): fname = "./cache/ocr/cropforanki.png" os.makedirs("./cache/ocr", exist_ok=True) img.save(fname) + self.editpath.setText("") self.editpath.setText(os.path.abspath(fname)) self.asyncocr(fname) rangeselct_function(self, ocroncefunction, False, False) - def __init__(self, parent) -> None: - super().__init__(parent, globalconfig, "ankiwindow") + def __init__(self) -> None: + super().__init__() self.setWindowTitle("Anki Connect") - + self.currentword = "" self.tabs = QTabWidget() self.tabs.addTab(self.createaddtab(), _TR("添加")) tabadd_lazy(self.tabs, "设置", self.creatsetdtab) tabadd_lazy(self.tabs, "模板", self.creattemplatetab) - self.setCentralWidget(self.tabs) + + l = QHBoxLayout() + l.setContentsMargins(0, 0, 0, 0) + l.setSpacing(0) + l.addWidget(self.tabs) + self.setLayout(l) self.refreshhtml.connect(self.refreshhtmlfunction) self.tabs.currentChanged.connect(self.ifshowrefresh) @@ -127,6 +135,7 @@ class AnkiWindow(closeashidewindow): layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) wid = QWidget() wid.setLayout(layout) @@ -139,7 +148,6 @@ class AnkiWindow(closeashidewindow): layout.addLayout( getboxlayout( [ - QLabel(_TR("编辑")), edittemptab, getboxlayout([revertbtn, savebtn], makewidget=True), ], @@ -152,7 +160,7 @@ class AnkiWindow(closeashidewindow): self.htmlbrowser.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) layout.addLayout( getboxlayout( - [QLabel(_TR("预览")), self.previewtab, self.htmlbrowser], + [self.previewtab, self.htmlbrowser], lc=QVBoxLayout, margin0=True, ) @@ -179,7 +187,7 @@ class AnkiWindow(closeashidewindow): object.setPlainText(text) def loadfileds(self): - word = self.wordedit.text() + word = self.currentword explain = json.dumps(gobject.baseobject.searchwordW.generate_explains()) remarks = self.remarks.toHtml() example = self.example.toPlainText() @@ -205,12 +213,24 @@ class AnkiWindow(closeashidewindow): if len(self.audiopath.text()): with open(self.audiopath.text(), "rb") as image_file: encoded_string2 = base64.b64encode(image_file.read()).decode("utf-8") - encoded_string2 = ''.format( + encoded_string2 = """""".format( encoded_string2 ) else: encoded_string2 = "" - fields = {"audio": encoded_string2, "image": encoded_string} + if len(self.audiopath_sentence.text()): + with open(self.audiopath_sentence.text(), "rb") as image_file: + encoded_string3 = base64.b64encode(image_file.read()).decode("utf-8") + encoded_string3 = """""".format( + encoded_string3 + ) + else: + encoded_string3 = "" + fields = { + "audio": encoded_string2, + "audio_sentence": encoded_string3, + "image": encoded_string, + } return fields def saveedits(self): @@ -236,13 +256,17 @@ class AnkiWindow(closeashidewindow): _TR("DeckName"), getlineedit(globalconfig["ankiconnect"], "DeckName") ) layout.addRow( - _TR("ModelName"), getlineedit(globalconfig["ankiconnect"], "ModelName") + _TR("ModelName"), getlineedit(globalconfig["ankiconnect"], "ModelName2") ) layout.addRow( _TR("allowDuplicate"), getsimpleswitch(globalconfig["ankiconnect"], "allowDuplicate"), ) + layout.addRow( + _TR("autoUpdateModel"), + getsimpleswitch(globalconfig["ankiconnect"], "autoUpdateModel"), + ) return wid @@ -252,42 +276,94 @@ class AnkiWindow(closeashidewindow): wid.setLayout(layout) soundbutton = QPushButton(qtawesome.icon("fa.music"), "") soundbutton.clicked.connect(self.langdu) + soundbutton2 = QPushButton(qtawesome.icon("fa.music"), "") + soundbutton2.clicked.connect(self.langdu2) cropbutton = QPushButton(qtawesome.icon("fa.crop"), "") cropbutton.clicked.connect(self.crop) - self.wordedit = QLineEdit() - self.wordedit.textEdited.connect(self.reset) - layout.addLayout( - getboxlayout([QLabel(_TR("Word")), self.wordedit]) - ) + + self.audiopath = QLineEdit() + self.audiopath.setReadOnly(True) + self.audiopath_sentence = QLineEdit() + self.audiopath_sentence.setReadOnly(True) + self.editpath = QLineEdit() + self.editpath.setReadOnly(True) + self.viewimagelabel = QLabel() + self.editpath.textChanged.connect(self.wrappedpixmap) self.example = QPlainTextEdit() - layout.addWidget(QLabel(_TR("例句"))) - layout.addWidget(self.example) self.remarks = QTextEdit() - layout.addWidget(QLabel(_TR("备注"))) - layout.addWidget(self.remarks) + layout.addLayout( + getboxlayout( + [ + getboxlayout( + [ + getboxlayout( + [QLabel(_TR("例句")), self.example], + QVBoxLayout, + margin0=True, + ), + getboxlayout( + [QLabel(_TR("备注")), self.remarks], + QVBoxLayout, + margin0=True, + ), + ], + QVBoxLayout, + ), + getboxlayout( + [ + getboxlayout( + [ + QLabel(_TR("语音")), + self.audiopath, + soundbutton, + getcolorbutton( + "", + "", + functools.partial(self.selectaudio), + icon="fa.gear", + constcolor="#FF69B4", + ), + ] + ), + getboxlayout( + [ + QLabel(_TR("语音_例句")), + self.audiopath_sentence, + soundbutton2, + getcolorbutton( + "", + "", + functools.partial(self.selectaudio2), + icon="fa.gear", + constcolor="#FF69B4", + ), + ] + ), + getboxlayout( + [ + QLabel(_TR("截图")), + self.editpath, + cropbutton, + getcolorbutton( + "", + "", + functools.partial(self.selectimage), + icon="fa.gear", + constcolor="#FF69B4", + ), + ] + ), + self.viewimagelabel, + ], + QVBoxLayout, + ), + ] + ) + ) self.tagsedit = QLineEdit() layout.addLayout(getboxlayout([QLabel(_TR("Tags(split by |)")), self.tagsedit])) - - self.audiopath = QLineEdit() - self.audiopath.setReadOnly(True) - layout.addLayout(getboxlayout([QLabel(_TR("语音")),self.audiopath,soundbutton,getcolorbutton( - "", - "", - functools.partial(self.selectaudio), - icon="fa.gear", - constcolor="#FF69B4", - )])) - - self.editpath = QLineEdit() - self.editpath.setReadOnly(True) - layout.addLayout(getboxlayout([QLabel(_TR("截图")),self.editpath,cropbutton,getcolorbutton( - "", - "", - functools.partial(self.selectimage), - icon="fa.gear", - constcolor="#FF69B4", - )])) + btn = QPushButton(_TR("添加")) btn.clicked.connect(self.errorwrap) layout.addWidget(btn) @@ -298,24 +374,46 @@ class AnkiWindow(closeashidewindow): self.reset("") return wid + + def wrappedpixmap(self, src): + pix = QPixmap.fromImage(QImage(src)) + rate = self.devicePixelRatioF() + pix.setDevicePixelRatio(rate) + if ( + pix.width() > self.viewimagelabel.width() + or pix.height() > self.viewimagelabel.height() + ): + pix = pix.scaled(self.viewimagelabel.size() * rate, Qt.KeepAspectRatio) + self.viewimagelabel.setPixmap(pix) + def selectimage(self): f = QFileDialog.getOpenFileName() res = f[0] if res != "": self.editpath.setText(res) + def selectaudio(self): f = QFileDialog.getOpenFileName() res = f[0] if res != "": self.audiopath.setText(res) + + def selectaudio2(self): + f = QFileDialog.getOpenFileName() + res = f[0] + if res != "": + self.audiopath_sentence.setText(res) + def reset(self, text): - self.wordedit.setText(text) + self.currentword = text if text and len(text): self.ruby = json.dumps(gobject.baseobject.translation_ui.parsehira(text)) else: self.ruby = "" self.editpath.clear() self.audiopath.clear() + self.audiopath_sentence.clear() + def errorwrap(self): try: self.addanki() @@ -345,9 +443,10 @@ class AnkiWindow(closeashidewindow): return model_htmlfront, model_htmlback, model_css def addanki(self): + autoUpdateModel = globalconfig["ankiconnect"]["autoUpdateModel"] allowDuplicate = globalconfig["ankiconnect"]["allowDuplicate"] anki.global_port = globalconfig["ankiconnect"]["port"] - ModelName = globalconfig["ankiconnect"]["ModelName"] + ModelName = globalconfig["ankiconnect"]["ModelName2"] DeckName = globalconfig["ankiconnect"]["DeckName"] model_htmlfront, model_htmlback, model_css = self.tryloadankitemplates() try: @@ -370,19 +469,24 @@ class AnkiWindow(closeashidewindow): ], ) except anki.AnkiModelExists: - model = anki.Model(ModelName) - model.updateStyling(model_css) - model.updateTemplates( - { - "LUNACARDTEMPLATE1": { - "Front": model_htmlfront, - "Back": model_htmlback, + if autoUpdateModel: + model = anki.Model(ModelName) + model.updateStyling(model_css) + model.updateTemplates( + { + "LUNACARDTEMPLATE1": { + "Front": model_htmlfront, + "Back": model_htmlback, + } } - } - ) + ) media = [] tempfiles = [] - for k, _ in [("audio", self.audiopath.text()), ("image", self.editpath.text())]: + for k, _ in [ + ("audio", self.audiopath.text()), + ("audio_sentence", self.audiopath_sentence.text()), + ("image", self.editpath.text()), + ]: if len(_): media.append( [ @@ -403,49 +507,47 @@ class AnkiWindow(closeashidewindow): self.loadfileds(), allowDuplicate, tags, - media[0], - media[1], + media[0] + media[1], + media[2], ) class searchwordW(closeashidewindow): getnewsentencesignal = pyqtSignal(str, bool) - searchthreadsignal = pyqtSignal(str, dict, str) showtabsignal = pyqtSignal(str, str) def __init__(self, parent): super(searchwordW, self).__init__(parent, globalconfig, "sw_geo") - self.ankiwindow = AnkiWindow(self) + self.ankiwindow = AnkiWindow() self.setupUi() # self.setWindowFlags(self.windowFlags()&~Qt.WindowMinimizeButtonHint) self.getnewsentencesignal.connect(self.getnewsentence) self.setWindowTitle(_TR("查词")) def showresfun(self, k, res): - first = res.split("