mirror of
https://github.com/HIllya51/LunaTranslator.git
synced 2024-12-28 08:04:13 +08:00
format
This commit is contained in:
parent
3b3f06389e
commit
2cbdb8273f
@ -1040,10 +1040,13 @@ class MAINUI:
|
|||||||
+ (globalconfig["settingfonttype"])
|
+ (globalconfig["settingfonttype"])
|
||||||
+ "' ; }"
|
+ "' ; }"
|
||||||
)
|
)
|
||||||
style += f"""
|
style += """
|
||||||
QListWidget {{
|
QListWidget {{
|
||||||
font:{globalconfig["settingfontsize"] + 4}pt {globalconfig["settingfonttype"]}; }}
|
font:{fontsize}pt {fonttype}; }}
|
||||||
"""
|
""".format(
|
||||||
|
fontsize=globalconfig["settingfontsize"] + 4,
|
||||||
|
fonttype=globalconfig["settingfonttype"],
|
||||||
|
)
|
||||||
self.commonstylebase.setStyleSheet(style)
|
self.commonstylebase.setStyleSheet(style)
|
||||||
font = QFont()
|
font = QFont()
|
||||||
font.setFamily(globalconfig["settingfonttype"])
|
font.setFamily(globalconfig["settingfonttype"])
|
||||||
@ -1173,7 +1176,7 @@ class MAINUI:
|
|||||||
|
|
||||||
for k in globalconfig["metadata"]:
|
for k in globalconfig["metadata"]:
|
||||||
try:
|
try:
|
||||||
targetmod[k] = importlib.import_module(f"metadata.{k}").searcher(k)
|
targetmod[k] = importlib.import_module("metadata." + k).searcher(k)
|
||||||
except:
|
except:
|
||||||
print_exc()
|
print_exc()
|
||||||
|
|
||||||
@ -1189,5 +1192,5 @@ class MAINUI:
|
|||||||
winreg.HKEY_CURRENT_USER,
|
winreg.HKEY_CURRENT_USER,
|
||||||
r"Software\Classes\lunatranslator\shell\open\command",
|
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)
|
winreg.SetValue(keysub, r"", winreg.REG_SZ, command)
|
||||||
|
@ -12,7 +12,7 @@ class japandict(cishubase):
|
|||||||
proxies=self.proxy,
|
proxies=self.proxy,
|
||||||
).content.replace(b"padding-top:60px !important", b"")
|
).content.replace(b"padding-top:60px !important", b"")
|
||||||
base64_content = base64.b64encode(html).decode("utf-8")
|
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):
|
def search(self, word):
|
||||||
url = "https://www.japandict.com/?s={}&lang=eng&list=1".format(quote(word))
|
url = "https://www.japandict.com/?s={}&lang=eng&list=1".format(quote(word))
|
||||||
|
@ -14,10 +14,14 @@ class jisho(cishubase):
|
|||||||
for title, res in allres:
|
for title, res in allres:
|
||||||
idx += 1
|
idx += 1
|
||||||
btns.append(
|
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(
|
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 = """
|
commonstyle = """
|
||||||
<script>
|
<script>
|
||||||
@ -67,17 +71,17 @@ function onclickbtn_xxxxxx_internal(_id) {
|
|||||||
</style>
|
</style>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
res = f"""
|
res = """
|
||||||
{commonstyle}
|
{commonstyle}
|
||||||
<div class="tab-widget_xxxxxx_internal">
|
<div class="tab-widget_xxxxxx_internal">
|
||||||
|
|
||||||
<div class="centerdiv_xxxxxx_internal"><div>
|
<div class="centerdiv_xxxxxx_internal"><div>
|
||||||
{''.join(btns)}
|
{btns}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div class="tab-content_xxxxxx_internal">
|
<div class="tab-content_xxxxxx_internal">
|
||||||
{''.join(contents)}
|
{contents}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -85,7 +89,9 @@ function onclickbtn_xxxxxx_internal(_id) {
|
|||||||
if(document.querySelectorAll('.tab-widget_xxxxxx_internal .tab-button_xxxx_internal').length)
|
if(document.querySelectorAll('.tab-widget_xxxxxx_internal .tab-button_xxxx_internal').length)
|
||||||
document.querySelectorAll('.tab-widget_xxxxxx_internal .tab-button_xxxx_internal')[0].click()
|
document.querySelectorAll('.tab-widget_xxxxxx_internal .tab-button_xxxx_internal')[0].click()
|
||||||
</script>
|
</script>
|
||||||
"""
|
""".format(
|
||||||
|
commonstyle=commonstyle, btns="".join(btns), contents="".join(contents)
|
||||||
|
)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
def paradown(self, word, key, saver):
|
def paradown(self, word, key, saver):
|
||||||
|
@ -2167,30 +2167,32 @@ class mdict(cishubase):
|
|||||||
for type_, string in items:
|
for type_, string in items:
|
||||||
ishtml = False
|
ishtml = False
|
||||||
if type_ == 1:
|
if type_ == 1:
|
||||||
htmlitem = f'<font color="#FF0000" size=5>{string}</font>'
|
htmlitem = '<font color="#FF0000" size=5>{}</font>'.format(string)
|
||||||
elif type_ == 3:
|
elif type_ == 3:
|
||||||
htmlitem = (
|
htmlitem = (
|
||||||
f'<font color="#FB8C42" face="Droid Sans Fallback">{string}</font>'
|
'<font color="#FB8C42" face="Droid Sans Fallback">{}</font>'.format(
|
||||||
|
string
|
||||||
|
)
|
||||||
)
|
)
|
||||||
elif type_ == 4:
|
elif type_ == 4:
|
||||||
htmlitem = f"<font color=black>{string}</font>"
|
htmlitem = "<font color=black>{}</font>".format(string)
|
||||||
elif type_ == 5:
|
elif type_ == 5:
|
||||||
htmlitem = f'<font color="#04A6B5">{string}</font>'
|
htmlitem = '<font color="#04A6B5">{}</font>'.format(string)
|
||||||
elif type_ == 6:
|
elif type_ == 6:
|
||||||
htmlitem = f'<font color="#9900CC">{string}</font>'
|
htmlitem = '<font color="#9900CC">{}</font>'.format(string)
|
||||||
elif type_ == 7:
|
elif type_ == 7:
|
||||||
htmlitem = f'<font color="#F27A04">{string}</font>'
|
htmlitem = '<font color="#F27A04">{}</font>'.format(string)
|
||||||
else:
|
else:
|
||||||
if str(type_).startswith("2"):
|
if str(type_).startswith("2"):
|
||||||
num = str(type_)[1:]
|
num = str(type_)[1:]
|
||||||
if len(num):
|
if len(num):
|
||||||
num += " "
|
num += " "
|
||||||
htmlitem = f'<font color="#0000FF">{num}{string}</font>'
|
htmlitem = '<font color="#0000FF">{}{}</font>'.format(num, string)
|
||||||
elif str(type_).startswith("8"):
|
elif str(type_).startswith("8"):
|
||||||
num = str(type_)[1:]
|
num = str(type_)[1:]
|
||||||
if len(num):
|
if len(num):
|
||||||
num += " "
|
num += " "
|
||||||
htmlitem = f'<font color="#330099">{num}{string}</font>'
|
htmlitem = '<font color="#330099">{}{}</font>'.format(num, string)
|
||||||
elif (
|
elif (
|
||||||
str(type_).startswith("11")
|
str(type_).startswith("11")
|
||||||
or str(type_).startswith("9")
|
or str(type_).startswith("9")
|
||||||
@ -2218,7 +2220,9 @@ class mdict(cishubase):
|
|||||||
break
|
break
|
||||||
if idx != -1:
|
if idx != -1:
|
||||||
string = string[:idx] + num + string[idx:]
|
string = string[:idx] + num + string[idx:]
|
||||||
htmlitem = f'<font color="#{color}">{num}{string}</font>'
|
htmlitem = '<font color="#{}">{}{}</font>'.format(
|
||||||
|
color, num, string
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
ishtml = True
|
ishtml = True
|
||||||
htmlitem = string
|
htmlitem = string
|
||||||
@ -2266,10 +2270,12 @@ class mdict(cishubase):
|
|||||||
uid = str(uuid.uuid4())
|
uid = str(uuid.uuid4())
|
||||||
# with open(uid+'.mp3','wb') as ff:
|
# with open(uid+'.mp3','wb') as ff:
|
||||||
# ff.write(file_content)
|
# 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(
|
html_content = audio + html_content.replace(
|
||||||
url,
|
url,
|
||||||
f"javascript:document.getElementById('{uid}').play()",
|
"javascript:document.getElementById('{}').play()".format(uid),
|
||||||
)
|
)
|
||||||
return html_content
|
return html_content
|
||||||
|
|
||||||
@ -2402,7 +2408,7 @@ class mdict(cishubase):
|
|||||||
print_exc()
|
print_exc()
|
||||||
base64_content = base64.b64encode(file_content.encode("utf8")).decode("utf-8")
|
base64_content = base64.b64encode(file_content.encode("utf8")).decode("utf-8")
|
||||||
html_content = html_content.replace(
|
html_content = html_content.replace(
|
||||||
url, f"data:text/css;base64,{base64_content}"
|
url, "data:text/css;base64," + base64_content
|
||||||
)
|
)
|
||||||
return html_content
|
return html_content
|
||||||
|
|
||||||
@ -2433,9 +2439,9 @@ class mdict(cishubase):
|
|||||||
elif _type == 0:
|
elif _type == 0:
|
||||||
base64_content = base64.b64encode(file_content).decode("utf-8")
|
base64_content = base64.b64encode(file_content).decode("utf-8")
|
||||||
html_content = html_content.replace(
|
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):
|
def searchthread_internal(self, index, k, __safe):
|
||||||
allres = []
|
allres = []
|
||||||
@ -2484,10 +2490,14 @@ class mdict(cishubase):
|
|||||||
for _, foldflow, title, res in allres:
|
for _, foldflow, title, res in allres:
|
||||||
idx += 1
|
idx += 1
|
||||||
btns.append(
|
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(
|
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 = """
|
commonstyle = """
|
||||||
<script>
|
<script>
|
||||||
@ -2537,17 +2547,17 @@ function onclickbtn_mdict_internal(_id) {
|
|||||||
</style>
|
</style>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
res = f"""
|
res = """
|
||||||
{commonstyle}
|
{commonstyle}
|
||||||
<div class="tab-widget_mdict_internal">
|
<div class="tab-widget_mdict_internal">
|
||||||
|
|
||||||
<div class="centerdiv_mdict_internal"><div>
|
<div class="centerdiv_mdict_internal"><div>
|
||||||
{''.join(btns)}
|
{btns}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div class="tab-content_mdict_internal">
|
<div class="tab-content_mdict_internal">
|
||||||
{''.join(contents)}
|
{contents}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -2555,7 +2565,9 @@ function onclickbtn_mdict_internal(_id) {
|
|||||||
if(document.querySelectorAll('.tab-widget_mdict_internal .tab-button_mdict_internal').length)
|
if(document.querySelectorAll('.tab-widget_mdict_internal .tab-button_mdict_internal').length)
|
||||||
document.querySelectorAll('.tab-widget_mdict_internal .tab-button_mdict_internal')[0].click()
|
document.querySelectorAll('.tab-widget_mdict_internal .tab-button_mdict_internal')[0].click()
|
||||||
</script>
|
</script>
|
||||||
"""
|
""".format(
|
||||||
|
commonstyle=commonstyle, btns="".join(btns), contents="".join(contents)
|
||||||
|
)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
def generatehtml_flow(self, allres):
|
def generatehtml_flow(self, allres):
|
||||||
|
@ -57,7 +57,7 @@ def mojiclicksearch(self, word):
|
|||||||
if subdetail["lang"] == "zh-CN":
|
if subdetail["lang"] == "zh-CN":
|
||||||
collect[i] = title + collect[i]
|
collect[i] = title + collect[i]
|
||||||
elif subdetail["lang"] == "ja":
|
elif subdetail["lang"] == "ja":
|
||||||
title = f"({title})"
|
title = "(" + title + ")"
|
||||||
collect[i] = collect[i] + title
|
collect[i] = collect[i] + title
|
||||||
good = True
|
good = True
|
||||||
if not good:
|
if not good:
|
||||||
@ -559,15 +559,15 @@ def mojiclicksearch(self, word):
|
|||||||
|
|
||||||
</style>
|
</style>
|
||||||
"""
|
"""
|
||||||
spell = f"<span>{spell}|{pron}{accent}</span>"
|
spell = "<span>{}|{}{}</span>".format(spell, pron, accent)
|
||||||
spell = f'<div class="spell" style="font-size: 18px;">{spell}</div>'
|
spell = '<div class="spell" style="font-size: 18px;">{}</div>'.format(spell)
|
||||||
_type = re.match("\\[(.*?)\\]", excerpt).groups()[0]
|
_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)):
|
for i in range(len(collect)):
|
||||||
collect[i] = f"<p>{i+1}. {collect[i]}</p>"
|
collect[i] = "<p>{}. {}</p>".format(i + 1, collect[i])
|
||||||
detail = f"""<div class="detail">{_type}{''.join(collect)}</div>"""
|
detail = """<div class="detail">{}{}</div>""".format(_type, "".join(collect))
|
||||||
result = f'<div class="cloud-result">{spell}{detail}</div>'
|
result = '<div class="cloud-result">{}{}</div>'.format(spell, detail)
|
||||||
result += style
|
result += style
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
@ -40,7 +40,7 @@ def gettempdir_1():
|
|||||||
|
|
||||||
|
|
||||||
def gettempdir(filename):
|
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
|
return tgt
|
||||||
|
|
||||||
|
|
||||||
|
@ -93,7 +93,9 @@ class dialog_savedgame_integrated(saveposwindow):
|
|||||||
| Qt.WindowType.WindowCloseButtonHint,
|
| Qt.WindowType.WindowCloseButtonHint,
|
||||||
poslist=globalconfig["savegamedialoggeo"],
|
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(
|
w, self.internallayout = getboxlayout(
|
||||||
[], margin0=True, makewidget=True, both=True
|
[], margin0=True, makewidget=True, both=True
|
||||||
)
|
)
|
||||||
@ -356,9 +358,9 @@ class dialog_savedgame_new(QWidget):
|
|||||||
if fontstring:
|
if fontstring:
|
||||||
_f = QFont()
|
_f = QFont()
|
||||||
_f.fromString(fontstring)
|
_f.fromString(fontstring)
|
||||||
_style += f"font-size:{_f.pointSize()}pt;"
|
_style += "font-size:{}pt;".format(_f.pointSize())
|
||||||
_style += f'font-family:"{_f.family()}";'
|
_style += 'font-family:"{}";'.format(_f.family())
|
||||||
style = f"#{key}{{ {_style} }}"
|
style = "#{}{{ {} }}".format(key, _style)
|
||||||
for exits in [True, False]:
|
for exits in [True, False]:
|
||||||
c = globalconfig["dialog_savegame_layout"][
|
c = globalconfig["dialog_savegame_layout"][
|
||||||
("onfilenoexistscolor1", "backcolor1")[exits]
|
("onfilenoexistscolor1", "backcolor1")[exits]
|
||||||
@ -370,8 +372,13 @@ class dialog_savedgame_new(QWidget):
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
style += f"#savegame_exists{exits}{{background-color:{c};}}"
|
style += "#savegame_exists{}{{background-color:{};}}".format(exits, c)
|
||||||
style += f'#savegame_onselectcolor1{{background-color: {str2rgba(globalconfig["dialog_savegame_layout"]["onselectcolor1"],globalconfig["dialog_savegame_layout"]["transparentselect"])};}}'
|
style += "#savegame_onselectcolor1{{background-color: {};}}".format(
|
||||||
|
str2rgba(
|
||||||
|
globalconfig["dialog_savegame_layout"]["onselectcolor1"],
|
||||||
|
globalconfig["dialog_savegame_layout"]["transparentselect"],
|
||||||
|
)
|
||||||
|
)
|
||||||
self.setStyleSheet(style)
|
self.setStyleSheet(style)
|
||||||
|
|
||||||
def __init__(self, parent) -> None:
|
def __init__(self, parent) -> None:
|
||||||
|
@ -405,7 +405,7 @@ def getcachedimage(src, small):
|
|||||||
return _pix
|
return _pix
|
||||||
if not os.path.exists(src):
|
if not os.path.exists(src):
|
||||||
return None
|
return None
|
||||||
src2 = gobject.getcachedir(f"icon2/{__b64string(src)}.jpg")
|
src2 = gobject.getcachedir("icon2/{}.jpg".format(__b64string(src)))
|
||||||
_pix = QPixmap(src2)
|
_pix = QPixmap(src2)
|
||||||
if not _pix.isNull():
|
if not _pix.isNull():
|
||||||
return _pix
|
return _pix
|
||||||
|
@ -801,9 +801,9 @@ class dialog_savedgame_v3(QWidget):
|
|||||||
if fontstring:
|
if fontstring:
|
||||||
_f = QFont()
|
_f = QFont()
|
||||||
_f.fromString(fontstring)
|
_f.fromString(fontstring)
|
||||||
_style += f"font-size:{_f.pointSize()}pt;"
|
_style += "font-size:{}pt;".format(_f.pointSize())
|
||||||
_style += f'font-family:"{_f.family()}";'
|
_style += 'font-family:"{}";'.format(_f.family())
|
||||||
style = f"#{key}{{ {_style} }}"
|
style = "#{}{{ {} }}".format(key, _style)
|
||||||
for exits in [True, False]:
|
for exits in [True, False]:
|
||||||
c = globalconfig["dialog_savegame_layout"][
|
c = globalconfig["dialog_savegame_layout"][
|
||||||
("onfilenoexistscolor1", "backcolor1")[exits]
|
("onfilenoexistscolor1", "backcolor1")[exits]
|
||||||
@ -815,8 +815,13 @@ class dialog_savedgame_v3(QWidget):
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
style += f"#savegame_exists{exits}{{background-color:{c};}}"
|
style += "#savegame_exists{}{{background-color:{};}}".format(exits, c)
|
||||||
style += f'#savegame_onselectcolor1{{background-color: {str2rgba(globalconfig["dialog_savegame_layout"]["onselectcolor1"],globalconfig["dialog_savegame_layout"]["transparentselect"])};}}'
|
style += "#savegame_onselectcolor1{{background-color: {};}}".format(
|
||||||
|
str2rgba(
|
||||||
|
globalconfig["dialog_savegame_layout"]["onselectcolor1"],
|
||||||
|
globalconfig["dialog_savegame_layout"]["transparentselect"],
|
||||||
|
)
|
||||||
|
)
|
||||||
self.setStyleSheet(style)
|
self.setStyleSheet(style)
|
||||||
|
|
||||||
def __init__(self, parent) -> None:
|
def __init__(self, parent) -> None:
|
||||||
|
@ -377,8 +377,8 @@ def setTab_update(self, basel):
|
|||||||
if version is None:
|
if version is None:
|
||||||
versionstring = "unknown"
|
versionstring = "unknown"
|
||||||
else:
|
else:
|
||||||
versionstring = (
|
versionstring = ("v{}.{}.{} {}").format(
|
||||||
f"v{version[0]}.{version[1]}.{version[2]} {platform.architecture()[0]}"
|
version[0], version[1], version[2], platform.architecture()[0]
|
||||||
)
|
)
|
||||||
inner, vis = [_[1] for _ in static_data["language_list_show"]], [
|
inner, vis = [_[1] for _ in static_data["language_list_show"]], [
|
||||||
_[0] for _ in static_data["language_list_show"]
|
_[0] for _ in static_data["language_list_show"]
|
||||||
|
@ -174,13 +174,13 @@ def createinternalfontsettings(self, forml: LFormLayout, group, _type):
|
|||||||
|
|
||||||
def doinstallqweb(self, dd, base):
|
def doinstallqweb(self, dd, base):
|
||||||
if not dd["k"].endswith(base):
|
if not dd["k"].endswith(base):
|
||||||
getQMessageBox(self, "错误", f"请选择_{base}")
|
getQMessageBox(self, "错误", "请选择_" + base)
|
||||||
return
|
return
|
||||||
with zipfile.ZipFile(dd["k"]) as zipf:
|
with zipfile.ZipFile(dd["k"]) as zipf:
|
||||||
target = gobject.gettempdir("QWebEngine/")
|
target = gobject.gettempdir("QWebEngine/")
|
||||||
zipf.extractall(target)
|
zipf.extractall(target)
|
||||||
bit = ["x86", "x64"][platform.architecture()[0] == "64bit"]
|
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, "成功", "安装成功")
|
getQMessageBox(self, "成功", "安装成功")
|
||||||
|
|
||||||
|
|
||||||
|
@ -157,7 +157,7 @@ class AnkiWindow(QWidget):
|
|||||||
fields = self.loadfileds()
|
fields = self.loadfileds()
|
||||||
fields.update(self.loadfakefields())
|
fields.update(self.loadfakefields())
|
||||||
html = self.parse_template(html, fields)
|
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)
|
self.htmlbrowser.setHtml(html)
|
||||||
|
|
||||||
def creattemplatetab(self, baselay):
|
def creattemplatetab(self, baselay):
|
||||||
@ -220,7 +220,11 @@ class AnkiWindow(QWidget):
|
|||||||
return ""
|
return ""
|
||||||
htmlcontents = ""
|
htmlcontents = ""
|
||||||
for iiii in range(len(dictionarys)):
|
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
|
return htmlcontents
|
||||||
|
|
||||||
def loadfileds(self):
|
def loadfileds(self):
|
||||||
@ -234,7 +238,7 @@ class AnkiWindow(QWidget):
|
|||||||
collect = []
|
collect = []
|
||||||
for hira in self.example.hiras:
|
for hira in self.example.hiras:
|
||||||
if hira["orig"] == word or hira.get("origorig", None) == word:
|
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:
|
else:
|
||||||
collect.append(hira["orig"])
|
collect.append(hira["orig"])
|
||||||
example = "".join(collect)
|
example = "".join(collect)
|
||||||
|
@ -30,7 +30,7 @@ class Textbrowser(QFrame):
|
|||||||
if __ == "QWebEngine":
|
if __ == "QWebEngine":
|
||||||
__ = "webview"
|
__ = "webview"
|
||||||
try:
|
try:
|
||||||
tb = importlib.import_module(f"rendertext.{__}").TextBrowser
|
tb = importlib.import_module("rendertext." + __).TextBrowser
|
||||||
self.textbrowser = tb(self)
|
self.textbrowser = tb(self)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if isinstance(e, webview_exception):
|
if isinstance(e, webview_exception):
|
||||||
@ -48,7 +48,7 @@ class Textbrowser(QFrame):
|
|||||||
else:
|
else:
|
||||||
print_exc()
|
print_exc()
|
||||||
globalconfig["rendertext_using"] = "textbrowser"
|
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 = tb(self)
|
||||||
self.textbrowser.move(0, 0)
|
self.textbrowser.move(0, 0)
|
||||||
self.textbrowser.setMouseTracking(True)
|
self.textbrowser.setMouseTracking(True)
|
||||||
|
@ -1187,15 +1187,14 @@ class abstractwebview(QWidget):
|
|||||||
|
|
||||||
def _parsehtml_codec(self, html):
|
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
|
return html
|
||||||
|
|
||||||
def _parsehtml_font(self, html):
|
def _parsehtml_font(self, html):
|
||||||
|
font = QFontDatabase.systemFont(QFontDatabase.SystemFont.GeneralFont).family()
|
||||||
html = """<body style=" font-family:'{}'">{}</body>""".format(
|
html = """<body style=" font-family:'{}'">{}</body>""".format(font, html)
|
||||||
QFontDatabase.systemFont(QFontDatabase.SystemFont.GeneralFont).family(),
|
|
||||||
html,
|
|
||||||
)
|
|
||||||
return html
|
return html
|
||||||
|
|
||||||
def _parsehtml_dark(self, html):
|
def _parsehtml_dark(self, html):
|
||||||
|
@ -75,15 +75,16 @@ class common:
|
|||||||
elif len(pair) == 3:
|
elif len(pair) == 3:
|
||||||
gameuid, vid, retrytime = pair
|
gameuid, vid, retrytime = pair
|
||||||
remove = True
|
remove = True
|
||||||
|
info = "{}: {} ".format(self.config_all["name"], vid)
|
||||||
try:
|
try:
|
||||||
self.__do_searchfordata(gameuid, vid)
|
self.__do_searchfordata(gameuid, vid)
|
||||||
vis = f"{self.config_all['name']}: {vid} data loaded success"
|
vis = info + "data loaded success"
|
||||||
except RequestException:
|
except RequestException:
|
||||||
remove = False
|
remove = False
|
||||||
vis = f"{self.config_all['name']}: {vid} network error, retry later"
|
vis = info + "network error, retry later"
|
||||||
except:
|
except:
|
||||||
print_exc()
|
print_exc()
|
||||||
vis = f"{self.config_all['name']}: {vid} load failed"
|
vis = info + " load failed"
|
||||||
if remove:
|
if remove:
|
||||||
|
|
||||||
self.__safe_remove_task("searchfordatatasks", pair[:2])
|
self.__safe_remove_task("searchfordatatasks", pair[:2])
|
||||||
@ -131,7 +132,7 @@ class common:
|
|||||||
def dispatchdownloadtask(self, url):
|
def dispatchdownloadtask(self, url):
|
||||||
if not url:
|
if not url:
|
||||||
return None
|
return None
|
||||||
__routine = f"cache/metadata/{self.typename}"
|
__routine = "cache/metadata/" + self.typename
|
||||||
if self.typename == "vndb":
|
if self.typename == "vndb":
|
||||||
__routine = "cache/vndb"
|
__routine = "cache/vndb"
|
||||||
|
|
||||||
@ -139,7 +140,7 @@ class common:
|
|||||||
__ = url[url.rfind(".") :]
|
__ = url[url.rfind(".") :]
|
||||||
else:
|
else:
|
||||||
__ = ".jpg"
|
__ = ".jpg"
|
||||||
savepath = f"{__routine}/{self.__b64string(url)}{__}"
|
savepath = __routine + "/" + self.__b64string(url) + __
|
||||||
|
|
||||||
globalconfig["metadata"][self.typename]["downloadtasks"].append((url, savepath))
|
globalconfig["metadata"][self.typename]["downloadtasks"].append((url, savepath))
|
||||||
self.__tasks_downloadimg.put((url, savepath))
|
self.__tasks_downloadimg.put((url, savepath))
|
||||||
|
@ -35,7 +35,7 @@ class bgmsettings(QDialog):
|
|||||||
}
|
}
|
||||||
collectresults = []
|
collectresults = []
|
||||||
response = requests.get(
|
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,
|
params=params,
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
proxies=self._ref.proxy,
|
proxies=self._ref.proxy,
|
||||||
@ -86,7 +86,7 @@ class bgmsettings(QDialog):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
requests.post(
|
requests.post(
|
||||||
f"https://api.bgm.tv/v0/users/-/collections/{vid}",
|
"https://api.bgm.tv/v0/users/-/collections/{}".format(vid),
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
json={
|
json={
|
||||||
"type": 4,
|
"type": 4,
|
||||||
@ -104,7 +104,7 @@ class bgmsettings(QDialog):
|
|||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
requests.post(
|
requests.post(
|
||||||
f"https://api.bgm.tv/v0/users/-/collections/{vid}",
|
"https://api.bgm.tv/v0/users/-/collections/{}".format(vid),
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
json={
|
json={
|
||||||
"type": 4,
|
"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",
|
"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(
|
response = requests.post(
|
||||||
f"https://bgm.tv/oauth/token_status",
|
"https://bgm.tv/oauth/token_status",
|
||||||
params={"access_token": k},
|
params={"access_token": k},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
proxies=self._ref.proxy,
|
proxies=self._ref.proxy,
|
||||||
@ -151,7 +151,7 @@ class bgmsettings(QDialog):
|
|||||||
info = ""
|
info = ""
|
||||||
try:
|
try:
|
||||||
response1 = requests.get(
|
response1 = requests.get(
|
||||||
f"https://api.bgm.tv/v0/me",
|
"https://api.bgm.tv/v0/me",
|
||||||
params={"access_token": k},
|
params={"access_token": k},
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
proxies=self._ref.proxy,
|
proxies=self._ref.proxy,
|
||||||
@ -190,7 +190,9 @@ class bgmsettings(QDialog):
|
|||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
gobject.baseobject.openlink(
|
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()
|
self.__wait()
|
||||||
|
|
||||||
@ -209,7 +211,7 @@ class bgmsettings(QDialog):
|
|||||||
print(code)
|
print(code)
|
||||||
os.remove(bangumioauth)
|
os.remove(bangumioauth)
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f"https://bgm.tv/oauth/access_token",
|
"https://bgm.tv/oauth/access_token",
|
||||||
json={
|
json={
|
||||||
"grant_type": "authorization_code",
|
"grant_type": "authorization_code",
|
||||||
"client_id": static_data["bangumi_oauth"]["client_id"],
|
"client_id": static_data["bangumi_oauth"]["client_id"],
|
||||||
@ -261,12 +263,16 @@ class bgmsettings(QDialog):
|
|||||||
fl2.addRow(btn)
|
fl2.addRow(btn)
|
||||||
btn = LPushButton("上传游戏列表")
|
btn = LPushButton("上传游戏列表")
|
||||||
btn.clicked.connect(
|
btn.clicked.connect(
|
||||||
functools.partial(self.__getalistname, "上传游戏列表", self.getalistname_upload)
|
functools.partial(
|
||||||
|
self.__getalistname, "上传游戏列表", self.getalistname_upload
|
||||||
|
)
|
||||||
)
|
)
|
||||||
fl2.addRow(btn)
|
fl2.addRow(btn)
|
||||||
btn = LPushButton("获取游戏列表")
|
btn = LPushButton("获取游戏列表")
|
||||||
btn.clicked.connect(
|
btn.clicked.connect(
|
||||||
functools.partial(self.__getalistname, "添加到列表", self.getalistname_download)
|
functools.partial(
|
||||||
|
self.__getalistname, "添加到列表", self.getalistname_download
|
||||||
|
)
|
||||||
)
|
)
|
||||||
fl2.addRow(btn)
|
fl2.addRow(btn)
|
||||||
fl.addRow(ww)
|
fl.addRow(ww)
|
||||||
@ -327,7 +333,7 @@ class searcher(common):
|
|||||||
return response["list"][0]["id"]
|
return response["list"][0]["id"]
|
||||||
|
|
||||||
def refmainpage(self, _id):
|
def refmainpage(self, _id):
|
||||||
return f"https://bangumi.tv/subject/{_id}"
|
return "https://bangumi.tv/subject/{}".format(_id)
|
||||||
|
|
||||||
def searchfordata(self, sid):
|
def searchfordata(self, sid):
|
||||||
|
|
||||||
@ -338,7 +344,7 @@ class searcher(common):
|
|||||||
if self.config["access-token"].strip() != "":
|
if self.config["access-token"].strip() != "":
|
||||||
headers["Authorization"] = "Bearer " + self.config["access-token"]
|
headers["Authorization"] = "Bearer " + self.config["access-token"]
|
||||||
response = self.proxysession.get(
|
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)
|
print(response.text)
|
||||||
try:
|
try:
|
||||||
@ -365,7 +371,8 @@ class searcher(common):
|
|||||||
namemaps = {}
|
namemaps = {}
|
||||||
try:
|
try:
|
||||||
charas = self.proxysession.get(
|
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()
|
).json()
|
||||||
for _ in charas:
|
for _ in charas:
|
||||||
namemaps[_["name"]] = _["name"]
|
namemaps[_["name"]] = _["name"]
|
||||||
|
@ -18,7 +18,8 @@ class searcher(common):
|
|||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
response = requests.get(
|
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,
|
headers=headers,
|
||||||
proxies=self.proxy,
|
proxies=self.proxy,
|
||||||
)
|
)
|
||||||
@ -35,7 +36,8 @@ class searcher(common):
|
|||||||
|
|
||||||
except:
|
except:
|
||||||
response = requests.get(
|
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,
|
headers=headers,
|
||||||
proxies=self.proxy,
|
proxies=self.proxy,
|
||||||
)
|
)
|
||||||
@ -52,9 +54,9 @@ class searcher(common):
|
|||||||
|
|
||||||
def refmainpage(self, RJ: str):
|
def refmainpage(self, RJ: str):
|
||||||
if RJ.startswith("RJ"):
|
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"):
|
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):
|
def searchfordata(self, RJ):
|
||||||
|
|
||||||
|
@ -57,7 +57,7 @@ class searcher(common):
|
|||||||
}
|
}
|
||||||
|
|
||||||
response = self.proxysession.get(
|
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,
|
headers=headers,
|
||||||
cookies=cookies,
|
cookies=cookies,
|
||||||
)
|
)
|
||||||
@ -67,7 +67,7 @@ class searcher(common):
|
|||||||
return _id
|
return _id
|
||||||
|
|
||||||
def refmainpage(self, _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):
|
def searchfordata(self, RJ):
|
||||||
cookies = {
|
cookies = {
|
||||||
|
@ -38,7 +38,7 @@ class steamsettings(QDialog):
|
|||||||
pagei += 1
|
pagei += 1
|
||||||
|
|
||||||
response = requests.get(
|
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,
|
cookies=cookies,
|
||||||
params=params,
|
params=params,
|
||||||
headers=headers,
|
headers=headers,
|
||||||
@ -111,7 +111,7 @@ class searcher(common):
|
|||||||
return response.json()[0]["appid"]
|
return response.json()[0]["appid"]
|
||||||
|
|
||||||
def refmainpage(self, _id):
|
def refmainpage(self, _id):
|
||||||
return f"https://store.steampowered.com/app/{_id}/_/"
|
return "https://store.steampowered.com/app/{}/_/".format(_id)
|
||||||
|
|
||||||
def gettagfromhtml(self, _id):
|
def gettagfromhtml(self, _id):
|
||||||
|
|
||||||
@ -169,7 +169,7 @@ class searcher(common):
|
|||||||
|
|
||||||
def searchfordata(self, _id):
|
def searchfordata(self, _id):
|
||||||
data = requests.get(
|
data = requests.get(
|
||||||
f"https://store.steampowered.com/api/appdetails?appids={_id}",
|
"https://store.steampowered.com/api/appdetails?appids={}".format(_id),
|
||||||
proxies=self.proxy,
|
proxies=self.proxy,
|
||||||
).json()[str(_id)]["data"]
|
).json()[str(_id)]["data"]
|
||||||
|
|
||||||
|
@ -161,7 +161,7 @@ class vndbsettings(QDialog):
|
|||||||
@property
|
@property
|
||||||
def headers(self):
|
def headers(self):
|
||||||
return {
|
return {
|
||||||
"Authorization": f"Token {self._ref.config['Token']}",
|
"Authorization": "Token " + self._ref.config["Token"],
|
||||||
}
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -234,7 +234,7 @@ class vndbsettings(QDialog):
|
|||||||
saferequestvndb(
|
saferequestvndb(
|
||||||
self._ref.proxy,
|
self._ref.proxy,
|
||||||
"PATCH",
|
"PATCH",
|
||||||
f"ulist/v{vid}",
|
"ulist/v{}".format(vid),
|
||||||
json={
|
json={
|
||||||
"labels_set": [1],
|
"labels_set": [1],
|
||||||
},
|
},
|
||||||
@ -249,7 +249,7 @@ class vndbsettings(QDialog):
|
|||||||
saferequestvndb(
|
saferequestvndb(
|
||||||
self._ref.proxy,
|
self._ref.proxy,
|
||||||
"PATCH",
|
"PATCH",
|
||||||
f"ulist/v{vid}",
|
"ulist/v{}".format(vid),
|
||||||
json={
|
json={
|
||||||
"labels_set": [1],
|
"labels_set": [1],
|
||||||
# "labels_unset": [1],
|
# "labels_unset": [1],
|
||||||
@ -337,7 +337,7 @@ class searcher(common):
|
|||||||
vndbsettings(parent, self, gameuid)
|
vndbsettings(parent, self, gameuid)
|
||||||
|
|
||||||
def refmainpage(self, _id):
|
def refmainpage(self, _id):
|
||||||
return f"https://vndb.org/v{_id}"
|
return "https://vndb.org/v{}".format(_id)
|
||||||
|
|
||||||
def getidbytitle(self, title):
|
def getidbytitle(self, title):
|
||||||
vid = getidbytitle_(self.proxy, title)
|
vid = getidbytitle_(self.proxy, title)
|
||||||
|
@ -13,7 +13,7 @@ class AnkiModelExists(AnkiException):
|
|||||||
|
|
||||||
def invoke(action, **params):
|
def invoke(action, **params):
|
||||||
response = requests.get(
|
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={"action": action, "params": params, "version": 6},
|
||||||
).json()
|
).json()
|
||||||
if len(response) != 2:
|
if len(response) != 2:
|
||||||
@ -45,7 +45,7 @@ class Deck:
|
|||||||
self.did = did
|
self.did = did
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"(Deck {self.name},{self.did})"
|
return "(Deck {},{})".format(self.name, self.did)
|
||||||
|
|
||||||
def delete(self):
|
def delete(self):
|
||||||
return invoke("deleteDecks", decks=[self.name], cardsToo=True)
|
return invoke("deleteDecks", decks=[self.name], cardsToo=True)
|
||||||
@ -61,7 +61,7 @@ class Deck:
|
|||||||
|
|
||||||
class Card:
|
class Card:
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"(Card {self.cardId})"
|
return "(Card {})".format(self.cardId)
|
||||||
|
|
||||||
def __init__(self, cardId):
|
def __init__(self, cardId):
|
||||||
self.cardId = cardId
|
self.cardId = cardId
|
||||||
|
@ -86,7 +86,7 @@ else:
|
|||||||
__gamepath2uid = {}
|
__gamepath2uid = {}
|
||||||
__savehook_new_data = {}
|
__savehook_new_data = {}
|
||||||
for k in 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] = savehook_new_data[k]
|
||||||
__savehook_new_data[uid].update(gamepath=k)
|
__savehook_new_data[uid].update(gamepath=k)
|
||||||
|
@ -42,7 +42,9 @@ def grabwindow(app="PNG", callback_origin=None, tocliponly=False):
|
|||||||
uid = gobject.baseobject.gameuid
|
uid = gobject.baseobject.gameuid
|
||||||
screenshot_savepath: str = globalconfig.get("screenshot_savepath", "")
|
screenshot_savepath: str = globalconfig.get("screenshot_savepath", "")
|
||||||
fnamef = lambda: gobject.getcachedir(
|
fnamef = lambda: gobject.getcachedir(
|
||||||
f"screenshot/{exename}/"
|
"screenshot/"
|
||||||
|
+ exename
|
||||||
|
+ "/"
|
||||||
+ time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()),
|
+ time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()),
|
||||||
abspath=False,
|
abspath=False,
|
||||||
)
|
)
|
||||||
@ -212,7 +214,7 @@ def getExeIcon(name: str, icon=True, cache=False):
|
|||||||
|
|
||||||
def injectdll(injectpids, bit, dll):
|
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])
|
pid = " ".join([str(_) for _ in injectpids])
|
||||||
for _ in (0,):
|
for _ in (0,):
|
||||||
if not test_injectable(injectpids):
|
if not test_injectable(injectpids):
|
||||||
|
@ -65,7 +65,7 @@ class playtimemanager:
|
|||||||
table = ["trace_loose", "trace_strict"][globalconfig["is_tracetime_strict"]]
|
table = ["trace_loose", "trace_strict"][globalconfig["is_tracetime_strict"]]
|
||||||
gameinternalid = self.get_gameinternalid(gameuid)
|
gameinternalid = self.get_gameinternalid(gameuid)
|
||||||
return self.sqlsavegameinfo.execute(
|
return self.sqlsavegameinfo.execute(
|
||||||
f"SELECT timestart,timestop FROM {table} WHERE gameinternalid = ?",
|
"SELECT timestart,timestop FROM {} WHERE gameinternalid = ?".format(table),
|
||||||
(gameinternalid,),
|
(gameinternalid,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
|
|
||||||
@ -111,14 +111,14 @@ class playtimemanager:
|
|||||||
gameinternalid = self.get_gameinternalid(uid)
|
gameinternalid = self.get_gameinternalid(uid)
|
||||||
if uid in dic:
|
if uid in dic:
|
||||||
self.sqlsavegameinfo.execute(
|
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]),
|
(_t, gameinternalid, dic[uid]),
|
||||||
)
|
)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
dic[uid] = _t
|
dic[uid] = _t
|
||||||
self.sqlsavegameinfo.execute(
|
self.sqlsavegameinfo.execute(
|
||||||
f"INSERT INTO {table} VALUES(?,?,?)",
|
"INSERT INTO {} VALUES(?,?,?)".format(table),
|
||||||
(gameinternalid, _t, _t),
|
(gameinternalid, _t, _t),
|
||||||
)
|
)
|
||||||
for k in list(dic.keys()):
|
for k in list(dic.keys()):
|
||||||
|
@ -99,8 +99,8 @@ def findenclose(text, tag):
|
|||||||
tags = "<link"
|
tags = "<link"
|
||||||
tage = ">"
|
tage = ">"
|
||||||
else:
|
else:
|
||||||
tags = f"<{tag}"
|
tags = "<{}".format(tag)
|
||||||
tage = f"</{tag}>"
|
tage = "</{}>".format(tag)
|
||||||
collect = ""
|
collect = ""
|
||||||
__ = 0
|
__ = 0
|
||||||
while True:
|
while True:
|
||||||
@ -243,7 +243,7 @@ def trysearchforid_1(gameuid, searchargs: list, target=None):
|
|||||||
idname = targetmod[key].idname
|
idname = targetmod[key].idname
|
||||||
savehook_new_data[gameuid][idname] = vid
|
savehook_new_data[gameuid][idname] = vid
|
||||||
gobject.baseobject.translation_ui.displayglobaltooltip.emit(
|
gobject.baseobject.translation_ui.displayglobaltooltip.emit(
|
||||||
f"{key}: found {vid}"
|
"{}: found {}".format(key, vid)
|
||||||
)
|
)
|
||||||
if infoid is None or key == primitivtemetaorigin:
|
if infoid is None or key == primitivtemetaorigin:
|
||||||
infoid = key, vid
|
infoid = key, vid
|
||||||
@ -292,13 +292,13 @@ class gamepath2uid_index_helper(dict):
|
|||||||
|
|
||||||
|
|
||||||
def initanewitem(title):
|
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)
|
savehook_new_data[uid] = gamepath2uid_index_helper(getdefaultsavehook(title), uid)
|
||||||
return uid
|
return uid
|
||||||
|
|
||||||
|
|
||||||
def duplicateconfig(uidold):
|
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]))
|
savehook_new_data[uid] = json.loads(json.dumps(savehook_new_data[uidold]))
|
||||||
return uid
|
return uid
|
||||||
|
|
||||||
@ -389,7 +389,7 @@ def argsort(l):
|
|||||||
|
|
||||||
def selectdebugfile(path: str, ismypost=False):
|
def selectdebugfile(path: str, ismypost=False):
|
||||||
if ismypost:
|
if ismypost:
|
||||||
path = f"./userconfig/posts/{path}.py"
|
path = "./userconfig/posts/{}.py".format(path)
|
||||||
p = os.path.abspath((path))
|
p = os.path.abspath((path))
|
||||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||||
print(path)
|
print(path)
|
||||||
@ -406,7 +406,7 @@ def selectdebugfile(path: str, ismypost=False):
|
|||||||
p,
|
p,
|
||||||
)
|
)
|
||||||
threading.Thread(
|
threading.Thread(
|
||||||
target=subprocess.run, args=(f'notepad "{os.path.normpath(p)}"',)
|
target=subprocess.run, args=("notepad " + os.path.normpath(p),)
|
||||||
).start()
|
).start()
|
||||||
return p
|
return p
|
||||||
|
|
||||||
@ -883,7 +883,7 @@ class SafeFormatter(Formatter):
|
|||||||
if key in kwargs:
|
if key in kwargs:
|
||||||
return super().get_value(key, args, kwargs)
|
return super().get_value(key, args, kwargs)
|
||||||
else:
|
else:
|
||||||
print(f"{key} is missing")
|
print("{} is missing".format(key))
|
||||||
return key
|
return key
|
||||||
|
|
||||||
|
|
||||||
@ -891,9 +891,9 @@ def checkv1(api_url: str):
|
|||||||
# 傻逼豆包大模型是非要v3,不是v1
|
# 傻逼豆包大模型是非要v3,不是v1
|
||||||
# 智谱AI v4
|
# 智谱AI v4
|
||||||
for i in range(1, 10):
|
for i in range(1, 10):
|
||||||
if api_url.endswith(f"/v{i}"):
|
if api_url.endswith("/v{}".format(i)):
|
||||||
return api_url
|
return api_url
|
||||||
elif api_url.endswith(f"/v{i}/"):
|
elif api_url.endswith("/v{}/".format(i)):
|
||||||
return api_url[:-1]
|
return api_url[:-1]
|
||||||
if api_url.endswith("/"):
|
if api_url.endswith("/"):
|
||||||
return api_url + "v1"
|
return api_url + "v1"
|
||||||
|
@ -319,14 +319,14 @@ class CURLException(RequestException):
|
|||||||
LAST = 100
|
LAST = 100
|
||||||
|
|
||||||
def __init__(self, code) -> None:
|
def __init__(self, code) -> None:
|
||||||
error = f"UNKNOWN ERROR {code}"
|
error = "UNKNOWN ERROR {}".format(code)
|
||||||
message = curl_easy_strerror(code).decode("utf8")
|
message = curl_easy_strerror(code).decode("utf8")
|
||||||
for _ in dir(self):
|
for _ in dir(self):
|
||||||
if _.startswith("") and code == getattr(self, _):
|
if _.startswith("") and code == getattr(self, _):
|
||||||
error = _
|
error = _
|
||||||
break
|
break
|
||||||
if message:
|
if message:
|
||||||
error += f": {message}"
|
error += ": {}".format(message)
|
||||||
super().__init__(error)
|
super().__init__(error)
|
||||||
|
|
||||||
|
|
||||||
|
@ -213,13 +213,13 @@ class WinhttpException(RequestException):
|
|||||||
):
|
):
|
||||||
module = Winhttp._handle
|
module = Winhttp._handle
|
||||||
message = windows.FormatMessage(code, module)
|
message = windows.FormatMessage(code, module)
|
||||||
error = f"UNKNOWN ERROR {code}"
|
error = "UNKNOWN ERROR {}".format(code)
|
||||||
for _ in dir(self):
|
for _ in dir(self):
|
||||||
if _.startswith("ERROR") and code == getattr(self, _):
|
if _.startswith("ERROR") and code == getattr(self, _):
|
||||||
error = _
|
error = _
|
||||||
break
|
break
|
||||||
if message:
|
if message:
|
||||||
error += f": {message}"
|
error += ": {}".format(message)
|
||||||
|
|
||||||
super().__init__(error)
|
super().__init__(error)
|
||||||
|
|
||||||
|
@ -50,7 +50,7 @@ class OCR(baseocr):
|
|||||||
if self.config["use_custom_prompt"]:
|
if self.config["use_custom_prompt"]:
|
||||||
prompt = self.config["custom_prompt"]
|
prompt = self.config["custom_prompt"]
|
||||||
else:
|
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")
|
base64_image = base64.b64encode(imagebinary).decode("utf-8")
|
||||||
message = [
|
message = [
|
||||||
@ -61,7 +61,7 @@ class OCR(baseocr):
|
|||||||
{
|
{
|
||||||
"type": "image_url",
|
"type": "image_url",
|
||||||
"image_url": {
|
"image_url": {
|
||||||
"url": f"data:image/jpeg;base64,{base64_image}",
|
"url": "data:image/jpeg;base64," + base64_image,
|
||||||
"detail": "low",
|
"detail": "low",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
@ -42,7 +42,7 @@ class OCR(baseocr):
|
|||||||
if self.config["use_custom_prompt"]:
|
if self.config["use_custom_prompt"]:
|
||||||
prompt = self.config["custom_prompt"]
|
prompt = self.config["custom_prompt"]
|
||||||
else:
|
else:
|
||||||
prompt = f"Recognize the {self.srclang} text in the picture."
|
prompt = "Recognize the {} text in the picture.".format(self.srclang)
|
||||||
payload = {
|
payload = {
|
||||||
"contents": [
|
"contents": [
|
||||||
{
|
{
|
||||||
@ -61,7 +61,7 @@ class OCR(baseocr):
|
|||||||
response = requests.post(
|
response = requests.post(
|
||||||
urlpathjoin(
|
urlpathjoin(
|
||||||
self.config["BASE_URL"],
|
self.config["BASE_URL"],
|
||||||
f"v1beta/models/{model}:generateContent?key={api_key}",
|
"v1beta/models/{}:generateContent?key={}".format(model, api_key),
|
||||||
),
|
),
|
||||||
headers=headers,
|
headers=headers,
|
||||||
json=payload,
|
json=payload,
|
||||||
|
@ -10,7 +10,7 @@ class OCR(baseocr):
|
|||||||
regex = re.compile(r">AF_initDataCallback\(({key: 'ds:1'.*?)\);</script>")
|
regex = re.compile(r">AF_initDataCallback\(({key: 'ds:1'.*?)\);</script>")
|
||||||
|
|
||||||
timestamp = int(time.time() * 1000)
|
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 = {
|
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",
|
"User-Agent": "Mozilla/5.0 (Linux; Android 13; RMX3771) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.6167.144 Mobile Safari/537.36",
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,7 @@ class OCR(baseocr):
|
|||||||
absolute_img_path = os.path.abspath(fname)
|
absolute_img_path = os.path.abspath(fname)
|
||||||
params = {"image_path": absolute_img_path}
|
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)
|
os.remove(absolute_img_path)
|
||||||
try:
|
try:
|
||||||
return response.json()["text"]
|
return response.json()["text"]
|
||||||
|
@ -37,7 +37,7 @@ class wcocr:
|
|||||||
mojo = os.path.join(
|
mojo = os.path.join(
|
||||||
default,
|
default,
|
||||||
r"resources\app\versions",
|
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")
|
ocr = os.path.join(mojo, r"QQScreenShot\Bin\TencentOCR.exe")
|
||||||
return ocr, mojo
|
return ocr, mojo
|
||||||
|
@ -22,7 +22,7 @@ class dataget:
|
|||||||
if not color:
|
if not color:
|
||||||
return None
|
return None
|
||||||
r, g, b, a = color
|
r, g, b, a = color
|
||||||
return f"rgba({r}, {g}, {b}, {a})"
|
return "rgba({}, {}, {}, {})".format(r, g, b, a)
|
||||||
|
|
||||||
def _getfontinfo(self, origin):
|
def _getfontinfo(self, origin):
|
||||||
if origin:
|
if origin:
|
||||||
|
@ -163,7 +163,7 @@ class TextBrowser(QWidget, dataget):
|
|||||||
"textrender"
|
"textrender"
|
||||||
]["textbrowser"][0]
|
]["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)
|
self.currentclass = functools.partial(__.TextLine, self.currenttype)
|
||||||
|
|
||||||
|
@ -127,26 +127,26 @@ class TextBrowser(QWidget, dataget):
|
|||||||
|
|
||||||
# js api
|
# js api
|
||||||
def showhidetranslate(self, show):
|
def showhidetranslate(self, show):
|
||||||
self.debugeval(f'showhidetranslate("{int(show)}")')
|
self.debugeval('showhidetranslate("{}")'.format(int(show)))
|
||||||
|
|
||||||
def showhideorigin(self, show):
|
def showhideorigin(self, show):
|
||||||
self.debugeval(f'showhideorigin("{int(show)}")')
|
self.debugeval('showhideorigin("{}")'.format(int(show)))
|
||||||
|
|
||||||
def showhidetranslatorname(self, 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):
|
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):
|
def clear_all(self):
|
||||||
self.debugeval(f"clear_all()")
|
self.debugeval("clear_all()")
|
||||||
|
|
||||||
def set_extra_html(self, html):
|
def set_extra_html(self, html):
|
||||||
if not globalconfig["useextrahtml"]:
|
if not globalconfig["useextrahtml"]:
|
||||||
self.debugeval(f'set_extra_html("")')
|
self.debugeval('set_extra_html("")')
|
||||||
return
|
return
|
||||||
html = quote(html)
|
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):
|
def create_internal_text(self, style, styleargs, _id, name, text, args):
|
||||||
name = quote(name)
|
name = quote(name)
|
||||||
@ -154,7 +154,9 @@ class TextBrowser(QWidget, dataget):
|
|||||||
args = quote(json.dumps(args))
|
args = quote(json.dumps(args))
|
||||||
styleargs = quote(json.dumps(styleargs))
|
styleargs = quote(json.dumps(styleargs))
|
||||||
self.debugeval(
|
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):
|
def create_internal_rubytext(self, style, styleargs, _id, tag, args):
|
||||||
@ -162,7 +164,9 @@ class TextBrowser(QWidget, dataget):
|
|||||||
args = quote(json.dumps(args))
|
args = quote(json.dumps(args))
|
||||||
styleargs = quote(json.dumps(styleargs))
|
styleargs = quote(json.dumps(styleargs))
|
||||||
self.debugeval(
|
self.debugeval(
|
||||||
f'create_internal_rubytext("{style}","{styleargs}","{_id}","{tag}","{args}");'
|
'create_internal_rubytext("{}","{}","{}","{}","{}");'.format(
|
||||||
|
style, styleargs, _id, tag, args
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
def calllunaheightchange(self, h):
|
def calllunaheightchange(self, h):
|
||||||
@ -196,7 +200,7 @@ class TextBrowser(QWidget, dataget):
|
|||||||
|
|
||||||
def createtextlineid(self, origin):
|
def createtextlineid(self, origin):
|
||||||
|
|
||||||
_id = f"luna_{uuid.uuid4()}"
|
_id = "luna_{}".format(uuid.uuid4())
|
||||||
self.create_div_line_id(_id, origin)
|
self.create_div_line_id(_id, origin)
|
||||||
return _id
|
return _id
|
||||||
|
|
||||||
|
@ -184,14 +184,15 @@ class ResponseBase:
|
|||||||
yield pending
|
yield pending
|
||||||
|
|
||||||
def raise_for_status(self):
|
def raise_for_status(self):
|
||||||
http_error_msg = ""
|
which = None
|
||||||
if 400 <= self.status_code < 500:
|
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:
|
elif 500 <= self.status_code < 600:
|
||||||
http_error_msg = f"{self.status_code} Server Error: {self.status_text} for url: {self.url}"
|
which = "Server"
|
||||||
|
if which:
|
||||||
if http_error_msg:
|
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)
|
raise HTTPError(http_error_msg)
|
||||||
|
|
||||||
|
|
||||||
|
@ -28,7 +28,7 @@ class websocketserver:
|
|||||||
self.server_socket.listen(1)
|
self.server_socket.listen(1)
|
||||||
while True:
|
while True:
|
||||||
client_socket, address = self.server_socket.accept()
|
client_socket, address = self.server_socket.accept()
|
||||||
print(f"Client connected: {address}")
|
print("Client connected: {}".format(address))
|
||||||
|
|
||||||
self.handle_client(client_socket)
|
self.handle_client(client_socket)
|
||||||
|
|
||||||
@ -43,13 +43,13 @@ class websocketserver:
|
|||||||
if "Sec-WebSocket-Key:" in line:
|
if "Sec-WebSocket-Key:" in line:
|
||||||
key = line.split(":")[1].strip()
|
key = line.split(":")[1].strip()
|
||||||
break
|
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()
|
hashed = base64encode(hashlib.sha1(value).digest()).strip().decode()
|
||||||
# 构造握手响应
|
# 构造握手响应
|
||||||
response = "HTTP/1.1 101 Switching Protocols\r\n"
|
response = "HTTP/1.1 101 Switching Protocols\r\n"
|
||||||
response += "Upgrade: websocket\r\n"
|
response += "Upgrade: websocket\r\n"
|
||||||
response += "Connection: Upgrade\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())
|
client_socket.send(response.encode())
|
||||||
|
@ -342,10 +342,10 @@ class texthook(basetext):
|
|||||||
self.gameuid = gameuid
|
self.gameuid = gameuid
|
||||||
self.detachall()
|
self.detachall()
|
||||||
_filename, _ = os.path.splitext(os.path.basename(gamepath))
|
_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:
|
if os.path.exists(sqlitef) == False:
|
||||||
md5 = getfilemd5(gamepath)
|
md5 = getfilemd5(gamepath)
|
||||||
f2 = gobject.gettranslationrecorddir(f"{_filename}_{md5}.sqlite")
|
f2 = gobject.gettranslationrecorddir("{}_{}.sqlite".format(_filename, md5))
|
||||||
try:
|
try:
|
||||||
os.rename(f2, sqlitef)
|
os.rename(f2, sqlitef)
|
||||||
except:
|
except:
|
||||||
@ -396,7 +396,7 @@ class texthook(basetext):
|
|||||||
injectpids.append(pid)
|
injectpids.append(pid)
|
||||||
if len(injectpids):
|
if len(injectpids):
|
||||||
arch = ["32", "64"][self.is64bit]
|
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)
|
injectdll(injectpids, arch, dll)
|
||||||
|
|
||||||
@threader
|
@threader
|
||||||
|
@ -3,6 +3,7 @@ import json, requests
|
|||||||
from traceback import print_exc
|
from traceback import print_exc
|
||||||
from myutils.utils import createenglishlangmap
|
from myutils.utils import createenglishlangmap
|
||||||
|
|
||||||
|
|
||||||
class TS(basetrans):
|
class TS(basetrans):
|
||||||
|
|
||||||
def langmap(self):
|
def langmap(self):
|
||||||
@ -88,11 +89,15 @@ class TS(basetrans):
|
|||||||
query, "use_user_user_prompt", "user_user_prompt"
|
query, "use_user_user_prompt", "user_user_prompt"
|
||||||
)
|
)
|
||||||
message = []
|
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})
|
message.append({"role": "user", "content": query})
|
||||||
|
|
||||||
usingstream = self.config["usingstream"]
|
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(
|
response = self.proxysession.post(
|
||||||
url,
|
url,
|
||||||
|
@ -179,7 +179,7 @@ class TS(basetrans):
|
|||||||
|
|
||||||
def encode_as_ids(self, content):
|
def encode_as_ids(self, content):
|
||||||
input_str = ctypes.c_char_p(
|
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)()
|
token_ids = ctypes.POINTER(ctypes.c_int32)()
|
||||||
n_tokens = ctypes.c_size_t()
|
n_tokens = ctypes.c_size_t()
|
||||||
@ -256,15 +256,30 @@ class TS(basetrans):
|
|||||||
return output_ids_py
|
return output_ids_py
|
||||||
|
|
||||||
def translate(self, content):
|
def translate(self, content):
|
||||||
delimiters = ['.','。','\n',':',':','?','?','!','!','…','「','」',]
|
delimiters = [
|
||||||
raw_split = [i.strip() for i in re.split('(['+''.join(delimiters)+'])', content)]
|
".",
|
||||||
|
"。",
|
||||||
|
"\n",
|
||||||
|
":",
|
||||||
|
":",
|
||||||
|
"?",
|
||||||
|
"?",
|
||||||
|
"!",
|
||||||
|
"!",
|
||||||
|
"…",
|
||||||
|
"「",
|
||||||
|
"」",
|
||||||
|
]
|
||||||
|
raw_split = [
|
||||||
|
i.strip() for i in re.split("([" + "".join(delimiters) + "])", content)
|
||||||
|
]
|
||||||
content_split = [i for i in raw_split if i]
|
content_split = [i for i in raw_split if i]
|
||||||
translated_list = []
|
translated_list = []
|
||||||
i = 0
|
i = 0
|
||||||
while i < len(content_split):
|
while i < len(content_split):
|
||||||
sentence = content_split[i]
|
sentence = content_split[i]
|
||||||
while i + 1 < len(content_split):
|
while i + 1 < len(content_split):
|
||||||
if content_split[i+1] not in delimiters:
|
if content_split[i + 1] not in delimiters:
|
||||||
break
|
break
|
||||||
i += 1
|
i += 1
|
||||||
sentence += content_split[i]
|
sentence += content_split[i]
|
||||||
@ -273,7 +288,7 @@ class TS(basetrans):
|
|||||||
translated_sentence = self.decode_from_ids(output_ids_py)
|
translated_sentence = self.decode_from_ids(output_ids_py)
|
||||||
translated_list.append(translated_sentence)
|
translated_list.append(translated_sentence)
|
||||||
i += 1
|
i += 1
|
||||||
translated = ''.join(translated_list)
|
translated = "".join(translated_list)
|
||||||
return translated
|
return translated
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
|
@ -32,25 +32,27 @@ class commonllmdev(basetransdev):
|
|||||||
prompt = self._gptlike_createsys("use_custom_prompt", "custom_prompt")
|
prompt = self._gptlike_createsys("use_custom_prompt", "custom_prompt")
|
||||||
content = prompt + content
|
content = prompt + content
|
||||||
self.Runtime_evaluate(
|
self.Runtime_evaluate(
|
||||||
f"document.querySelector(`{repr(self.textarea_selector)}`).foucs()"
|
"document.querySelector(`{}`).foucs()".format(repr(self.textarea_selector))
|
||||||
)
|
)
|
||||||
self.clear_input()
|
self.clear_input()
|
||||||
self.send_keys(content)
|
self.send_keys(content)
|
||||||
# chatgpt网站没有焦点时,用这个也可以。
|
# chatgpt网站没有焦点时,用这个也可以。
|
||||||
self.Runtime_evaluate(
|
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:
|
try:
|
||||||
# 月之暗面
|
# 月之暗面
|
||||||
while self.Runtime_evaluate(
|
while self.Runtime_evaluate(
|
||||||
f"document.querySelector({repr(self.button_selector)}).disabled"
|
"document.querySelector({}).disabled".format(repr(self.button_selector))
|
||||||
)["result"]["value"]:
|
)["result"]["value"]:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
self.Runtime_evaluate(
|
self.Runtime_evaluate(
|
||||||
f"document.querySelector({repr(self.button_selector)}).click()"
|
"document.querySelector({}).click()".format(repr(self.button_selector))
|
||||||
)
|
)
|
||||||
if self.config["usingstream"]:
|
if self.config["usingstream"]:
|
||||||
__ = [""]
|
__ = [""]
|
||||||
|
@ -63,7 +63,9 @@ class TS(basetrans):
|
|||||||
res = self.proxysession.post(
|
res = self.proxysession.post(
|
||||||
urlpathjoin(
|
urlpathjoin(
|
||||||
self.config["BASE_URL"].strip(),
|
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"]},
|
params={"key": self.multiapikeycurrent["SECRET_KEY"]},
|
||||||
json=payload,
|
json=payload,
|
||||||
|
@ -28,7 +28,9 @@ class qianfanIAM:
|
|||||||
def sign(access_key_id, secret_access_key):
|
def sign(access_key_id, secret_access_key):
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
canonical_time = now.strftime("%Y-%m-%dT%H:%M:%SZ")
|
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(
|
sign_key = hmac.new(
|
||||||
secret_access_key.encode(), sign_key_info.encode(), hashlib.sha256
|
secret_access_key.encode(), sign_key_info.encode(), hashlib.sha256
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
@ -36,7 +38,7 @@ class qianfanIAM:
|
|||||||
sign_result = hmac.new(
|
sign_result = hmac.new(
|
||||||
sign_key.encode(), string_to_sign.encode(), hashlib.sha256
|
sign_key.encode(), string_to_sign.encode(), hashlib.sha256
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
return f"{sign_key_info}/host/{sign_result}"
|
return "{}/host/{}".format(sign_key_info, sign_result)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def getkey(ak, sk, proxy):
|
def getkey(ak, sk, proxy):
|
||||||
|
@ -317,7 +317,9 @@ class TS(basetrans):
|
|||||||
raise Exception(response.maybejson)
|
raise Exception(response.maybejson)
|
||||||
self.cacheproject[(end, ak, sk)] = project_id
|
self.cacheproject[(end, ak, sk)] = project_id
|
||||||
project_id = self.cacheproject.get((end, ak, sk))
|
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 = {
|
body = {
|
||||||
"text": query,
|
"text": query,
|
||||||
"from": self.srclang,
|
"from": self.srclang,
|
||||||
@ -332,7 +334,7 @@ class TS(basetrans):
|
|||||||
"User-Agent": "huaweicloud-usdk-python/3.0",
|
"User-Agent": "huaweicloud-usdk-python/3.0",
|
||||||
}
|
}
|
||||||
r.host = end
|
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.method = "POST"
|
||||||
r.body = body
|
r.body = body
|
||||||
r = Signer((ak, sk)).sign(r)
|
r = Signer((ak, sk)).sign(r)
|
||||||
|
@ -122,5 +122,5 @@ class TS(basetrans):
|
|||||||
if (not res) and ("\n" in content):
|
if (not res) and ("\n" in content):
|
||||||
res = self.tryfindtranslate_single(content)
|
res = self.tryfindtranslate_single(content)
|
||||||
if not res:
|
if not res:
|
||||||
raise Exception(f"can't find: {content}")
|
raise Exception("can't find: " + content)
|
||||||
return res
|
return res
|
||||||
|
@ -50,9 +50,9 @@ class TS(basetrans):
|
|||||||
info = gpt["info"] if "info" in gpt.keys() else None
|
info = gpt["info"] if "info" in gpt.keys() else None
|
||||||
|
|
||||||
if info:
|
if info:
|
||||||
single = f"{src}->{dst} #{info}"
|
single = "{}->{} #{}".format(src, dst, info)
|
||||||
else:
|
else:
|
||||||
single = f"{src}->{dst}"
|
single = "{}->{}".format(src, dst)
|
||||||
gpt_dict_text_list.append(single)
|
gpt_dict_text_list.append(single)
|
||||||
|
|
||||||
gpt_dict_raw_text = "\n".join(gpt_dict_text_list)
|
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)
|
self._gpt_common_parse_context_2(messages, self.context, contextnum)
|
||||||
messages.append(
|
messages.append(
|
||||||
{"role": "user", "content": f"将下面的日文文本翻译成中文:{query}"}
|
{"role": "user", "content": "将下面的日文文本翻译成中文:" + query}
|
||||||
)
|
)
|
||||||
elif self.config["prompt_version"] == 1:
|
elif self.config["prompt_version"] == 1:
|
||||||
messages = [
|
messages = [
|
||||||
@ -155,7 +155,7 @@ class TS(basetrans):
|
|||||||
)
|
)
|
||||||
|
|
||||||
except requests.RequestException as e:
|
except requests.RequestException as e:
|
||||||
raise ValueError(f"连接到Sakura API超时:{self.api_url}")
|
raise ValueError("连接到Sakura API超时:" + self.api_url)
|
||||||
try:
|
try:
|
||||||
yield output.json()
|
yield output.json()
|
||||||
except:
|
except:
|
||||||
@ -190,7 +190,7 @@ class TS(basetrans):
|
|||||||
stream=True,
|
stream=True,
|
||||||
)
|
)
|
||||||
except requests.RequestException:
|
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 (
|
if (not output.headers["Content-Type"].startswith("text/event-stream")) and (
|
||||||
output.status_code != 200
|
output.status_code != 200
|
||||||
|
@ -51,7 +51,7 @@ class TTS(TTSbase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def getvoicelist(self):
|
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")
|
exe = os.path.abspath("./files/plugins/shareddllproxy32.exe")
|
||||||
subprocess.run('"{}" neospeechlist "{}"'.format(exe, cachefname))
|
subprocess.run('"{}" neospeechlist "{}"'.format(exe, cachefname))
|
||||||
|
|
||||||
|
@ -15,16 +15,22 @@ from tts.basettsclass import TTSbase
|
|||||||
BASE_URL = "speech.platform.bing.com/consumer/speech/synthesize/readaloud"
|
BASE_URL = "speech.platform.bing.com/consumer/speech/synthesize/readaloud"
|
||||||
TRUSTED_CLIENT_TOKEN = "6A5AA1D4EAFF4E9FB37E23D68491D6F4"
|
TRUSTED_CLIENT_TOKEN = "6A5AA1D4EAFF4E9FB37E23D68491D6F4"
|
||||||
|
|
||||||
WSS_URL = f"wss://{BASE_URL}/edge/v1?TrustedClientToken={TRUSTED_CLIENT_TOKEN}"
|
WSS_URL = "wss://{}/edge/v1?TrustedClientToken={}".format(
|
||||||
VOICE_LIST = f"https://{BASE_URL}/voices/list?trustedclienttoken={TRUSTED_CLIENT_TOKEN}"
|
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_FULL_VERSION = "130.0.2849.68"
|
||||||
CHROMIUM_MAJOR_VERSION = CHROMIUM_FULL_VERSION.split(".", maxsplit=1)[0]
|
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 = {
|
BASE_HEADERS = {
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
"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"
|
" (KHTML, like Gecko) Chrome/{CHROMIUM_MAJOR_VERSION}.0.0.0 Safari/537.36"
|
||||||
f" Edg/{CHROMIUM_MAJOR_VERSION}.0.0.0",
|
" Edg/{CHROMIUM_MAJOR_VERSION}.0.0.0".format(
|
||||||
|
CHROMIUM_MAJOR_VERSION=CHROMIUM_MAJOR_VERSION
|
||||||
|
),
|
||||||
"Accept-Encoding": "gzip, deflate, br",
|
"Accept-Encoding": "gzip, deflate, br",
|
||||||
"Accept-Language": "en-US,en;q=0.9",
|
"Accept-Language": "en-US,en;q=0.9",
|
||||||
}
|
}
|
||||||
@ -36,8 +42,9 @@ WSS_HEADERS = {
|
|||||||
WSS_HEADERS.update(BASE_HEADERS)
|
WSS_HEADERS.update(BASE_HEADERS)
|
||||||
VOICE_HEADERS = {
|
VOICE_HEADERS = {
|
||||||
"Authority": "speech.platform.bing.com",
|
"Authority": "speech.platform.bing.com",
|
||||||
"Sec-CH-UA": f'" Not;A Brand";v="99", "Microsoft Edge";v="{CHROMIUM_MAJOR_VERSION}",'
|
"Sec-CH-UA": '" Not;A Brand";v="99", "Microsoft Edge";v="{CHROMIUM_MAJOR_VERSION}", "Chromium";v="{CHROMIUM_MAJOR_VERSION}"'.format(
|
||||||
f' "Chromium";v="{CHROMIUM_MAJOR_VERSION}"',
|
CHROMIUM_MAJOR_VERSION=CHROMIUM_MAJOR_VERSION
|
||||||
|
),
|
||||||
"Sec-CH-UA-Mobile": "?0",
|
"Sec-CH-UA-Mobile": "?0",
|
||||||
"Accept": "*/*",
|
"Accept": "*/*",
|
||||||
"Sec-Fetch-Site": "none",
|
"Sec-Fetch-Site": "none",
|
||||||
@ -91,7 +98,7 @@ class DRM:
|
|||||||
ticks *= S_TO_NS / 100
|
ticks *= S_TO_NS / 100
|
||||||
|
|
||||||
# Create the string to hash by concatenating the ticks and the trusted client token
|
# 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
|
# Compute the SHA256 hash and return the uppercased hex digest
|
||||||
return hashlib.sha256(str_to_hash.encode("ascii")).hexdigest().upper()
|
return hashlib.sha256(str_to_hash.encode("ascii")).hexdigest().upper()
|
||||||
@ -101,8 +108,9 @@ class TTS(TTSbase):
|
|||||||
|
|
||||||
def getvoicelist(self):
|
def getvoicelist(self):
|
||||||
alllist = requests.get(
|
alllist = requests.get(
|
||||||
f"{VOICE_LIST}&Sec-MS-GEC={DRM.generate_sec_ms_gec()}"
|
"{}&Sec-MS-GEC={}&Sec-MS-GEC-Version={}".format(
|
||||||
f"&Sec-MS-GEC-Version={SEC_MS_GEC_VERSION}",
|
VOICE_LIST, DRM.generate_sec_ms_gec(), SEC_MS_GEC_VERSION
|
||||||
|
),
|
||||||
headers=VOICE_HEADERS,
|
headers=VOICE_HEADERS,
|
||||||
proxies=self.proxy,
|
proxies=self.proxy,
|
||||||
).json()
|
).json()
|
||||||
@ -218,9 +226,9 @@ def transferMsTTSData(rate, content, voice, proxy):
|
|||||||
else:
|
else:
|
||||||
ip = port = None
|
ip = port = None
|
||||||
ws = websocket.create_connection(
|
ws = websocket.create_connection(
|
||||||
f"{WSS_URL}&Sec-MS-GEC={DRM.generate_sec_ms_gec()}"
|
"{}&Sec-MS-GEC={}&Sec-MS-GEC-Version={}&ConnectionId={}".format(
|
||||||
f"&Sec-MS-GEC-Version={SEC_MS_GEC_VERSION}"
|
WSS_URL, DRM.generate_sec_ms_gec(), SEC_MS_GEC_VERSION, connect_id()
|
||||||
f"&ConnectionId={connect_id()}",
|
),
|
||||||
header=WSS_HEADERS,
|
header=WSS_HEADERS,
|
||||||
http_proxy_host=ip,
|
http_proxy_host=ip,
|
||||||
http_proxy_port=port,
|
http_proxy_port=port,
|
||||||
|
@ -15,7 +15,7 @@ class TTS(TTSbase):
|
|||||||
for modelType in modelTypes:
|
for modelType in modelTypes:
|
||||||
vits_data = responseVits[modelType]
|
vits_data = responseVits[modelType]
|
||||||
for item in vits_data:
|
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)
|
voicelist.append(model_info)
|
||||||
internal.append((modelType, item["id"], item["name"]))
|
internal.append((modelType, item["id"], item["name"]))
|
||||||
return internal, voicelist
|
return internal, voicelist
|
||||||
|
@ -11,7 +11,7 @@ class TTS(TTSbase):
|
|||||||
voicelist = []
|
voicelist = []
|
||||||
_p = os.path.join(self.config["path"], "Voice")
|
_p = os.path.join(self.config["path"], "Voice")
|
||||||
if os.path.exists(_p) == False:
|
if os.path.exists(_p) == False:
|
||||||
raise Exception(f"not exists {_p}")
|
raise Exception("not exists " + _p)
|
||||||
l = os.listdir(_p)
|
l = os.listdir(_p)
|
||||||
|
|
||||||
for _ in l:
|
for _ in l:
|
||||||
|
@ -26,7 +26,7 @@ class TTS(TTSbase):
|
|||||||
}
|
}
|
||||||
|
|
||||||
response = requests.get(
|
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,
|
headers=headers,
|
||||||
proxies={"http": None, "https": None},
|
proxies={"http": None, "https": None},
|
||||||
).json()
|
).json()
|
||||||
@ -50,7 +50,7 @@ class TTS(TTSbase):
|
|||||||
params = {"speaker": voice, "text": content}
|
params = {"speaker": voice, "text": content}
|
||||||
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f"http://localhost:{self.config['Port']}/audio_query",
|
"http://localhost:{}/audio_query".format(self.config['Port']),
|
||||||
params=params,
|
params=params,
|
||||||
headers=headers,
|
headers=headers,
|
||||||
proxies={"http": None, "https": None},
|
proxies={"http": None, "https": None},
|
||||||
@ -63,7 +63,7 @@ class TTS(TTSbase):
|
|||||||
"speaker": voice,
|
"speaker": voice,
|
||||||
}
|
}
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f"http://localhost:{self.config['Port']}/synthesis",
|
"http://localhost:{}/synthesis".format(self.config['Port']),
|
||||||
params=params,
|
params=params,
|
||||||
headers=headers,
|
headers=headers,
|
||||||
data=json.dumps(response.json()),
|
data=json.dumps(response.json()),
|
||||||
|
Loading…
x
Reference in New Issue
Block a user