diff --git a/py/LunaTranslator/LunaTranslator.py b/py/LunaTranslator/LunaTranslator.py index 1c447a0e..8bde5a9d 100644 --- a/py/LunaTranslator/LunaTranslator.py +++ b/py/LunaTranslator/LunaTranslator.py @@ -1040,10 +1040,13 @@ class MAINUI: + (globalconfig["settingfonttype"]) + "' ; }" ) - style += f""" + style += """ QListWidget {{ - font:{globalconfig["settingfontsize"] + 4}pt {globalconfig["settingfonttype"]}; }} - """ + font:{fontsize}pt {fonttype}; }} + """.format( + fontsize=globalconfig["settingfontsize"] + 4, + fonttype=globalconfig["settingfonttype"], + ) self.commonstylebase.setStyleSheet(style) font = QFont() font.setFamily(globalconfig["settingfonttype"]) @@ -1173,7 +1176,7 @@ class MAINUI: for k in globalconfig["metadata"]: try: - targetmod[k] = importlib.import_module(f"metadata.{k}").searcher(k) + targetmod[k] = importlib.import_module("metadata." + k).searcher(k) except: print_exc() @@ -1189,5 +1192,5 @@ class MAINUI: winreg.HKEY_CURRENT_USER, r"Software\Classes\lunatranslator\shell\open\command", ) - command = f'"{getcurrexe()}" --URLProtocol "%1"' + command = '"{}" --URLProtocol "%1"'.format(getcurrexe()) winreg.SetValue(keysub, r"", winreg.REG_SZ, command) diff --git a/py/LunaTranslator/cishu/japandict.py b/py/LunaTranslator/cishu/japandict.py index 238c9157..c5c3a37a 100644 --- a/py/LunaTranslator/cishu/japandict.py +++ b/py/LunaTranslator/cishu/japandict.py @@ -12,7 +12,7 @@ class japandict(cishubase): proxies=self.proxy, ).content.replace(b"padding-top:60px !important", b"") base64_content = base64.b64encode(html).decode("utf-8") - saver[link] = f"data:application/octet-stream;base64,{base64_content}" + saver[link] = "data:application/octet-stream;base64," + base64_content def search(self, word): url = "https://www.japandict.com/?s={}&lang=eng&list=1".format(quote(word)) diff --git a/py/LunaTranslator/cishu/jisho.py b/py/LunaTranslator/cishu/jisho.py index ab5e1a1b..7ddccc7e 100644 --- a/py/LunaTranslator/cishu/jisho.py +++ b/py/LunaTranslator/cishu/jisho.py @@ -14,10 +14,14 @@ class jisho(cishubase): for title, res in allres: idx += 1 btns.append( - f"""""" + """""".format( + idx=idx, title=title + ) ) contents.append( - f"""
{res}
""" + """
{res}
""".format( + idx=idx, res=res + ) ) commonstyle = """ -""" +""".format( + commonstyle=commonstyle, btns="".join(btns), contents="".join(contents) + ) return res def paradown(self, word, key, saver): diff --git a/py/LunaTranslator/cishu/mdict.py b/py/LunaTranslator/cishu/mdict.py index fa7cefa1..0663c1d0 100644 --- a/py/LunaTranslator/cishu/mdict.py +++ b/py/LunaTranslator/cishu/mdict.py @@ -2167,30 +2167,32 @@ class mdict(cishubase): for type_, string in items: ishtml = False if type_ == 1: - htmlitem = f'{string}' + htmlitem = '{}'.format(string) elif type_ == 3: htmlitem = ( - f'{string}' + '{}'.format( + string + ) ) elif type_ == 4: - htmlitem = f"{string}" + htmlitem = "{}".format(string) elif type_ == 5: - htmlitem = f'{string}' + htmlitem = '{}'.format(string) elif type_ == 6: - htmlitem = f'{string}' + htmlitem = '{}'.format(string) elif type_ == 7: - htmlitem = f'{string}' + htmlitem = '{}'.format(string) else: if str(type_).startswith("2"): num = str(type_)[1:] if len(num): num += " " - htmlitem = f'{num}{string}' + htmlitem = '{}{}'.format(num, string) elif str(type_).startswith("8"): num = str(type_)[1:] if len(num): num += " " - htmlitem = f'{num}{string}' + htmlitem = '{}{}'.format(num, string) elif ( str(type_).startswith("11") or str(type_).startswith("9") @@ -2218,7 +2220,9 @@ class mdict(cishubase): break if idx != -1: string = string[:idx] + num + string[idx:] - htmlitem = f'{num}{string}' + htmlitem = '{}{}'.format( + color, num, string + ) else: ishtml = True htmlitem = string @@ -2266,10 +2270,12 @@ class mdict(cishubase): uid = str(uuid.uuid4()) # with open(uid+'.mp3','wb') as ff: # ff.write(file_content) - audio = f'' + audio = ''.format( + uid, self.get_mime_type_from_magic(file_content), base64_content + ) html_content = audio + html_content.replace( url, - f"javascript:document.getElementById('{uid}').play()", + "javascript:document.getElementById('{}').play()".format(uid), ) return html_content @@ -2402,7 +2408,7 @@ class mdict(cishubase): print_exc() base64_content = base64.b64encode(file_content.encode("utf8")).decode("utf-8") html_content = html_content.replace( - url, f"data:text/css;base64,{base64_content}" + url, "data:text/css;base64," + base64_content ) return html_content @@ -2433,9 +2439,9 @@ class mdict(cishubase): elif _type == 0: base64_content = base64.b64encode(file_content).decode("utf-8") html_content = html_content.replace( - url, f"data:application/octet-stream;base64,{base64_content}" + url, "data:application/octet-stream;base64," + base64_content ) - return f'
{html_content}
' + return '
{}
'.format(divid, html_content) def searchthread_internal(self, index, k, __safe): allres = [] @@ -2484,10 +2490,14 @@ class mdict(cishubase): for _, foldflow, title, res in allres: idx += 1 btns.append( - f"""""" + """""".format( + idx=idx, title=title + ) ) contents.append( - f"""
{res}
""" + """
{res}
""".format( + idx=idx, res=res + ) ) commonstyle = """ -""" +""".format( + commonstyle=commonstyle, btns="".join(btns), contents="".join(contents) + ) return res def generatehtml_flow(self, allres): diff --git a/py/LunaTranslator/cishu/mojidict.py b/py/LunaTranslator/cishu/mojidict.py index 362ef8a3..4a0f4888 100644 --- a/py/LunaTranslator/cishu/mojidict.py +++ b/py/LunaTranslator/cishu/mojidict.py @@ -57,7 +57,7 @@ def mojiclicksearch(self, word): if subdetail["lang"] == "zh-CN": collect[i] = title + collect[i] elif subdetail["lang"] == "ja": - title = f"({title})" + title = "(" + title + ")" collect[i] = collect[i] + title good = True if not good: @@ -559,15 +559,15 @@ def mojiclicksearch(self, word): """ - spell = f"{spell}|{pron}{accent}" - spell = f'
{spell}
' + spell = "{}|{}{}".format(spell, pron, accent) + spell = '
{}
'.format(spell) _type = re.match("\\[(.*?)\\]", excerpt).groups()[0] - _type = f'

{_type}

' + _type = '

{}

'.format(_type) for i in range(len(collect)): - collect[i] = f"

{i+1}. {collect[i]}

" - detail = f"""
{_type}{''.join(collect)}
""" - result = f'
{spell}{detail}
' + collect[i] = "

{}. {}

".format(i + 1, collect[i]) + detail = """
{}{}
""".format(_type, "".join(collect)) + result = '
{}{}
'.format(spell, detail) result += style return result diff --git a/py/LunaTranslator/gobject.py b/py/LunaTranslator/gobject.py index c5c6b5d0..cf1650bc 100644 --- a/py/LunaTranslator/gobject.py +++ b/py/LunaTranslator/gobject.py @@ -40,7 +40,7 @@ def gettempdir_1(): def gettempdir(filename): - tgt = getcachedir(os.path.join(f"temp/{os.getpid()}", filename)) + tgt = getcachedir(os.path.join("temp/{}".format(os.getpid()), filename)) return tgt diff --git a/py/LunaTranslator/gui/dialog_savedgame.py b/py/LunaTranslator/gui/dialog_savedgame.py index d847d1ad..0423f6b0 100644 --- a/py/LunaTranslator/gui/dialog_savedgame.py +++ b/py/LunaTranslator/gui/dialog_savedgame.py @@ -93,7 +93,9 @@ class dialog_savedgame_integrated(saveposwindow): | Qt.WindowType.WindowCloseButtonHint, poslist=globalconfig["savegamedialoggeo"], ) - self.setWindowIcon(qtawesome.icon(globalconfig["toolbutton"]["buttons"]["gamepad_new"]["icon"])) + self.setWindowIcon( + qtawesome.icon(globalconfig["toolbutton"]["buttons"]["gamepad_new"]["icon"]) + ) w, self.internallayout = getboxlayout( [], margin0=True, makewidget=True, both=True ) @@ -356,9 +358,9 @@ class dialog_savedgame_new(QWidget): if fontstring: _f = QFont() _f.fromString(fontstring) - _style += f"font-size:{_f.pointSize()}pt;" - _style += f'font-family:"{_f.family()}";' - style = f"#{key}{{ {_style} }}" + _style += "font-size:{}pt;".format(_f.pointSize()) + _style += 'font-family:"{}";'.format(_f.family()) + style = "#{}{{ {} }}".format(key, _style) for exits in [True, False]: c = globalconfig["dialog_savegame_layout"][ ("onfilenoexistscolor1", "backcolor1")[exits] @@ -370,8 +372,13 @@ class dialog_savedgame_new(QWidget): ], ) - style += f"#savegame_exists{exits}{{background-color:{c};}}" - style += f'#savegame_onselectcolor1{{background-color: {str2rgba(globalconfig["dialog_savegame_layout"]["onselectcolor1"],globalconfig["dialog_savegame_layout"]["transparentselect"])};}}' + style += "#savegame_exists{}{{background-color:{};}}".format(exits, c) + style += "#savegame_onselectcolor1{{background-color: {};}}".format( + str2rgba( + globalconfig["dialog_savegame_layout"]["onselectcolor1"], + globalconfig["dialog_savegame_layout"]["transparentselect"], + ) + ) self.setStyleSheet(style) def __init__(self, parent) -> None: diff --git a/py/LunaTranslator/gui/dialog_savedgame_common.py b/py/LunaTranslator/gui/dialog_savedgame_common.py index 482487b5..1b95717f 100644 --- a/py/LunaTranslator/gui/dialog_savedgame_common.py +++ b/py/LunaTranslator/gui/dialog_savedgame_common.py @@ -405,7 +405,7 @@ def getcachedimage(src, small): return _pix if not os.path.exists(src): return None - src2 = gobject.getcachedir(f"icon2/{__b64string(src)}.jpg") + src2 = gobject.getcachedir("icon2/{}.jpg".format(__b64string(src))) _pix = QPixmap(src2) if not _pix.isNull(): return _pix diff --git a/py/LunaTranslator/gui/dialog_savedgame_v3.py b/py/LunaTranslator/gui/dialog_savedgame_v3.py index a38a4f29..4c969cee 100644 --- a/py/LunaTranslator/gui/dialog_savedgame_v3.py +++ b/py/LunaTranslator/gui/dialog_savedgame_v3.py @@ -801,9 +801,9 @@ class dialog_savedgame_v3(QWidget): if fontstring: _f = QFont() _f.fromString(fontstring) - _style += f"font-size:{_f.pointSize()}pt;" - _style += f'font-family:"{_f.family()}";' - style = f"#{key}{{ {_style} }}" + _style += "font-size:{}pt;".format(_f.pointSize()) + _style += 'font-family:"{}";'.format(_f.family()) + style = "#{}{{ {} }}".format(key, _style) for exits in [True, False]: c = globalconfig["dialog_savegame_layout"][ ("onfilenoexistscolor1", "backcolor1")[exits] @@ -815,8 +815,13 @@ class dialog_savedgame_v3(QWidget): ], ) - style += f"#savegame_exists{exits}{{background-color:{c};}}" - style += f'#savegame_onselectcolor1{{background-color: {str2rgba(globalconfig["dialog_savegame_layout"]["onselectcolor1"],globalconfig["dialog_savegame_layout"]["transparentselect"])};}}' + style += "#savegame_exists{}{{background-color:{};}}".format(exits, c) + style += "#savegame_onselectcolor1{{background-color: {};}}".format( + str2rgba( + globalconfig["dialog_savegame_layout"]["onselectcolor1"], + globalconfig["dialog_savegame_layout"]["transparentselect"], + ) + ) self.setStyleSheet(style) def __init__(self, parent) -> None: diff --git a/py/LunaTranslator/gui/setting_about.py b/py/LunaTranslator/gui/setting_about.py index 95796163..daeabfea 100644 --- a/py/LunaTranslator/gui/setting_about.py +++ b/py/LunaTranslator/gui/setting_about.py @@ -377,8 +377,8 @@ def setTab_update(self, basel): if version is None: versionstring = "unknown" else: - versionstring = ( - f"v{version[0]}.{version[1]}.{version[2]} {platform.architecture()[0]}" + versionstring = ("v{}.{}.{} {}").format( + version[0], version[1], version[2], platform.architecture()[0] ) inner, vis = [_[1] for _ in static_data["language_list_show"]], [ _[0] for _ in static_data["language_list_show"] diff --git a/py/LunaTranslator/gui/setting_display_text.py b/py/LunaTranslator/gui/setting_display_text.py index ccf53052..1634c433 100644 --- a/py/LunaTranslator/gui/setting_display_text.py +++ b/py/LunaTranslator/gui/setting_display_text.py @@ -174,13 +174,13 @@ def createinternalfontsettings(self, forml: LFormLayout, group, _type): def doinstallqweb(self, dd, base): if not dd["k"].endswith(base): - getQMessageBox(self, "错误", f"请选择_{base}") + getQMessageBox(self, "错误", "请选择_" + base) return with zipfile.ZipFile(dd["k"]) as zipf: target = gobject.gettempdir("QWebEngine/") zipf.extractall(target) bit = ["x86", "x64"][platform.architecture()[0] == "64bit"] - copytree(f"{target}/{bit}/PyQt5", "files/runtime/PyQt5") + copytree("{}/{}/PyQt5".format(target, bit), "files/runtime/PyQt5") getQMessageBox(self, "成功", "安装成功") diff --git a/py/LunaTranslator/gui/showword.py b/py/LunaTranslator/gui/showword.py index 6907da7e..4138e304 100644 --- a/py/LunaTranslator/gui/showword.py +++ b/py/LunaTranslator/gui/showword.py @@ -157,7 +157,7 @@ class AnkiWindow(QWidget): fields = self.loadfileds() fields.update(self.loadfakefields()) html = self.parse_template(html, fields) - html = f'
{html}
' + html = '
{}
'.format(model_css, html) self.htmlbrowser.setHtml(html) def creattemplatetab(self, baselay): @@ -220,7 +220,11 @@ class AnkiWindow(QWidget): return "" htmlcontents = "" for iiii in range(len(dictionarys)): - htmlcontents += f'
{dictionarys[iiii]["content"]}
' + htmlcontents += ( + '
{}
'.format( + dictionarys[iiii]["dict"], dictionarys[iiii]["content"] + ) + ) return htmlcontents def loadfileds(self): @@ -234,7 +238,7 @@ class AnkiWindow(QWidget): collect = [] for hira in self.example.hiras: if hira["orig"] == word or hira.get("origorig", None) == word: - collect.append(f'{hira["orig"]}') + collect.append('{}'.format(hira["orig"])) else: collect.append(hira["orig"]) example = "".join(collect) diff --git a/py/LunaTranslator/gui/textbrowser.py b/py/LunaTranslator/gui/textbrowser.py index aadf6aa0..d05b1587 100644 --- a/py/LunaTranslator/gui/textbrowser.py +++ b/py/LunaTranslator/gui/textbrowser.py @@ -30,7 +30,7 @@ class Textbrowser(QFrame): if __ == "QWebEngine": __ = "webview" try: - tb = importlib.import_module(f"rendertext.{__}").TextBrowser + tb = importlib.import_module("rendertext." + __).TextBrowser self.textbrowser = tb(self) except Exception as e: if isinstance(e, webview_exception): @@ -48,7 +48,7 @@ class Textbrowser(QFrame): else: print_exc() globalconfig["rendertext_using"] = "textbrowser" - tb = importlib.import_module(f"rendertext.textbrowser").TextBrowser + tb = importlib.import_module("rendertext.textbrowser").TextBrowser self.textbrowser = tb(self) self.textbrowser.move(0, 0) self.textbrowser.setMouseTracking(True) diff --git a/py/LunaTranslator/gui/usefulwidget.py b/py/LunaTranslator/gui/usefulwidget.py index 0502c6e8..2246c72f 100644 --- a/py/LunaTranslator/gui/usefulwidget.py +++ b/py/LunaTranslator/gui/usefulwidget.py @@ -1187,15 +1187,14 @@ class abstractwebview(QWidget): def _parsehtml_codec(self, html): - html = f"""{html}""" + html = """{}""".format( + html + ) return html def _parsehtml_font(self, html): - - html = """{}""".format( - QFontDatabase.systemFont(QFontDatabase.SystemFont.GeneralFont).family(), - html, - ) + font = QFontDatabase.systemFont(QFontDatabase.SystemFont.GeneralFont).family() + html = """{}""".format(font, html) return html def _parsehtml_dark(self, html): diff --git a/py/LunaTranslator/metadata/abstract.py b/py/LunaTranslator/metadata/abstract.py index d5427350..cb9b29a4 100644 --- a/py/LunaTranslator/metadata/abstract.py +++ b/py/LunaTranslator/metadata/abstract.py @@ -75,15 +75,16 @@ class common: elif len(pair) == 3: gameuid, vid, retrytime = pair remove = True + info = "{}: {} ".format(self.config_all["name"], vid) try: self.__do_searchfordata(gameuid, vid) - vis = f"{self.config_all['name']}: {vid} data loaded success" + vis = info + "data loaded success" except RequestException: remove = False - vis = f"{self.config_all['name']}: {vid} network error, retry later" + vis = info + "network error, retry later" except: print_exc() - vis = f"{self.config_all['name']}: {vid} load failed" + vis = info + " load failed" if remove: self.__safe_remove_task("searchfordatatasks", pair[:2]) @@ -131,7 +132,7 @@ class common: def dispatchdownloadtask(self, url): if not url: return None - __routine = f"cache/metadata/{self.typename}" + __routine = "cache/metadata/" + self.typename if self.typename == "vndb": __routine = "cache/vndb" @@ -139,7 +140,7 @@ class common: __ = url[url.rfind(".") :] else: __ = ".jpg" - savepath = f"{__routine}/{self.__b64string(url)}{__}" + savepath = __routine + "/" + self.__b64string(url) + __ globalconfig["metadata"][self.typename]["downloadtasks"].append((url, savepath)) self.__tasks_downloadimg.put((url, savepath)) diff --git a/py/LunaTranslator/metadata/bangumi.py b/py/LunaTranslator/metadata/bangumi.py index 2161899d..47c20d9c 100644 --- a/py/LunaTranslator/metadata/bangumi.py +++ b/py/LunaTranslator/metadata/bangumi.py @@ -35,7 +35,7 @@ class bgmsettings(QDialog): } collectresults = [] response = requests.get( - f"https://api.bgm.tv/v0/users/{self.username}/collections", + "https://api.bgm.tv/v0/users/{}/collections".format(self.username), params=params, headers=self.headers, proxies=self._ref.proxy, @@ -86,7 +86,7 @@ class bgmsettings(QDialog): continue requests.post( - f"https://api.bgm.tv/v0/users/-/collections/{vid}", + "https://api.bgm.tv/v0/users/-/collections/{}".format(vid), headers=self.headers, json={ "type": 4, @@ -104,7 +104,7 @@ class bgmsettings(QDialog): return try: requests.post( - f"https://api.bgm.tv/v0/users/-/collections/{vid}", + "https://api.bgm.tv/v0/users/-/collections/{}".format(vid), headers=self.headers, json={ "type": 4, @@ -138,7 +138,7 @@ class bgmsettings(QDialog): "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", } response = requests.post( - f"https://bgm.tv/oauth/token_status", + "https://bgm.tv/oauth/token_status", params={"access_token": k}, headers=headers, proxies=self._ref.proxy, @@ -151,7 +151,7 @@ class bgmsettings(QDialog): info = "" try: response1 = requests.get( - f"https://api.bgm.tv/v0/me", + "https://api.bgm.tv/v0/me", params={"access_token": k}, headers=self.headers, proxies=self._ref.proxy, @@ -190,7 +190,9 @@ class bgmsettings(QDialog): except: pass gobject.baseobject.openlink( - f'https://bgm.tv/oauth/authorize?client_id={static_data["bangumi_oauth"]["client_id"]}&response_type=code&redirect_uri=lunatranslator://bangumioauth' + "https://bgm.tv/oauth/authorize?client_id={}&response_type=code&redirect_uri=lunatranslator://bangumioauth".format( + static_data["bangumi_oauth"]["client_id"] + ) ) self.__wait() @@ -209,7 +211,7 @@ class bgmsettings(QDialog): print(code) os.remove(bangumioauth) response = requests.post( - f"https://bgm.tv/oauth/access_token", + "https://bgm.tv/oauth/access_token", json={ "grant_type": "authorization_code", "client_id": static_data["bangumi_oauth"]["client_id"], @@ -261,12 +263,16 @@ class bgmsettings(QDialog): fl2.addRow(btn) btn = LPushButton("上传游戏列表") btn.clicked.connect( - functools.partial(self.__getalistname, "上传游戏列表", self.getalistname_upload) + functools.partial( + self.__getalistname, "上传游戏列表", self.getalistname_upload + ) ) fl2.addRow(btn) btn = LPushButton("获取游戏列表") btn.clicked.connect( - functools.partial(self.__getalistname, "添加到列表", self.getalistname_download) + functools.partial( + self.__getalistname, "添加到列表", self.getalistname_download + ) ) fl2.addRow(btn) fl.addRow(ww) @@ -327,7 +333,7 @@ class searcher(common): return response["list"][0]["id"] def refmainpage(self, _id): - return f"https://bangumi.tv/subject/{_id}" + return "https://bangumi.tv/subject/{}".format(_id) def searchfordata(self, sid): @@ -338,7 +344,7 @@ class searcher(common): if self.config["access-token"].strip() != "": headers["Authorization"] = "Bearer " + self.config["access-token"] response = self.proxysession.get( - f"https://api.bgm.tv/v0/subjects/{sid}", headers=headers + "https://api.bgm.tv/v0/subjects/{}".format(sid), headers=headers ) print(response.text) try: @@ -365,7 +371,8 @@ class searcher(common): namemaps = {} try: charas = self.proxysession.get( - f"https://api.bgm.tv/v0/subjects/{sid}/characters", headers=headers + "https://api.bgm.tv/v0/subjects/{}/characters".format(sid), + headers=headers, ).json() for _ in charas: namemaps[_["name"]] = _["name"] diff --git a/py/LunaTranslator/metadata/dlsite.py b/py/LunaTranslator/metadata/dlsite.py index ed53d2c3..953e8ee3 100644 --- a/py/LunaTranslator/metadata/dlsite.py +++ b/py/LunaTranslator/metadata/dlsite.py @@ -18,7 +18,8 @@ class searcher(common): } try: response = requests.get( - f"https://www.dlsite.com/pro/fsr/=/language/jp/sex_category[0]/male/keyword/{title}", + "https://www.dlsite.com/pro/fsr/=/language/jp/sex_category[0]/male/keyword/" + + title, headers=headers, proxies=self.proxy, ) @@ -35,7 +36,8 @@ class searcher(common): except: response = requests.get( - f"https://www.dlsite.com/maniax/fsr/=/language/jp/sex_category[0]/male/keyword/{title}", + "https://www.dlsite.com/maniax/fsr/=/language/jp/sex_category[0]/male/keyword/" + + title, headers=headers, proxies=self.proxy, ) @@ -52,9 +54,9 @@ class searcher(common): def refmainpage(self, RJ: str): if RJ.startswith("RJ"): - return f"https://www.dlsite.com/maniax/work/=/product_id/{RJ}.html" + return "https://www.dlsite.com/maniax/work/=/product_id/{}.html".format(RJ) elif RJ.startswith("VJ"): - return f"https://www.dlsite.com/pro/work/=/product_id/{RJ}.html" + return "https://www.dlsite.com/pro/work/=/product_id/{}.html".format(RJ) def searchfordata(self, RJ): diff --git a/py/LunaTranslator/metadata/fanza.py b/py/LunaTranslator/metadata/fanza.py index 46ed0e51..5fcee30a 100644 --- a/py/LunaTranslator/metadata/fanza.py +++ b/py/LunaTranslator/metadata/fanza.py @@ -57,7 +57,7 @@ class searcher(common): } response = self.proxysession.get( - f"https://dlsoft.dmm.co.jp/search/?floor=digital_pcgame&searchstr={title}&service=pcgame", + "https://dlsoft.dmm.co.jp/search/?floor=digital_pcgame&searchstr={}&service=pcgame".format(title), headers=headers, cookies=cookies, ) @@ -67,7 +67,7 @@ class searcher(common): return _id def refmainpage(self, _id): - return f"https://dlsoft.dmm.co.jp/detail/{_id}/" + return "https://dlsoft.dmm.co.jp/detail/{}/".format(_id) def searchfordata(self, RJ): cookies = { diff --git a/py/LunaTranslator/metadata/steam.py b/py/LunaTranslator/metadata/steam.py index a250c98d..27c6b520 100644 --- a/py/LunaTranslator/metadata/steam.py +++ b/py/LunaTranslator/metadata/steam.py @@ -38,7 +38,7 @@ class steamsettings(QDialog): pagei += 1 response = requests.get( - f'https://store.steampowered.com/wishlist/profiles/{self._ref.config["userid"] }/wishlistdata/', + 'https://store.steampowered.com/wishlist/profiles/{}/wishlistdata/'.format(self._ref.config["userid"]), cookies=cookies, params=params, headers=headers, @@ -111,7 +111,7 @@ class searcher(common): return response.json()[0]["appid"] def refmainpage(self, _id): - return f"https://store.steampowered.com/app/{_id}/_/" + return "https://store.steampowered.com/app/{}/_/".format(_id) def gettagfromhtml(self, _id): @@ -169,7 +169,7 @@ class searcher(common): def searchfordata(self, _id): data = requests.get( - f"https://store.steampowered.com/api/appdetails?appids={_id}", + "https://store.steampowered.com/api/appdetails?appids={}".format(_id), proxies=self.proxy, ).json()[str(_id)]["data"] diff --git a/py/LunaTranslator/metadata/vndb.py b/py/LunaTranslator/metadata/vndb.py index 2e9138da..f09b3435 100644 --- a/py/LunaTranslator/metadata/vndb.py +++ b/py/LunaTranslator/metadata/vndb.py @@ -161,7 +161,7 @@ class vndbsettings(QDialog): @property def headers(self): return { - "Authorization": f"Token {self._ref.config['Token']}", + "Authorization": "Token " + self._ref.config["Token"], } @property @@ -234,7 +234,7 @@ class vndbsettings(QDialog): saferequestvndb( self._ref.proxy, "PATCH", - f"ulist/v{vid}", + "ulist/v{}".format(vid), json={ "labels_set": [1], }, @@ -249,7 +249,7 @@ class vndbsettings(QDialog): saferequestvndb( self._ref.proxy, "PATCH", - f"ulist/v{vid}", + "ulist/v{}".format(vid), json={ "labels_set": [1], # "labels_unset": [1], @@ -337,7 +337,7 @@ class searcher(common): vndbsettings(parent, self, gameuid) def refmainpage(self, _id): - return f"https://vndb.org/v{_id}" + return "https://vndb.org/v{}".format(_id) def getidbytitle(self, title): vid = getidbytitle_(self.proxy, title) diff --git a/py/LunaTranslator/myutils/ankiconnect.py b/py/LunaTranslator/myutils/ankiconnect.py index 30f63398..1bc67211 100644 --- a/py/LunaTranslator/myutils/ankiconnect.py +++ b/py/LunaTranslator/myutils/ankiconnect.py @@ -13,7 +13,7 @@ class AnkiModelExists(AnkiException): def invoke(action, **params): response = requests.get( - f"http://127.0.0.1:{global_port}", + "http://127.0.0.1:{}".format(global_port), json={"action": action, "params": params, "version": 6}, ).json() if len(response) != 2: @@ -45,7 +45,7 @@ class Deck: self.did = did def __repr__(self): - return f"(Deck {self.name},{self.did})" + return "(Deck {},{})".format(self.name, self.did) def delete(self): return invoke("deleteDecks", decks=[self.name], cardsToo=True) @@ -61,7 +61,7 @@ class Deck: class Card: def __repr__(self): - return f"(Card {self.cardId})" + return "(Card {})".format(self.cardId) def __init__(self, cardId): self.cardId = cardId diff --git a/py/LunaTranslator/myutils/config.py b/py/LunaTranslator/myutils/config.py index 0b850250..cb7f86d0 100644 --- a/py/LunaTranslator/myutils/config.py +++ b/py/LunaTranslator/myutils/config.py @@ -86,7 +86,7 @@ else: __gamepath2uid = {} __savehook_new_data = {} for k in savehook_new_data: - uid = f"{time.time()}_{uuid.uuid4()}" + uid = "{}_{}".format(time.time(), uuid.uuid4()) __savehook_new_data[uid] = savehook_new_data[k] __savehook_new_data[uid].update(gamepath=k) diff --git a/py/LunaTranslator/myutils/hwnd.py b/py/LunaTranslator/myutils/hwnd.py index 71638f23..e293d042 100644 --- a/py/LunaTranslator/myutils/hwnd.py +++ b/py/LunaTranslator/myutils/hwnd.py @@ -42,7 +42,9 @@ def grabwindow(app="PNG", callback_origin=None, tocliponly=False): uid = gobject.baseobject.gameuid screenshot_savepath: str = globalconfig.get("screenshot_savepath", "") fnamef = lambda: gobject.getcachedir( - f"screenshot/{exename}/" + "screenshot/" + + exename + + "/" + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()), abspath=False, ) @@ -212,7 +214,7 @@ def getExeIcon(name: str, icon=True, cache=False): def injectdll(injectpids, bit, dll): - injecter = os.path.abspath(f"./files/plugins/shareddllproxy{bit}.exe") + injecter = os.path.abspath("./files/plugins/shareddllproxy{}.exe".format(bit)) pid = " ".join([str(_) for _ in injectpids]) for _ in (0,): if not test_injectable(injectpids): diff --git a/py/LunaTranslator/myutils/traceplaytime.py b/py/LunaTranslator/myutils/traceplaytime.py index f12dd9ad..3208838b 100644 --- a/py/LunaTranslator/myutils/traceplaytime.py +++ b/py/LunaTranslator/myutils/traceplaytime.py @@ -65,7 +65,7 @@ class playtimemanager: table = ["trace_loose", "trace_strict"][globalconfig["is_tracetime_strict"]] gameinternalid = self.get_gameinternalid(gameuid) return self.sqlsavegameinfo.execute( - f"SELECT timestart,timestop FROM {table} WHERE gameinternalid = ?", + "SELECT timestart,timestop FROM {} WHERE gameinternalid = ?".format(table), (gameinternalid,), ).fetchall() @@ -111,14 +111,14 @@ class playtimemanager: gameinternalid = self.get_gameinternalid(uid) if uid in dic: self.sqlsavegameinfo.execute( - f"UPDATE {table} SET timestop = ? WHERE (gameinternalid = ? and timestart = ?)", + "UPDATE {} SET timestop = ? WHERE (gameinternalid = ? and timestart = ?)".format(table), (_t, gameinternalid, dic[uid]), ) else: dic[uid] = _t self.sqlsavegameinfo.execute( - f"INSERT INTO {table} VALUES(?,?,?)", + "INSERT INTO {} VALUES(?,?,?)".format(table), (gameinternalid, _t, _t), ) for k in list(dic.keys()): diff --git a/py/LunaTranslator/myutils/utils.py b/py/LunaTranslator/myutils/utils.py index dc29f6e9..e36b5f71 100644 --- a/py/LunaTranslator/myutils/utils.py +++ b/py/LunaTranslator/myutils/utils.py @@ -99,8 +99,8 @@ def findenclose(text, tag): tags = "" + tags = "<{}".format(tag) + tage = "".format(tag) collect = "" __ = 0 while True: @@ -243,7 +243,7 @@ def trysearchforid_1(gameuid, searchargs: list, target=None): idname = targetmod[key].idname savehook_new_data[gameuid][idname] = vid gobject.baseobject.translation_ui.displayglobaltooltip.emit( - f"{key}: found {vid}" + "{}: found {}".format(key, vid) ) if infoid is None or key == primitivtemetaorigin: infoid = key, vid @@ -292,13 +292,13 @@ class gamepath2uid_index_helper(dict): def initanewitem(title): - uid = f"{time.time()}_{uuid.uuid4()}" + uid = "{}_{}".format(time.time(), uuid.uuid4()) savehook_new_data[uid] = gamepath2uid_index_helper(getdefaultsavehook(title), uid) return uid def duplicateconfig(uidold): - uid = f"{time.time()}_{uuid.uuid4()}" + uid = "{}_{}".format(time.time(), uuid.uuid4()) savehook_new_data[uid] = json.loads(json.dumps(savehook_new_data[uidold])) return uid @@ -389,7 +389,7 @@ def argsort(l): def selectdebugfile(path: str, ismypost=False): if ismypost: - path = f"./userconfig/posts/{path}.py" + path = "./userconfig/posts/{}.py".format(path) p = os.path.abspath((path)) os.makedirs(os.path.dirname(p), exist_ok=True) print(path) @@ -406,7 +406,7 @@ def selectdebugfile(path: str, ismypost=False): p, ) threading.Thread( - target=subprocess.run, args=(f'notepad "{os.path.normpath(p)}"',) + target=subprocess.run, args=("notepad " + os.path.normpath(p),) ).start() return p @@ -883,7 +883,7 @@ class SafeFormatter(Formatter): if key in kwargs: return super().get_value(key, args, kwargs) else: - print(f"{key} is missing") + print("{} is missing".format(key)) return key @@ -891,9 +891,9 @@ def checkv1(api_url: str): # 傻逼豆包大模型是非要v3,不是v1 # 智谱AI v4 for i in range(1, 10): - if api_url.endswith(f"/v{i}"): + if api_url.endswith("/v{}".format(i)): return api_url - elif api_url.endswith(f"/v{i}/"): + elif api_url.endswith("/v{}/".format(i)): return api_url[:-1] if api_url.endswith("/"): return api_url + "v1" diff --git a/py/LunaTranslator/network/libcurl/libcurl.py b/py/LunaTranslator/network/libcurl/libcurl.py index 2a323dc9..0b689cca 100644 --- a/py/LunaTranslator/network/libcurl/libcurl.py +++ b/py/LunaTranslator/network/libcurl/libcurl.py @@ -319,14 +319,14 @@ class CURLException(RequestException): LAST = 100 def __init__(self, code) -> None: - error = f"UNKNOWN ERROR {code}" + error = "UNKNOWN ERROR {}".format(code) message = curl_easy_strerror(code).decode("utf8") for _ in dir(self): if _.startswith("") and code == getattr(self, _): error = _ break if message: - error += f": {message}" + error += ": {}".format(message) super().__init__(error) diff --git a/py/LunaTranslator/network/winhttp/winhttp.py b/py/LunaTranslator/network/winhttp/winhttp.py index a04c4a39..f777ee3b 100644 --- a/py/LunaTranslator/network/winhttp/winhttp.py +++ b/py/LunaTranslator/network/winhttp/winhttp.py @@ -213,13 +213,13 @@ class WinhttpException(RequestException): ): module = Winhttp._handle message = windows.FormatMessage(code, module) - error = f"UNKNOWN ERROR {code}" + error = "UNKNOWN ERROR {}".format(code) for _ in dir(self): if _.startswith("ERROR") and code == getattr(self, _): error = _ break if message: - error += f": {message}" + error += ": {}".format(message) super().__init__(error) diff --git a/py/LunaTranslator/ocrengines/chatgptlike.py b/py/LunaTranslator/ocrengines/chatgptlike.py index b458e4ee..f7b0f750 100644 --- a/py/LunaTranslator/ocrengines/chatgptlike.py +++ b/py/LunaTranslator/ocrengines/chatgptlike.py @@ -50,7 +50,7 @@ class OCR(baseocr): if self.config["use_custom_prompt"]: prompt = self.config["custom_prompt"] else: - prompt = f"Recognize the {self.srclang} text in the picture." + prompt = "Recognize the {} text in the picture.".format(self.srclang) base64_image = base64.b64encode(imagebinary).decode("utf-8") message = [ @@ -61,7 +61,7 @@ class OCR(baseocr): { "type": "image_url", "image_url": { - "url": f"data:image/jpeg;base64,{base64_image}", + "url": "data:image/jpeg;base64," + base64_image, "detail": "low", }, }, diff --git a/py/LunaTranslator/ocrengines/geminiocr.py b/py/LunaTranslator/ocrengines/geminiocr.py index f60c70f2..d990809d 100644 --- a/py/LunaTranslator/ocrengines/geminiocr.py +++ b/py/LunaTranslator/ocrengines/geminiocr.py @@ -42,7 +42,7 @@ class OCR(baseocr): if self.config["use_custom_prompt"]: prompt = self.config["custom_prompt"] else: - prompt = f"Recognize the {self.srclang} text in the picture." + prompt = "Recognize the {} text in the picture.".format(self.srclang) payload = { "contents": [ { @@ -61,7 +61,7 @@ class OCR(baseocr): response = requests.post( urlpathjoin( self.config["BASE_URL"], - f"v1beta/models/{model}:generateContent?key={api_key}", + "v1beta/models/{}:generateContent?key={}".format(model, api_key), ), headers=headers, json=payload, diff --git a/py/LunaTranslator/ocrengines/googlelens.py b/py/LunaTranslator/ocrengines/googlelens.py index ac1c8798..331f0be0 100644 --- a/py/LunaTranslator/ocrengines/googlelens.py +++ b/py/LunaTranslator/ocrengines/googlelens.py @@ -10,7 +10,7 @@ class OCR(baseocr): regex = re.compile(r">AF_initDataCallback\(({key: 'ds:1'.*?)\);") timestamp = int(time.time() * 1000) - url = f"https://lens.google.com/v3/upload?stcs={timestamp}" + url = "https://lens.google.com/v3/upload?stcs={}".format(timestamp) headers = { "User-Agent": "Mozilla/5.0 (Linux; Android 13; RMX3771) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.6167.144 Mobile Safari/537.36", } diff --git a/py/LunaTranslator/ocrengines/mangaocr.py b/py/LunaTranslator/ocrengines/mangaocr.py index 0bd53c70..c2a2b5af 100644 --- a/py/LunaTranslator/ocrengines/mangaocr.py +++ b/py/LunaTranslator/ocrengines/mangaocr.py @@ -15,7 +15,7 @@ class OCR(baseocr): absolute_img_path = os.path.abspath(fname) params = {"image_path": absolute_img_path} - response = requests.get(f"http://127.0.0.1:{self.port}/image", params=params) + response = requests.get("http://127.0.0.1:{}/image".format(self.port), params=params) os.remove(absolute_img_path) try: return response.json()["text"] diff --git a/py/LunaTranslator/ocrengines/weixinocr.py b/py/LunaTranslator/ocrengines/weixinocr.py index f23906f2..c82461a5 100644 --- a/py/LunaTranslator/ocrengines/weixinocr.py +++ b/py/LunaTranslator/ocrengines/weixinocr.py @@ -37,7 +37,7 @@ class wcocr: mojo = os.path.join( default, r"resources\app\versions", - f"{version[0]}.{version[1]}.{version[2]}-{version[3]}", + "{}.{}.{}-{}".format(version[0], version[1], version[2], version[3]), ) ocr = os.path.join(mojo, r"QQScreenShot\Bin\TencentOCR.exe") return ocr, mojo diff --git a/py/LunaTranslator/rendertext/somefunctions.py b/py/LunaTranslator/rendertext/somefunctions.py index 1c2e8605..564edb13 100644 --- a/py/LunaTranslator/rendertext/somefunctions.py +++ b/py/LunaTranslator/rendertext/somefunctions.py @@ -22,7 +22,7 @@ class dataget: if not color: return None r, g, b, a = color - return f"rgba({r}, {g}, {b}, {a})" + return "rgba({}, {}, {}, {})".format(r, g, b, a) def _getfontinfo(self, origin): if origin: diff --git a/py/LunaTranslator/rendertext/textbrowser.py b/py/LunaTranslator/rendertext/textbrowser.py index d27e93ec..b771d439 100644 --- a/py/LunaTranslator/rendertext/textbrowser.py +++ b/py/LunaTranslator/rendertext/textbrowser.py @@ -163,7 +163,7 @@ class TextBrowser(QWidget, dataget): "textrender" ]["textbrowser"][0] - __ = importlib.import_module(f"rendertext.textbrowser_imp.{self.currenttype}") + __ = importlib.import_module("rendertext.textbrowser_imp." + self.currenttype) self.currentclass = functools.partial(__.TextLine, self.currenttype) diff --git a/py/LunaTranslator/rendertext/webview.py b/py/LunaTranslator/rendertext/webview.py index 58d1a3e5..70892b18 100644 --- a/py/LunaTranslator/rendertext/webview.py +++ b/py/LunaTranslator/rendertext/webview.py @@ -127,26 +127,26 @@ class TextBrowser(QWidget, dataget): # js api def showhidetranslate(self, show): - self.debugeval(f'showhidetranslate("{int(show)}")') + self.debugeval('showhidetranslate("{}")'.format(int(show))) def showhideorigin(self, show): - self.debugeval(f'showhideorigin("{int(show)}")') + self.debugeval('showhideorigin("{}")'.format(int(show))) def showhidetranslatorname(self, show): - self.debugeval(f'showhidetranslatorname("{int(show)}")') + self.debugeval('showhidetranslatorname("{}")'.format(int(show))) def create_div_line_id(self, _id, origin): - self.debugeval(f'create_div_line_id("{_id}","{int(origin)}")') + self.debugeval('create_div_line_id("{}","{}")'.format(_id, int(origin))) def clear_all(self): - self.debugeval(f"clear_all()") + self.debugeval("clear_all()") def set_extra_html(self, html): if not globalconfig["useextrahtml"]: - self.debugeval(f'set_extra_html("")') + self.debugeval('set_extra_html("")') return html = quote(html) - self.debugeval(f'set_extra_html("{html}")') + self.debugeval('set_extra_html("{}")'.format(html)) def create_internal_text(self, style, styleargs, _id, name, text, args): name = quote(name) @@ -154,7 +154,9 @@ class TextBrowser(QWidget, dataget): args = quote(json.dumps(args)) styleargs = quote(json.dumps(styleargs)) self.debugeval( - f'create_internal_text("{style}","{styleargs}","{_id}","{name}","{text}","{args}");' + 'create_internal_text("{}","{}","{}","{}","{}","{}");'.format( + style, styleargs, _id, name, text, args + ) ) def create_internal_rubytext(self, style, styleargs, _id, tag, args): @@ -162,7 +164,9 @@ class TextBrowser(QWidget, dataget): args = quote(json.dumps(args)) styleargs = quote(json.dumps(styleargs)) self.debugeval( - f'create_internal_rubytext("{style}","{styleargs}","{_id}","{tag}","{args}");' + 'create_internal_rubytext("{}","{}","{}","{}","{}");'.format( + style, styleargs, _id, tag, args + ) ) def calllunaheightchange(self, h): @@ -196,7 +200,7 @@ class TextBrowser(QWidget, dataget): def createtextlineid(self, origin): - _id = f"luna_{uuid.uuid4()}" + _id = "luna_{}".format(uuid.uuid4()) self.create_div_line_id(_id, origin) return _id diff --git a/py/LunaTranslator/requests.py b/py/LunaTranslator/requests.py index f3429532..23dd8ae7 100644 --- a/py/LunaTranslator/requests.py +++ b/py/LunaTranslator/requests.py @@ -184,14 +184,15 @@ class ResponseBase: yield pending def raise_for_status(self): - http_error_msg = "" + which = None if 400 <= self.status_code < 500: - http_error_msg = f"{self.status_code} Client Error: {self.status_text} for url: {self.url}" - + which = "Client" elif 500 <= self.status_code < 600: - http_error_msg = f"{self.status_code} Server Error: {self.status_text} for url: {self.url}" - - if http_error_msg: + which = "Server" + if which: + http_error_msg = "{code} {which} Error: {text} for url: {url}".format( + code=self.status_code, which=which, text=self.status_text, url=self.url + ) raise HTTPError(http_error_msg) diff --git a/py/LunaTranslator/textoutput/websocket.py b/py/LunaTranslator/textoutput/websocket.py index e40c4d00..3fef96cb 100644 --- a/py/LunaTranslator/textoutput/websocket.py +++ b/py/LunaTranslator/textoutput/websocket.py @@ -28,7 +28,7 @@ class websocketserver: self.server_socket.listen(1) while True: client_socket, address = self.server_socket.accept() - print(f"Client connected: {address}") + print("Client connected: {}".format(address)) self.handle_client(client_socket) @@ -43,13 +43,13 @@ class websocketserver: if "Sec-WebSocket-Key:" in line: key = line.split(":")[1].strip() break - value = f"{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".encode("utf-8") + value = "{}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".format(key).encode("utf-8") hashed = base64encode(hashlib.sha1(value).digest()).strip().decode() # 构造握手响应 response = "HTTP/1.1 101 Switching Protocols\r\n" response += "Upgrade: websocket\r\n" response += "Connection: Upgrade\r\n" - response += f"Sec-WebSocket-Accept: {hashed}\r\n\r\n" + response += "Sec-WebSocket-Accept: {}\r\n\r\n".format(hashed) # 发送握手响应给客户端 client_socket.send(response.encode()) diff --git a/py/LunaTranslator/textsource/texthook.py b/py/LunaTranslator/textsource/texthook.py index 9cd6f16d..356b5147 100644 --- a/py/LunaTranslator/textsource/texthook.py +++ b/py/LunaTranslator/textsource/texthook.py @@ -342,10 +342,10 @@ class texthook(basetext): self.gameuid = gameuid self.detachall() _filename, _ = os.path.splitext(os.path.basename(gamepath)) - sqlitef = gobject.gettranslationrecorddir(f"{_filename}_{gameuid}.sqlite") + sqlitef = gobject.gettranslationrecorddir("{}_{}.sqlite".format(_filename, gameuid)) if os.path.exists(sqlitef) == False: md5 = getfilemd5(gamepath) - f2 = gobject.gettranslationrecorddir(f"{_filename}_{md5}.sqlite") + f2 = gobject.gettranslationrecorddir("{}_{}.sqlite".format(_filename, md5)) try: os.rename(f2, sqlitef) except: @@ -396,7 +396,7 @@ class texthook(basetext): injectpids.append(pid) if len(injectpids): arch = ["32", "64"][self.is64bit] - dll = os.path.abspath(f"./files/plugins/LunaHook/LunaHook{arch}.dll") + dll = os.path.abspath("./files/plugins/LunaHook/LunaHook{}.dll".format(arch)) injectdll(injectpids, arch, dll) @threader diff --git a/py/LunaTranslator/translator/_baiduqianfan.py b/py/LunaTranslator/translator/_baiduqianfan.py index 75d5eec5..9dd5fb50 100644 --- a/py/LunaTranslator/translator/_baiduqianfan.py +++ b/py/LunaTranslator/translator/_baiduqianfan.py @@ -3,6 +3,7 @@ import json, requests from traceback import print_exc from myutils.utils import createenglishlangmap + class TS(basetrans): def langmap(self): @@ -88,11 +89,15 @@ class TS(basetrans): query, "use_user_user_prompt", "user_user_prompt" ) message = [] - self._gpt_common_parse_context(message, self.context, self.config["context_num"]) + self._gpt_common_parse_context( + message, self.context, self.config["context_num"] + ) message.append({"role": "user", "content": query}) usingstream = self.config["usingstream"] - url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/{self.config['model']}?access_token={acss}" + url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/{}?access_token={}".format( + self.config["model"], acss + ) response = self.proxysession.post( url, diff --git a/py/LunaTranslator/translator/_ort_sp.py b/py/LunaTranslator/translator/_ort_sp.py index f7ed31d5..fe9f413c 100644 --- a/py/LunaTranslator/translator/_ort_sp.py +++ b/py/LunaTranslator/translator/_ort_sp.py @@ -179,7 +179,7 @@ class TS(basetrans): def encode_as_ids(self, content): input_str = ctypes.c_char_p( - bytes(f"<-{self.srclang}2{self.tgtlang}-> " + content, "utf8") + "<-{}2{}-> {}".format(self.srclang, self.tgtlang, content).encode("utf8") ) token_ids = ctypes.POINTER(ctypes.c_int32)() n_tokens = ctypes.c_size_t() @@ -256,15 +256,30 @@ class TS(basetrans): return output_ids_py def translate(self, content): - delimiters = ['.','。','\n',':',':','?','?','!','!','…','「','」',] - raw_split = [i.strip() for i in re.split('(['+''.join(delimiters)+'])', content)] + delimiters = [ + ".", + "。", + "\n", + ":", + ":", + "?", + "?", + "!", + "!", + "…", + "「", + "」", + ] + raw_split = [ + i.strip() for i in re.split("([" + "".join(delimiters) + "])", content) + ] content_split = [i for i in raw_split if i] translated_list = [] i = 0 while i < len(content_split): sentence = content_split[i] while i + 1 < len(content_split): - if content_split[i+1] not in delimiters: + if content_split[i + 1] not in delimiters: break i += 1 sentence += content_split[i] @@ -273,7 +288,7 @@ class TS(basetrans): translated_sentence = self.decode_from_ids(output_ids_py) translated_list.append(translated_sentence) i += 1 - translated = ''.join(translated_list) + translated = "".join(translated_list) return translated def __del__(self): diff --git a/py/LunaTranslator/translator/dev_llm_common.py b/py/LunaTranslator/translator/dev_llm_common.py index fe8b2941..975a2c45 100644 --- a/py/LunaTranslator/translator/dev_llm_common.py +++ b/py/LunaTranslator/translator/dev_llm_common.py @@ -32,25 +32,27 @@ class commonllmdev(basetransdev): prompt = self._gptlike_createsys("use_custom_prompt", "custom_prompt") content = prompt + content self.Runtime_evaluate( - f"document.querySelector(`{repr(self.textarea_selector)}`).foucs()" + "document.querySelector(`{}`).foucs()".format(repr(self.textarea_selector)) ) self.clear_input() self.send_keys(content) # chatgpt网站没有焦点时,用这个也可以。 self.Runtime_evaluate( - f'textarea=document.querySelector({repr(self.textarea_selector)});textarea.value="";event = new Event("input", {{bubbles: true, cancelable: true }});textarea.dispatchEvent(event);textarea.value=`{content}`;event = new Event("input", {{bubbles: true, cancelable: true }});textarea.dispatchEvent(event);' + 'textarea=document.querySelector({});textarea.value="";event = new Event("input", {{bubbles: true, cancelable: true }});textarea.dispatchEvent(event);textarea.value=`{}`;event = new Event("input", {{bubbles: true, cancelable: true }});textarea.dispatchEvent(event);'.format( + repr(self.textarea_selector), content + ) ) try: # 月之暗面 while self.Runtime_evaluate( - f"document.querySelector({repr(self.button_selector)}).disabled" + "document.querySelector({}).disabled".format(repr(self.button_selector)) )["result"]["value"]: time.sleep(0.1) except: pass self.Runtime_evaluate( - f"document.querySelector({repr(self.button_selector)}).click()" + "document.querySelector({}).click()".format(repr(self.button_selector)) ) if self.config["usingstream"]: __ = [""] diff --git a/py/LunaTranslator/translator/gemini.py b/py/LunaTranslator/translator/gemini.py index bc76c4fa..e57d2d9b 100644 --- a/py/LunaTranslator/translator/gemini.py +++ b/py/LunaTranslator/translator/gemini.py @@ -63,7 +63,9 @@ class TS(basetrans): res = self.proxysession.post( urlpathjoin( self.config["BASE_URL"].strip(), - f"v1beta/models/{model}:{['generateContent','streamGenerateContent'][usingstream]}", + "v1beta/models/{}:{}".format( + model, ["generateContent", "streamGenerateContent"][usingstream] + ), ), params={"key": self.multiapikeycurrent["SECRET_KEY"]}, json=payload, diff --git a/py/LunaTranslator/translator/gptcommon.py b/py/LunaTranslator/translator/gptcommon.py index ab4a6f84..eb5152e6 100644 --- a/py/LunaTranslator/translator/gptcommon.py +++ b/py/LunaTranslator/translator/gptcommon.py @@ -28,7 +28,9 @@ class qianfanIAM: def sign(access_key_id, secret_access_key): now = datetime.now(timezone.utc) canonical_time = now.strftime("%Y-%m-%dT%H:%M:%SZ") - sign_key_info = f"bce-auth-v1/{access_key_id}/{canonical_time}/8640000" + sign_key_info = "bce-auth-v1/{}/{}/8640000".format( + access_key_id, canonical_time + ) sign_key = hmac.new( secret_access_key.encode(), sign_key_info.encode(), hashlib.sha256 ).hexdigest() @@ -36,7 +38,7 @@ class qianfanIAM: sign_result = hmac.new( sign_key.encode(), string_to_sign.encode(), hashlib.sha256 ).hexdigest() - return f"{sign_key_info}/host/{sign_result}" + return "{}/host/{}".format(sign_key_info, sign_result) @staticmethod def getkey(ak, sk, proxy): diff --git a/py/LunaTranslator/translator/hwcloud.py b/py/LunaTranslator/translator/hwcloud.py index adc0d487..9e136c85 100644 --- a/py/LunaTranslator/translator/hwcloud.py +++ b/py/LunaTranslator/translator/hwcloud.py @@ -317,7 +317,9 @@ class TS(basetrans): raise Exception(response.maybejson) self.cacheproject[(end, ak, sk)] = project_id project_id = self.cacheproject.get((end, ak, sk)) - url = f"https://{end}/v1/{project_id}/machine-translation/text-translation" + url = "https://{}/v1/{}/machine-translation/text-translation".format( + end, project_id + ) body = { "text": query, "from": self.srclang, @@ -332,7 +334,7 @@ class TS(basetrans): "User-Agent": "huaweicloud-usdk-python/3.0", } r.host = end - r.resource_path = f"/v1/{project_id}/machine-translation/text-translation" + r.resource_path = "/v1/{}/machine-translation/text-translation".format(project_id) r.method = "POST" r.body = body r = Signer((ak, sk)).sign(r) diff --git a/py/LunaTranslator/translator/rengong.py b/py/LunaTranslator/translator/rengong.py index 1bb242f4..e156e0a5 100644 --- a/py/LunaTranslator/translator/rengong.py +++ b/py/LunaTranslator/translator/rengong.py @@ -122,5 +122,5 @@ class TS(basetrans): if (not res) and ("\n" in content): res = self.tryfindtranslate_single(content) if not res: - raise Exception(f"can't find: {content}") + raise Exception("can't find: " + content) return res diff --git a/py/LunaTranslator/translator/sakura.py b/py/LunaTranslator/translator/sakura.py index dad5f8c3..bc5c07b0 100644 --- a/py/LunaTranslator/translator/sakura.py +++ b/py/LunaTranslator/translator/sakura.py @@ -50,9 +50,9 @@ class TS(basetrans): info = gpt["info"] if "info" in gpt.keys() else None if info: - single = f"{src}->{dst} #{info}" + single = "{}->{} #{}".format(src, dst, info) else: - single = f"{src}->{dst}" + single = "{}->{}".format(src, dst) gpt_dict_text_list.append(single) gpt_dict_raw_text = "\n".join(gpt_dict_text_list) @@ -87,7 +87,7 @@ class TS(basetrans): ] self._gpt_common_parse_context_2(messages, self.context, contextnum) messages.append( - {"role": "user", "content": f"将下面的日文文本翻译成中文:{query}"} + {"role": "user", "content": "将下面的日文文本翻译成中文:" + query} ) elif self.config["prompt_version"] == 1: messages = [ @@ -155,7 +155,7 @@ class TS(basetrans): ) except requests.RequestException as e: - raise ValueError(f"连接到Sakura API超时:{self.api_url}") + raise ValueError("连接到Sakura API超时:" + self.api_url) try: yield output.json() except: @@ -190,7 +190,7 @@ class TS(basetrans): stream=True, ) except requests.RequestException: - raise ValueError(f"连接到Sakura API超时:{self.api_url}") + raise ValueError("连接到Sakura API超时:" + self.api_url) if (not output.headers["Content-Type"].startswith("text/event-stream")) and ( output.status_code != 200 diff --git a/py/LunaTranslator/tts/NeoSpeech.py b/py/LunaTranslator/tts/NeoSpeech.py index 4612aaa3..b65550ff 100644 --- a/py/LunaTranslator/tts/NeoSpeech.py +++ b/py/LunaTranslator/tts/NeoSpeech.py @@ -51,7 +51,7 @@ class TTS(TTSbase): ) def getvoicelist(self): - cachefname = gobject.gettempdir(f"{time.time()}.txt") + cachefname = gobject.gettempdir("{}.txt".format(time.time())) exe = os.path.abspath("./files/plugins/shareddllproxy32.exe") subprocess.run('"{}" neospeechlist "{}"'.format(exe, cachefname)) diff --git a/py/LunaTranslator/tts/edgetts.py b/py/LunaTranslator/tts/edgetts.py index b44a9c49..7be5d35a 100644 --- a/py/LunaTranslator/tts/edgetts.py +++ b/py/LunaTranslator/tts/edgetts.py @@ -15,16 +15,22 @@ from tts.basettsclass import TTSbase BASE_URL = "speech.platform.bing.com/consumer/speech/synthesize/readaloud" TRUSTED_CLIENT_TOKEN = "6A5AA1D4EAFF4E9FB37E23D68491D6F4" -WSS_URL = f"wss://{BASE_URL}/edge/v1?TrustedClientToken={TRUSTED_CLIENT_TOKEN}" -VOICE_LIST = f"https://{BASE_URL}/voices/list?trustedclienttoken={TRUSTED_CLIENT_TOKEN}" +WSS_URL = "wss://{}/edge/v1?TrustedClientToken={}".format( + BASE_URL, TRUSTED_CLIENT_TOKEN +) +VOICE_LIST = "https://{}/voices/list?trustedclienttoken={}".format( + BASE_URL, TRUSTED_CLIENT_TOKEN +) CHROMIUM_FULL_VERSION = "130.0.2849.68" CHROMIUM_MAJOR_VERSION = CHROMIUM_FULL_VERSION.split(".", maxsplit=1)[0] -SEC_MS_GEC_VERSION = f"1-{CHROMIUM_FULL_VERSION}" +SEC_MS_GEC_VERSION = "1-{}".format(CHROMIUM_FULL_VERSION) BASE_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" - f" (KHTML, like Gecko) Chrome/{CHROMIUM_MAJOR_VERSION}.0.0.0 Safari/537.36" - f" Edg/{CHROMIUM_MAJOR_VERSION}.0.0.0", + " (KHTML, like Gecko) Chrome/{CHROMIUM_MAJOR_VERSION}.0.0.0 Safari/537.36" + " Edg/{CHROMIUM_MAJOR_VERSION}.0.0.0".format( + CHROMIUM_MAJOR_VERSION=CHROMIUM_MAJOR_VERSION + ), "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9", } @@ -36,8 +42,9 @@ WSS_HEADERS = { WSS_HEADERS.update(BASE_HEADERS) VOICE_HEADERS = { "Authority": "speech.platform.bing.com", - "Sec-CH-UA": f'" Not;A Brand";v="99", "Microsoft Edge";v="{CHROMIUM_MAJOR_VERSION}",' - f' "Chromium";v="{CHROMIUM_MAJOR_VERSION}"', + "Sec-CH-UA": '" Not;A Brand";v="99", "Microsoft Edge";v="{CHROMIUM_MAJOR_VERSION}", "Chromium";v="{CHROMIUM_MAJOR_VERSION}"'.format( + CHROMIUM_MAJOR_VERSION=CHROMIUM_MAJOR_VERSION + ), "Sec-CH-UA-Mobile": "?0", "Accept": "*/*", "Sec-Fetch-Site": "none", @@ -91,7 +98,7 @@ class DRM: ticks *= S_TO_NS / 100 # Create the string to hash by concatenating the ticks and the trusted client token - str_to_hash = f"{ticks:.0f}{TRUSTED_CLIENT_TOKEN}" + str_to_hash = "{:.0f}{}".format(ticks, TRUSTED_CLIENT_TOKEN) # Compute the SHA256 hash and return the uppercased hex digest return hashlib.sha256(str_to_hash.encode("ascii")).hexdigest().upper() @@ -101,8 +108,9 @@ class TTS(TTSbase): def getvoicelist(self): alllist = requests.get( - f"{VOICE_LIST}&Sec-MS-GEC={DRM.generate_sec_ms_gec()}" - f"&Sec-MS-GEC-Version={SEC_MS_GEC_VERSION}", + "{}&Sec-MS-GEC={}&Sec-MS-GEC-Version={}".format( + VOICE_LIST, DRM.generate_sec_ms_gec(), SEC_MS_GEC_VERSION + ), headers=VOICE_HEADERS, proxies=self.proxy, ).json() @@ -218,9 +226,9 @@ def transferMsTTSData(rate, content, voice, proxy): else: ip = port = None ws = websocket.create_connection( - f"{WSS_URL}&Sec-MS-GEC={DRM.generate_sec_ms_gec()}" - f"&Sec-MS-GEC-Version={SEC_MS_GEC_VERSION}" - f"&ConnectionId={connect_id()}", + "{}&Sec-MS-GEC={}&Sec-MS-GEC-Version={}&ConnectionId={}".format( + WSS_URL, DRM.generate_sec_ms_gec(), SEC_MS_GEC_VERSION, connect_id() + ), header=WSS_HEADERS, http_proxy_host=ip, http_proxy_port=port, diff --git a/py/LunaTranslator/tts/vitsSimpleAPI.py b/py/LunaTranslator/tts/vitsSimpleAPI.py index c86b3192..f5664943 100644 --- a/py/LunaTranslator/tts/vitsSimpleAPI.py +++ b/py/LunaTranslator/tts/vitsSimpleAPI.py @@ -15,7 +15,7 @@ class TTS(TTSbase): for modelType in modelTypes: vits_data = responseVits[modelType] for item in vits_data: - model_info = f'{modelType}_{item["id"]}_{item["name"]}' + model_info = "{}_{}_{}".format(modelType, item["id"], item["name"]) voicelist.append(model_info) internal.append((modelType, item["id"], item["name"])) return internal, voicelist diff --git a/py/LunaTranslator/tts/voiceroid2.py b/py/LunaTranslator/tts/voiceroid2.py index c0f76697..9b862688 100644 --- a/py/LunaTranslator/tts/voiceroid2.py +++ b/py/LunaTranslator/tts/voiceroid2.py @@ -11,7 +11,7 @@ class TTS(TTSbase): voicelist = [] _p = os.path.join(self.config["path"], "Voice") if os.path.exists(_p) == False: - raise Exception(f"not exists {_p}") + raise Exception("not exists " + _p) l = os.listdir(_p) for _ in l: diff --git a/py/LunaTranslator/tts/voicevox.py b/py/LunaTranslator/tts/voicevox.py index ac217b65..b802c78b 100644 --- a/py/LunaTranslator/tts/voicevox.py +++ b/py/LunaTranslator/tts/voicevox.py @@ -26,7 +26,7 @@ class TTS(TTSbase): } response = requests.get( - f"http://127.0.0.1:{self.config['Port']}/speakers", + "http://127.0.0.1:{}/speakers".format(self.config['Port']), headers=headers, proxies={"http": None, "https": None}, ).json() @@ -50,7 +50,7 @@ class TTS(TTSbase): params = {"speaker": voice, "text": content} response = requests.post( - f"http://localhost:{self.config['Port']}/audio_query", + "http://localhost:{}/audio_query".format(self.config['Port']), params=params, headers=headers, proxies={"http": None, "https": None}, @@ -63,7 +63,7 @@ class TTS(TTSbase): "speaker": voice, } response = requests.post( - f"http://localhost:{self.config['Port']}/synthesis", + "http://localhost:{}/synthesis".format(self.config['Port']), params=params, headers=headers, data=json.dumps(response.json()),