This commit is contained in:
恍兮惚兮 2024-06-07 19:03:52 +08:00
parent e8f9a9da2e
commit 6aea1f3e00
95 changed files with 1367 additions and 646 deletions

View File

@ -9,8 +9,9 @@ from myutils.config import (
savehook_new_data, savehook_new_data,
setlanguage, setlanguage,
static_data, static_data,
tryreadconfig,
) )
import zipfile import zipfile, sqlite3
from myutils.utils import ( from myutils.utils import (
minmaxmoveobservefunc, minmaxmoveobservefunc,
parsemayberegexreplace, parsemayberegexreplace,
@ -44,6 +45,7 @@ from winsharedutils import pid_running
from myutils.post import POSTSOLVE from myutils.post import POSTSOLVE
from myutils.utils import nowisdark from myutils.utils import nowisdark
class commonstylebase(QWidget): class commonstylebase(QWidget):
setstylesheetsignal = pyqtSignal() setstylesheetsignal = pyqtSignal()
@ -77,6 +79,7 @@ class MAINUI:
self.edittextui = None self.edittextui = None
self.edittextui_cached = None self.edittextui_cached = None
self.edittextui_sync = True self.edittextui_sync = True
self.sqlsavegameinfo = None
@property @property
def textsource(self): def textsource(self):
@ -800,24 +803,124 @@ class MAINUI:
int(widget.winId()), dark, globalconfig["WindowBackdrop"] int(widget.winId()), dark, globalconfig["WindowBackdrop"]
) )
def checkgameplayingthread(self): def createsavegamedb(self):
self.tracestarted = False self.sqlsavegameinfo = sqlite3.connect(
"userconfig/savegame.db", check_same_thread=False, isolation_level=None
)
try:
self.sqlsavegameinfo.execute(
"CREATE TABLE gameinternalid(gameinternalid INTEGER PRIMARY KEY AUTOINCREMENT,gamepath TEXT);"
)
self.sqlsavegameinfo.execute(
"CREATE TABLE traceplaytime_v4(id INTEGER PRIMARY KEY AUTOINCREMENT,gameinternalid INT,timestart BIGINT,timestop BIGINT);"
)
except:
pass
self.migrate_info()
@threader
def migrate_info(self):
for k in savehook_new_data:
self.migrate_traceplaytime_v2(k)
self.migrate_vndbtags(k)
self.migrate_images(k)
def migrate_traceplaytime_v2(self, k):
if "traceplaytime_v2" not in savehook_new_data[k]:
return
traceplaytime_v2 = savehook_new_data[k].get("traceplaytime_v2", [])
for slice in traceplaytime_v2.copy():
self.traceplaytime(k, slice[0], slice[1], True)
savehook_new_data[k]["traceplaytime_v2"].pop(0)
savehook_new_data[k].pop("traceplaytime_v2")
def migrate_vndbtags(self, k):
def getvndbrealtags(vndbtags_naive):
vndbtagdata = tryreadconfig("vndbtagdata.json")
vndbtags = []
for tagid in vndbtags_naive:
if tagid in vndbtagdata:
vndbtags.append(vndbtagdata[tagid])
return vndbtags
if "vndbtags" not in savehook_new_data[k]:
return
vndbtags = savehook_new_data[k].get("vndbtags", [])
vndbtags = getvndbrealtags(vndbtags)
savehook_new_data[k]["webtags"] = vndbtags
savehook_new_data[k].pop("vndbtags")
def migrate_images(self, k):
if (
"imagepath" not in savehook_new_data[k]
and "imagepath_much2" not in savehook_new_data[k]
):
return
single = savehook_new_data[k].get("imagepath", None)
much = savehook_new_data[k].get("imagepath_much2", [])
__ = []
if single:
__.append(single)
__ += much
savehook_new_data[k]["imagepath_all"] = __
savehook_new_data[k].pop("imagepath")
savehook_new_data[k].pop("imagepath_much2")
def querytraceplaytime_v4(self, k):
gameinternalid = self.get_gameinternalid(k)
return self.sqlsavegameinfo.execute(
"SELECT timestart,timestop FROM traceplaytime_v4 WHERE gameinternalid = ?",
(gameinternalid,),
).fetchall()
def get_gameinternalid(self, k):
while True:
ret = self.sqlsavegameinfo.execute(
"SELECT gameinternalid FROM gameinternalid WHERE gamepath = ?", (k,)
).fetchone()
if ret is None:
self.sqlsavegameinfo.execute(
"INSERT INTO gameinternalid VALUES(NULL,?)", (k,)
)
else:
return ret[0]
def traceplaytime(self, k, start, end, new):
gameinternalid = self.get_gameinternalid(k)
if new:
self.sqlsavegameinfo.execute(
"INSERT INTO traceplaytime_v4 VALUES(NULL,?,?,?)",
(gameinternalid, start, end),
)
else:
self.sqlsavegameinfo.execute(
"UPDATE traceplaytime_v4 SET timestop = ? WHERE (gameinternalid = ? and timestart = ?)",
(end, gameinternalid, start),
)
def checkgameplayingthread(self):
self.__currentexe = None
self.__statistictime = time.time()
while True: while True:
statistictime = time.time()
time.sleep(1) time.sleep(1)
def isok(name_): def isok(name_):
now = time.time() if self.__currentexe == name_:
if self.tracestarted == False: _t = time.time()
self.tracestarted = True self.traceplaytime(name_, self.__statistictime - 1, _t, False)
savehook_new_data[name_]["traceplaytime_v2"].append( savehook_new_data[name_]["statistic_playtime"] += (
[statistictime, statistictime] _t + 1 - self.__statistictime
) )
savehook_new_data[name_]["statistic_playtime"] += now - statistictime else:
savehook_new_data[name_]["traceplaytime_v2"][-1][1] = now self.__statistictime = time.time()
self.__currentexe = name_
def isbad(): self.traceplaytime(
self.tracestarted = False name_, self.__statistictime - 1, self.__statistictime, True
)
savehook_new_data[name_]["statistic_playtime"] += 1
try: try:
_hwnd = windows.GetForegroundWindow() _hwnd = windows.GetForegroundWindow()
@ -829,13 +932,13 @@ class MAINUI:
if _pid in self.textsource.pids or _pid == os.getpid(): if _pid in self.textsource.pids or _pid == os.getpid():
isok(self.textsource.pname) isok(self.textsource.pname)
else: else:
isbad() self.__currentexe = None
except: except:
name_ = getpidexe(_pid) name_ = getpidexe(_pid)
if name_ and name_ in savehook_new_list: if name_ and name_ in savehook_new_list:
isok(name_) isok(name_)
else: else:
isbad() self.__currentexe = None
except: except:
print_exc() print_exc()
@ -968,6 +1071,7 @@ class MAINUI:
threading.Thread(target=self.checkgameplayingthread).start() threading.Thread(target=self.checkgameplayingthread).start()
threading.Thread(target=self.darklistener).start() threading.Thread(target=self.darklistener).start()
self.inittray() self.inittray()
self.createsavegamedb()
def darklistener(self): def darklistener(self):
sema = winsharedutils.startdarklistener() sema = winsharedutils.startdarklistener()

View File

@ -1,14 +1,22 @@
from myutils.config import globalconfig from myutils.config import globalconfig
from myutils.wrapper import threader from myutils.wrapper import threader
from traceback import print_exc from traceback import print_exc
from myutils.proxy import getproxy
class cishubase: class cishubase:
typename = None
def init(self): def init(self):
pass pass
def search(self, word): def search(self, word):
return word return word
@property
def proxy(self):
return getproxy(("cishu", self.typename))
def __init__(self, typename) -> None: def __init__(self, typename) -> None:
self.typename = typename self.typename = typename
self.callback = print self.callback = print

View File

@ -1,7 +1,6 @@
import requests import requests
from urllib.parse import quote from urllib.parse import quote
import re, os import re, os
from myutils.proxy import getproxy
from cishu.cishubase import cishubase from cishu.cishubase import cishubase
@ -9,13 +8,13 @@ class goo(cishubase):
def search(self, word): def search(self, word):
url = "https://dictionary.goo.ne.jp/srch/all/{}/m1u/".format(quote(word)) url = "https://dictionary.goo.ne.jp/srch/all/{}/m1u/".format(quote(word))
x = requests.get(url, proxies=getproxy()).text x = requests.get(url, proxies=self.proxy).text
xx = re.findall("<section>([\\s\\S]*?)</section>", x) xx = re.findall("<section>([\\s\\S]*?)</section>", x)
xx = "".join(xx).replace('href="/', 'href="https://dictionary.goo.ne.jp/') xx = "".join(xx).replace('href="/', 'href="https://dictionary.goo.ne.jp/')
if os.path.exists("cache/temp/goo.css") == False: if os.path.exists("cache/temp/goo.css") == False:
stl = requests.get( stl = requests.get(
"https://dictionary.goo.ne.jp/mix/css/app.css", proxies=getproxy() "https://dictionary.goo.ne.jp/mix/css/app.css", proxies=self.proxy
).text ).text
os.makedirs("cache/temp", exist_ok=True) os.makedirs("cache/temp", exist_ok=True)
with open("cache/temp/goo.css", "w", encoding="utf8") as ff: with open("cache/temp/goo.css", "w", encoding="utf8") as ff:

View File

