From ccbbd2a02bee38158fe44a7dcce54518d5de698a 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: Wed, 4 Sep 2024 19:30:06 +0800 Subject: [PATCH] something --- .../network/libcurl/requester.py | 35 ++++++------------- .../network/winhttp/requester.py | 5 +-- .../LunaTranslator/rendertext/webview.html | 30 +++++++++++----- .../LunaTranslator/rendertext/webview.py | 25 +++++++++---- LunaTranslator/LunaTranslator/requests.py | 21 +++++++++++ .../LunaTranslator/translator/deepl.py | 2 +- .../LunaTranslator/translator/premt.py | 5 ++- .../LunaTranslator/translator/selfbuild.py | 2 +- plugins/CMakeLists.txt | 2 +- 9 files changed, 80 insertions(+), 47 deletions(-) diff --git a/LunaTranslator/LunaTranslator/network/libcurl/requester.py b/LunaTranslator/LunaTranslator/network/libcurl/requester.py index 8b8bcfb0..085a261c 100644 --- a/LunaTranslator/LunaTranslator/network/libcurl/requester.py +++ b/LunaTranslator/LunaTranslator/network/libcurl/requester.py @@ -4,16 +4,13 @@ from ctypes import c_long, cast, pointer, POINTER, c_char from requests import ResponseBase, Timeout, Requester_common from traceback import print_exc - - class Response(ResponseBase): def __init__(self, stream=False): super().__init__(stream) - self.last_error = 0 self.keeprefs = [] self.queue = queue.Queue() - + def iter_content_impl(self, chunk_size=1): downloadeddata = b"" @@ -36,9 +33,6 @@ class Response(ResponseBase): yield downloadeddata[:chunk_size] downloadeddata = downloadeddata[chunk_size:] - def raise_for_status(self): - MaybeRaiseException(self.last_error) - class autostatus: def __init__(self, ref) -> None: @@ -63,22 +57,18 @@ class Requester(Requester_common): curl_easy_setopt(curl, CURLoption.USERAGENT, self.default_UA.encode("utf8")) return curl - def raise_for_status(self): - MaybeRaiseException(self.last_error) def _getStatusCode(self, curl): status_code = c_long() - self.last_error = curl_easy_getinfo( - curl, CURLINFO.RESPONSE_CODE, pointer(status_code) + MaybeRaiseException( + curl_easy_getinfo(curl, CURLINFO.RESPONSE_CODE, pointer(status_code)) ) - self.raise_for_status() return status_code.value def _set_proxy(self, curl, proxy): if proxy: - self.last_error = curl_easy_setopt( - curl, CURLoption.PROXY, proxy.encode("utf8") + MaybeRaiseException( + curl_easy_setopt(curl, CURLoption.PROXY, proxy.encode("utf8")) ) - self.raise_for_status() def _set_verify(self, curl, verify): if verify == False: @@ -89,8 +79,7 @@ class Requester(Requester_common): curl_easy_setopt(curl, CURLoption.SSL_VERIFYHOST, 2) def _perform(self, curl): - self.last_error = curl_easy_perform(curl) - self.raise_for_status() + MaybeRaiseException(curl_easy_perform(curl)) def _set_allow_redirects(self, curl, allow_redirects): @@ -116,7 +105,7 @@ class Requester(Requester_common): if _headerb == 0: break elif _headerb == 1: - self.raise_for_status() + raise CURLException() _headerb = _headerb.decode("utf8") if _headerb.startswith("HTTP/"): header = "" @@ -131,8 +120,7 @@ class Requester(Requester_common): lheaders = curl_slist_append( cast(lheaders, POINTER(curl_slist)), _.encode("utf8") ) - self.last_error = curl_easy_setopt(curl, CURLoption.HTTPHEADER, lheaders) - self.raise_for_status() + MaybeRaiseException(curl_easy_setopt(curl, CURLoption.HTTPHEADER, lheaders)) if cookies: cookie = self._parsecookie(cookies) @@ -176,8 +164,7 @@ class Requester(Requester_common): if method == "HEAD": curl_easy_setopt(curl, CURLoption.NOBODY, 1) curl_easy_setopt(curl, CURLoption.CUSTOMREQUEST, method.encode("utf8")) - self.last_error = curl_easy_setopt(curl, CURLoption.URL, url.encode("utf8")) - self.raise_for_status() + MaybeRaiseException(curl_easy_setopt(curl, CURLoption.URL, url.encode("utf8"))) curl_easy_setopt(curl, CURLoption.PORT, port) self._setheaders(curl, headers, cookies) @@ -231,7 +218,7 @@ class Requester(Requester_common): resp.queue.put(None) if error: print(url) - self.raise_for_status() + raise CURLException() threading.Thread(target=___perform, daemon=True).start() @@ -244,6 +231,6 @@ class Requester(Requester_common): resp.headers, resp.cookies = self._parseheader2dict(header) resp.status_code = self._getStatusCode(curl) + resp.url = url - resp.last_error = self.last_error return resp diff --git a/LunaTranslator/LunaTranslator/network/winhttp/requester.py b/LunaTranslator/LunaTranslator/network/winhttp/requester.py index 38fe3d96..46414fa3 100644 --- a/LunaTranslator/LunaTranslator/network/winhttp/requester.py +++ b/LunaTranslator/LunaTranslator/network/winhttp/requester.py @@ -42,9 +42,6 @@ class Response(ResponseBase): yield downloadeddata[:chunk_size] downloadeddata = downloadeddata[chunk_size:] - def raise_for_status(self): - MaybeRaiseException() - class Requester(Requester_common): def request(self, *argc, **kwarg) -> ResponseBase: @@ -183,6 +180,7 @@ class Requester(Requester_common): resp.headers, resp.cookies = self._parseheader2dict(self._getheaders(hRequest)) resp.status_code = self._getStatusCode(hRequest) + resp.url = url if stream: resp.hSession = self.hSession resp.hconn = hConnect @@ -204,7 +202,6 @@ class Requester(Requester_common): if succ == 0: MaybeRaiseException() downloadeddata += buff[: downloadedSize.value] - resp.content = self.decompress(downloadeddata, resp.headers) return resp diff --git a/LunaTranslator/LunaTranslator/rendertext/webview.html b/LunaTranslator/LunaTranslator/rendertext/webview.html index 53512a2d..be63147f 100644 --- a/LunaTranslator/LunaTranslator/rendertext/webview.html +++ b/LunaTranslator/LunaTranslator/rendertext/webview.html @@ -49,17 +49,22 @@ ele.style.fontWeight = args.bold ? "bold" : "" ele.style.textAlign = args.atcenter ? "center" : "" } + function maybesethtml(ele, args, text) { + if (args.userawhtml) + ele.innerHTML = text + else + ele.innerText = text + } function normal_create_internal(styleargs, text, args) { let ele = document.createElement('div') - - ele.innerText = text + maybesethtml(ele, args, text) ele.style.color = args.color commoninit_font_align_height(ele, args) return ele } function yinying_create_internal(styleargs, text, args) { let ele = document.createElement('div') - ele.innerText = text + maybesethtml(ele, args, text) ele.style.color = styleargs.fillcolor commoninit_font_align_height(ele, args) @@ -81,7 +86,7 @@ function miaobian0_create_internal(styleargs, text, args) { let ele = document.createElement('div') - ele.innerText = text + maybesethtml(ele, args, text) ele.style.color = styleargs.fillcolor commoninit_font_align_height(ele, args) let _id = _simpleuid() @@ -129,13 +134,13 @@ } ele.appendChild(style) let p = document.createElement('div') - p.innerText = text; + maybesethtml(p, args, text) p.classList.add('nostroken') ele.appendChild(p) for (let i = 0; i < 1 + styleargs.trace * 10; i++) { let p = document.createElement('div') - p.innerText = text; + maybesethtml(p, args, text) p.classList.add(`stroken${i}`) ele.appendChild(p) } @@ -150,6 +155,15 @@ } function dispatch_text_style_line(style, styleargs, text, args) { let ele = regist_style_imp[style](styleargs, text, args); + if (args.userawhtml) { + if (args.atcenter) { + let wrap = document.createElement('div') + wrap.style.textAlign = "center" + wrap.appendChild(ele) + return wrap + } + return ele + } let begin = 0; let begin1 = ""; let end = text.length - 1; let end1 = ""; for (; (begin < text.length) && (text[begin] == ' '); begin++) { begin1 += " " } @@ -211,7 +225,7 @@ let args = JSON.parse(decodeURIComponent(argsjson)) let styleargs = JSON.parse(decodeURIComponent(styleargsjson)) let text = decodeURIComponent(textu) - let innerele = dispatch_text_style(style, styleargs, text, { atcenter: args.atcenter, fontFamily: args.fm, fontSize: args.fs, bold: args.bold, color: args.color, lineHeight: args.line_height }) + let innerele = dispatch_text_style(style, styleargs, text, args) let ele = document.getElementById(_id) ele.innerHTML = '' ele.appendChild(innerele) @@ -265,7 +279,7 @@ tag.forEach(word => { let eleori = dispatch_text_style_inlineblock(style, styleargs, word.orig, { atcenter: true, fontFamily: fmori, fontSize: fsori, bold: boldori, color: color, lineHeight: line_height }) - if ((isshow_fenci || isfenciclick) && word.hira.trim().length) { + if ((isshow_fenci || isfenciclick) && word.hira.trim().length) { let div = document.createElement('div') div.style.display = 'inline-block' div.id = _simpleuid() diff --git a/LunaTranslator/LunaTranslator/rendertext/webview.py b/LunaTranslator/LunaTranslator/rendertext/webview.py index 9d8c8b14..48db93ff 100644 --- a/LunaTranslator/LunaTranslator/rendertext/webview.py +++ b/LunaTranslator/LunaTranslator/rendertext/webview.py @@ -68,7 +68,7 @@ class TextBrowser(QWidget, dataget): self.masklabel_top = QLabel(self) self.masklabel_top.setMouseTracking(True) # self.masklabel_bottom.setStyleSheet('background-color:red') - self.saveclickfunction={} + self.saveclickfunction = {} self.masklabel = QLabel(self.webivewwidget) self.masklabel.setMouseTracking(True) self.webivewwidget.navigate( @@ -205,7 +205,7 @@ class TextBrowser(QWidget, dataget): ) def calllunaclickedword(self, wordinfo): - clickfunction= wordinfo.get('clickfunction',None) + clickfunction = wordinfo.get("clickfunction", None) if clickfunction: self.saveclickfunction.get(clickfunction)(False) else: @@ -250,7 +250,7 @@ class TextBrowser(QWidget, dataget): ]["webview"][0] return currenttype - def _webview_append(self, _id, origin, atcenter, text, tag, flags, color): + def _webview_append(self, _id, origin, atcenter, text: str, tag, flags, color): fmori, fsori, boldori = self._getfontinfo(origin) fmkana, fskana, boldkana = self._getfontinfo_kana() @@ -287,17 +287,28 @@ class TextBrowser(QWidget, dataget): if clickfunction: func = "luna" + str(uuid.uuid4()).replace("-", "_") _tag["clickfunction"] = func - self.saveclickfunction[func]=clickfunction + self.saveclickfunction[func] = clickfunction self.create_internal_rubytext(style, styleargs, _id, tag, args) else: + sig = "LUNASHOWHTML" + userawhtml = text.startswith(sig) + if userawhtml: + text = text[len(sig) :] + else: + if sig in text: + # 显示名称时。不管了,就这样吧 + text = text.replace(sig, "") + userawhtml = True args = dict( atcenter=atcenter, - fm=fmori, - fs=fsori, + fontFamily=fmori, + fontSize=fsori, bold=boldori, color=color, - line_height=line_height, + lineHeight=line_height, + userawhtml=userawhtml, ) + self.create_internal_text(style, styleargs, _id, text, args) def clear(self): diff --git a/LunaTranslator/LunaTranslator/requests.py b/LunaTranslator/LunaTranslator/requests.py index c126bbc0..45aa950f 100644 --- a/LunaTranslator/LunaTranslator/requests.py +++ b/LunaTranslator/LunaTranslator/requests.py @@ -16,6 +16,10 @@ class Timeout(RequestException): pass +class HTTPError(RequestException): + pass + + class CaseInsensitiveDict(MutableMapping): def __init__(self, data=None, **kwargs): @@ -65,6 +69,7 @@ class ResponseBase: def __init__(self, stream): self.headers = CaseInsensitiveDict() self.stream = stream + self.url = "" self.cookies = {} self.status_code = 0 self.__content = b"" @@ -150,6 +155,22 @@ class ResponseBase: if pending is not None: yield pending + def raise_for_status(self): + reason = "" + http_error_msg = "" + if 400 <= self.status_code < 500: + http_error_msg = ( + f"{self.status_code} Client Error: {reason} for url: {self.url}" + ) + + elif 500 <= self.status_code < 600: + http_error_msg = ( + f"{self.status_code} Server Error: {reason} for url: {self.url}" + ) + + if http_error_msg: + raise HTTPError(http_error_msg) + class Requester_common: Accept_Encoding = "gzip, deflate, br" diff --git a/LunaTranslator/LunaTranslator/translator/deepl.py b/LunaTranslator/LunaTranslator/translator/deepl.py index 14b2dfe5..f6068cc6 100644 --- a/LunaTranslator/LunaTranslator/translator/deepl.py +++ b/LunaTranslator/LunaTranslator/translator/deepl.py @@ -75,7 +75,7 @@ class TS(basetrans): "target_lang": self.tgtlang, } - response = self.proxysession.post(self.config["api"], json=payload) + response = self.proxysession.post(self.multiapikeycurrent["api"], json=payload) try: return response.json()["data"] diff --git a/LunaTranslator/LunaTranslator/translator/premt.py b/LunaTranslator/LunaTranslator/translator/premt.py index 418b6573..82e1bc84 100644 --- a/LunaTranslator/LunaTranslator/translator/premt.py +++ b/LunaTranslator/LunaTranslator/translator/premt.py @@ -41,7 +41,8 @@ class TS(basetrans): maxsim = 0 savet = "{}" ret = self.sql.execute("SELECT * FROM artificialtrans ").fetchall() - + if not ret: + return {} for line in ret: text = line[1] trans = line[2] @@ -61,6 +62,8 @@ class TS(basetrans): ret = self.sql.execute( "SELECT machineTrans FROM artificialtrans WHERE source = ?", (content,) ).fetchone() + if not ret: + return {} try: ret = json.loads(ret[0]) except: diff --git a/LunaTranslator/LunaTranslator/translator/selfbuild.py b/LunaTranslator/LunaTranslator/translator/selfbuild.py index 96dfbc79..5be13f9b 100644 --- a/LunaTranslator/LunaTranslator/translator/selfbuild.py +++ b/LunaTranslator/LunaTranslator/translator/selfbuild.py @@ -5,7 +5,7 @@ from myutils.utils import checkmd5reloadmodule class TS(basetrans): def mayreinit(self): isnew, module = checkmd5reloadmodule("./userconfig/selfbuild.py", "selfbuild") - if not isnew: + if (not isnew) and self.internal: return if module: self.internal = module.TS("selfbuild") diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index a55acdae..783d1bc6 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -29,7 +29,7 @@ include(generate_product_version) set(VERSION_MAJOR 5) set(VERSION_MINOR 33) -set(VERSION_PATCH 8) +set(VERSION_PATCH 9) add_library(pch pch.cpp) target_precompile_headers(pch PUBLIC pch.h)