This commit is contained in:
恍兮惚兮 2024-11-14 22:50:54 +08:00
parent 3b3f06389e
commit 2cbdb8273f
51 changed files with 281 additions and 192 deletions

View File

@ -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)

View File

@ -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))

View File

@ -14,10 +14,14 @@ class jisho(cishubase):
for title, res in allres:
idx += 1
btns.append(
f"""<button type="button" onclick="onclickbtn_xxxxxx_internal('buttonid_xxxxx_internal{idx}')" id="buttonid_xxxxx_internal{idx}" class="tab-button_xxxx_internal" data-tab="tab_xxxxx_internal{idx}">{title}</button>"""
"""<button type="button" onclick="onclickbtn_xxxxxx_internal('buttonid_xxxxx_internal{idx}')" id="buttonid_xxxxx_internal{idx}" class="tab-button_xxxx_internal" data-tab="tab_xxxxx_internal{idx}">{title}</button>""".format(
idx=idx, title=title
)
)
contents.append(
f"""<div id="tab_xxxxx_internal{idx}" class="tab-pane_xxxxx_internal">{res}</div>"""
"""<div id="tab_xxxxx_internal{idx}" class="tab-pane_xxxxx_internal">{res}</div>""".format(
idx=idx, res=res
)
)
commonstyle = """
<script>
@ -67,17 +71,17 @@ function onclickbtn_xxxxxx_internal(_id) {
</style>
"""
res = f"""
res = """
{commonstyle}
<div class="tab-widget_xxxxxx_internal">
<div class="centerdiv_xxxxxx_internal"><div>
{''.join(btns)}
{btns}
</div>
</div>
<div>
<div class="tab-content_xxxxxx_internal">
{''.join(contents)}
{contents}
</div>
</div>
</div>
@ -85,7 +89,9 @@ function onclickbtn_xxxxxx_internal(_id) {
if(document.querySelectorAll('.tab-widget_xxxxxx_internal .tab-button_xxxx_internal').length)
document.querySelectorAll('.tab-widget_xxxxxx_internal .tab-button_xxxx_internal')[0].click()
</script>
"""
""".format(
commonstyle=commonstyle, btns="".join(btns), contents="".join(contents)
)
return res
def paradown(self, word, key, saver):

View File

@ -2167,30 +2167,32 @@ class mdict(cishubase):
for type_, string in items:
ishtml = False
if type_ == 1:
htmlitem = f'<font color="#FF0000" size=5>{string}</font>'
htmlitem = '<font color="#FF0000" size=5>{}</font>'.format(string)
elif type_ == 3:
htmlitem = (
f'<font color="#FB8C42" face="Droid Sans Fallback">{string}</font>'
'<font color="#FB8C42" face="Droid Sans Fallback">{}</font>'.format(
string
)
)
elif type_ == 4:
htmlitem = f"<font color=black>{string}</font>"
htmlitem = "<font color=black>{}</font>".format(string)
elif type_ == 5:
htmlitem = f'<font color="#04A6B5">{string}</font>'
htmlitem = '<font color="#04A6B5">{}</font>'.format(string)
elif type_ == 6:
htmlitem = f'<font color="#9900CC">{string}</font>'
htmlitem = '<font color="#9900CC">{}</font>'.format(string)
elif type_ == 7:
htmlitem = f'<font color="#F27A04">{string}</font>'
htmlitem = '<font color="#F27A04">{}</font>'.format(string)
else:
if str(type_).startswith("2"):
num = str(type_)[1:]
if len(num):
num += " "
htmlitem = f'<font color="#0000FF">{num}{string}</font>'
htmlitem = '<font color="#0000FF">{}{}</font>'.format(num, string)
elif str(type_).startswith("8"):
num = str(type_)[1:]
if len(num):
num += " "
htmlitem = f'<font color="#330099">{num}{string}</font>'
htmlitem = '<font color="#330099">{}{}</font>'.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'<font color="#{color}">{num}{string}</font>'
htmlitem = '<font color="#{}">{}{}</font>'.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 controls id="{uid}" style="display: none"><source src="data:{self.get_mime_type_from_magic(file_content)};base64,{base64_content}"></audio>'
audio = '<audio controls id="{}" style="display: none"><source src="data:{};base64,{}"></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'<div id="{divid}">{html_content}</div>'
return '<div id="{}">{}</div>'.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"""<button type="button" onclick="onclickbtn_mdict_internal('buttonid_mdict_internal{idx}')" id="buttonid_mdict_internal{idx}" class="tab-button_mdict_internal" data-tab="tab_mdict_internal{idx}">{title}</button>"""
"""<button type="button" onclick="onclickbtn_mdict_internal('buttonid_mdict_internal{idx}')" id="buttonid_mdict_internal{idx}" class="tab-button_mdict_internal" data-tab="tab_mdict_internal{idx}">{title}</button>""".format(
idx=idx, title=title
)
)
contents.append(
f"""<div id="tab_mdict_internal{idx}" class="tab-pane_mdict_internal">{res}</div>"""
"""<div id="tab_mdict_internal{idx}" class="tab-pane_mdict_internal">{res}</div>""".format(
idx=idx, res=res
)
)
commonstyle = """
<script>
@ -2537,17 +2547,17 @@ function onclickbtn_mdict_internal(_id) {
</style>
"""
res = f"""
res = """
{commonstyle}
<div class="tab-widget_mdict_internal">
<div class="centerdiv_mdict_internal"><div>
{''.join(btns)}
{btns}
</div>
</div>
<div>
<div class="tab-content_mdict_internal">
{''.join(contents)}
{contents}
</div>
</div>
</div>
@ -2555,7 +2565,9 @@ function onclickbtn_mdict_internal(_id) {
if(document.querySelectorAll('.tab-widget_mdict_internal .tab-button_mdict_internal').length)
document.querySelectorAll('.tab-widget_mdict_internal .tab-button_mdict_internal')[0].click()
</script>
"""
""".format(
commonstyle=commonstyle, btns="".join(btns), contents="".join(contents)
)
return res
def generatehtml_flow(self, allres):

View File

@ -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):
</style>
"""
spell = f"<span>{spell}{pron}{accent}</span>"
spell = f'<div class="spell" style="font-size: 18px;">{spell}</div>'
spell = "<span>{}{}{}</span>".format(spell, pron, accent)
spell = '<div class="spell" style="font-size: 18px;">{}</div>'.format(spell)
_type = re.match("\\[(.*?)\\]", excerpt).groups()[0]
_type = f'<p class="type">{_type}</p>'
_type = '<p class="type">{}</p>'.format(_type)
for i in range(len(collect)):
collect[i] = f"<p>{i+1}. {collect[i]}</p>"
detail = f"""<div class="detail">{_type}{''.join(collect)}</div>"""
result = f'<div class="cloud-result">{spell}{detail}</div>'
collect[i] = "<p>{}. {}</p>".format(i + 1, collect[i])
detail = """<div class="detail">{}{}</div>""".format(_type, "".join(collect))
result = '<div class="cloud-result">{}{}</div>'.format(spell, detail)
result += style
return result

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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:

View File

@ -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"]

View File

@ -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, "成功", "安装成功")

View File

@ -157,7 +157,7 @@ class AnkiWindow(QWidget):
fields = self.loadfileds()
fields.update(self.loadfakefields())
html = self.parse_template(html, fields)
html = f'<style>{model_css}</style><div class="card">{html}</div>'
html = '<style>{}</style><div class="card">{}</div>'.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'<div id="luna_dict_tab_{dictionarys[iiii]["dict"]}" class="tab-pane">{dictionarys[iiii]["content"]}</div>'
htmlcontents += (
'<div id="luna_dict_tab_{}" class="tab-pane">{}</div>'.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'<b>{hira["orig"]}</b>')
collect.append('<b>{}</b>'.format(hira["orig"]))
else:
collect.append(hira["orig"])
example = "".join(collect)

View File

@ -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)

View File

@ -1187,15 +1187,14 @@ class abstractwebview(QWidget):
def _parsehtml_codec(self, html):
html = f"""<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /></head>{html}</html>"""
html = """<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /></head>{}</html>""".format(
html
)
return html
def _parsehtml_font(self, html):
html = """<body style=" font-family:'{}'">{}</body>""".format(
QFontDatabase.systemFont(QFontDatabase.SystemFont.GeneralFont).family(),
html,
)
font = QFontDatabase.systemFont(QFontDatabase.SystemFont.GeneralFont).family()
html = """<body style=" font-family:'{}'">{}</body>""".format(font, html)
return html
def _parsehtml_dark(self, html):

View File

@ -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))

View File

@ -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"]

View File

@ -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):

View File

@ -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 = {

View File

@ -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"]

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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):

View File

@ -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()):

View File

@ -99,8 +99,8 @@ def findenclose(text, tag):
tags = "<link"
tage = ">"
else:
tags = f"<{tag}"
tage = f"</{tag}>"
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"

View File

@ -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)

View File

@ -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)

View File

@ -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",
},
},

View File

@ -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,

View File

@ -10,7 +10,7 @@ class OCR(baseocr):
regex = re.compile(r">AF_initDataCallback\(({key: 'ds:1'.*?)\);</script>")
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",
}

View File

@ -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"]

View File

@ -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

View File

@ -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:

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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())

View File

@ -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

View File

@ -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,

View File

@ -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):

View File

@ -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"]:
__ = [""]

View File

@ -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,

View File

@ -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):

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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))

View File

@ -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,

View File

@ -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

View File

@ -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:

View File

@ -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()),