@ -1,7 +1,6 @@
import requests import requests
from urllib.parse import quote from urllib.parse import quote
import re import re
from myutils.proxy import getproxy
from cishu.cishubase import cishubase from cishu.cishubase import cishubase
from html.parser import HTMLParser from html.parser import HTMLParser
@ -83,7 +82,7 @@ class jisho(cishubase):
url = "https://jisho.org/word/{}".format(quote(word)) url = "https://jisho.org/word/{}".format(quote(word))
html = requests.get( html = requests.get(
url, url,
proxies=getproxy(), proxies=self.proxy,
).text ).text
res = get_element_by_id("page_container", html) res = get_element_by_id("page_container", html)
@ -98,7 +97,7 @@ class jisho(cishubase):
) )
ss = re.search('href="https://assets.jisho.org/assets/application(.*)"', html) ss = re.search('href="https://assets.jisho.org/assets/application(.*)"', html)
stl = requests.get(ss.group()[6:-1], proxies=getproxy()).text stl = requests.get(ss.group()[6:-1], proxies=self.proxy).text
return ( return (
'<div style="text-align: center;"><a href="{}">link</a></div><br>'.format( '<div style="text-align: center;"><a href="{}">link</a></div><br>'.format(

View File

@ -1,10 +1,9 @@
import requests, re, json import requests, re, json
from myutils.proxy import getproxy
from cishu.cishubase import cishubase from cishu.cishubase import cishubase
def mojiclicksearch(word): def mojiclicksearch(self,word):
headers = { headers = {
"accept": "*/*", "accept": "*/*",
@ -39,7 +38,7 @@ def mojiclicksearch(word):
"https://api.mojidict.com/parse/functions/word-clickSearchV2", "https://api.mojidict.com/parse/functions/word-clickSearchV2",
headers=headers, headers=headers,
data=data, data=data,
proxies=getproxy(), proxies=self.proxy,
) )
result = response.json()["result"]["result"] result = response.json()["result"]["result"]
@ -574,7 +573,7 @@ def mojiclicksearch(word):
return result return result
def mojizonghe(word): def mojizonghe(self,word):
response = requests.post( response = requests.post(
"https://api.mojidict.com/parse/functions/union-api", "https://api.mojidict.com/parse/functions/union-api",
json={ json={
@ -597,7 +596,7 @@ def mojizonghe(word):
"content-type": "text/plain", "content-type": "text/plain",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
}, },
proxies=getproxy(), proxies=self.proxy,
) )
result = "" result = ""
@ -614,12 +613,12 @@ class mojidict(cishubase):
result = "" result = ""
try: try:
result += mojiclicksearch(word) result += mojiclicksearch(self,word)
result += "<br>" result += "<br>"
except: except:
pass pass
try: try:
result += mojizonghe(word) result += mojizonghe(self,word)
result += "<br>" result += "<br>"
except: except:
pass pass

View File

@ -2,7 +2,6 @@ import requests
from urllib.parse import quote from urllib.parse import quote
from cishu.cishubase import cishubase from cishu.cishubase import cishubase
from myutils.proxy import getproxy
import re import re
@ -10,7 +9,7 @@ class weblio(cishubase):
def search(self, word): def search(self, word):
url = "https://www.weblio.jp/content/" + quote(word) url = "https://www.weblio.jp/content/" + quote(word)
x = requests.get(url, proxies=getproxy()).text x = requests.get(url, proxies=self.proxy).text
x = re.sub("<img(.*?)>", "", x) x = re.sub("<img(.*?)>", "", x)
_all = [] _all = []
_xx = re.findall('<div class="kijiWrp">([\\s\\S]*?)<br class=clr>', x) _xx = re.findall('<div class="kijiWrp">([\\s\\S]*?)<br class=clr>', x)

View File

@ -2,7 +2,6 @@ from myutils.config import getlangsrc
import requests import requests
from urllib.parse import quote from urllib.parse import quote
import re, os import re, os
from myutils.proxy import getproxy
from cishu.cishubase import cishubase from cishu.cishubase import cishubase
@ -22,7 +21,7 @@ class youdao(cishubase):
"https://dict.youdao.com/result?word={}&lang={}".format( "https://dict.youdao.com/result?word={}&lang={}".format(
quote(word), self.srclang quote(word), self.srclang
), ),
proxies=getproxy(), proxies=self.proxy,
).text ).text
fnd = re.search('<section class="modules"(.*?)>([\\s\\S]*?)</section>', text) fnd = re.search('<section class="modules"(.*?)>([\\s\\S]*?)</section>', text)
fnd = fnd.group() fnd = fnd.group()

View File

@ -4,12 +4,10 @@ import os, functools, uuid, threading
from datetime import datetime, timedelta from datetime import datetime, timedelta
from traceback import print_exc from traceback import print_exc
import windows, gobject, winsharedutils import windows, gobject, winsharedutils
from myutils.vndb import parsehtmlmethod
from myutils.config import ( from myutils.config import (
savehook_new_list, savehook_new_list,
savehook_new_data, savehook_new_data,
savegametaged, savegametaged,
vndbtagdata,
_TR, _TR,
_TRL, _TRL,
globalconfig, globalconfig,
@ -17,7 +15,13 @@ from myutils.config import (
) )
from myutils.hwnd import getExeIcon from myutils.hwnd import getExeIcon
from myutils.wrapper import Singleton_close, Singleton, threader, tryprint from myutils.wrapper import Singleton_close, Singleton, threader, tryprint
from myutils.utils import checkifnewgame, str2rgba, vidchangedtask, titlechangedtask from myutils.utils import (
checkifnewgame,
str2rgba,
gamdidchangedtask,
titlechangedtask,
targetmod,
)
from gui.inputdialog import noundictconfigdialog1, autoinitdialog from gui.inputdialog import noundictconfigdialog1, autoinitdialog
from gui.specialwidget import ( from gui.specialwidget import (
ScrollFlow, ScrollFlow,
@ -375,12 +379,7 @@ class TagWidget(QWidget):
class browserdialog(saveposwindow): class browserdialog(saveposwindow):
seturlsignal = pyqtSignal(str) seturlsignal = pyqtSignal(str)
def parsehtml(self, url): def parsehtml(self, newpath):
try:
newpath = parsehtmlmethod(url)
except:
print_exc()
newpath = url
if newpath[:4].lower() != "http": if newpath[:4].lower() != "http":
newpath = os.path.abspath(newpath) newpath = os.path.abspath(newpath)
return newpath return newpath
@ -557,14 +556,6 @@ class browserdialog(saveposwindow):
) )
def getvndbrealtags(vndbtags_naive):
vndbtags = []
for tagid in vndbtags_naive:
if tagid in vndbtagdata:
vndbtags.append(vndbtagdata[tagid])
return vndbtags
_global_dialog_savedgame_new = None _global_dialog_savedgame_new = None
_global_dialog_setting_game = None _global_dialog_setting_game = None
@ -597,8 +588,8 @@ class dialog_setting_game_internal(QWidget):
def __init__(self, parent, exepath) -> None: def __init__(self, parent, exepath) -> None:
super().__init__(parent) super().__init__(parent)
vbox = QVBoxLayout(self) vbox = QVBoxLayout(self)
self.setLayout(vbox)
formLayout = QFormLayout() formLayout = QFormLayout()
self.setLayout(vbox)
self.exepath = exepath self.exepath = exepath
self.editpath = QLineEdit(exepath) self.editpath = QLineEdit(exepath)
self.editpath.setReadOnly(True) self.editpath.setReadOnly(True)
@ -614,29 +605,6 @@ class dialog_setting_game_internal(QWidget):
icon="fa.gear", icon="fa.gear",
constcolor="#FF69B4", constcolor="#FF69B4",
), ),
]
),
)
titleedit = QLineEdit(savehook_new_data[exepath]["title"])
def _titlechange(x):
titlechangedtask(exepath, x)
self.setWindowTitle(x)
titleedit.textChanged.connect(_titlechange)
formLayout.addRow(_TR("标题"), titleedit)
vndbid = QLineEdit(str(savehook_new_data[exepath]["vid"]))
vndbid.setValidator(QIntValidator())
vndbid.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
vndbid.textEdited.connect(functools.partial(vidchangedtask, exepath))
formLayout.addRow(
"vndbid",
getboxlayout(
[
vndbid,
getcolorbutton( getcolorbutton(
"", "",
"", "",
@ -644,94 +612,124 @@ class dialog_setting_game_internal(QWidget):
icon="fa.book", icon="fa.book",
constcolor="#FF69B4", constcolor="#FF69B4",
), ),
getcolorbutton(
"",
"",
lambda: os.startfile(
"https://vndb.org/v{}".format(
savehook_new_data[exepath]["vid"]
)
),
icon="fa.chrome",
constcolor="#FF69B4",
),
getcolorbutton(
"",
"",
lambda: vidchangedtask(
exepath, savehook_new_data[exepath]["vid"]
),
icon="fa.refresh",
constcolor="#FF69B4",
),
] ]
), ),
) )
titleedit = QLineEdit(savehook_new_data[exepath]["title"])
def _titlechange():
x = titleedit.text()
titlechangedtask(exepath, x)
self.setWindowTitle(x)
titleedit.textEdited.connect(
functools.partial(savehook_new_data[exepath].__setitem__, "title")
)
titleedit.returnPressed.connect(_titlechange)
formLayout.addRow(_TR("标题"), titleedit)
methodtab, do = makesubtab_lazy( methodtab, do = makesubtab_lazy(
_TRL( _TRL(
[ [
"启动", "启动",
"HOOK", "HOOK",
"画廊",
"标签",
"元数据",
"统计",
"预翻译", "预翻译",
"语音", "语音",
"标签",
"统计信息",
"存档备份", "存档备份",
"封面",
] ]
), ),
[ [
functools.partial(self.doaddtab, self.starttab, exepath), functools.partial(self.doaddtab, self.starttab, exepath),
functools.partial(self.doaddtab, self.gethooktab, exepath), functools.partial(self.doaddtab, self.gethooktab, exepath),
functools.partial(self.doaddtab, self.fengmiantab, exepath),
functools.partial(self.doaddtab, self.getlabelsetting, exepath),
functools.partial(self.doaddtab, self.metadataorigin, exepath),
functools.partial(self.doaddtab, self.getstatistic, exepath),
functools.partial(self.doaddtab, self.getpretranstab, exepath), functools.partial(self.doaddtab, self.getpretranstab, exepath),
functools.partial(self.doaddtab, self.getttssetting, exepath), functools.partial(self.doaddtab, self.getttssetting, exepath),
functools.partial(self.doaddtab, self.getlabelsetting, exepath),
functools.partial(self.doaddtab, self.getstatistic, exepath),
functools.partial(self.doaddtab, self.getbackup, exepath), functools.partial(self.doaddtab, self.getbackup, exepath),
functools.partial(self.doaddtab, self.fengmiantab, exepath),
], ],
delay=True, delay=True,
) )
self.methodtab = methodtab
vbox.addLayout(formLayout) vbox.addLayout(formLayout)
vbox.addWidget(methodtab) vbox.addWidget(methodtab)
do() do()
def openrefmainpage(self, key, idname, exepath):
try:
os.startfile(targetmod[key].refmainpage(savehook_new_data[exepath][idname]))
except:
print_exc()
def metadataorigin(self, exepath):
formLayout = QFormLayout()
_w = QWidget()
_w.setLayout(formLayout)
formLayout.addRow(
_TR("首选的"),
getsimplecombobox(
list(globalconfig["metadata"].keys()),
globalconfig,
"primitivtemetaorigin",
internallist=list(globalconfig["metadata"].keys()),
),
)
for key in globalconfig["metadata"]:
idname = globalconfig["metadata"][key]["target"]
vndbid = QLineEdit(str(savehook_new_data[exepath][idname]))
if globalconfig["metadata"][key]["idtype"] == 0:
vndbid.setValidator(QIntValidator())
vndbid.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
vndbid.textEdited.connect(
functools.partial(savehook_new_data[exepath].__setitem__, idname)
)
vndbid.returnPressed.connect(
functools.partial(gamdidchangedtask, key, idname, exepath)
)
formLayout.addRow(
key,
getboxlayout(
[
vndbid,
getcolorbutton(
"",
"",
functools.partial(
self.openrefmainpage, key, idname, exepath
),
icon="fa.chrome",
constcolor="#FF69B4",
),
getcolorbutton(
"",
"",
functools.partial(gamdidchangedtask, key, idname, exepath),
icon="fa.search",
constcolor="#FF69B4",
),
]
),
)
return _w
def fengmiantab(self, exepath): def fengmiantab(self, exepath):
_w = QWidget() _w = QWidget()
formLayout = QFormLayout() formLayout = QFormLayout()
_w.setLayout(formLayout) _w.setLayout(formLayout)
def selectimg(res):
savehook_new_data[exepath]["imagepath"] = res
savehook_new_data[exepath]["isimagepathusersetted"] = True
formLayout.addRow( formLayout.addRow(
_TR("封面"), _TR("画廊"),
getsimplepatheditor( getsimplepatheditor(
savehook_new_data[exepath]["imagepath"], reflist=savehook_new_data[exepath]["imagepath_all"],
False, multi=True,
False, isdir=False,
None, name=_TR("画廊"),
selectimg, header=_TR("画廊"),
True,
),
)
def selectimg2(ress):
savehook_new_data[exepath]["isimagepathusersetted_much"] = True
savehook_new_data[exepath]["imagepath_much2"] = ress
formLayout.addRow(
_TR("封面_大"),
getsimplepatheditor(
savehook_new_data[exepath]["imagepath_much2"],
True,
False,
None,
selectimg2,
True,
), ),
) )
return _w return _w
@ -862,7 +860,8 @@ class dialog_setting_game_internal(QWidget):
t = QTimer(self) t = QTimer(self)
t.setInterval(1000) t.setInterval(1000)
t.timeout.connect(self.refresh) t.timeout.connect(self.refresh)
t.start(0) t.timeout.emit()
t.start()
return _w return _w
def split_range_into_days(self, times): def split_range_into_days(self, times):
@ -909,7 +908,7 @@ class dialog_setting_game_internal(QWidget):
) )
self.chart.setdata( self.chart.setdata(
self.split_range_into_days( self.split_range_into_days(
savehook_new_data[self.exepath]["traceplaytime_v2"] gobject.baseobject.querytraceplaytime_v4(self.exepath)
) )
) )
@ -970,7 +969,7 @@ class dialog_setting_game_internal(QWidget):
newitem(tag, True, _type=tagitem.TYPE_USERTAG) newitem(tag, True, _type=tagitem.TYPE_USERTAG)
for tag in savehook_new_data[exepath]["developers"]: for tag in savehook_new_data[exepath]["developers"]:
newitem(tag, False, _type=tagitem.TYPE_DEVELOPER) newitem(tag, False, _type=tagitem.TYPE_DEVELOPER)
for tag in getvndbrealtags(savehook_new_data[exepath]["vndbtags"]): for tag in savehook_new_data[exepath]["webtags"]:
newitem(tag, False, _type=tagitem.TYPE_TAG) newitem(tag, False, _type=tagitem.TYPE_TAG)
formLayout.addWidget(self.labelflow) formLayout.addWidget(self.labelflow)
_dict = {"new": 0} _dict = {"new": 0}
@ -1088,34 +1087,14 @@ class dialog_setting_game_internal(QWidget):
getsimpleswitch(savehook_new_data[exepath], "removeuseless"), getsimpleswitch(savehook_new_data[exepath], "removeuseless"),
) )
model = QStandardItemModel() formLayout.addRow(
model.setHorizontalHeaderLabels( _TR("特殊码"),
_TRL( listediterline(
[ _TR("特殊码"),
"删除", _TR("特殊码"),
"特殊码", savehook_new_data[exepath]["needinserthookcode"],
] ),
)
) # ,'HOOK'])
self.hcmodel = model
table = QTableView()
table.horizontalHeader().setSectionResizeMode(
QHeaderView.ResizeMode.ResizeToContents
) )
table.horizontalHeader().setStretchLastSection(True)
# table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers);
table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
table.setSelectionMode((QAbstractItemView.SelectionMode.SingleSelection))
table.setWordWrap(False)
table.setModel(model)
self.hctable = table
for row, k in enumerate(savehook_new_data[exepath]["needinserthookcode"]): # 2
self.newline(row, k)
formLayout.addRow(self.hctable)
formLayout.addRow( formLayout.addRow(
_TR("插入特殊码延迟(ms)"), _TR("插入特殊码延迟(ms)"),
@ -1131,31 +1110,11 @@ class dialog_setting_game_internal(QWidget):
) )
return _w return _w
def clicked2(self):
try:
savehook_new_data[self.exepath]["needinserthookcode"].pop(
self.hctable.currentIndex().row()
)
self.hcmodel.removeRow(self.hctable.currentIndex().row())
except:
pass
def newline(self, row, k):
self.hcmodel.insertRow(row, [QStandardItem(), QStandardItem(k)])
self.hctable.setIndexWidget(
self.hcmodel.index(row, 0),
getcolorbutton(
"", "", self.clicked2, icon="fa.times", constcolor="#FF69B4"
),
)
@Singleton_close @Singleton_close
class dialog_setting_game(QDialog): class dialog_setting_game(QDialog):
def __init__(self, parent, exepath) -> None: def __init__(self, parent, exepath, setindexhook=False) -> None:
super().__init__(parent, Qt.WindowType.WindowCloseButtonHint) super().__init__(parent, Qt.WindowType.WindowCloseButtonHint)
global _global_dialog_setting_game global _global_dialog_setting_game
_global_dialog_setting_game = self _global_dialog_setting_game = self
@ -1164,7 +1123,8 @@ class dialog_setting_game(QDialog):
self.setWindowIcon(getExeIcon(exepath, cache=True)) self.setWindowIcon(getExeIcon(exepath, cache=True))
_ = dialog_setting_game_internal(self, exepath) _ = dialog_setting_game_internal(self, exepath)
if setindexhook:
_.methodtab.setCurrentIndex(1)
_.setMinimumSize(QSize(600, 500)) _.setMinimumSize(QSize(600, 500))
l = QHBoxLayout(self) l = QHBoxLayout(self)
self.setLayout(l) self.setLayout(l)
@ -1357,9 +1317,18 @@ def opendir(f):
def _getpixfunction(kk): def _getpixfunction(kk):
_pix = QPixmap(savehook_new_data[kk]["imagepath"]) if (
if _pix.isNull(): savehook_new_data[kk]["currentmainimage"]
_pix = getExeIcon(kk, False, cache=True) in savehook_new_data[kk]["imagepath_all"]
):
_pix = QPixmap(savehook_new_data[kk]["currentmainimage"])
if _pix and not _pix.isNull():
return _pix
for _ in savehook_new_data[kk]["imagepath_all"]:
_pix = QPixmap(_)
if _pix and not _pix.isNull():
return _pix
_pix = getExeIcon(kk, False, cache=True)
return _pix return _pix
@ -1531,6 +1500,7 @@ class dialog_savedgame_new(QWidget):
self.flow.bgclicked.connect(ItemWidget.clearfocus) self.flow.bgclicked.connect(ItemWidget.clearfocus)
self.formLayout.insertWidget(self.formLayout.count() - 1, self.flow) self.formLayout.insertWidget(self.formLayout.count() - 1, self.flow)
idx = 0 idx = 0
for k in savehook_new_list: for k in savehook_new_list:
if newtags != self.currtags: if newtags != self.currtags:
break break
@ -1545,7 +1515,7 @@ class dialog_savedgame_new(QWidget):
notshow = True notshow = True
break break
elif _type == tagitem.TYPE_TAG: elif _type == tagitem.TYPE_TAG:
if tag not in getvndbrealtags(savehook_new_data[k]["vndbtags"]): if tag not in savehook_new_data[k]["webtags"]:
notshow = True notshow = True
break break
elif _type == tagitem.TYPE_USERTAG: elif _type == tagitem.TYPE_USERTAG:
@ -1554,7 +1524,7 @@ class dialog_savedgame_new(QWidget):
break break
elif _type == tagitem.TYPE_RAND: elif _type == tagitem.TYPE_RAND:
if ( if (
tag not in getvndbrealtags(savehook_new_data[k]["vndbtags"]) tag not in savehook_new_data[k]["webtags"]
and tag not in savehook_new_data[k]["usertags"] and tag not in savehook_new_data[k]["usertags"]
and tag not in savehook_new_data[k]["title"] and tag not in savehook_new_data[k]["title"]
and tag not in savehook_new_data[k]["developers"] and tag not in savehook_new_data[k]["developers"]
@ -1565,6 +1535,7 @@ class dialog_savedgame_new(QWidget):
continue continue
self.newline(k, idx == 0) self.newline(k, idx == 0)
idx += 1 idx += 1
self.flow.directshow()
def showmenu(self, p): def showmenu(self, p):
menu = QMenu(self) menu = QMenu(self)
@ -2053,6 +2024,8 @@ class pixwrapper(QWidget):
super().__init__() super().__init__()
self.pixview = QLabel(self) self.pixview = QLabel(self)
self.pixmaps = [] self.pixmaps = []
self.rflist = []
self.iternalpixmaps = []
self.k = None self.k = None
self.pixmapi = 0 self.pixmapi = 0
self.pixview.setAlignment(Qt.AlignmentFlag.AlignCenter) self.pixview.setAlignment(Qt.AlignmentFlag.AlignCenter)
@ -2064,9 +2037,9 @@ class pixwrapper(QWidget):
self.visidx() self.visidx()
def mousePressEvent(self, a0: QMouseEvent) -> None: def mousePressEvent(self, a0: QMouseEvent) -> None:
if a0.pos().x() < self.width() * 2 / 5: if a0.pos().x() < self.width() / 3:
self.tolastnext(-1) self.tolastnext(-1)
elif a0.pos().x() > self.width() * 3 / 5: elif a0.pos().x() > self.width() * 2 / 3:
self.tolastnext(1) self.tolastnext(1)
else: else:
pass pass
@ -2078,22 +2051,40 @@ class pixwrapper(QWidget):
def visidx(self): def visidx(self):
if self.k and len(self.pixmaps) == 0: if self.k and len(self.pixmaps) == 0:
self.pixmaps = [_getpixfunction(self.k)] pixmap = getExeIcon(self.k, False, cache=True)
if self.pixmapi < len(self.pixmaps): pixmap.setDevicePixelRatio(self.devicePixelRatioF())
self.pixview.setPixmap(self.scalepix(pixmap))
elif self.pixmapi < len(self.pixmaps):
pixmap = self.pixmaps[self.pixmapi] pixmap = self.pixmaps[self.pixmapi]
if isinstance(pixmap, str):
pixmap = QPixmap.fromImage(QImage(pixmap)) savehook_new_data[self.k]["currentvisimage"] = pixmap
if pixmap.isNull(): pixmap = QPixmap.fromImage(QImage(pixmap))
if pixmap is None or pixmap.isNull():
self.pixmaps.pop(self.pixmapi) self.pixmaps.pop(self.pixmapi)
return self.visidx() return self.visidx()
pixmap.setDevicePixelRatio(self.devicePixelRatioF()) pixmap.setDevicePixelRatio(self.devicePixelRatioF())
self.pixview.setPixmap(self.scalepix(pixmap)) self.pixview.setPixmap(self.scalepix(pixmap))
def removecurrent(self):
if len(self.pixmaps):
path = self.pixmaps[self.pixmapi]
self.rflist.pop(self.rflist.index(path))
self.pixmaps.pop(self.pixmapi)
if self.pixmapi < len(self.pixmaps):
pass
else:
self.pixmapi -= 1
self.visidx()
def setpix(self, k): def setpix(self, k):
self.k = k self.k = k
self.pixmaps = savehook_new_data[k]["imagepath_much2"] self.pixmaps = savehook_new_data[k]["imagepath_all"].copy()
self.rflist = savehook_new_data[k]["imagepath_all"]
self.pixmapi = 0 self.pixmapi = 0
if savehook_new_data[k]["currentvisimage"] in self.pixmaps:
self.pixmapi = self.pixmaps.index(savehook_new_data[k]["currentvisimage"])
self.visidx() self.visidx()
def scalepix(self, pix: QPixmap): def scalepix(self, pix: QPixmap):
@ -2162,7 +2153,7 @@ class dialog_savedgame_v3(QWidget):
) )
self.stack.directshow() self.stack.directshow()
def stack_showmenu(self, p): def stack_showmenu(self, ispixmenu, p):
if not self.currentfocuspath: if not self.currentfocuspath:
return return
menu = QMenu(self) menu = QMenu(self)
@ -2170,7 +2161,8 @@ class dialog_savedgame_v3(QWidget):
delgame = QAction(_TR("删除游戏")) delgame = QAction(_TR("删除游戏"))
opendir = QAction(_TR("打开目录")) opendir = QAction(_TR("打开目录"))
addtolist = QAction(_TR("添加到列表")) addtolist = QAction(_TR("添加到列表"))
setimage = QAction(_TR("设为封面"))
deleteimage = QAction(_TR("删除图片"))
exists = os.path.exists(self.currentfocuspath) exists = os.path.exists(self.currentfocuspath)
if exists: if exists:
menu.addAction(startgame) menu.addAction(startgame)
@ -2178,15 +2170,24 @@ class dialog_savedgame_v3(QWidget):
if exists: if exists:
menu.addAction(opendir) menu.addAction(opendir)
menu.addAction(addtolist) menu.addAction(addtolist)
if ispixmenu:
menu.addAction(setimage)
menu.addAction(deleteimage)
action = menu.exec(QCursor.pos()) action = menu.exec(QCursor.pos())
if action == startgame: if action == startgame:
startgamecheck(self, self.currentfocuspath) startgamecheck(self, self.currentfocuspath)
elif action == delgame: elif action == delgame:
self.clicked2() self.clicked2()
elif action == deleteimage:
self.pixview.removecurrent()
elif action == opendir: elif action == opendir:
self.clicked4() self.clicked4()
elif action == addtolist: elif action == addtolist:
self.addtolist() self.addtolist()
elif action == setimage:
curr = savehook_new_data[self.currentfocuspath]["currentvisimage"]
if curr and os.path.exists(curr):
savehook_new_data[self.currentfocuspath]["currentmainimage"] = curr
def addtolistcallback(self, __d, __uid, path): def addtolistcallback(self, __d, __uid, path):
@ -2248,7 +2249,9 @@ class dialog_savedgame_v3(QWidget):
self.reallist = {} self.reallist = {}
self.stack = stackedlist() self.stack = stackedlist()
self.stack.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.stack.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.stack.customContextMenuRequested.connect(self.stack_showmenu) self.stack.customContextMenuRequested.connect(
functools.partial(self.stack_showmenu, False)
)
self.stack.setFixedWidth( self.stack.setFixedWidth(
globalconfig["dialog_savegame_layout"]["listitemwidth"] globalconfig["dialog_savegame_layout"]["listitemwidth"]
) )
@ -2263,11 +2266,13 @@ class dialog_savedgame_v3(QWidget):
rightlay = QVBoxLayout() rightlay = QVBoxLayout()
rightlay.setContentsMargins(0, 0, 0, 0) rightlay.setContentsMargins(0, 0, 0, 0)
_w.setLayout(rightlay) _w.setLayout(rightlay)
self.righttop.addTab(_w, _TR("封面")) self.righttop.addTab(_w, _TR("画廊"))
lay.addWidget(self.righttop) lay.addWidget(self.righttop)
rightlay.addWidget(self.pixview) rightlay.addWidget(self.pixview)
self.pixview.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.pixview.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.pixview.customContextMenuRequested.connect(self.stack_showmenu) self.pixview.customContextMenuRequested.connect(
functools.partial(self.stack_showmenu, True)
)
self.buttonlayout = QHBoxLayout() self.buttonlayout = QHBoxLayout()
self.savebutton = [] self.savebutton = []
rightlay.addLayout(self.buttonlayout) rightlay.addLayout(self.buttonlayout)

View File

@ -117,7 +117,8 @@ class edittrans(QMainWindow):
t = QTimer(self) t = QTimer(self)
t.setInterval(100) t.setInterval(100)
t.timeout.connect(self.follow) t.timeout.connect(self.follow)
t.start(0) t.timeout.emit()
t.start()
def follow(self): def follow(self):
rect = windows.GetWindowRect(self.followhwnd) rect = windows.GetWindowRect(self.followhwnd)

View File

@ -270,6 +270,9 @@ class autoinitdialog(QDialog):
line["dir"], line["dir"],
line.get("filter", None), line.get("filter", None),
callback=functools.partial(__temp.__setitem__, "k"), callback=functools.partial(__temp.__setitem__, "k"),
reflist=__temp["k"],
name=line.get("name", ""),
header=line.get("name", ""),
) )
regist.append([dd, key, functools.partial(__temp.__getitem__, "k")]) regist.append([dd, key, functools.partial(__temp.__getitem__, "k")])

View File

@ -712,7 +712,7 @@ class hookselect(closeashidewindow):
def opengamesetting(self): def opengamesetting(self):
try: try:
dialog_setting_game(self, gobject.baseobject.textsource.pname) dialog_setting_game(self, gobject.baseobject.textsource.pname, True)
except: except:
print_exc() print_exc()

View File

@ -11,7 +11,7 @@ from gui.usefulwidget import (
) )
def getall(l, item="fanyi", name=""): def getall(l, item="fanyi", name=None):
grids = [] grids = []
i = 0 i = 0
line = [] line = []
@ -19,13 +19,14 @@ def getall(l, item="fanyi", name=""):
if fanyi not in l: if fanyi not in l:
continue continue
_f = name % fanyi if name:
if fanyi != "selfbuild" and os.path.exists(_f) == False: _f = name % fanyi
continue if fanyi != "selfbuild" and os.path.exists(_f) == False:
continue
i += 1 i += 1
line += [ line += [
(globalconfig[item][fanyi]["name"], 6), (globalconfig[item][fanyi].get("name", fanyi), 6),
D_getsimpleswitch(globalconfig[item][fanyi], "useproxy", default=True), D_getsimpleswitch(globalconfig[item][fanyi], "useproxy", default=True),
"", "",
] ]
@ -62,6 +63,14 @@ def _ifusesysproxy(self, x):
self.__checkproxybtn.setEnabled(not x) self.__checkproxybtn.setEnabled(not x)
def getnotofflines(key):
__ = []
for k in globalconfig[key]:
if globalconfig[key][k].get("type", None) != "offline":
__.append(k)
return __
def setTab_proxy_lazy(self, basel): def setTab_proxy_lazy(self, basel):
grid1 = [ grid1 = [
@ -89,20 +98,60 @@ def setTab_proxy_lazy(self, basel):
mianfei = getall(l=mianfei, item="fanyi", name="./Lunatranslator/translator/%s.py") mianfei = getall(l=mianfei, item="fanyi", name="./Lunatranslator/translator/%s.py")
shoufei = getall(l=shoufei, item="fanyi", name="./Lunatranslator/translator/%s.py") shoufei = getall(l=shoufei, item="fanyi", name="./Lunatranslator/translator/%s.py")
ocrs = getall( ocrs = getall(
l=set(globalconfig["ocr"].keys()) - set(["local", "windowsocr"]), l=getnotofflines("ocr"),
item="ocr", item="ocr",
name="./Lunatranslator/ocrengines/%s.py", name="./Lunatranslator/ocrengines/%s.py",
) )
meta = getall(
l=list(globalconfig["metadata"].keys()),
item="metadata",
name="./LunaTranslator/myutils/metadata/%s.py",
)
readers = getall(
l=getnotofflines("reader"),
item="reader",
name="./LunaTranslator/tts/%s.py",
)
cishus = getall(
l=getnotofflines("cishu"),
item="cishu",
name="./LunaTranslator/cishu/%s.py",
)
hira = getall(
l=getnotofflines("hirasetting"),
item="hirasetting",
name="./LunaTranslator/hiraparse/%s.py",
)
github = getall(
l=list(globalconfig["github"].keys()),
item="github",
)
vw, vl = getvboxwidget() vw, vl = getvboxwidget()
basel.addWidget(vw) basel.addWidget(vw)
gridlayoutwidget, do = makegrid(grid1, delay=True) gridlayoutwidget, do = makegrid(grid1, delay=True)
vl.addWidget(gridlayoutwidget) vl.addWidget(gridlayoutwidget)
tab, dotab = makesubtab_lazy( tab, dotab = makesubtab_lazy(
_TRL(["在线翻译", "注册在线翻译", "在线OCR"]), _TRL(
[
"在线翻译",
"注册在线翻译",
"OCR",
"语音合成",
"辞书",
"元数据",
"分词",
"github",
]
),
[ [
functools.partial(makescrollgrid, mianfei), functools.partial(makescrollgrid, mianfei),
functools.partial(makescrollgrid, shoufei), functools.partial(makescrollgrid, shoufei),
functools.partial(makescrollgrid, ocrs), functools.partial(makescrollgrid, ocrs),
functools.partial(makescrollgrid, readers),
functools.partial(makescrollgrid, cishus),
functools.partial(makescrollgrid, meta),
functools.partial(makescrollgrid, hira),
functools.partial(makescrollgrid, github),
], ],
delay=True, delay=True,
) )

View File

@ -311,7 +311,8 @@ class lazyscrollflow(ScrollArea):
def directshow(self): def directshow(self):
QApplication.processEvents() QApplication.processEvents()
self.doshowlazywidget(True, self.internalwid.visibleRegion().rects()[0]) if len(self.internalwid.visibleRegion().rects()):
self.doshowlazywidget(True, self.internalwid.visibleRegion().rects()[0])
def __init__(self): def __init__(self):
super().__init__() super().__init__()

View File

@ -861,7 +861,8 @@ class QUnFrameWindow(resizableframeless):
try: try:
gobject.baseobject.settin_ui.show_original_switch.click() gobject.baseobject.settin_ui.show_original_switch.click()
except: except:
pass globalconfig["isshowrawtext"] = not globalconfig["isshowrawtext"]
gobject.baseobject.translation_ui.refreshtoolicon()
def changeTranslateMode(self): def changeTranslateMode(self):
globalconfig["autorun"] = not globalconfig["autorun"] globalconfig["autorun"] = not globalconfig["autorun"]

View File

@ -711,11 +711,12 @@ class mshtmlWidget(abstractwebview):
if HTMLBrowser.version() < 10001: # ie10之前sethtml会乱码 if HTMLBrowser.version() < 10001: # ie10之前sethtml会乱码
self.html_limit = 0 self.html_limit = 0
self.browser = HTMLBrowser(int(self.winId())) self.browser = HTMLBrowser(int(self.winId()))
self.curr_url = None
t = QTimer(self) t = QTimer(self)
t.setInterval(100) t.setInterval(100)
t.timeout.connect(self.__getcurrenturl) t.timeout.connect(self.__getcurrenturl)
t.start(0) t.timeout.emit()
self.curr_url = None t.start()
def __getcurrenturl(self): def __getcurrenturl(self):
_u = self.browser.get_current_url() _u = self.browser.get_current_url()
@ -785,7 +786,8 @@ class QWebWrap(abstractwebview):
t = QTimer(self) t = QTimer(self)
t.setInterval(100) t.setInterval(100)
t.timeout.connect(self.__getzoomfactor) t.timeout.connect(self.__getzoomfactor)
t.start(0) t.timeout.emit()
t.start()
def set_zoom(self, zoom): def set_zoom(self, zoom):
self.internal_zoom = zoom self.internal_zoom = zoom
@ -1061,10 +1063,54 @@ def makesubtab_lazy(
@Singleton_close @Singleton_close
class listediter(QDialog): class listediter(QDialog):
def __init__(self, p, title, header, lst, closecallback=None) -> None: def showmenu(self, p: QPoint):
r = self.hctable.currentIndex().row()
if r < 0:
return
menu = QMenu(self.hctable)
remove = QAction(_TR("删除"))
copy = QAction(_TR("复制"))
up = QAction(_TR("上移"))
down = QAction(_TR("下移"))
menu.addAction(remove)
menu.addAction(copy)
menu.addAction(up)
menu.addAction(down)
action = menu.exec(self.hctable.cursor().pos())
if action == remove:
self.hcmodel.removeRow(self.hctable.currentIndex().row())
elif action == copy:
winsharedutils.clipboard_set(
self.hcmodel.item(
self.hctable.currentIndex().row(),
self.hctable.currentIndex().column(),
).text()
)
elif action == up:
self.moverank(-1)
elif action == down:
self.moverank(1)
def moverank(self, dy):
target = (self.hctable.currentIndex().row() + dy) % self.hcmodel.rowCount()
text = self.hcmodel.item(
self.hctable.currentIndex().row(), self.hctable.currentIndex().column()
).text()
self.hcmodel.removeRow(self.hctable.currentIndex().row())
self.hcmodel.insertRow(target, [QStandardItem(text)])
def __init__(
self, p, title, header, lst, closecallback=None, ispathsedit=False
) -> None:
super().__init__(p) super().__init__(p)
self.lst = lst self.lst = lst
self.closecallback = closecallback self.closecallback = closecallback
self.ispathsedit = ispathsedit
try: try:
self.setWindowTitle(title) self.setWindowTitle(title)
model = QStandardItemModel() model = QStandardItemModel()
@ -1076,23 +1122,28 @@ class listediter(QDialog):
QHeaderView.ResizeMode.ResizeToContents QHeaderView.ResizeMode.ResizeToContents
) )
table.horizontalHeader().setStretchLastSection(True) table.horizontalHeader().setStretchLastSection(True)
# table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers); if ispathsedit:
table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
table.setSelectionMode((QAbstractItemView.SelectionMode.SingleSelection)) table.setSelectionMode((QAbstractItemView.SelectionMode.SingleSelection))
table.setWordWrap(False) table.setWordWrap(False)
table.setModel(model) table.setModel(model)
table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
table.customContextMenuRequested.connect(self.showmenu)
self.hctable = table self.hctable = table
for row, k in enumerate(lst): # 2 for row, k in enumerate(lst): # 2
self.newline(row, k) self.hcmodel.insertRow(row, [QStandardItem(k)])
formLayout = QVBoxLayout() formLayout = QVBoxLayout()
formLayout.addWidget(self.hctable) formLayout.addWidget(self.hctable)
self.buttons = threebuttons(btns=2) self.buttons = threebuttons(btns=2)
self.buttons.btn1clicked.connect(lambda: self.newline(0, "")) self.buttons.btn1clicked.connect(self.click1)
self.buttons.btn2clicked.connect(self.clicked2) self.buttons.btn2clicked.connect(self.clicked2)
formLayout.addWidget(self.buttons) formLayout.addWidget(self.buttons)
self.setLayout(formLayout) self.setLayout(formLayout)
self.resize(600, self.sizeHint().height())
self.show() self.show()
except: except:
print_exc() print_exc()
@ -1116,14 +1167,29 @@ class listediter(QDialog):
if self.closecallback: if self.closecallback:
self.closecallback() self.closecallback()
def newline(self, row, k): def __cb(self, path):
self.hcmodel.insertRow(row, [QStandardItem(k)])
self.hcmodel.insertRow(0, [QStandardItem(path)])
def click1(self):
if self.ispathsedit:
openfiledirectory(
"",
multi=False,
edit=None,
isdir=self.ispathsedit["isdir"],
filter1=self.ispathsedit["filter1"],
callback=self.__cb,
)
else:
self.hcmodel.insertRow(0, [QStandardItem("")])
class listediterline(QLineEdit): class listediterline(QLineEdit):
clicked = pyqtSignal() clicked = pyqtSignal()
def __init__(self, name, header, reflist): def __init__(self, name, header, reflist, ispathsedit=False):
super().__init__() super().__init__()
self.setReadOnly(True) self.setReadOnly(True)
self.reflist = reflist self.reflist = reflist
@ -1131,7 +1197,13 @@ class listediterline(QLineEdit):
self.clicked.connect( self.clicked.connect(
functools.partial( functools.partial(
listediter, self, name, header, reflist, closecallback=self.callback listediter,
self,
name,
header,
reflist,
closecallback=self.callback,
ispathsedit=ispathsedit,
) )
) )
@ -1156,40 +1228,49 @@ def openfiledirectory(directory, multi, edit, isdir, filter1="*.*", callback=Non
if len(res) == 0: if len(res) == 0:
return return
edit.setText("|".join(res) if multi else res) if edit:
edit.setText("|".join(res) if multi else res)
if callback: if callback:
callback(res) callback(res)
def getsimplepatheditor( def getsimplepatheditor(
text, text=None,
multi, multi=False,
isdir, isdir=False,
filter1="*.*", filter1="*.*",
callback=None, callback=None,
useiconbutton=False, useiconbutton=False,
reflist=None,
name=None,
header=None,
): ):
lay = QHBoxLayout() lay = QHBoxLayout()
lay.setContentsMargins(0, 0, 0, 0) lay.setContentsMargins(0, 0, 0, 0)
director = (text[0] if len(text) else "") if multi else text if multi:
e = QLineEdit("|".join(text) if multi else text) e = listediterline(
e.setReadOnly(True) name, header, reflist, dict(isdir=isdir, multi=False, filter1=filter1)
if useiconbutton:
bu = getcolorbutton("", "", None, icon="fa.gear", constcolor="#FF69B4")
else:
bu = QPushButton(_TR("选择" + ("文件夹" if isdir else "文件")))
bu.clicked.connect(
functools.partial(
openfiledirectory,
director,
multi,
e,
isdir,
"" if isdir else filter1,
callback,
) )
) lay.addWidget(e)
lay.addWidget(e) else:
lay.addWidget(bu) e = QLineEdit(text)
e.setReadOnly(True)
if useiconbutton:
bu = getcolorbutton("", "", None, icon="fa.gear", constcolor="#FF69B4")
else:
bu = QPushButton(_TR("选择" + ("文件夹" if isdir else "文件")))
bu.clicked.connect(
functools.partial(
openfiledirectory,
text,
multi,
e,
isdir,
"" if isdir else filter1,
callback,
)
)
lay.addWidget(e)
lay.addWidget(bu)
return lay return lay

View File

@ -1,5 +1,6 @@
from myutils.config import globalconfig, static_data from myutils.config import globalconfig, static_data
from traceback import print_exc from traceback import print_exc
from myutils.proxy import getproxy
class basehira: class basehira:
@ -25,6 +26,10 @@ class basehira:
def config(self): def config(self):
return globalconfig["hirasetting"][self.typename]["args"] return globalconfig["hirasetting"][self.typename]["args"]
@property
def proxy(self):
return getproxy(("cishu", self.typename))
def parseparse(self, text): def parseparse(self, text):
hira = [] hira = []
try: try:

View File

@ -1,4 +1,3 @@
from myutils.proxy import getproxy
import requests import requests
from hiraparse.basehira import basehira from hiraparse.basehira import basehira
@ -19,7 +18,7 @@ class mojinlt(basehira):
"content-type": "text/plain", "content-type": "text/plain",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
}, },
proxies=getproxy(), proxies=self.proxy,
) )
return [ return [

View File

@ -96,7 +96,7 @@ class commonbase:
self.level2init() self.level2init()
def renewsesion(self): def renewsesion(self):
self.session = proxysession(self._globalconfig_key, self.typename) self.proxysession = proxysession(self._globalconfig_key, self.typename)
def level2init(self): def level2init(self):
pass pass

View File

@ -57,8 +57,6 @@ except:
translatorsetting = tryreadconfig("translatorsetting.json") translatorsetting = tryreadconfig("translatorsetting.json")
ocrsetting = tryreadconfig("ocrsetting.json") ocrsetting = tryreadconfig("ocrsetting.json")
vndbtagdata = tryreadconfig("vndbtagdata.json")
def getdefaultsavehook(gamepath, title=None): def getdefaultsavehook(gamepath, title=None):
default = { default = {
@ -67,14 +65,6 @@ def getdefaultsavehook(gamepath, title=None):
"onloadautoswitchsrclang": 0, "onloadautoswitchsrclang": 0,
"needinserthookcode": [], "needinserthookcode": [],
"embedablehook": [], "embedablehook": [],
"imagepath": None,
"imagepath_much2": [],
"isimagepathusersetted": False,
"isimagepathusersetted_much": False,
"istitlesetted": False,
"infopath": None,
"vid": 0,
"namemap": {},
"statistic_playtime": 0, "statistic_playtime": 0,
"statistic_wordcount": 0, "statistic_wordcount": 0,
"statistic_wordcount_nodump": 0, "statistic_wordcount_nodump": 0,
@ -86,24 +76,42 @@ def getdefaultsavehook(gamepath, title=None):
"needinserthookcode": [], "needinserthookcode": [],
"removeuseless": False, "removeuseless": False,
"codepage_index": 0, "codepage_index": 0,
# "allow_tts_auto_names": "", # "allow_tts_auto_names": "",#->v4
"allow_tts_auto_names_v4": [], "allow_tts_auto_names_v4": [],
"tts_repair": False, "tts_repair": False,
"tts_repair_regex": [], "tts_repair_regex": [],
"hooktypeasname": {}, "hooktypeasname": {},
"use_saved_text_process": False, "use_saved_text_process": False,
"searchnoresulttime": 0, # "searchnoresulttime": 0,
"relationlinks": [],
"gamejsonfile": "", "gamejsonfile": "",
"gamesqlitefile": "", "gamesqlitefile": "",
"vndbtags": [], "relationlinks": [],
# "vndbtags": [],#->webtags
"usertags": [], "usertags": [],
"traceplaytime_v2": [], # [[start,end]] # "traceplaytime_v2": [], # [[start,end]]->db.traceplaytime_v4这个东西增加到太快了有点膨胀
"autosavesavedata": "", "autosavesavedata": "",
# 判断是否为自定义元数据,避免覆写
# "isimagepathusersetted": False,
# "isimagepathusersetted_much": False,
"istitlesetted": False,
"currentvisimage": None,
"currentmainimage": "",
# 元数据
"namemap": {}, # 人名翻译映射vndb独占用于优化翻译
#
"vid": 0,
"bgmsid": 0,
"dlsiteid": 'RJ',
"title": "",
# "imagepath": None, # 封面->imagepath_all[0]
# "imagepath_much2": [], # 截图->imagepath_all[1:]
"imagepath_all": [],
"developers": [], "developers": [],
"webtags": [], # 标签
"infopath": None, # 离线存储的主页
} }
if title and len(title): if title and len(title):
default["title"] = title default["title"] = title # metadata
else: else:
default["title"] = ( default["title"] = (
os.path.basename(os.path.dirname(gamepath)) os.path.basename(os.path.dirname(gamepath))
@ -116,15 +124,6 @@ def getdefaultsavehook(gamepath, title=None):
_dfsavehook = getdefaultsavehook("") _dfsavehook = getdefaultsavehook("")
for game in savehook_new_data: for game in savehook_new_data:
if ("traceplaytime_v2" not in savehook_new_data[game]) and (
"statistic_playtime" in savehook_new_data[game]
):
savehook_new_data[game]["traceplaytime_v2"] = [
[
0,
savehook_new_data[game]["statistic_playtime"],
]
]
if ( if (
("allow_tts_auto_names_v4" not in savehook_new_data[game]) ("allow_tts_auto_names_v4" not in savehook_new_data[game])
and ("allow_tts_auto_names" in savehook_new_data[game]) and ("allow_tts_auto_names" in savehook_new_data[game])
@ -335,16 +334,18 @@ def _TRL(kk):
return x return x
def saveallconfig(): def safesave(fname, js):
def safesave(fname, js): # 有时保存时意外退出会导致config文件被清空
# 有时保存时意外退出会导致config文件被清空
with open(fname + ".tmp", "w", encoding="utf-8") as ff:
ff.write(json.dumps(js, ensure_ascii=False, sort_keys=False, indent=4))
if os.path.exists(fname):
os.remove(fname)
os.rename(fname + ".tmp", fname)
os.makedirs("./userconfig", exist_ok=True) os.makedirs("./userconfig", exist_ok=True)
with open(fname + ".tmp", "w", encoding="utf-8") as ff:
ff.write(json.dumps(js, ensure_ascii=False, sort_keys=False, indent=4))
if os.path.exists(fname):
os.remove(fname)
os.rename(fname + ".tmp", fname)
def saveallconfig():
safesave("./userconfig/config.json", globalconfig) safesave("./userconfig/config.json", globalconfig)
safesave("./userconfig/magpie_config.json", magpie_config) safesave("./userconfig/magpie_config.json", magpie_config)
safesave("./userconfig/postprocessconfig.json", postprocessconfig) safesave("./userconfig/postprocessconfig.json", postprocessconfig)
@ -353,7 +354,6 @@ def saveallconfig():
safesave("./userconfig/translatorsetting.json", translatorsetting) safesave("./userconfig/translatorsetting.json", translatorsetting)
safesave("./userconfig/ocrerrorfix.json", ocrerrorfix) safesave("./userconfig/ocrerrorfix.json", ocrerrorfix)
safesave("./userconfig/ocrsetting.json", ocrsetting) safesave("./userconfig/ocrsetting.json", ocrsetting)
safesave("./userconfig/vndbtagdata.json", vndbtagdata)
safesave( safesave(
"./userconfig/savehook_new_1.39.4.json", "./userconfig/savehook_new_1.39.4.json",
[savehook_new_list, savehook_new_data, savegametaged], [savehook_new_list, savehook_new_data, savegametaged],

View File

@ -22,6 +22,7 @@ def getvesionmethod():
"https://api.github.com/repos/HIllya51/LunaTranslator/releases/latest", "https://api.github.com/repos/HIllya51/LunaTranslator/releases/latest",
headers=headers, headers=headers,
verify=False, verify=False,
proxies=getproxy(("github", "versioncheck")),
).json() ).json()
# print(res) # print(res)
_version = res["tag_name"] _version = res["tag_name"]
@ -89,13 +90,17 @@ def updatemethod(_version, progresscallback):
return False return False
try: try:
r2 = requests.get(url, stream=True, verify=False, proxies=getproxy()) r2 = requests.get(
url, stream=True, verify=False, proxies=getproxy(("github", "download"))
)
size = int(r2.headers["Content-Length"]) size = int(r2.headers["Content-Length"])
if checkalready(size): if checkalready(size):
return return
with open(savep, "wb") as file: with open(savep, "wb") as file:
sess = requests.session() sess = requests.session()
r = sess.get(url, stream=True, verify=False, proxies=getproxy()) r = sess.get(
url, stream=True, verify=False, proxies=getproxy(("github", "download"))
)
file_size = 0 file_size = 0
for i in r.iter_content(chunk_size=1024): for i in r.iter_content(chunk_size=1024):
if globalconfig["autoupdate"] == False: if globalconfig["autoupdate"] == False:

View File

@ -0,0 +1,93 @@
import time, requests, os, hashlib, re, queue
from myutils.proxy import getproxy
from threading import Thread
from myutils.commonbase import proxysession
from myutils.config import globalconfig
class common:
typename = None
def searchfordata(_id):
return None
def refmainpage(_id):
return None
def getidbytitle(title):
return None
@property
def proxy(self):
return getproxy(("metadata", self.typename))
def __init__(self, typename) -> None:
self.typename = typename
self.proxysession = proxysession("metadata", self.typename)
self.__tasks = queue.Queue()
for url, save in globalconfig["metadata"][self.typename]["downloadtasks"]:
self.__tasks.put((url, save))
Thread(target=self.__autodownloadimage).start()
def __autodownloadimage(self):
while True:
url, save = self.__tasks.get()
if os.path.exists(save):
continue
if self.__realdodownload(url, save):
try:
globalconfig["metadata"][self.typename]["downloadtasks"].remove(
(url, save)
)
except:
pass
else:
self.__tasks.put((url, save))
time.sleep(1)
def __realdodownload(self, url, save):
if os.path.exists(save):
return True
print(url, save)
headers = {
"sec-ch-ua": '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
"Referer": "https://vndb.org/",
"sec-ch-ua-mobile": "?0",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42",
"sec-ch-ua-platform": '"Windows"',
}
try:
_content = self.proxysession.get(url, headers=headers).content
with open(save, "wb") as ff:
ff.write(_content)
return True
except:
return False
def dispatchdownloadtask(self, url, ishtml=False, delay=True):
__routine = f"cache/metadata/{self.typename}"
if self.typename == "vndb":
__routine = "cache/vndb"
os.makedirs(__routine, exist_ok=True)
if ishtml:
__ = ".html"
else:
if "." in url[5:]:
__ = url[url.rfind(".") :]
else:
__ = ".jpg"
savepath = f"{__routine}/{self.b64string(url)}{__}"
if delay:
globalconfig["metadata"][self.typename]["downloadtasks"].append(
(url, savepath)
)
self.__tasks.put((url, savepath))
return savepath
else:
if self.__realdodownload(url, savepath):
return savepath
else:
return None
def b64string(self, a):
return hashlib.md5(a.encode("utf8")).hexdigest()

View File

@ -0,0 +1,66 @@
from myutils.metadata.abstract import common
class searcher(common):
def getidbytitle(self, title):
headers = {
"accept": "application/json",
"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",
}
params = {
"type": "4",
"responseGroup": "small",
}
response = self.proxysession.get(
"https://api.bgm.tv/search/subject/" + title, params=params, headers=headers
)
print(response.text)
try:
response = response.json()
except:
return None
if len(response["list"]) == 0:
return None
return response["list"][0]["id"]
def refmainpage(self, _id):
return f"https://bangumi.tv/subject/{_id}"
def searchfordata(self, sid):
headers = {
"accept": "application/json",
"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 = self.proxysession.get(
f"https://api.bgm.tv/v0/subjects/{sid}", headers=headers
)
print(response.text)
try:
response = response.json()
except:
return {}
try:
imagepath = self.dispatchdownloadtask(response["images"]["large"])
except:
imagepath = []
vndbtags = [_["name"] for _ in response["tags"]]
developers = []
for _ in response["infobox"]:
if _["key"] == "游戏开发商":
developers = [_["value"]]
break
return {
# "namemap": namemap,
"title": response["name_cn"],
# "infopath": parsehtmlmethod(vndbdowloadinfo(vid)),
"imagepath_all": [imagepath],
"webtags": vndbtags,
"developers": developers,
}

View File

@ -0,0 +1,122 @@
import requests, re
from myutils.utils import simplehtmlparser
from myutils.metadata.abstract import common
class searcher(common):
def getidbytitle(self, title):
headers = {
"Referer": "https://www.dlsite.com/maniax/work/=/product_id/RJ01166543.html",
"Upgrade-Insecure-Requests": "1",
"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",
"sec-ch-ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
try:
response = requests.get(
f"https://www.dlsite.com/pro/fsr/=/language/jp/sex_category[0]/male/keyword/{title}",
headers=headers,
proxies=self.proxy,
)
inner = simplehtmlparser(
response.text,
"div",
'<div id="search_result_list" class="loading_display_open"',
)
# print(inner)
_id = re.search('id="_link_VJ(.*?)"', inner).groups()[0]
return "VJ" + _id
except:
response = requests.get(
f"https://www.dlsite.com/maniax/fsr/=/language/jp/sex_category[0]/male/keyword/{title}",
headers=headers,
proxies=self.proxy,
)
inner = simplehtmlparser(
response.text,
"div",
'<div id="search_result_list" class="loading_display_open"',
)
# print(inner)
_id = re.search('id="_link_RJ(.*?)"', inner).groups()[0]
return "RJ" + _id
def refmainpage(self, RJ: str):
if RJ.startswith("RJ"):
return f"https://www.dlsite.com/maniax/work/=/product_id/{RJ}.html"
elif RJ.startswith("VJ"):
return f"https://www.dlsite.com/pro/work/=/product_id/{RJ}.html"
def searchfordata(self, RJ):
headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"accept-language": "zh-CN,zh;q=0.9,ar;q=0.8,sq;q=0.7,ru;q=0.6",
"cache-control": "max-age=0",
"priority": "u=0, i",
"referer": "https://www.dlsite.com/home/",
"sec-ch-ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"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 = self.proxysession.get(
self.refmainpage(RJ),
headers=headers,
)
title = re.search(
'<h1 itemprop="name" id="work_name">(.*?)</h1>', response.text
).groups()[0]
print(title)
devp = re.search(
'<span itemprop="brand" class="maker_name">([\\s\\S]*?)<a ([\\s\\S]*?)>(.*?)</a>([\\s\\S]*?)</span>',
response.text,
).groups()[2]
print(devp)
tags = re.search(
'<div class="main_genre">([\\s\\S]*?)</div>', response.text
).groups()[0]
tags = [_[1] for _ in re.findall('<a href="(.*?)">(.*?)</a>', tags)]
print(tags)
inner = simplehtmlparser(
response.text,
"div",
'<div itemprop="description" class="work_parts_container">',
)
imags2 = ["https:" + _[0] for _ in re.findall('<img src="(.*?)"(.*?)>', inner)]
print(imags2)
inner = simplehtmlparser(response.text, "div", '<div ref="product_slider_data"')
imags1 = [
"https:" + _[0] for _ in re.findall('<div data-src="(.*?)"(.*?)>', inner)
]
print(imags1)
return {
# "namemap": namemap,
"title": title,
# "infopath": parsehtmlmethod(vndbdowloadinfo(vid)),
"imagepath_all": [self.dispatchdownloadtask(_) for _ in imags1 + imags2],
"webtags": tags,
"developers": [devp],
}

View File

@ -1,88 +1,19 @@
import time, requests, re, os, hashlib import time, requests, re, os
from myutils.proxy import getproxy from myutils.config import globalconfig, tryreadconfig, safesave
from myutils.config import globalconfig, vndbtagdata
from threading import Thread from threading import Thread
import gzip, json import gzip, json
import shutil import shutil
from myutils.metadata.abstract import common
def b64string(a):
return hashlib.md5(a.encode("utf8")).hexdigest()
def vndbdownloadimg(url, wait=True): def safegetvndbjson(proxy, url, json, getter):
os.makedirs("./cache/vndb", exist_ok=True)
savepath = "./cache/vndb/" + b64string(url) + ".jpg"
if os.path.exists(savepath):
return savepath
def _(url, savepath):
headers = {
"sec-ch-ua": '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
"Referer": "https://vndb.org/",
"sec-ch-ua-mobile": "?0",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42",
"sec-ch-ua-platform": '"Windows"',
}
try:
time.sleep(1)
_content = requests.get(url, headers=headers, proxies=getproxy()).content
with open(savepath, "wb") as ff:
ff.write(_content)
return savepath
except:
return None
if wait:
return _(url, savepath)
else:
Thread(target=_, args=(url, savepath)).start()
return None
def vndbdowloadinfo(vid):
cookies = {
"vndb_samesite": "1",
}
headers = {
"authority": "vndb.org",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
"sec-ch-ua": '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42",
}
url = "https://vndb.org/" + vid
os.makedirs("./cache/vndb", exist_ok=True)
savepath = "./cache/vndb/" + b64string(url) + ".html"
# print(url,savepath)
if not os.path.exists(savepath):
try:
time.sleep(1)
response = requests.get(
url, cookies=cookies, headers=headers, proxies=getproxy()
)
with open(savepath, "w", encoding="utf8") as ff:
ff.write(response.text)
except:
return None
return savepath
def safegetvndbjson(url, json, getter):
try: try:
print(url, json) print(url, json)
_ = requests.post( _ = requests.post(
url, url,
json=json, json=json,
proxies=getproxy(), proxies=proxy,
) )
print(_.text) print(_.text)
try: try:
@ -94,7 +25,7 @@ def safegetvndbjson(url, json, getter):
return None return None
def gettitlebyid(vid): def gettitlebyid(proxy, vid):
def _getter(js): def _getter(js):
try: try:
@ -110,13 +41,14 @@ def gettitlebyid(vid):
return js["results"][0]["title"] return js["results"][0]["title"]
return safegetvndbjson( return safegetvndbjson(
proxy,
"https://api.vndb.org/kana/vn", "https://api.vndb.org/kana/vn",
{"filters": ["id", "=", vid], "fields": "title,titles.title,titles.main"}, {"filters": ["id", "=", vid], "fields": "title,titles.title,titles.main"},
_getter, _getter,
) )
def getscreenshotsbyid(vid): def getscreenshotsbyid(proxy, vid):
def _getter(js): def _getter(js):
___ = [] ___ = []
@ -126,30 +58,34 @@ def getscreenshotsbyid(vid):
return ___ return ___
return safegetvndbjson( return safegetvndbjson(
proxy,
"https://api.vndb.org/kana/vn", "https://api.vndb.org/kana/vn",
{"filters": ["id", "=", vid], "fields": "screenshots.url"}, {"filters": ["id", "=", vid], "fields": "screenshots.url"},
_getter, _getter,
) )
def getimgbyid(vid): def getimgbyid(proxy, vid):
return safegetvndbjson( return safegetvndbjson(
proxy,
"https://api.vndb.org/kana/vn", "https://api.vndb.org/kana/vn",
{"filters": ["id", "=", vid], "fields": "image.url"}, {"filters": ["id", "=", vid], "fields": "image.url"},
lambda js: js["results"][0]["image"]["url"], lambda js: js["results"][0]["image"]["url"],
) )
def getvidbytitle_vn(title): def getvidbytitle_vn(proxy, title):
return safegetvndbjson( return safegetvndbjson(
proxy,
"https://api.vndb.org/kana/vn", "https://api.vndb.org/kana/vn",
{"filters": ["search", "=", title], "fields": "id", "sort": "searchrank"}, {"filters": ["search", "=", title], "fields": "id", "sort": "searchrank"},
lambda js: js["results"][0]["id"], lambda js: js["results"][0]["id"],
) )
def getvidbytitle_release(title): def getvidbytitle_release(proxy, title):
return safegetvndbjson( return safegetvndbjson(
proxy,
"https://api.vndb.org/kana/release", "https://api.vndb.org/kana/release",
{ {
"filters": ["search", "=", title], "filters": ["search", "=", title],
@ -160,7 +96,7 @@ def getvidbytitle_release(title):
) )
def getdevelopersbyid(vid): def getdevelopersbyid(proxy, vid):
def _js(js): def _js(js):
_ = [] _ = []
@ -171,6 +107,7 @@ def getdevelopersbyid(vid):
return _ return _
name = safegetvndbjson( name = safegetvndbjson(
proxy,
"https://api.vndb.org/kana/vn", "https://api.vndb.org/kana/vn",
{"filters": ["id", "=", vid], "fields": "developers.name,developers.original"}, {"filters": ["id", "=", vid], "fields": "developers.name,developers.original"},
_js, _js,
@ -178,15 +115,16 @@ def getdevelopersbyid(vid):
return name return name
def getvidbytitle(title): def getidbytitle_(proxy, title):
vid = getvidbytitle_vn(title) vid = getvidbytitle_vn(proxy, title)
if vid: if vid:
return vid return vid
return getvidbytitle_release(title) return getvidbytitle_release(proxy, title)
def getcharnamemapbyid(vid): def getcharnamemapbyid(proxy, vid):
res = safegetvndbjson( res = safegetvndbjson(
proxy,
"https://api.vndb.org/kana/character", "https://api.vndb.org/kana/character",
{ {
"filters": [ "filters": [
@ -213,11 +151,11 @@ def decompress_gzip_file(gzip_file, output_file):
shutil.copyfileobj(f_in, f_out) shutil.copyfileobj(f_in, f_out)
def safedownload(): def safedownload(proxy):
try: try:
resp = requests.get( resp = requests.get(
"https://dl.vndb.org/dump/vndb-tags-latest.json.gz", "https://dl.vndb.org/dump/vndb-tags-latest.json.gz",
proxies=getproxy(), proxies=proxy,
) )
os.makedirs("cache/temp", exist_ok=True) os.makedirs("cache/temp", exist_ok=True)
with open("cache/temp/vndb-tags-latest.json.gz", "wb") as ff: with open("cache/temp/vndb-tags-latest.json.gz", "wb") as ff:
@ -241,7 +179,7 @@ def safedownload():
return None return None
def getvntagsbyid(vid): def getvntagsbyid(proxy, vid):
res = safegetvndbjson( res = safegetvndbjson(
"https://api.vndb.org/kana/vn", "https://api.vndb.org/kana/vn",
@ -258,44 +196,26 @@ def getvntagsbyid(vid):
if not res: if not res:
return return
tags = [] tags = []
vndbtagdata = tryreadconfig("vndbtagdata.json")
changed = False
try: try:
for r in res: for r in res:
tag = r["id"] tag = r["id"]
if tag not in vndbtagdata: if tag not in vndbtagdata and not changed:
js = safedownload() js = safedownload(proxy)
if js: if js:
vndbtagdata.update(js) vndbtagdata.update(js)
changed = True
tags.append(r["id"]) if tag not in vndbtagdata:
continue
tags.append(vndbtagdata[r["id"]])
except: except:
pass pass
if changed:
safesave("./userconfig/vndbtagdata.json", vndbtagdata)
return tags return tags
def searchfordata(vid):
os.makedirs("./cache/vndb", exist_ok=True)
vid = "v{}".format(vid)
img = getimgbyid(vid)
title = gettitlebyid(vid)
namemap = getcharnamemapbyid(vid)
vndbtags = getvntagsbyid(vid)
developers = getdevelopersbyid(vid)
try:
imagepath_much2 = [vndbdownloadimg(_) for _ in getscreenshotsbyid(vid)]
except:
imagepath_much2 = []
return {
"namemap": namemap,
"title": title,
"infopath": vndbdowloadinfo(vid),
"imagepath": vndbdownloadimg(img),
"imagepath_much2": imagepath_much2,
"vndbtags": vndbtags,
"developers": developers,
}
import re import re
@ -324,8 +244,70 @@ def parsehtmlmethod(infopath):
text, text,
) )
with open(resavepath, "w", encoding="utf8") as ff: with open(resavepath, "w", encoding="utf8") as ff:
ff.write(text) ff.write(text)
return resavepath return resavepath
def gettagfromhtml(path):
if path and os.path.exists(path):
with open(path, "r", encoding="utf8") as ff:
html = ff.read()
find = re.search('<div id="vntags">([\\s\\S]*?)</div>', html)
if find:
html = find.groups()[0]
return [_[1] for _ in re.findall("<a(.*?)>(.*?)</a>", html)]
return []
class searcher(common):
def refmainpage(self, _id):
return f"https://vndb.org/v{_id}"
def getidbytitle(self, title):
vid = getidbytitle_(self.proxy, title)
if vid:
return int(vid[1:])
return None
def searchfordata(self, vid):
os.makedirs("./cache/vndb", exist_ok=True)
vid = "v{}".format(vid)
img = getimgbyid(self.proxy, vid)
title = gettitlebyid(self.proxy, vid)
namemap = getcharnamemapbyid(self.proxy, vid)
vndbtags = [] # getvntagsbyid(self.proxy, vid) #这个东西谜之慢
if len(vndbtags) == 0:
# 没代理时下不动那个tag的json
vndbtags = gettagfromhtml(
self.dispatchdownloadtask(
self.refmainpage(vid), ishtml=True, delay=False
)
)
developers = getdevelopersbyid(self.proxy, vid)
try:
imagepath_much2 = [
self.dispatchdownloadtask(_)
for _ in getscreenshotsbyid(self.proxy, vid)
]
except:
imagepath_much2 = []
_image = self.dispatchdownloadtask(img)
__ = []
if _image:
__.append(_image)
__ += imagepath_much2
return {
"namemap": namemap,
"title": title,
"infopath": parsehtmlmethod(
self.dispatchdownloadtask(
self.refmainpage(vid), ishtml=True, delay=False
)
),
"imagepath_all": __,
"webtags": vndbtags,
"developers": developers,
}

View File

@ -20,9 +20,39 @@ from myutils.config import (
from ctypes import c_float, pointer, c_void_p from ctypes import c_float, pointer, c_void_p
import threading import threading
import re, heapq, winsharedutils import re, heapq, winsharedutils
from myutils.vndb import searchfordata, getvidbytitle
from myutils.wrapper import tryprint from myutils.wrapper import tryprint
def findenclose(text, tag):
i = 0
tags = f"<{tag}"
tage = f"</{tag}>"
collect = ""
__ = 0
while True:
if text.startswith(tags):
i += 1
text = text[len(tags) :]
collect += tags
elif text.startswith(tage):
i -= 1
text = text[len(tage) :]
collect += tage
else:
collect += text[0]
text = text[1:]
if i == 0:
break
return collect
def simplehtmlparser(text, tag, sign):
text = text[text.find(sign) :]
inner = findenclose(text, tag)
return inner
def nowisdark(): def nowisdark():
dl = globalconfig["darklight"] dl = globalconfig["darklight"]
if dl == 0: if dl == 0:
@ -33,6 +63,7 @@ def nowisdark():
dark = winsharedutils.isDark() dark = winsharedutils.isDark()
return dark return dark
def getimageformatlist(): def getimageformatlist():
_ = [_.data().decode() for _ in QImageWriter.supportedImageFormats()] _ = [_.data().decode() for _ in QImageWriter.supportedImageFormats()]
if globalconfig["imageformat"] == -1 or globalconfig["imageformat"] >= len(_): if globalconfig["imageformat"] == -1 or globalconfig["imageformat"] >= len(_):
@ -67,12 +98,6 @@ class PriorityQueue:
searchvndbqueue = PriorityQueue() searchvndbqueue = PriorityQueue()
def checkimage(gamepath):
return (savehook_new_data[gamepath]["imagepath"] is None) or (
os.path.exists(savehook_new_data[gamepath]["imagepath"]) == False
)
def checkinfo(gamepath): def checkinfo(gamepath):
return (savehook_new_data[gamepath]["infopath"] is None) or ( return (savehook_new_data[gamepath]["infopath"] is None) or (
(savehook_new_data[gamepath]["infopath"][:4].lower() != "http") (savehook_new_data[gamepath]["infopath"][:4].lower() != "http")
@ -82,120 +107,146 @@ def checkinfo(gamepath):
def checkvid(gamepath): def checkvid(gamepath):
return ( return checkinfo(gamepath) or (
checkimage(gamepath) (len(savehook_new_data[gamepath]["webtags"]) == 0)
or checkinfo(gamepath) and (len(savehook_new_data[gamepath]["developers"]) == 0)
or (
(len(savehook_new_data[gamepath]["vndbtags"]) == 0)
and (len(savehook_new_data[gamepath]["developers"]) == 0)
)
) )
def dispatachtask(gamepath): def guessmaybetitle(gamepath):
__t = [] __t = []
if savehook_new_data[gamepath]["vid"]:
if not checkvid(gamepath): print(gamepath)
return for _ in [
print(gamepath) savehook_new_data[gamepath]["title"],
searchvndbqueue.put((1, gamepath, savehook_new_data[gamepath]["vid"])) os.path.basename(os.path.dirname(gamepath)),
else: os.path.basename(gamepath)[:-4],
if ( ]:
time.time() _ = _.replace("(同人ゲーム)", "").replace("(18禁ゲーム)", "")
< savehook_new_data[gamepath]["searchnoresulttime"] + 3600 * 24 * 7 _ = re.sub(r"\[RJ(.*?)\]", "", _)
): _ = re.sub(r"\[\d{4}-?\d{2}\-?\d{2}\]", "", _)
return __t.append(_)
print(gamepath) _ = re.sub(r"\[(.*?)\]", "", _)
for _ in [ if _ != __t[-1]:
savehook_new_data[gamepath]["title"],
os.path.basename(os.path.dirname(gamepath)),
os.path.basename(gamepath)[:-4],
]:
_ = _.replace("(同人ゲーム)", "").replace("(18禁ゲーム)", "")
_ = re.sub(r"\[RJ(.*?)\]", "", _)
_ = re.sub(r"\[\d{4}-?\d{2}\-?\d{2}\]", "", _)
__t.append(_) __t.append(_)
_ = re.sub(r"\[(.*?)\]", "", _) _ = re.sub(r"\((.*?)\)", "", _)
if _ != __t[-1]: if _ != __t[-1]:
__t.append(_) __t.append(_)
_ = re.sub(r"\((.*?)\)", "", _) lst = []
if _ != __t[-1]: for i, t in enumerate(__t):
__t.append(_) t = t.strip()
lst = [] if t in lst:
for i, t in enumerate(__t): continue
t = t.strip() if (len(t) < 10) and (all(ord(c) < 128 for c in t)):
if t in lst: continue
continue lst.append(t)
if (len(t) < 10) and (all(ord(c) < 128 for c in t)): return lst
continue
lst.append(t)
searchvndbqueue.put((0, gamepath, lst))
def parsetask(_type, gamepath, arg): targetmod = {}
if _type == 2: for k in globalconfig["metadata"]:
dispatachtask(gamepath) targetmod[k] = importlib.import_module(f"myutils.metadata.{k}").searcher(k)
elif _type == 0:
searchargs = arg
def trysearchforid(gamepath, searchargs: list):
infoid = None
primitivtemetaorigin = globalconfig["primitivtemetaorigin"]
__ = list(targetmod.keys())
if primitivtemetaorigin not in __:
primitivtemetaorigin = __[0]
__.remove(primitivtemetaorigin)
__.insert(0, primitivtemetaorigin)
for key in __:
vid = None vid = None
for arg in searchargs: for arg in searchargs:
vid = getvidbytitle(arg) vid = targetmod[key].getidbytitle(arg)
if vid: if vid:
break break
if not vid: if not vid:
return continue
savehook_new_data[gamepath]["vid"] = int(vid[1:]) idname = globalconfig["metadata"][key]["target"]
savehook_new_data[gamepath]["searchnoresulttime"] = time.time() savehook_new_data[gamepath][idname] = vid
searchvndbqueue.put((1, gamepath, int(vid[1:]))) if infoid is None or key == primitivtemetaorigin:
infoid = key, vid
if key == primitivtemetaorigin:
break
if infoid:
searchvndbqueue.put((1, gamepath, infoid))
def trysearchfordata(gamepath, arg):
key, vid = arg
try:
data = targetmod[key].searchfordata(vid)
except:
data = {}
infopath = data.get("infopath", None)
title = data.get("title", None)
namemap = data.get("namemap", None)
developers = data.get("developers", [])
webtags = data.get("webtags", [])
imagepath_all = data.get("imagepath_all", [])
for _ in imagepath_all:
if _ is None:
continue
if _ not in savehook_new_data[gamepath]["imagepath_all"]:
savehook_new_data[gamepath]["imagepath_all"].append(_)
if title and (not savehook_new_data[gamepath]["istitlesetted"]):
savehook_new_data[gamepath]["title"] = title
if infopath:
savehook_new_data[gamepath]["infopath"] = infopath
if namemap:
savehook_new_data[gamepath]["namemap"] = namemap
if len(webtags):
savehook_new_data[gamepath]["webtags"] = webtags
if len(developers):
savehook_new_data[gamepath]["developers"] = developers
def parsetask(_type, gamepath, arg):
if _type == 0:
trysearchforid(gamepath, arg)
elif _type == 1: elif _type == 1:
vid = arg trysearchforid(gamepath, arg)
data = searchfordata(vid)
imagepath = data.get("imagepath", None)
infopath = data.get("infopath", None)
title = data.get("title", None)
namemap = data.get("namemap", None)
developers = data.get("developers", None)
vndbtags = data.get("vndbtags", None)
imagepath_much2=data.get('imagepath_much2',[])
if imagepath and (not savehook_new_data[gamepath]["isimagepathusersetted"]):
savehook_new_data[gamepath]["imagepath"] = imagepath
if len(imagepath_much2) and (not savehook_new_data[gamepath]["isimagepathusersetted_much"]):
savehook_new_data[gamepath]["imagepath_much2"] = imagepath_much2
if title and (not savehook_new_data[gamepath]["istitlesetted"]):
savehook_new_data[gamepath]["title"] = title
if infopath:
savehook_new_data[gamepath]["infopath"] = infopath
if namemap:
savehook_new_data[gamepath]["namemap"] = namemap
if vndbtags:
savehook_new_data[gamepath]["vndbtags"] = vndbtags
if developers:
savehook_new_data[gamepath]["developers"] = developers
def everymethodsthread(): def everymethodsthread():
while True: while True:
_ = searchvndbqueue.get() _ = searchvndbqueue.get()
_type, gamepath, arg = _ _type, gamepath, arg = _
tryprint(parsetask)(_type, gamepath, arg) try:
if _type == 0:
trysearchforid(gamepath, arg)
elif _type == 1:
trysearchfordata(gamepath, arg)
except:
print_exc()
threading.Thread(target=everymethodsthread).start() threading.Thread(target=everymethodsthread).start()
def vidchangedtask(gamepath, vid): def gamdidchangedtask(key, idname, gamepath):
try: vid = savehook_new_data[gamepath][idname]
vid = int(vid) if vid == "":
except:
return return
else:
savehook_new_data[gamepath]["isimagepathusersetted_much"] = False try:
savehook_new_data[gamepath]["isimagepathusersetted"] = False if globalconfig["metadata"][key]["idtype"] == 0:
savehook_new_data[gamepath]["vid"] = vid try:
searchvndbqueue.put((1, gamepath, vid), 1) vid = int(vid)
except:
print(vid)
return
savehook_new_data[gamepath][idname] = vid
searchvndbqueue.put((1, gamepath, (key, vid)), 1)
except:
print_exc()
def titlechangedtask(gamepath, title): def titlechangedtask(gamepath, title):
@ -205,14 +256,14 @@ def titlechangedtask(gamepath, title):
def checkifnewgame(targetlist, gamepath, title=None): def checkifnewgame(targetlist, gamepath, title=None):
if gamepath in targetlist: isnew = gamepath in targetlist
return False if not isnew:
targetlist.insert(0, gamepath) targetlist.insert(0, gamepath)
if gamepath not in savehook_new_data: if gamepath not in savehook_new_data:
savehook_new_data[gamepath] = getdefaultsavehook(gamepath, title) savehook_new_data[gamepath] = getdefaultsavehook(gamepath, title)
searchvndbqueue.put((2, gamepath, None)) searchvndbqueue.put((0, gamepath, [title] + guessmaybetitle(gamepath)))
return True return isnew
kanjichs2ja = str.maketrans(static_data["kanjichs2ja"]) kanjichs2ja = str.maketrans(static_data["kanjichs2ja"])

View File

@ -29,7 +29,7 @@ class OCR(baseocr):
self.config["API Key"], self.config["API Key"],
self.config["Secret Key"], self.config["Secret Key"],
) )
self.accstoken = self.session.get( self.accstoken = self.proxysession.get(
"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="
+ self.appid + self.appid
+ "&client_secret=" + "&client_secret="
@ -73,7 +73,7 @@ class OCR(baseocr):
"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic", "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic",
"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate", "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate",
][interfacetype] ][interfacetype]
response = self.session.post(url, params=params, headers=headers, data=data) response = self.proxysession.post(url, params=params, headers=headers, data=data)
try: try:
self.countnum() self.countnum()

View File

@ -67,7 +67,7 @@ class OCR(baseocr):
headers = { headers = {
"content-type": "multipart/form-data; boundary=6d94758aed493e27c73620d74ff01fc4", "content-type": "multipart/form-data; boundary=6d94758aed493e27c73620d74ff01fc4",
} }
response = self.session.post(url, params=payload, headers=headers, data=data) response = self.proxysession.post(url, params=payload, headers=headers, data=data)
try: try:
js = response.json() js = response.json()

View File

@ -33,7 +33,7 @@ class OCR(baseocr):
+ "\r\n------WebKitFormBoundaryUjYOv45hug6CFh3t--\r\n".encode("latin-1") + "\r\n------WebKitFormBoundaryUjYOv45hug6CFh3t--\r\n".encode("latin-1")
) )
response = self.session.post( response = self.proxysession.post(
"https://ocrserver.docsumo.com/api/v1/ocr/extract/", "https://ocrserver.docsumo.com/api/v1/ocr/extract/",
headers=headers, headers=headers,
data=data, data=data,

View File

@ -12,7 +12,7 @@ class OCR(baseocr):
app_id = self.config["app_id"] app_id = self.config["app_id"]
app_secret = self.config["app_secret"] app_secret = self.config["app_secret"]
if (app_id, app_secret) not in self.tokens: if (app_id, app_secret) not in self.tokens:
res = self.session.post( res = self.proxysession.post(
"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
headers={"Content-Type": "application/json; charset=utf-8"}, headers={"Content-Type": "application/json; charset=utf-8"},
json={"app_id": app_id, "app_secret": app_secret}, json={"app_id": app_id, "app_secret": app_secret},
@ -27,7 +27,7 @@ class OCR(baseocr):
def ocr(self, imagebinary): def ocr(self, imagebinary):
token = self.check() token = self.check()
b64 = base64.b64encode(imagebinary) b64 = base64.b64encode(imagebinary)
res = self.session.post( res = self.proxysession.post(
"https://open.feishu.cn/open-apis/optical_char_recognition/v1/image/basic_recognize", "https://open.feishu.cn/open-apis/optical_char_recognition/v1/image/basic_recognize",
headers={ headers={
"Content-Type": "application/json; charset=utf-8", "Content-Type": "application/json; charset=utf-8",

View File

@ -21,7 +21,7 @@ class OCR(baseocr):
} }
] ]
} }
response = self.session.post(ocr_url, json=data) response = self.proxysession.post(ocr_url, json=data)
try: try:
boxs = [] boxs = []
texts = [] texts = []

View File

@ -48,7 +48,7 @@ class OCR(baseocr):
"apikey": apikey, "apikey": apikey,
} }
response = self.session.post( response = self.proxysession.post(
"https://" + base + "/parse/image", headers=headers, data=data "https://" + base + "/parse/image", headers=headers, data=data
) )
# print(response.text) # print(response.text)

View File

@ -55,7 +55,7 @@ class OCR(baseocr):
hashed = hmac.new(key, raw, sha1) hashed = hmac.new(key, raw, sha1)
b64output = base64.encodebytes(hashed.digest()).decode("utf-8") b64output = base64.encodebytes(hashed.digest()).decode("utf-8")
req_para.update({"Signature": b64output}) req_para.update({"Signature": b64output})
r = self.session.get( r = self.proxysession.get(
url="https://ocr.tencentcloudapi.com/", params=req_para, timeout=10 url="https://ocr.tencentcloudapi.com/", params=req_para, timeout=10
) )
# print(r.text) # print(r.text)

View File

@ -103,7 +103,7 @@ class OCR(baseocr):
+ signature + signature
) )
r = self.session.post( r = self.proxysession.post(
url="https://tmt.tencentcloudapi.com", url="https://tmt.tencentcloudapi.com",
headers={ headers={
"Authorization": authorization, "Authorization": authorization,

View File

@ -120,7 +120,7 @@ class OCR(baseocr):
# print("request_url:", request_url) # print("request_url:", request_url)
body = printed_word_recognition.get_body(file_path=imagebinary) body = printed_word_recognition.get_body(file_path=imagebinary)
response = self.session.post( response = self.proxysession.post(
request_url, data=json.dumps(body), headers=headers request_url, data=json.dumps(body), headers=headers
) )

View File

@ -33,7 +33,7 @@ class OCR(baseocr):
"company": "", "company": "",
} }
response = self.session.post( response = self.proxysession.post(
"https://aidemo.youdao.com/ocrapi1", headers=headers, data=data "https://aidemo.youdao.com/ocrapi1", headers=headers, data=data
) )
@ -82,7 +82,7 @@ class OCR(baseocr):
data["sign"] = sign data["sign"] = sign
headers = {"Content-Type": "application/x-www-form-urlencoded"} headers = {"Content-Type": "application/x-www-form-urlencoded"}
response = self.session.post(YOUDAO_URL, data=data, headers=headers) response = self.proxysession.post(YOUDAO_URL, data=data, headers=headers)
self.countnum() self.countnum()
try: try:
_ = [] _ = []

View File

@ -33,7 +33,7 @@ class OCR(baseocr):
"company": "", "company": "",
} }
response = self.session.post( response = self.proxysession.post(
"https://aidemo.youdao.com/ocrtransapi1", headers=headers, data=data "https://aidemo.youdao.com/ocrtransapi1", headers=headers, data=data
) )
@ -134,9 +134,9 @@ class OCR(baseocr):
def doCall(url, header, params, method): def doCall(url, header, params, method):
if "get" == method: if "get" == method:
return self.session.get(url, params) return self.proxysession.get(url, params)
elif "post" == method: elif "post" == method:
return self.session.post(url, params, header) return self.proxysession.post(url, params, header)
def readFileAsBase64(imagebinary): def readFileAsBase64(imagebinary):
return str(base64.b64encode(imagebinary), "utf-8") return str(base64.b64encode(imagebinary), "utf-8")

View File

@ -17,7 +17,7 @@ class TS(basetrans):
"target_lang": self.tgtlang, "target_lang": self.tgtlang,
} }
response = self.session.post(self.config["api"], json=payload) response = self.proxysession.post(self.config["api"], json=payload)
try: try:
return response.json()["data"] return response.json()["data"]

View File

@ -8,7 +8,7 @@ class TS(basetrans):
def inittranslator(self): def inittranslator(self):
self.session.get( self.proxysession.get(
"https://translate.alibaba.com", "https://translate.alibaba.com",
headers={ headers={
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
@ -34,7 +34,7 @@ class TS(basetrans):
}, },
).text ).text
self.csrf = self.session.get( self.csrf = self.proxysession.get(
"https://translate.alibaba.com/api/translate/csrftoken" "https://translate.alibaba.com/api/translate/csrftoken"
).json()["token"] ).json()["token"]
@ -69,7 +69,7 @@ class TS(basetrans):
"query": content, "query": content,
"_csrf": self.csrf, "_csrf": self.csrf,
} }
r = self.session.post( r = self.proxysession.post(
"https://translate.alibaba.com/api/translate/text", "https://translate.alibaba.com/api/translate/text",
headers=headers, headers=headers,
params=form_data, params=form_data,

View File

@ -53,7 +53,7 @@ class TS(basetrans):
"x-acs-signature-method": "HMAC-SHA1", "x-acs-signature-method": "HMAC-SHA1",
"x-acs-version": "2019-01-02", "x-acs-version": "2019-01-02",
} }
request = self.session.post(url, headers=headers, data=req_body) request = self.proxysession.post(url, headers=headers, data=req_body)
try: try:
response = request.json() response = request.json()
return response["Data"]["Translated"] return response["Data"]["Translated"]

View File

@ -30,7 +30,7 @@ class TS(basetrans):
# You can pass more than one object in body. # You can pass more than one object in body.
body = [{"text": query}] body = [{"text": query}]
request = self.session.post( request = self.proxysession.post(
constructed_url, params=params, headers=headers, json=body constructed_url, params=params, headers=headers, json=body
) )
response = request.json() response = request.json()

View File

@ -22,7 +22,7 @@ class TS(basetrans):
"sec-ch-ua-mobile": "?0", "sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"', "sec-ch-ua-platform": '"Windows"',
} }
self.session.get( self.proxysession.get(
"https://fanyi.baidu.com/mtpe-individual/multimodal#/", headers=headers "https://fanyi.baidu.com/mtpe-individual/multimodal#/", headers=headers
) )
@ -74,7 +74,7 @@ class TS(basetrans):
"milliTimestamp": int(time.time() * 1000), "milliTimestamp": int(time.time() * 1000),
} }
response = self.session.post( response = self.proxysession.post(
"https://fanyi.baidu.com/ait/text/translate", "https://fanyi.baidu.com/ait/text/translate",
headers=headers, headers=headers,
json=json_data, json=json_data,

View File

@ -47,7 +47,7 @@ class TS(basetrans):
+ sign + sign
) )
res = self.session.get("https://api.fanyi.baidu.com" + myurl) res = self.proxysession.get("https://api.fanyi.baidu.com" + myurl)
try: try:
_ = "\n".join([_["dst"] for _ in res.json()["trans_result"]]) _ = "\n".join([_["dst"] for _ in res.json()["trans_result"]])

View File

@ -61,12 +61,12 @@ class TS(basetrans):
json_data = { json_data = {
"browser_id": self.bid, "browser_id": self.bid,
} }
self.session.options( self.proxysession.options(
"https://api.interpreter.caiyunai.com/v1/user/jwt/generate", "https://api.interpreter.caiyunai.com/v1/user/jwt/generate",
headers=headers, headers=headers,
json=json_data, json=json_data,
) )
self.jwt = self.session.post( self.jwt = self.proxysession.post(
"https://api.interpreter.caiyunai.com/v1/user/jwt/generate", "https://api.interpreter.caiyunai.com/v1/user/jwt/generate",
headers=headers, headers=headers,
json=json_data, json=json_data,
@ -108,12 +108,12 @@ class TS(basetrans):
"detect": True, "detect": True,
"browser_id": self.bid, "browser_id": self.bid,
} }
self.session.options( self.proxysession.options(
"https://api.interpreter.caiyunai.com/v1/translator", "https://api.interpreter.caiyunai.com/v1/translator",
headers=headers, headers=headers,
json=json_data, json=json_data,
) )
response = self.session.post( response = self.proxysession.post(
"https://api.interpreter.caiyunai.com/v1/translator", "https://api.interpreter.caiyunai.com/v1/translator",
headers=headers, headers=headers,
json=json_data, json=json_data,

View File

@ -22,7 +22,7 @@ class TS(basetrans):
"content-type": "application/json", "content-type": "application/json",
"x-authorization": "token " + token, "x-authorization": "token " + token,
} }
response = self.session.request( response = self.proxysession.request(
"POST", url, data=json.dumps(payload), headers=headers "POST", url, data=json.dumps(payload), headers=headers
) )
try: try:

View File

@ -88,7 +88,7 @@ class TS(basetrans):
temperature=temperature, temperature=temperature,
stream=usingstream, stream=usingstream,
) )
response = self.session.post( response = self.proxysession.post(
self.checkv1(self.config["BASE_URL"]) + "/messages", self.checkv1(self.config["BASE_URL"]) + "/messages",
headers=headers, headers=headers,
json=data, json=data,

View File

@ -124,7 +124,7 @@ class TS(basetrans):
temperature=temperature, temperature=temperature,
stream=usingstream, stream=usingstream,
) )
response = self.session.post( response = self.proxysession.post(
"https://api.cohere.ai/v1/chat", "https://api.cohere.ai/v1/chat",
headers=headers, headers=headers,
json=data, json=data,

View File

@ -77,7 +77,7 @@ class TS(basetrans):
"id": 3266547795, "id": 3266547795,
} }
response = self.session.post( response = self.proxysession.post(
"https://www2.deepl.com/jsonrpc?client=chrome-extension,1.11.2", "https://www2.deepl.com/jsonrpc?client=chrome-extension,1.11.2",
headers=headers, headers=headers,
json=json_data, json=json_data,

View File

@ -28,7 +28,7 @@ class TS(basetrans):
+ self.srclang + self.srclang
) )
response = self.session.post( response = self.proxysession.post(
"https://api-free.deepl.com/v2/translate", "https://api-free.deepl.com/v2/translate",
headers=headers, headers=headers,
verify=False, verify=False,

View File

@ -28,7 +28,7 @@ class TS(basetrans):
+ self.srclang + self.srclang
) )
response = self.session.post( response = self.proxysession.post(
"https://api.deepl.com/v2/translate", "https://api.deepl.com/v2/translate",
headers=headers, headers=headers,
verify=False, verify=False,

View File

@ -14,7 +14,7 @@ class TS(basetrans):
app_id = self.multiapikeycurrent["app_id"] app_id = self.multiapikeycurrent["app_id"]
app_secret = self.multiapikeycurrent["app_secret"] app_secret = self.multiapikeycurrent["app_secret"]
if (app_id, app_secret) not in self.tokens: if (app_id, app_secret) not in self.tokens:
res = self.session.post( res = self.proxysession.post(
"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
headers={"Content-Type": "application/json; charset=utf-8"}, headers={"Content-Type": "application/json; charset=utf-8"},
json={"app_id": app_id, "app_secret": app_secret}, json={"app_id": app_id, "app_secret": app_secret},
@ -29,7 +29,7 @@ class TS(basetrans):
def translate(self, query): def translate(self, query):
token = self.check() token = self.check()
res = self.session.post( res = self.proxysession.post(
"https://open.feishu.cn/open-apis/translation/v1/text/translate", "https://open.feishu.cn/open-apis/translation/v1/text/translate",
headers={ headers={
"Content-Type": "application/json; charset=utf-8", "Content-Type": "application/json; charset=utf-8",

View File

@ -86,9 +86,9 @@ class TS(basetrans):
payload= {**contents, **safety, **sys_message, **gen_config } payload= {**contents, **safety, **sys_message, **gen_config }
res = self.session.post( res = self.proxysession.post(
f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent", f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent",
params={"key": self.config["SECRET_KEY"]}, params={"key": self.multiapikeycurrent["SECRET_KEY"]},
json=payload json=payload
) )
try: try:

View File

@ -11,7 +11,7 @@ class TS(basetrans):
def inittranslator(self): def inittranslator(self):
_ = self.session.get( _ = self.proxysession.get(
"https://translate.google.com/", "https://translate.google.com/",
headers={ headers={
"authority": "translate.google.com", "authority": "translate.google.com",
@ -71,7 +71,7 @@ class TS(basetrans):
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
} }
response = self.session.post( response = self.proxysession.post(
"https://translate.google.com/_/TranslateWebserverUi/data/batchexecute", "https://translate.google.com/_/TranslateWebserverUi/data/batchexecute",
verify=False, verify=False,
headers=headers, headers=headers,

View File

@ -39,7 +39,7 @@ class TS(basetrans):
"q": content, "q": content,
} }
response = self.session.get( response = self.proxysession.get(
"https://translate.google.com/m", "https://translate.google.com/m",
params=params, params=params,
verify=False, verify=False,

View File

@ -16,7 +16,7 @@ class TS(basetrans):
"target": self.tgtlang, "target": self.tgtlang,
"q": (query), "q": (query),
} }
response = self.session.get( response = self.proxysession.get(
"https://translation.googleapis.com/language/translate/v2/", params=params "https://translation.googleapis.com/language/translate/v2/", params=params
) )

View File

@ -91,7 +91,7 @@ class gptcommon(basetrans):
frequency_penalty=self.config["frequency_penalty"], frequency_penalty=self.config["frequency_penalty"],
stream=usingstream, stream=usingstream,
) )
response = self.session.post( response = self.proxysession.post(
self.createurl(), self.createurl(),
headers=self.createheaders(), headers=self.createheaders(),
params=self.createparam(), params=self.createparam(),

View File

@ -28,7 +28,7 @@ class TS(basetrans):
"glossary_list": [], "glossary_list": [],
"category": "", "category": "",
} }
response = self.session.post( response = self.proxysession.post(
"https://translate.volcengine.com/crx/translate/v1/", "https://translate.volcengine.com/crx/translate/v1/",
headers=headers, headers=headers,
json=json_data, json=json_data,

View File

@ -12,7 +12,7 @@ class TS(basetrans):
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
data = {"text": [query], "source": self.srclang, "target": self.tgtlang} data = {"text": [query], "source": self.srclang, "target": self.tgtlang}
response = self.session.post( response = self.proxysession.post(
url, auth=("apikey", apikey), headers=headers, data=json.dumps(data) url, auth=("apikey", apikey), headers=headers, data=json.dumps(data)
) )
try: try:

View File

@ -22,7 +22,7 @@ class TS(basetrans):
def translate(self, content): def translate(self, content):
# print(self.url%(self.srclang,self.tgtlang,urllib.parse.quote(content))) # print(self.url%(self.srclang,self.tgtlang,urllib.parse.quote(content)))
x = self.session.get( x = self.proxysession.get(
"https://" "https://"
+ self.config["host"] + self.config["host"]
+ "/api/v1/%s/%s/%s" % (self.srclang, self.tgtlang, quote_plus(content)), + "/api/v1/%s/%s/%s" % (self.srclang, self.tgtlang, quote_plus(content)),

View File

@ -91,7 +91,7 @@ def translate_async(text, to_language, from_language=None, self=None):
"Content-Type": "application/json", "Content-Type": "application/json",
} }
json_data = [{"Text": text}] json_data = [{"Text": text}]
response = self.session.post( response = self.proxysession.post(
"https://{}".format(url), "https://{}".format(url),
headers=headers, headers=headers,
data=json.dumps(json_data).encode("utf-8"), data=json.dumps(json_data).encode("utf-8"),

View File

@ -22,10 +22,10 @@ class TS(basetrans):
"upgrade-insecure-requests": "1", "upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
} }
host_html = self.session.get("https://papago.naver.com/", headers=headers).text host_html = self.proxysession.get("https://papago.naver.com/", headers=headers).text
url_path = re.compile("/home.(.*?).chunk.js").search(host_html).group() url_path = re.compile("/home.(.*?).chunk.js").search(host_html).group()
self.language_url = "".join(["https://papago.naver.com", url_path]) self.language_url = "".join(["https://papago.naver.com", url_path])
lang_html = self.session.get(self.language_url, headers=headers).text lang_html = self.proxysession.get(self.language_url, headers=headers).text
self.auth_key = self.get_auth_key(lang_html) self.auth_key = self.get_auth_key(lang_html)
self.uuid = uuid.uuid4().__str__() self.uuid = uuid.uuid4().__str__()
@ -80,7 +80,7 @@ class TS(basetrans):
"text": content, "text": content,
} }
r = self.session.post( r = self.proxysession.post(
"https://papago.naver.com/apis/n2mt/translate", headers=headers, data=data "https://papago.naver.com/apis/n2mt/translate", headers=headers, data=data
) )

View File

@ -32,7 +32,7 @@ class TS(basetrans):
"target": {"lang": self.tgtlang}, "target": {"lang": self.tgtlang},
} }
response = self.session.post( response = self.proxysession.post(
"https://transmart.qq.com/api/imt", headers=headers, json=data "https://transmart.qq.com/api/imt", headers=headers, json=data
) )
return response.json()["auto_translation"] return response.json()["auto_translation"]

View File

@ -25,7 +25,7 @@ class TS(basetrans):
"sec-ch-ua-mobile": "?0", "sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"', "sec-ch-ua-platform": '"Windows"',
} }
res = self.session.get( res = self.proxysession.get(
"https://fanyi.sogou.com/text?keyword=" "https://fanyi.sogou.com/text?keyword="
+ quote(content) + quote(content)
+ "&transfrom=" + "&transfrom="

View File

@ -11,7 +11,7 @@ class TS(basetrans):
"message": "translate sentences", "message": "translate sentences",
} }
response = self.session.post(self.config["api"], json=json_data) response = self.proxysession.post(self.config["api"], json=json_data)
try: try:
return response.json() return response.json()
except: except:

View File

@ -61,7 +61,7 @@ class TS(basetrans):
data["Signature"] = sign_str(secret_key, s, hashlib.sha1) data["Signature"] = sign_str(secret_key, s, hashlib.sha1)
# 此处会实际调用,成功后可能产生计费 # 此处会实际调用,成功后可能产生计费
r = self.session.get("https://" + endpoint, params=data, timeout=3) r = self.proxysession.get("https://" + endpoint, params=data, timeout=3)
# print(r.json()) # print(r.json())
return r return r

View File

@ -28,7 +28,7 @@ class TS(basetrans):
"src_text": query, "src_text": query,
"apikey": apikey, "apikey": apikey,
} }
response = self.session.post( response = self.proxysession.post(
"https://api.niutrans.com/NiuTransServer/translation", "https://api.niutrans.com/NiuTransServer/translation",
headers=headers, headers=headers,
params=params, params=params,

View File

@ -16,7 +16,7 @@ class TS(basetrans):
"text": content, "text": content,
} }
response = self.session.get(url, params=params) response = self.proxysession.get(url, params=params)
try: try:
return response.json()["text"][0] return response.json()["text"][0]

View File

@ -45,9 +45,9 @@ class TS(basetrans):
} }
# proxies = { "http": None, "https": None} # proxies = { "http": None, "https": None}
self.session.trust_env = False self.proxysession.trust_env = False
self.session.headers.update(self.headers) self.proxysession.headers.update(self.headers)
self.session.get("https://fanyi.youdao.com") self.proxysession.get("https://fanyi.youdao.com")
def translate(self, content): def translate(self, content):
@ -91,7 +91,7 @@ class TS(basetrans):
"sec-ch-ua-mobile": "?0", "sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"', "sec-ch-ua-platform": '"Windows"',
} }
response = self.session.post( response = self.proxysession.post(
"https://fanyi.youdao.com/translate_o", "https://fanyi.youdao.com/translate_o",
params=params, params=params,
headers=headers, headers=headers,

View File

@ -14,7 +14,7 @@ class TS(basetrans):
} }
def inittranslator(self): def inittranslator(self):
self.session.get( self.proxysession.get(
"https://m.youdao.com/translate", "https://m.youdao.com/translate",
headers={ headers={
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
@ -61,7 +61,7 @@ class TS(basetrans):
"sec-ch-ua-platform": '"Windows"', "sec-ch-ua-platform": '"Windows"',
} }
response = self.session.post( response = self.proxysession.post(
"https://m.youdao.com/translate", "https://m.youdao.com/translate",
data=data, data=data,
headers=headers, headers=headers,

View File

@ -22,9 +22,9 @@ class TS(basetrans):
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
} }
self.session.trust_env = False self.proxysession.trust_env = False
self.session.headers.update(self.headers) self.proxysession.headers.update(self.headers)
self.session.get("https://ai.youdao.com/product-fanyi-text.s") self.proxysession.get("https://ai.youdao.com/product-fanyi-text.s")
def translate(self, content): def translate(self, content):
@ -50,7 +50,7 @@ class TS(basetrans):
"to": self.tgtlang, "to": self.tgtlang,
} }
response = self.session.post( response = self.proxysession.post(
"https://aidemo.youdao.com/trans", data=data, headers=headers "https://aidemo.youdao.com/trans", data=data, headers=headers
) )
try: try:

View File

@ -41,7 +41,7 @@ class TS(basetrans):
"signType": "v3", # 签名类型,固定值 "signType": "v3", # 签名类型,固定值
"curtime": time_curtime, # 秒级时间戳 "curtime": time_curtime, # 秒级时间戳
} }
r = self.session.get(youdao_url, params=data) # 获取返回的json()内容 r = self.proxysession.get(youdao_url, params=data) # 获取返回的json()内容
try: try:
self.countnum(content) self.countnum(content)

View File

@ -118,7 +118,7 @@ class TS(basetrans):
"appVersion": "8.10.8.0", "appVersion": "8.10.8.0",
"product": "deskdict", "product": "deskdict",
} }
response = self.session.post( response = self.proxysession.post(
"https://dict.youdao.com/dicttranslate", "https://dict.youdao.com/dicttranslate",
params=param, params=param,
cookies=cookies, cookies=cookies,

View File

@ -25,7 +25,7 @@ class TS(basetrans):
"sec-ch-ua-platform": '"Windows"', "sec-ch-ua-platform": '"Windows"',
} }
response = self.session.post( response = self.proxysession.post(
"https://online.cloudtranslation.com/api/v1.0/request_translate/try_translate", "https://online.cloudtranslation.com/api/v1.0/request_translate/try_translate",
data={ data={
"type": "text", "type": "text",

View File

@ -2,9 +2,12 @@ from myutils.config import globalconfig
import threading, os, functools import threading, os, functools
from myutils.wrapper import threader from myutils.wrapper import threader
from traceback import print_exc from traceback import print_exc
from myutils.proxy import getproxy
class TTSbase: class TTSbase:
typename = None
def init(self): def init(self):
pass pass
@ -19,6 +22,10 @@ class TTSbase:
#################### ####################
# 一些可能需要的属性 # 一些可能需要的属性
@property
def proxy(self):
return getproxy(("reader", self.typename))
@property @property
def config(self): def config(self):
return self.privateconfig["args"] return self.privateconfig["args"]

View File

@ -1,5 +1,4 @@
import requests import requests
from myutils.proxy import getproxy
import websocket import websocket
from datetime import datetime from datetime import datetime
@ -17,12 +16,12 @@ class TTS(TTSbase):
def getvoicelist(self): def getvoicelist(self):
self.alllist = requests.get( self.alllist = requests.get(
"https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=6A5AA1D4EAFF4E9FB37E23D68491D6F4", "https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=6A5AA1D4EAFF4E9FB37E23D68491D6F4",
proxies=getproxy(), proxies=self.proxy,
).json() ).json()
return [_["ShortName"] for _ in self.alllist] return [_["ShortName"] for _ in self.alllist]
def speak(self, content, rate, voice, voiceidx): def speak(self, content, rate, voice, voiceidx):
return transferMsTTSData(rate, content, voice) return transferMsTTSData(rate, content, voice, self.proxy)
# Fix the time to match Americanisms # Fix the time to match Americanisms
@ -123,7 +122,7 @@ def connect_id() -> str:
return str(uuid.uuid4()).replace("-", "") return str(uuid.uuid4()).replace("-", "")
def transferMsTTSData(rate, content, voice): def transferMsTTSData(rate, content, voice, proxy):
endpoint2 = "wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=6A5AA1D4EAFF4E9FB37E23D68491D6F4" endpoint2 = "wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=6A5AA1D4EAFF4E9FB37E23D68491D6F4"
headers = { headers = {
@ -144,7 +143,7 @@ def transferMsTTSData(rate, content, voice):
"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"
" (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.41", " (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.41",
] ]
proxy = getproxy()["https"] proxy = proxy["https"]
if proxy: if proxy:
ip, port = proxy.split(":") ip, port = proxy.split(":")

View File

@ -4,7 +4,6 @@ import json, time
import logging, os import logging, os
import re import re
import urllib import urllib
from myutils.proxy import getproxy
import requests import requests
_langs = { _langs = {
@ -379,6 +378,7 @@ class gTTS:
def __init__( def __init__(
self, self,
ref,
text, text,
tld="com", tld="com",
lang="en", lang="en",
@ -400,7 +400,7 @@ class gTTS:
).run, ).run,
timeout=None, timeout=None,
): ):
self.ref = ref
# Debug # Debug
for k, v in dict(locals()).items(): for k, v in dict(locals()).items():
if k == "self": if k == "self":
@ -492,7 +492,7 @@ class gTTS:
url=translate_url, url=translate_url,
data=data, data=data,
headers=self.GOOGLE_TTS_HEADERS, headers=self.GOOGLE_TTS_HEADERS,
proxies=getproxy(), proxies=self.ref.proxy,
) )
# Prepare request # Prepare request
@ -597,6 +597,7 @@ class gTTSError(Exception):
from tts.basettsclass import TTSbase from tts.basettsclass import TTSbase
from myutils.config import getlangsrc from myutils.config import getlangsrc
@ -605,5 +606,5 @@ class TTS(TTSbase):
return [""] return [""]
def speak(self, content, rate, voice, voiceidx): def speak(self, content, rate, voice, voiceidx):
tts = gTTS(content, lang=getlangsrc()) tts = gTTS(self, content, lang=getlangsrc())
return tts.save() return tts.save()

View File

@ -1,7 +1,6 @@
from traceback import print_exc from traceback import print_exc
import requests import requests
import base64 import base64
import time, os
from tts.basettsclass import TTSbase from tts.basettsclass import TTSbase
@ -43,7 +42,7 @@ class TTS(TTSbase):
"https://translate.volcengine.com/crx/tts/v1/", "https://translate.volcengine.com/crx/tts/v1/",
headers=headers, headers=headers,
json=json_data, json=json_data,
proxies={"http": None, "https": None}, proxies=self.proxy,
) )
b64 = base64.b64decode(response.json()["audio"]["data"]) b64 = base64.b64decode(response.json()["audio"]["data"])

View File

@ -36,6 +36,6 @@ class TTS(TTSbase):
"https://dict.youdao.com/dictvoice", "https://dict.youdao.com/dictvoice",
params=params, params=params,
headers=headers, headers=headers,
proxies={"http": None, "https": None}, proxies=self.proxy,
).content ).content
return response return response

View File

@ -17,6 +17,30 @@
"network": 1, "network": 1,
"hookmagpie": true, "hookmagpie": true,
"imagewrapmode": 0, "imagewrapmode": 0,
"primitivtemetaorigin": "vid",
"metadata": {
"vndb": {
"name": "vndb",
"downloadtasks": [],
"useproxy": false,
"target": "vid",
"idtype": 0
},
"dlsite": {
"name": "dlsite",
"downloadtasks": [],
"useproxy": true,
"target": "dlsiteid",
"idtype": 1
},
"bangumi": {
"name": "bangumi",
"downloadtasks": [],
"useproxy": true,
"target": "bgmsid",
"idtype": 0
}
},
"relationlinks": [ "relationlinks": [
[ [
"LunaTranslator", "LunaTranslator",
@ -715,7 +739,8 @@
"huoshantts": { "huoshantts": {
"use": false, "use": false,
"voice": "", "voice": "",
"name": "火山TTS" "name": "火山TTS",
"useproxy": false
}, },
"edgetts": { "edgetts": {
"use": false, "use": false,
@ -725,22 +750,26 @@
"youdaotts": { "youdaotts": {
"use": false, "use": false,
"voice": "", "voice": "",
"name": "有道TTS" "name": "有道TTS",
"useproxy": false
}, },
"windowstts": { "windowstts": {
"use": false, "use": false,
"voice": "", "voice": "",
"name": "WindowsTTS" "name": "WindowsTTS",
"type": "offline"
}, },
"NeoSpeech": { "NeoSpeech": {
"use": false, "use": false,
"voice": "", "voice": "",
"name": "NeoSpeech" "name": "NeoSpeech",
"type": "offline"
}, },
"voiceroid2": { "voiceroid2": {
"use": false, "use": false,
"voice": "", "voice": "",
"name": "VoiceRoid2/VoiceRoid+", "name": "VoiceRoid2/VoiceRoid+",
"type": "offline",
"args": { "args": {
"path": "" "path": ""
}, },
@ -756,6 +785,7 @@
"use": false, "use": false,
"voice": "", "voice": "",
"name": "VOICEVOX", "name": "VOICEVOX",
"type": "offline",
"args": { "args": {
"path": "", "path": "",
"Port": 50021 "Port": 50021
@ -779,6 +809,7 @@
"use": false, "use": false,
"voice": "", "voice": "",
"name": "vits-simple-api", "name": "vits-simple-api",
"type": "offline",
"args": { "args": {
"Port": 23456, "Port": 23456,
"preset": "" "preset": ""
@ -802,6 +833,14 @@
"voice": "" "voice": ""
} }
}, },
"github": {
"versioncheck": {
"useproxy": false
},
"download": {
"useproxy": true
}
},
"hirasetting": { "hirasetting": {
"mecab": { "mecab": {
"use": false, "use": false,
@ -824,18 +863,21 @@
"shiftjis" "shiftjis"
] ]
} }
} },
"type": "offline"
}, },
"mojinlt": { "mojinlt": {
"use": false, "use": false,
"name": "mojinlt", "name": "mojinlt",
"args": { "args": {
"Moji NLT Token": "" "Moji NLT Token": ""
} },
"useproxy": false
}, },
"latin": { "latin": {
"use": false, "use": false,
"name": "标点", "name": "标点",
"type": "offline",
"args": { "args": {
"punctuations": [ "punctuations": [
" ", " ",
@ -909,7 +951,8 @@
} }
}, },
"use": false, "use": false,
"name": "小学馆" "name": "小学馆",
"type": "offline"
}, },
"edict": { "edict": {
"use": false, "use": false,
@ -940,7 +983,8 @@
"max": 10000, "max": 10000,
"step": 1 "step": 1
} }
} },
"type": "offline"
}, },
"edict2": { "edict2": {
"use": false, "use": false,
@ -970,7 +1014,8 @@
"max": 10000, "max": 10000,
"step": 1 "step": 1
} }
} },
"type": "offline"
}, },
"linggesi": { "linggesi": {
"use": false, "use": false,
@ -1000,7 +1045,8 @@
"max": 10000, "max": 10000,
"step": 1 "step": 1
} }
} },
"type": "offline"
}, },
"mojidict": { "mojidict": {
"use": false, "use": false,
@ -1016,7 +1062,8 @@
"max": 10000, "max": 10000,
"step": 1 "step": 1
} }
} },
"useproxy": false
}, },
"youdao": { "youdao": {
"use": false, "use": false,
@ -1032,7 +1079,8 @@
"max": 10000, "max": 10000,
"step": 1 "step": 1
} }
} },
"useproxy": false
}, },
"jisho": { "jisho": {
"use": false, "use": false,
@ -1127,7 +1175,8 @@
"Flow" "Flow"
] ]
} }
} },
"type": "offline"
} }
}, },
"darklight": 0, "darklight": 0,
@ -1159,15 +1208,18 @@
"ocr": { "ocr": {
"local": { "local": {
"use": true, "use": true,
"name": "本地OCR" "name": "本地OCR",
"type": "offline"
}, },
"windowsocr": { "windowsocr": {
"use": false, "use": false,
"name": "WindowsOCR" "name": "WindowsOCR",
"type": "offline"
}, },
"tesseract5": { "tesseract5": {
"use": false, "use": false,
"name": "Tesseract5" "name": "Tesseract5",
"type": "offline"
}, },
"baiduocr_X": { "baiduocr_X": {
"use": false, "use": false,
@ -1219,7 +1271,8 @@
}, },
"mangaocr": { "mangaocr": {
"use": false, "use": false,
"name": "manga-ocr" "name": "manga-ocr",
"type": "offline"
} }
}, },
"fanyi": { "fanyi": {

View File

@ -9,7 +9,6 @@
"获取失败": "الحصول على فشل", "获取失败": "الحصول على فشل",
"助動詞": "فعل مساعد", "助動詞": "فعل مساعد",
"添加行": "إضافة صف", "添加行": "إضافة صف",
"在线OCR": "التعرف الضوئي على الحروف على الانترنت",
"图标": "أيقونات", "图标": "أيقونات",
"首选翻译": "يفضل الترجمة", "首选翻译": "يفضل الترجمة",
"移除非选定hook": "إزالة غير اختيار هوك", "移除非选定hook": "إزالة غير اختيار هوك",
@ -498,7 +497,6 @@
"云译": "سحابة ترجمة", "云译": "سحابة ترجمة",
"普通字体": "الخط العادي", "普通字体": "الخط العادي",
"3D游戏模式": "لعبة وسائط 3D", "3D游戏模式": "لعبة وسائط 3D",
"统计信息": "معلومات إحصائية",
"合并多行识别结果": "دمج نتائج تحديد خط متعددة", "合并多行识别结果": "دمج نتائج تحديد خط متعددة",
"空心线宽": "جوفاء خط العرض", "空心线宽": "جوفاء خط العرض",
"显示": "عرض .", "显示": "عرض .",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "امتيازات غير كافية ، يرجى تشغيل مع امتيازات المسؤول !", "权限不足,请以管理员权限运行!": "امتيازات غير كافية ، يرجى تشغيل مع امتيازات المسؤول !",
"标点": "علامات الترقيم", "标点": "علامات الترقيم",
"添加到列表": "إضافة إلى قائمة", "添加到列表": "إضافة إلى قائمة",
"目标": "الهدف" "目标": "الهدف",
"统计": "إحصائيات",
"元数据": "البيانات الوصفية",
"来源": "المصدر",
"首选的": "مفضل",
"设为封面": "مجموعة غطاء",
"复制": "نسخ",
"画廊": "معرض",
"删除图片": "حذف الصور"
} }

View File

@ -440,7 +440,6 @@
"失败": "失敗", "失败": "失敗",
"仅使用激活的翻译": "僅使用啟動的翻譯", "仅使用激活的翻译": "僅使用啟動的翻譯",
"云译": "雲譯", "云译": "雲譯",
"在线OCR": "線上OCR",
"使用代理的项目": "使用代理的項目", "使用代理的项目": "使用代理的項目",
"相关说明": "相關說明", "相关说明": "相關說明",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "如果你感覺該軟件對你有幫助,歡迎微信掃碼贊助,謝謝~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "如果你感覺該軟件對你有幫助,歡迎微信掃碼贊助,謝謝~",
@ -485,7 +484,6 @@
"打开目录": "打開目錄", "打开目录": "打開目錄",
"标题": "標題", "标题": "標題",
"封面": "封面", "封面": "封面",
"统计信息": "統計資訊",
"游戏时间": "遊戲時間", "游戏时间": "遊戲時間",
"未开始": "未開始", "未开始": "未開始",
"秒": "秒", "秒": "秒",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "許可權不足,請以管理員許可權運行!", "权限不足,请以管理员权限运行!": "許可權不足,請以管理員許可權運行!",
"标点": "標點", "标点": "標點",
"添加到列表": "添加到清單", "添加到列表": "添加到清單",
"目标": "目標" "目标": "目標",
"统计": "統計",
"元数据": "中繼資料",
"来源": "來源",
"首选的": "首選的",
"设为封面": "設為封面",
"复制": "複製",
"画廊": "畫廊",
"删除图片": "删除圖片"
} }

View File

@ -440,7 +440,6 @@
"失败": "fail", "失败": "fail",
"仅使用激活的翻译": "Use only active translations", "仅使用激活的翻译": "Use only active translations",
"云译": "Cloud translation", "云译": "Cloud translation",
"在线OCR": "Online OCR",
"使用代理的项目": "Projects using proxies", "使用代理的项目": "Projects using proxies",
"相关说明": "Related instructions", "相关说明": "Related instructions",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "If you feel that this software is helpful to you, you are welcome to scan WeChat for sponsorship. Thank you~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "If you feel that this software is helpful to you, you are welcome to scan WeChat for sponsorship. Thank you~",
@ -485,7 +484,6 @@
"打开目录": "Open directory", "打开目录": "Open directory",
"标题": "title", "标题": "title",
"封面": "cover", "封面": "cover",
"统计信息": "statistical information ",
"游戏时间": "Game time", "游戏时间": "Game time",
"未开始": "Not Started", "未开始": "Not Started",
"秒": "second", "秒": "second",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Insufficient permissions, please run with administrator privileges!", "权限不足,请以管理员权限运行!": "Insufficient permissions, please run with administrator privileges!",
"标点": "punctuation", "标点": "punctuation",
"添加到列表": "Add to list", "添加到列表": "Add to list",
"目标": "target" "目标": "target",
"统计": "statistics",
"元数据": "metadata",
"来源": "source",
"首选的": "Preferred",
"设为封面": "Set as Cover",
"复制": "copy",
"画廊": "gallery",
"删除图片": "Delete image"
} }

View File

@ -440,7 +440,6 @@
"失败": "Fracaso", "失败": "Fracaso",
"仅使用激活的翻译": "Solo se utilizan traducciones activadas", "仅使用激活的翻译": "Solo se utilizan traducciones activadas",
"云译": "Traducción en la nube", "云译": "Traducción en la nube",
"在线OCR": "OCR en línea",
"使用代理的项目": "Proyectos con agentes", "使用代理的项目": "Proyectos con agentes",
"相关说明": "Instrucciones pertinentes", "相关说明": "Instrucciones pertinentes",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Si sientes que el software te ayuda, Bienvenido al patrocinio de escaneo de wechat, Gracias.", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Si sientes que el software te ayuda, Bienvenido al patrocinio de escaneo de wechat, Gracias.",
@ -485,7 +484,6 @@
"打开目录": "Abrir catálogo", "打开目录": "Abrir catálogo",
"标题": "Título", "标题": "Título",
"封面": "Portada", "封面": "Portada",
"统计信息": "Información Estadística",
"游戏时间": "Tiempo de juego", "游戏时间": "Tiempo de juego",
"未开始": "Sin empezar", "未开始": "Sin empezar",
"秒": "Segundos", "秒": "Segundos",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "¡Permisos insuficientes, ¡ por favor, ejecute con permisos de administrador!", "权限不足,请以管理员权限运行!": "¡Permisos insuficientes, ¡ por favor, ejecute con permisos de administrador!",
"标点": "Puntuación", "标点": "Puntuación",
"添加到列表": "Añadir a la lista", "添加到列表": "Añadir a la lista",
"目标": "Objetivo" "目标": "Objetivo",
"统计": "Estadísticas",
"元数据": "Metadata",
"来源": "Fuente",
"首选的": "Preferido",
"设为封面": "Como portada",
"复制": "Copiar",
"画廊": "Galería",
"删除图片": "Eliminar imagen"
} }

View File

@ -440,7 +440,6 @@
"失败": "L'échec", "失败": "L'échec",
"仅使用激活的翻译": "Utiliser uniquement les traductions activées", "仅使用激活的翻译": "Utiliser uniquement les traductions activées",
"云译": "Traduction Cloud", "云译": "Traduction Cloud",
"在线OCR": "OCR en ligne",
"使用代理的项目": "Projets utilisant des agents", "使用代理的项目": "Projets utilisant des agents",
"相关说明": "Instructions connexes", "相关说明": "Instructions connexes",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Si vous sentez que le logiciel vous aide, bienvenue Wechat scan code sponsoring, merci ~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Si vous sentez que le logiciel vous aide, bienvenue Wechat scan code sponsoring, merci ~",
@ -485,7 +484,6 @@
"打开目录": "Ouvrir le catalogue", "打开目录": "Ouvrir le catalogue",
"标题": "Titre", "标题": "Titre",
"封面": "Couverture", "封面": "Couverture",
"统计信息": "Informations statistiques",
"游戏时间": "Temps de jeu", "游戏时间": "Temps de jeu",
"未开始": "Pas commencé", "未开始": "Pas commencé",
"秒": "Secondes", "秒": "Secondes",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Autorisations insuffisantes, exécutez avec des privilèges d'administrateur!", "权限不足,请以管理员权限运行!": "Autorisations insuffisantes, exécutez avec des privilèges d'administrateur!",
"标点": "Ponctuation", "标点": "Ponctuation",
"添加到列表": "Ajouter à la Liste", "添加到列表": "Ajouter à la Liste",
"目标": "Objectifs" "目标": "Objectifs",
"统计": "Statistiques",
"元数据": "Métadonnées",
"来源": "Sources",
"首选的": "Préféré",
"设为封面": "Faire la couverture",
"复制": "Copier",
"画廊": "Galerie",
"删除图片": "Supprimer une image"
} }

View File

@ -428,7 +428,6 @@
"失败": "fail", "失败": "fail",
"仅使用激活的翻译": "Usa solo traduzioni attive", "仅使用激活的翻译": "Usa solo traduzioni attive",
"云译": "Traduzione cloud", "云译": "Traduzione cloud",
"在线OCR": "OCR online",
"使用代理的项目": "Progetti che utilizzano proxy", "使用代理的项目": "Progetti che utilizzano proxy",
"相关说明": "Istruzioni correlate", "相关说明": "Istruzioni correlate",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Se ritieni che questo software sia utile per te, sei il benvenuto a scansionare WeChat per la sponsorizzazione.", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Se ritieni che questo software sia utile per te, sei il benvenuto a scansionare WeChat per la sponsorizzazione.",
@ -485,7 +484,6 @@
"打开目录": "Apri directory", "打开目录": "Apri directory",
"标题": "titolo", "标题": "titolo",
"封面": "cover", "封面": "cover",
"统计信息": "informazioni statistiche",
"游戏时间": "Tempo di gioco", "游戏时间": "Tempo di gioco",
"未开始": "Non iniziato", "未开始": "Non iniziato",
"秒": "secondo", "秒": "secondo",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Permessi insufficienti, si prega di eseguire con privilegi di amministratore!", "权限不足,请以管理员权限运行!": "Permessi insufficienti, si prega di eseguire con privilegi di amministratore!",
"标点": "punteggiatura", "标点": "punteggiatura",
"添加到列表": "Aggiungi alla lista", "添加到列表": "Aggiungi alla lista",
"目标": "obiettivo" "目标": "obiettivo",
"统计": "statistiche",
"元数据": "metadati",
"来源": "fonte",
"首选的": "Preferito",
"设为封面": "Imposta come copertina",
"复制": "copia",
"画廊": "gallery",
"删除图片": "Elimina immagine"
} }

View File

@ -440,7 +440,6 @@
"失败": "に失敗", "失败": "に失敗",
"仅使用激活的翻译": "アクティブな翻訳のみを使用", "仅使用激活的翻译": "アクティブな翻訳のみを使用",
"云译": "クラウド翻訳", "云译": "クラウド翻訳",
"在线OCR": "オンラインOCR",
"使用代理的项目": "エージェントを使用したアイテム", "使用代理的项目": "エージェントを使用したアイテム",
"相关说明": "関連説明", "相关说明": "関連説明",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "もしあなたがこのソフトウェアがあなたに役立つと感じたら、微信スキャンコードの協賛を歓迎します、ありがとうございます~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "もしあなたがこのソフトウェアがあなたに役立つと感じたら、微信スキャンコードの協賛を歓迎します、ありがとうございます~",
@ -485,7 +484,6 @@
"打开目录": "ディレクトリを開く", "打开目录": "ディレクトリを開く",
"标题": "タイトル", "标题": "タイトル",
"封面": "カバー枚", "封面": "カバー枚",
"统计信息": "統計#トウケイ#",
"游戏时间": "ゲーム時間", "游戏时间": "ゲーム時間",
"未开始": "開始していません", "未开始": "開始していません",
"秒": "秒", "秒": "秒",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "権限が不足しています。管理者権限で実行してください。", "权限不足,请以管理员权限运行!": "権限が不足しています。管理者権限で実行してください。",
"标点": "ひょうてん", "标点": "ひょうてん",
"添加到列表": "リストに追加", "添加到列表": "リストに追加",
"目标": "ターゲット" "目标": "ターゲット",
"统计": "統計#トウケイ#",
"元数据": "メタデータ",
"来源": "ソース",
"首选的": "優先",
"设为封面": "表紙にする",
"复制": "レプリケーション",
"画廊": "ギャラリー",
"删除图片": "画像を削除"
} }

View File

@ -440,7 +440,6 @@
"失败": "실패", "失败": "실패",
"仅使用激活的翻译": "활성화된 번역만 사용", "仅使用激活的翻译": "활성화된 번역만 사용",
"云译": "클라우드 번역", "云译": "클라우드 번역",
"在线OCR": "온라인 OCR",
"使用代理的项目": "프록시 사용 항목", "使用代理的项目": "프록시 사용 항목",
"相关说明": "관련 설명", "相关说明": "관련 설명",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "만약 당신이 이 소프트웨어가 당신에게 도움이 된다고 느낀다면, 위챗 스캔 협찬을 환영합니다. 감사합니다~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "만약 당신이 이 소프트웨어가 당신에게 도움이 된다고 느낀다면, 위챗 스캔 협찬을 환영합니다. 감사합니다~",
@ -485,7 +484,6 @@
"打开目录": "디렉토리 열기", "打开目录": "디렉토리 열기",
"标题": "제목", "标题": "제목",
"封面": "표지", "封面": "표지",
"统计信息": "통계 정보",
"游戏时间": "게임 시간", "游戏时间": "게임 시간",
"未开始": "시작하지 않음", "未开始": "시작하지 않음",
"秒": "초", "秒": "초",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "권한이 부족합니다. 관리자 권한으로 실행하십시오!", "权限不足,请以管理员权限运行!": "권한이 부족합니다. 관리자 권한으로 실행하십시오!",
"标点": "구두점", "标点": "구두점",
"添加到列表": "목록에 추가", "添加到列表": "목록에 추가",
"目标": "목표" "目标": "목표",
"统计": "통계",
"元数据": "메타데이터",
"来源": "출처",
"首选的": "선호",
"设为封面": "표지로 설정하다",
"复制": "복제",
"画廊": "갤러리",
"删除图片": "그림 삭제"
} }

View File

@ -440,7 +440,6 @@
"失败": "niepowodzenie", "失败": "niepowodzenie",
"仅使用激活的翻译": "Używaj tylko aktywnych tłumaczeń", "仅使用激活的翻译": "Używaj tylko aktywnych tłumaczeń",
"云译": "Tłumaczenie chmury", "云译": "Tłumaczenie chmury",
"在线OCR": "OCR online",
"使用代理的项目": "Projekty wykorzystujące serwery proxy", "使用代理的项目": "Projekty wykorzystujące serwery proxy",
"相关说明": "Powiązane instrukcje", "相关说明": "Powiązane instrukcje",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Jeśli uważasz, że to oprogramowanie jest dla Ciebie pomocne, zapraszamy do skanowania WeChat w celu uzyskania sponsorowania.", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Jeśli uważasz, że to oprogramowanie jest dla Ciebie pomocne, zapraszamy do skanowania WeChat w celu uzyskania sponsorowania.",
@ -485,7 +484,6 @@
"打开目录": "Otwórz katalog", "打开目录": "Otwórz katalog",
"标题": "tytuł", "标题": "tytuł",
"封面": "osłona", "封面": "osłona",
"统计信息": "informacje statystyczne",
"游戏时间": "Czas gry", "游戏时间": "Czas gry",
"未开始": "Nie uruchomiono", "未开始": "Nie uruchomiono",
"秒": "drugie", "秒": "drugie",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Niewystarczające uprawnienia, proszę uruchomić z uprawnieniami administratora!", "权限不足,请以管理员权限运行!": "Niewystarczające uprawnienia, proszę uruchomić z uprawnieniami administratora!",
"标点": "interpunkcja", "标点": "interpunkcja",
"添加到列表": "Dodaj do listy", "添加到列表": "Dodaj do listy",
"目标": "cel" "目标": "cel",
"统计": "statystyki",
"元数据": "metadane",
"来源": "źródło",
"首选的": "Preferowane",
"设为封面": "Ustaw jako okładka",
"复制": "kopia",
"画廊": "galeria",
"删除图片": "Usuń obraz"
} }

View File

@ -440,7 +440,6 @@
"失败": "Неудача", "失败": "Неудача",
"仅使用激活的翻译": "Использовать только активный перевод", "仅使用激活的翻译": "Использовать только активный перевод",
"云译": "Облачный перевод", "云译": "Облачный перевод",
"在线OCR": "Онлайн OCR",
"使用代理的项目": "Использовать прокси - проекты", "使用代理的项目": "Использовать прокси - проекты",
"相关说明": "Примечания", "相关说明": "Примечания",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Если вы чувствуете, что программное обеспечение помогает вам, добро пожаловать в спонсорскую поддержку WeChat подметания, спасибо", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Если вы чувствуете, что программное обеспечение помогает вам, добро пожаловать в спонсорскую поддержку WeChat подметания, спасибо",
@ -485,7 +484,6 @@
"打开目录": "Открыть каталог", "打开目录": "Открыть каталог",
"标题": "Заголовок", "标题": "Заголовок",
"封面": "Обложка", "封面": "Обложка",
"统计信息": "Статистическая информация",
"游戏时间": "Время игры", "游戏时间": "Время игры",
"未开始": "Не началось", "未开始": "Не началось",
"秒": "Секунда", "秒": "Секунда",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Недостаточные права, пожалуйста, запустите с правами администратора!", "权限不足,请以管理员权限运行!": "Недостаточные права, пожалуйста, запустите с правами администратора!",
"标点": "Пунктуация", "标点": "Пунктуация",
"添加到列表": "Добавить в список", "添加到列表": "Добавить в список",
"目标": "Цель" "目标": "Цель",
"统计": "Статистика",
"元数据": "Метаданные",
"来源": "Источник",
"首选的": "Предпочтительный",
"设为封面": "Установить обложку",
"复制": "Копирование",
"画廊": "Галерея",
"删除图片": "Удалить изображение"
} }

View File

@ -156,7 +156,6 @@
"标题": "ชื่อเรื่อง", "标题": "ชื่อเรื่อง",
"过滤尖括号<>": "กรองวงเล็บแหลม <>", "过滤尖括号<>": "กรองวงเล็บแหลม <>",
"繁简转换": "การแปลงที่ง่ายดาย", "繁简转换": "การแปลงที่ง่ายดาย",
"统计信息": "ข้อมูลสถิติ",
"设置": "การตั้งค่า", "设置": "การตั้งค่า",
"接受的编码": "การเข้ารหัสที่ยอมรับ", "接受的编码": "การเข้ารหัสที่ยอมรับ",
"OCR自动化方法": "วิธีการอัตโนมัติ OCR", "OCR自动化方法": "วิธีการอัตโนมัติ OCR",
@ -269,7 +268,6 @@
"自动检测": "การตรวจจับอัตโนมัติ", "自动检测": "การตรวจจับอัตโนมัติ",
"繁体中文(BIG5)": "ภาษาจีนดั้งเดิม (BIG5)", "繁体中文(BIG5)": "ภาษาจีนดั้งเดิม (BIG5)",
"翻译等待时间(s)": "เวลารอการแปล (s)", "翻译等待时间(s)": "เวลารอการแปล (s)",
"在线OCR": "ออนไลน์ OCR",
"词性": "คำพูด เพศ", "词性": "คำพูด เพศ",
"收到翻译结果时才刷新": "รีเฟรชเมื่อได้รับผลการแปล", "收到翻译结果时才刷新": "รีเฟรชเมื่อได้รับผลการแปล",
"禁用DirectFlip": "ปิดใช้งาน DirectFlip", "禁用DirectFlip": "ปิดใช้งาน DirectFlip",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "สิทธิ์ไม่เพียงพอโปรดเรียกใช้ด้วยสิทธิ์ของผู้ดูแลระบบ!", "权限不足,请以管理员权限运行!": "สิทธิ์ไม่เพียงพอโปรดเรียกใช้ด้วยสิทธิ์ของผู้ดูแลระบบ!",
"标点": "เครื่องหมายวรรคตอน", "标点": "เครื่องหมายวรรคตอน",
"添加到列表": "เพิ่มลงในรายการ", "添加到列表": "เพิ่มลงในรายการ",
"目标": "วัตถุประสงค์" "目标": "วัตถุประสงค์",
"统计": "สถิติ",
"元数据": "ข้อมูลกำกับภาพ",
"来源": "แหล่งที่มา",
"首选的": "ตัวเลือกแรก",
"设为封面": "ตั้งค่าเป็นปก",
"复制": "คัดลอก",
"画廊": "แกลเลอรี่",
"删除图片": "ลบรูปภาพ"
} }

View File

@ -440,7 +440,6 @@
"失败": "başarısız", "失败": "başarısız",
"仅使用激活的翻译": "Sadece aktif çevirimleri kullan", "仅使用激活的翻译": "Sadece aktif çevirimleri kullan",
"云译": "Bulud çevirimi", "云译": "Bulud çevirimi",
"在线OCR": "Online OCR",
"使用代理的项目": "Proksiler kullanarak projeler", "使用代理的项目": "Proksiler kullanarak projeler",
"相关说明": "İlişkili talimatlar", "相关说明": "İlişkili talimatlar",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Eğer bu yazılım size yardımcı olduğunu hissediyorsanız, sponsorluk için WeChat'ı taramak için hoş geldiniz. Teşekkürler ~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Eğer bu yazılım size yardımcı olduğunu hissediyorsanız, sponsorluk için WeChat'ı taramak için hoş geldiniz. Teşekkürler ~",
@ -485,7 +484,6 @@
"打开目录": "Dizini Aç", "打开目录": "Dizini Aç",
"标题": "isim", "标题": "isim",
"封面": "cover", "封面": "cover",
"统计信息": "istatistik bilgi",
"游戏时间": "Oyun zamanı", "游戏时间": "Oyun zamanı",
"未开始": "Başlanmadı", "未开始": "Başlanmadı",
"秒": "saniye", "秒": "saniye",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Insufficient permissions, please run with administrator privileges!", "权限不足,请以管理员权限运行!": "Insufficient permissions, please run with administrator privileges!",
"标点": "noqtalama", "标点": "noqtalama",
"添加到列表": "Listeye ekle", "添加到列表": "Listeye ekle",
"目标": "hedef" "目标": "hedef",
"统计": "istatistikler",
"元数据": "metadata",
"来源": "kaynak",
"首选的": "Tercih et",
"设为封面": "Kapağı olarak ayarlayın",
"复制": "kopyalama",
"画廊": "Galeri",
"删除图片": "Resimi sil"
} }

View File

@ -428,7 +428,6 @@
"失败": "невдачі", "失败": "невдачі",
"仅使用激活的翻译": "Використовувати лише активні переклади", "仅使用激活的翻译": "Використовувати лише активні переклади",
"云译": "Переклад хмар", "云译": "Переклад хмар",
"在线OCR": "В мережі OCR",
"使用代理的项目": "Projects using proxies", "使用代理的项目": "Projects using proxies",
"相关说明": "Пов’ язані інструкції", "相关说明": "Пов’ язані інструкції",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Якщо ви відчуваєте, що це програмне забезпечення допомагає вам, ви можете сканувати WeChat для спонсорування. Дякую ~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Якщо ви відчуваєте, що це програмне забезпечення допомагає вам, ви можете сканувати WeChat для спонсорування. Дякую ~",
@ -485,7 +484,6 @@
"打开目录": "Відкрити каталог", "打开目录": "Відкрити каталог",
"标题": "заголовок", "标题": "заголовок",
"封面": "обкладинка", "封面": "обкладинка",
"统计信息": "статистична інформація",
"游戏时间": "Час гри", "游戏时间": "Час гри",
"未开始": "Не запущено", "未开始": "Не запущено",
"秒": "second", "秒": "second",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Недостатньо прав доступу, будь ласка, запускайте привілеї адміністратора!", "权限不足,请以管理员权限运行!": "Недостатньо прав доступу, будь ласка, запускайте привілеї адміністратора!",
"标点": "пунктуація", "标点": "пунктуація",
"添加到列表": "Додати до списку", "添加到列表": "Додати до списку",
"目标": "мета" "目标": "мета",
"统计": "статистика",
"元数据": "метадані",
"来源": "джерело",
"首选的": "Найбільше",
"设为封面": "Встановити як обкладинку",
"复制": "копіювати",
"画廊": "галерія",
"删除图片": "Вилучити зображення"
} }

View File

@ -440,7 +440,6 @@
"失败": "Thất bại", "失败": "Thất bại",
"仅使用激活的翻译": "Chỉ sử dụng bản dịch kích hoạt", "仅使用激活的翻译": "Chỉ sử dụng bản dịch kích hoạt",
"云译": "Dịch Mây", "云译": "Dịch Mây",
"在线OCR": "Trực tuyến OCR",
"使用代理的项目": "Các dự án sử dụng proxy", "使用代理的项目": "Các dự án sử dụng proxy",
"相关说明": "Hướng dẫn liên quan", "相关说明": "Hướng dẫn liên quan",
"如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Nếu bạn cảm thấy phần mềm này có ích cho bạn, hoan nghênh tài trợ quét mã wechat, cảm ơn~", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Nếu bạn cảm thấy phần mềm này có ích cho bạn, hoan nghênh tài trợ quét mã wechat, cảm ơn~",
@ -485,7 +484,6 @@
"打开目录": "Mở thư mục", "打开目录": "Mở thư mục",
"标题": "Tiêu đề", "标题": "Tiêu đề",
"封面": "Trang chủ", "封面": "Trang chủ",
"统计信息": "Thống kê",
"游戏时间": "Thời gian chơi", "游戏时间": "Thời gian chơi",
"未开始": "Chưa bắt đầu", "未开始": "Chưa bắt đầu",
"秒": "giây", "秒": "giây",
@ -820,5 +818,13 @@
"权限不足,请以管理员权限运行!": "Không đủ quyền, hãy chạy với quyền quản trị viên!", "权限不足,请以管理员权限运行!": "Không đủ quyền, hãy chạy với quyền quản trị viên!",
"标点": "Chấm câu", "标点": "Chấm câu",
"添加到列表": "Thêm vào danh sách", "添加到列表": "Thêm vào danh sách",
"目标": "Mục tiêu" "目标": "Mục tiêu",
"统计": "Thống kê",
"元数据": "Siêu dữ liệu",
"来源": "Nguồn",
"首选的": "Ưu tiên",
"设为封面": "Đặt làm bìa",
"复制": "Sao chép",
"画廊": "Thư viện",
"删除图片": "Xóa ảnh"
} }

View File

@ -155,7 +155,7 @@
"标题": "", "标题": "",
"过滤尖括号<>": "", "过滤尖括号<>": "",
"繁简转换": "", "繁简转换": "",
"统计信息": "", "统计": "",
"设置": "", "设置": "",
"接受的编码": "", "接受的编码": "",
"OCR自动化方法": "", "OCR自动化方法": "",
@ -266,7 +266,6 @@
"自动检测": "", "自动检测": "",
"繁体中文(BIG5)": "", "繁体中文(BIG5)": "",
"翻译等待时间(s)": "", "翻译等待时间(s)": "",
"在线OCR": "",
"词性": "", "词性": "",
"收到翻译结果时才刷新": "", "收到翻译结果时才刷新": "",
"禁用DirectFlip": "", "禁用DirectFlip": "",
@ -820,5 +819,12 @@
"权限不足,请以管理员权限运行!": "", "权限不足,请以管理员权限运行!": "",
"标点": "", "标点": "",
"添加到列表": "", "添加到列表": "",
"目标": "" "目标": "",
"元数据": "",
"来源": "",
"首选的": "",
"设为封面": "",
"复制": "",
"画廊": "",
"删除图片": ""
} }

View File

@ -39,12 +39,13 @@ if __name__=='__main__':
js.pop(k) js.pop(k)
with open(f'./files/lang/'+f,'w',encoding='utf8') as ff: with open(f'./files/lang/'+f,'w',encoding='utf8') as ff:
ff.write( json.dumps(js,ensure_ascii=False,sort_keys=False, indent=4)) ff.write( json.dumps(js,ensure_ascii=False,sort_keys=False, indent=4))
a=TS1('baiduapi')
for kk in xxx: for kk in xxx:
with open(f'./files/lang/{kk}.json','r',encoding='utf8') as ff: with open(f'./files/lang/{kk}.json','r',encoding='utf8') as ff:
jsen=json.loads(ff.read()) jsen=json.loads(ff.read())
a=TS1('baiduapi')
a.tgtlang=xxx[kk] a.tgtlang=xxx[kk]
needpop=[] needpop=[]

View File

@ -28,8 +28,8 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/version)
include(generate_product_version) include(generate_product_version)
set(VERSION_MAJOR 3) set(VERSION_MAJOR 3)
set(VERSION_MINOR 2) set(VERSION_MINOR 5)
set(VERSION_PATCH 3) set(VERSION_PATCH 0)
add_library(pch pch.cpp) add_library(pch pch.cpp)
target_precompile_headers(pch PUBLIC pch.h) target_precompile_headers(pch PUBLIC pch.h)