diff --git a/LunaTranslator/LunaTranslator/LunaTranslator.py b/LunaTranslator/LunaTranslator/LunaTranslator.py index 9a55a17d..17d52c70 100644 --- a/LunaTranslator/LunaTranslator/LunaTranslator.py +++ b/LunaTranslator/LunaTranslator/LunaTranslator.py @@ -9,8 +9,9 @@ from myutils.config import ( savehook_new_data, setlanguage, static_data, + tryreadconfig, ) -import zipfile +import zipfile, sqlite3 from myutils.utils import ( minmaxmoveobservefunc, parsemayberegexreplace, @@ -44,6 +45,7 @@ from winsharedutils import pid_running from myutils.post import POSTSOLVE from myutils.utils import nowisdark + class commonstylebase(QWidget): setstylesheetsignal = pyqtSignal() @@ -77,6 +79,7 @@ class MAINUI: self.edittextui = None self.edittextui_cached = None self.edittextui_sync = True + self.sqlsavegameinfo = None @property def textsource(self): @@ -800,24 +803,124 @@ class MAINUI: int(widget.winId()), dark, globalconfig["WindowBackdrop"] ) - def checkgameplayingthread(self): - self.tracestarted = False + def createsavegamedb(self): + 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: - statistictime = time.time() time.sleep(1) def isok(name_): - now = time.time() - if self.tracestarted == False: - self.tracestarted = True - savehook_new_data[name_]["traceplaytime_v2"].append( - [statistictime, statistictime] + if self.__currentexe == name_: + _t = time.time() + self.traceplaytime(name_, self.__statistictime - 1, _t, False) + savehook_new_data[name_]["statistic_playtime"] += ( + _t + 1 - self.__statistictime ) - savehook_new_data[name_]["statistic_playtime"] += now - statistictime - savehook_new_data[name_]["traceplaytime_v2"][-1][1] = now - - def isbad(): - self.tracestarted = False + else: + self.__statistictime = time.time() + self.__currentexe = name_ + self.traceplaytime( + name_, self.__statistictime - 1, self.__statistictime, True + ) + savehook_new_data[name_]["statistic_playtime"] += 1 try: _hwnd = windows.GetForegroundWindow() @@ -829,13 +932,13 @@ class MAINUI: if _pid in self.textsource.pids or _pid == os.getpid(): isok(self.textsource.pname) else: - isbad() + self.__currentexe = None except: name_ = getpidexe(_pid) if name_ and name_ in savehook_new_list: isok(name_) else: - isbad() + self.__currentexe = None except: print_exc() @@ -968,6 +1071,7 @@ class MAINUI: threading.Thread(target=self.checkgameplayingthread).start() threading.Thread(target=self.darklistener).start() self.inittray() + self.createsavegamedb() def darklistener(self): sema = winsharedutils.startdarklistener() diff --git a/LunaTranslator/LunaTranslator/cishu/cishubase.py b/LunaTranslator/LunaTranslator/cishu/cishubase.py index 020cef95..345b2fab 100644 --- a/LunaTranslator/LunaTranslator/cishu/cishubase.py +++ b/LunaTranslator/LunaTranslator/cishu/cishubase.py @@ -1,14 +1,22 @@ from myutils.config import globalconfig from myutils.wrapper import threader from traceback import print_exc +from myutils.proxy import getproxy + class cishubase: + typename = None + def init(self): pass def search(self, word): return word + @property + def proxy(self): + return getproxy(("cishu", self.typename)) + def __init__(self, typename) -> None: self.typename = typename self.callback = print diff --git a/LunaTranslator/LunaTranslator/cishu/goo.py b/LunaTranslator/LunaTranslator/cishu/goo.py index a2282833..65c38a5d 100644 --- a/LunaTranslator/LunaTranslator/cishu/goo.py +++ b/LunaTranslator/LunaTranslator/cishu/goo.py @@ -1,7 +1,6 @@ import requests from urllib.parse import quote import re, os -from myutils.proxy import getproxy from cishu.cishubase import cishubase @@ -9,13 +8,13 @@ class goo(cishubase): def search(self, 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("
([\\s\\S]*?)
", x) xx = "".join(xx).replace('href="/', 'href="https://dictionary.goo.ne.jp/') if os.path.exists("cache/temp/goo.css") == False: 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 os.makedirs("cache/temp", exist_ok=True) with open("cache/temp/goo.css", "w", encoding="utf8") as ff: diff --git a/LunaTranslator/LunaTranslator/cishu/jisho.py b/LunaTranslator/LunaTranslator/cishu/jisho.py index 944b60bd..43a0aa08 100644 --- a/LunaTranslator/LunaTranslator/cishu/jisho.py +++ b/LunaTranslator/LunaTranslator/cishu/jisho.py @@ -1,7 +1,6 @@ import requests from urllib.parse import quote import re -from myutils.proxy import getproxy from cishu.cishubase import cishubase from html.parser import HTMLParser @@ -83,7 +82,7 @@ class jisho(cishubase): url = "https://jisho.org/word/{}".format(quote(word)) html = requests.get( url, - proxies=getproxy(), + proxies=self.proxy, ).text 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) - stl = requests.get(ss.group()[6:-1], proxies=getproxy()).text + stl = requests.get(ss.group()[6:-1], proxies=self.proxy).text return ( '
link

'.format( diff --git a/LunaTranslator/LunaTranslator/cishu/mojidict.py b/LunaTranslator/LunaTranslator/cishu/mojidict.py index 496c93de..c51a9824 100644 --- a/LunaTranslator/LunaTranslator/cishu/mojidict.py +++ b/LunaTranslator/LunaTranslator/cishu/mojidict.py @@ -1,10 +1,9 @@ import requests, re, json -from myutils.proxy import getproxy from cishu.cishubase import cishubase -def mojiclicksearch(word): +def mojiclicksearch(self,word): headers = { "accept": "*/*", @@ -39,7 +38,7 @@ def mojiclicksearch(word): "https://api.mojidict.com/parse/functions/word-clickSearchV2", headers=headers, data=data, - proxies=getproxy(), + proxies=self.proxy, ) result = response.json()["result"]["result"] @@ -574,7 +573,7 @@ def mojiclicksearch(word): return result -def mojizonghe(word): +def mojizonghe(self,word): response = requests.post( "https://api.mojidict.com/parse/functions/union-api", json={ @@ -597,7 +596,7 @@ def mojizonghe(word): "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", }, - proxies=getproxy(), + proxies=self.proxy, ) result = "" @@ -614,12 +613,12 @@ class mojidict(cishubase): result = "" try: - result += mojiclicksearch(word) + result += mojiclicksearch(self,word) result += "
" except: pass try: - result += mojizonghe(word) + result += mojizonghe(self,word) result += "
" except: pass diff --git a/LunaTranslator/LunaTranslator/cishu/weblio.py b/LunaTranslator/LunaTranslator/cishu/weblio.py index 6a78398b..7da28f87 100644 --- a/LunaTranslator/LunaTranslator/cishu/weblio.py +++ b/LunaTranslator/LunaTranslator/cishu/weblio.py @@ -2,7 +2,6 @@ import requests from urllib.parse import quote from cishu.cishubase import cishubase -from myutils.proxy import getproxy import re @@ -10,7 +9,7 @@ class weblio(cishubase): def search(self, 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("", "", x) _all = [] _xx = re.findall('
([\\s\\S]*?)
', x) diff --git a/LunaTranslator/LunaTranslator/cishu/youdao.py b/LunaTranslator/LunaTranslator/cishu/youdao.py index a6fb1364..c0954ac7 100644 --- a/LunaTranslator/LunaTranslator/cishu/youdao.py +++ b/LunaTranslator/LunaTranslator/cishu/youdao.py @@ -2,7 +2,6 @@ from myutils.config import getlangsrc import requests from urllib.parse import quote import re, os -from myutils.proxy import getproxy from cishu.cishubase import cishubase @@ -22,7 +21,7 @@ class youdao(cishubase): "https://dict.youdao.com/result?word={}&lang={}".format( quote(word), self.srclang ), - proxies=getproxy(), + proxies=self.proxy, ).text fnd = re.search('
([\\s\\S]*?)
', text) fnd = fnd.group() diff --git a/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py b/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py index 0ff4fdb7..111306bc 100644 --- a/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py +++ b/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py @@ -4,12 +4,10 @@ import os, functools, uuid, threading from datetime import datetime, timedelta from traceback import print_exc import windows, gobject, winsharedutils -from myutils.vndb import parsehtmlmethod from myutils.config import ( savehook_new_list, savehook_new_data, savegametaged, - vndbtagdata, _TR, _TRL, globalconfig, @@ -17,7 +15,13 @@ from myutils.config import ( ) from myutils.hwnd import getExeIcon 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.specialwidget import ( ScrollFlow, @@ -375,12 +379,7 @@ class TagWidget(QWidget): class browserdialog(saveposwindow): seturlsignal = pyqtSignal(str) - def parsehtml(self, url): - try: - newpath = parsehtmlmethod(url) - except: - print_exc() - newpath = url + def parsehtml(self, newpath): if newpath[:4].lower() != "http": newpath = os.path.abspath(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_setting_game = None @@ -597,8 +588,8 @@ class dialog_setting_game_internal(QWidget): def __init__(self, parent, exepath) -> None: super().__init__(parent) vbox = QVBoxLayout(self) - self.setLayout(vbox) formLayout = QFormLayout() + self.setLayout(vbox) self.exepath = exepath self.editpath = QLineEdit(exepath) self.editpath.setReadOnly(True) @@ -614,29 +605,6 @@ class dialog_setting_game_internal(QWidget): icon="fa.gear", 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( "", "", @@ -644,94 +612,124 @@ class dialog_setting_game_internal(QWidget): icon="fa.book", 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( _TRL( [ "启动", "HOOK", + "画廊", + "标签", + "元数据", + "统计", "预翻译", "语音", - "标签", - "统计信息", "存档备份", - "封面", ] ), [ functools.partial(self.doaddtab, self.starttab, 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.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.fengmiantab, exepath), ], delay=True, ) - + self.methodtab = methodtab vbox.addLayout(formLayout) vbox.addWidget(methodtab) 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): _w = QWidget() formLayout = QFormLayout() _w.setLayout(formLayout) - def selectimg(res): - savehook_new_data[exepath]["imagepath"] = res - savehook_new_data[exepath]["isimagepathusersetted"] = True - formLayout.addRow( - _TR("封面"), + _TR("画廊"), getsimplepatheditor( - savehook_new_data[exepath]["imagepath"], - False, - False, - None, - selectimg, - 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, + reflist=savehook_new_data[exepath]["imagepath_all"], + multi=True, + isdir=False, + name=_TR("画廊"), + header=_TR("画廊"), ), ) return _w @@ -862,7 +860,8 @@ class dialog_setting_game_internal(QWidget): t = QTimer(self) t.setInterval(1000) t.timeout.connect(self.refresh) - t.start(0) + t.timeout.emit() + t.start() return _w def split_range_into_days(self, times): @@ -909,7 +908,7 @@ class dialog_setting_game_internal(QWidget): ) self.chart.setdata( 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) for tag in savehook_new_data[exepath]["developers"]: 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) formLayout.addWidget(self.labelflow) _dict = {"new": 0} @@ -1088,34 +1087,14 @@ class dialog_setting_game_internal(QWidget): getsimpleswitch(savehook_new_data[exepath], "removeuseless"), ) - model = QStandardItemModel() - model.setHorizontalHeaderLabels( - _TRL( - [ - "删除", - "特殊码", - ] - ) - ) # ,'HOOK']) - - self.hcmodel = model - - table = QTableView() - table.horizontalHeader().setSectionResizeMode( - QHeaderView.ResizeMode.ResizeToContents + formLayout.addRow( + _TR("特殊码"), + listediterline( + _TR("特殊码"), + _TR("特殊码"), + savehook_new_data[exepath]["needinserthookcode"], + ), ) - 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( _TR("插入特殊码延迟(ms)"), @@ -1131,31 +1110,11 @@ class dialog_setting_game_internal(QWidget): ) 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 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) global _global_dialog_setting_game _global_dialog_setting_game = self @@ -1164,7 +1123,8 @@ class dialog_setting_game(QDialog): self.setWindowIcon(getExeIcon(exepath, cache=True)) _ = dialog_setting_game_internal(self, exepath) - + if setindexhook: + _.methodtab.setCurrentIndex(1) _.setMinimumSize(QSize(600, 500)) l = QHBoxLayout(self) self.setLayout(l) @@ -1357,9 +1317,18 @@ def opendir(f): def _getpixfunction(kk): - _pix = QPixmap(savehook_new_data[kk]["imagepath"]) - if _pix.isNull(): - _pix = getExeIcon(kk, False, cache=True) + if ( + savehook_new_data[kk]["currentmainimage"] + 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 @@ -1531,6 +1500,7 @@ class dialog_savedgame_new(QWidget): self.flow.bgclicked.connect(ItemWidget.clearfocus) self.formLayout.insertWidget(self.formLayout.count() - 1, self.flow) idx = 0 + for k in savehook_new_list: if newtags != self.currtags: break @@ -1545,7 +1515,7 @@ class dialog_savedgame_new(QWidget): notshow = True break 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 break elif _type == tagitem.TYPE_USERTAG: @@ -1554,7 +1524,7 @@ class dialog_savedgame_new(QWidget): break elif _type == tagitem.TYPE_RAND: 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]["title"] and tag not in savehook_new_data[k]["developers"] @@ -1565,6 +1535,7 @@ class dialog_savedgame_new(QWidget): continue self.newline(k, idx == 0) idx += 1 + self.flow.directshow() def showmenu(self, p): menu = QMenu(self) @@ -2053,6 +2024,8 @@ class pixwrapper(QWidget): super().__init__() self.pixview = QLabel(self) self.pixmaps = [] + self.rflist = [] + self.iternalpixmaps = [] self.k = None self.pixmapi = 0 self.pixview.setAlignment(Qt.AlignmentFlag.AlignCenter) @@ -2064,9 +2037,9 @@ class pixwrapper(QWidget): self.visidx() def mousePressEvent(self, a0: QMouseEvent) -> None: - if a0.pos().x() < self.width() * 2 / 5: + if a0.pos().x() < self.width() / 3: self.tolastnext(-1) - elif a0.pos().x() > self.width() * 3 / 5: + elif a0.pos().x() > self.width() * 2 / 3: self.tolastnext(1) else: pass @@ -2078,22 +2051,40 @@ class pixwrapper(QWidget): def visidx(self): if self.k and len(self.pixmaps) == 0: - self.pixmaps = [_getpixfunction(self.k)] - if self.pixmapi < len(self.pixmaps): + pixmap = getExeIcon(self.k, False, cache=True) + pixmap.setDevicePixelRatio(self.devicePixelRatioF()) + self.pixview.setPixmap(self.scalepix(pixmap)) + elif self.pixmapi < len(self.pixmaps): pixmap = self.pixmaps[self.pixmapi] - if isinstance(pixmap, str): - pixmap = QPixmap.fromImage(QImage(pixmap)) - if pixmap.isNull(): + + savehook_new_data[self.k]["currentvisimage"] = pixmap + pixmap = QPixmap.fromImage(QImage(pixmap)) + if pixmap is None or pixmap.isNull(): self.pixmaps.pop(self.pixmapi) return self.visidx() pixmap.setDevicePixelRatio(self.devicePixelRatioF()) 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): 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 + if savehook_new_data[k]["currentvisimage"] in self.pixmaps: + self.pixmapi = self.pixmaps.index(savehook_new_data[k]["currentvisimage"]) self.visidx() def scalepix(self, pix: QPixmap): @@ -2162,7 +2153,7 @@ class dialog_savedgame_v3(QWidget): ) self.stack.directshow() - def stack_showmenu(self, p): + def stack_showmenu(self, ispixmenu, p): if not self.currentfocuspath: return menu = QMenu(self) @@ -2170,7 +2161,8 @@ class dialog_savedgame_v3(QWidget): delgame = QAction(_TR("删除游戏")) opendir = QAction(_TR("打开目录")) addtolist = QAction(_TR("添加到列表")) - + setimage = QAction(_TR("设为封面")) + deleteimage = QAction(_TR("删除图片")) exists = os.path.exists(self.currentfocuspath) if exists: menu.addAction(startgame) @@ -2178,15 +2170,24 @@ class dialog_savedgame_v3(QWidget): if exists: menu.addAction(opendir) menu.addAction(addtolist) + if ispixmenu: + menu.addAction(setimage) + menu.addAction(deleteimage) action = menu.exec(QCursor.pos()) if action == startgame: startgamecheck(self, self.currentfocuspath) elif action == delgame: self.clicked2() + elif action == deleteimage: + self.pixview.removecurrent() elif action == opendir: self.clicked4() elif action == 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): @@ -2248,7 +2249,9 @@ class dialog_savedgame_v3(QWidget): self.reallist = {} self.stack = stackedlist() 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( globalconfig["dialog_savegame_layout"]["listitemwidth"] ) @@ -2263,11 +2266,13 @@ class dialog_savedgame_v3(QWidget): rightlay = QVBoxLayout() rightlay.setContentsMargins(0, 0, 0, 0) _w.setLayout(rightlay) - self.righttop.addTab(_w, _TR("封面")) + self.righttop.addTab(_w, _TR("画廊")) lay.addWidget(self.righttop) rightlay.addWidget(self.pixview) 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.savebutton = [] rightlay.addLayout(self.buttonlayout) diff --git a/LunaTranslator/LunaTranslator/gui/edittext.py b/LunaTranslator/LunaTranslator/gui/edittext.py index a546acd4..8a8b6933 100644 --- a/LunaTranslator/LunaTranslator/gui/edittext.py +++ b/LunaTranslator/LunaTranslator/gui/edittext.py @@ -117,7 +117,8 @@ class edittrans(QMainWindow): t = QTimer(self) t.setInterval(100) t.timeout.connect(self.follow) - t.start(0) + t.timeout.emit() + t.start() def follow(self): rect = windows.GetWindowRect(self.followhwnd) diff --git a/LunaTranslator/LunaTranslator/gui/inputdialog.py b/LunaTranslator/LunaTranslator/gui/inputdialog.py index 254bc6db..76f795d5 100644 --- a/LunaTranslator/LunaTranslator/gui/inputdialog.py +++ b/LunaTranslator/LunaTranslator/gui/inputdialog.py @@ -270,6 +270,9 @@ class autoinitdialog(QDialog): line["dir"], line.get("filter", None), 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")]) diff --git a/LunaTranslator/LunaTranslator/gui/selecthook.py b/LunaTranslator/LunaTranslator/gui/selecthook.py index 92d87265..7a4d0079 100644 --- a/LunaTranslator/LunaTranslator/gui/selecthook.py +++ b/LunaTranslator/LunaTranslator/gui/selecthook.py @@ -712,7 +712,7 @@ class hookselect(closeashidewindow): def opengamesetting(self): try: - dialog_setting_game(self, gobject.baseobject.textsource.pname) + dialog_setting_game(self, gobject.baseobject.textsource.pname, True) except: print_exc() diff --git a/LunaTranslator/LunaTranslator/gui/setting_proxy.py b/LunaTranslator/LunaTranslator/gui/setting_proxy.py index 2e08aead..1fde599a 100644 --- a/LunaTranslator/LunaTranslator/gui/setting_proxy.py +++ b/LunaTranslator/LunaTranslator/gui/setting_proxy.py @@ -11,7 +11,7 @@ from gui.usefulwidget import ( ) -def getall(l, item="fanyi", name=""): +def getall(l, item="fanyi", name=None): grids = [] i = 0 line = [] @@ -19,13 +19,14 @@ def getall(l, item="fanyi", name=""): if fanyi not in l: continue - _f = name % fanyi - if fanyi != "selfbuild" and os.path.exists(_f) == False: - continue + if name: + _f = name % fanyi + if fanyi != "selfbuild" and os.path.exists(_f) == False: + continue i += 1 line += [ - (globalconfig[item][fanyi]["name"], 6), + (globalconfig[item][fanyi].get("name", fanyi), 6), D_getsimpleswitch(globalconfig[item][fanyi], "useproxy", default=True), "", ] @@ -62,6 +63,14 @@ def _ifusesysproxy(self, 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): grid1 = [ @@ -89,20 +98,60 @@ def setTab_proxy_lazy(self, basel): mianfei = getall(l=mianfei, item="fanyi", name="./Lunatranslator/translator/%s.py") shoufei = getall(l=shoufei, item="fanyi", name="./Lunatranslator/translator/%s.py") ocrs = getall( - l=set(globalconfig["ocr"].keys()) - set(["local", "windowsocr"]), + l=getnotofflines("ocr"), item="ocr", 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() basel.addWidget(vw) gridlayoutwidget, do = makegrid(grid1, delay=True) vl.addWidget(gridlayoutwidget) tab, dotab = makesubtab_lazy( - _TRL(["在线翻译", "注册在线翻译", "在线OCR"]), + _TRL( + [ + "在线翻译", + "注册在线翻译", + "OCR", + "语音合成", + "辞书", + "元数据", + "分词", + "github", + ] + ), [ functools.partial(makescrollgrid, mianfei), functools.partial(makescrollgrid, shoufei), 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, ) diff --git a/LunaTranslator/LunaTranslator/gui/specialwidget.py b/LunaTranslator/LunaTranslator/gui/specialwidget.py index 1fcb929e..10369e03 100644 --- a/LunaTranslator/LunaTranslator/gui/specialwidget.py +++ b/LunaTranslator/LunaTranslator/gui/specialwidget.py @@ -311,7 +311,8 @@ class lazyscrollflow(ScrollArea): def directshow(self): 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): super().__init__() diff --git a/LunaTranslator/LunaTranslator/gui/translatorUI.py b/LunaTranslator/LunaTranslator/gui/translatorUI.py index 2cb9b4fd..71286710 100644 --- a/LunaTranslator/LunaTranslator/gui/translatorUI.py +++ b/LunaTranslator/LunaTranslator/gui/translatorUI.py @@ -861,7 +861,8 @@ class QUnFrameWindow(resizableframeless): try: gobject.baseobject.settin_ui.show_original_switch.click() except: - pass + globalconfig["isshowrawtext"] = not globalconfig["isshowrawtext"] + gobject.baseobject.translation_ui.refreshtoolicon() def changeTranslateMode(self): globalconfig["autorun"] = not globalconfig["autorun"] diff --git a/LunaTranslator/LunaTranslator/gui/usefulwidget.py b/LunaTranslator/LunaTranslator/gui/usefulwidget.py index a84583e3..fd48bcfd 100644 --- a/LunaTranslator/LunaTranslator/gui/usefulwidget.py +++ b/LunaTranslator/LunaTranslator/gui/usefulwidget.py @@ -711,11 +711,12 @@ class mshtmlWidget(abstractwebview): if HTMLBrowser.version() < 10001: # ie10之前,sethtml会乱码 self.html_limit = 0 self.browser = HTMLBrowser(int(self.winId())) + self.curr_url = None t = QTimer(self) t.setInterval(100) t.timeout.connect(self.__getcurrenturl) - t.start(0) - self.curr_url = None + t.timeout.emit() + t.start() def __getcurrenturl(self): _u = self.browser.get_current_url() @@ -785,7 +786,8 @@ class QWebWrap(abstractwebview): t = QTimer(self) t.setInterval(100) t.timeout.connect(self.__getzoomfactor) - t.start(0) + t.timeout.emit() + t.start() def set_zoom(self, zoom): self.internal_zoom = zoom @@ -1061,10 +1063,54 @@ def makesubtab_lazy( @Singleton_close 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) self.lst = lst self.closecallback = closecallback + self.ispathsedit = ispathsedit try: self.setWindowTitle(title) model = QStandardItemModel() @@ -1076,23 +1122,28 @@ class listediter(QDialog): QHeaderView.ResizeMode.ResizeToContents ) table.horizontalHeader().setStretchLastSection(True) - # table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers); + if ispathsedit: + table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) table.setSelectionMode((QAbstractItemView.SelectionMode.SingleSelection)) table.setWordWrap(False) table.setModel(model) + + table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + table.customContextMenuRequested.connect(self.showmenu) self.hctable = table for row, k in enumerate(lst): # 2 - self.newline(row, k) + self.hcmodel.insertRow(row, [QStandardItem(k)]) formLayout = QVBoxLayout() formLayout.addWidget(self.hctable) 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) formLayout.addWidget(self.buttons) self.setLayout(formLayout) + self.resize(600, self.sizeHint().height()) self.show() except: print_exc() @@ -1116,14 +1167,29 @@ class listediter(QDialog): if self.closecallback: self.closecallback() - def newline(self, row, k): - self.hcmodel.insertRow(row, [QStandardItem(k)]) + def __cb(self, path): + + 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): clicked = pyqtSignal() - def __init__(self, name, header, reflist): + def __init__(self, name, header, reflist, ispathsedit=False): super().__init__() self.setReadOnly(True) self.reflist = reflist @@ -1131,7 +1197,13 @@ class listediterline(QLineEdit): self.clicked.connect( 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: return - edit.setText("|".join(res) if multi else res) + if edit: + edit.setText("|".join(res) if multi else res) if callback: callback(res) def getsimplepatheditor( - text, - multi, - isdir, + text=None, + multi=False, + isdir=False, filter1="*.*", callback=None, useiconbutton=False, + reflist=None, + name=None, + header=None, ): lay = QHBoxLayout() lay.setContentsMargins(0, 0, 0, 0) - director = (text[0] if len(text) else "") if multi else text - e = QLineEdit("|".join(text) if multi else 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, - director, - multi, - e, - isdir, - "" if isdir else filter1, - callback, + if multi: + e = listediterline( + name, header, reflist, dict(isdir=isdir, multi=False, filter1=filter1) ) - ) - lay.addWidget(e) - lay.addWidget(bu) + lay.addWidget(e) + else: + 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 diff --git a/LunaTranslator/LunaTranslator/hiraparse/basehira.py b/LunaTranslator/LunaTranslator/hiraparse/basehira.py index cd4a7317..7b8f4bb7 100644 --- a/LunaTranslator/LunaTranslator/hiraparse/basehira.py +++ b/LunaTranslator/LunaTranslator/hiraparse/basehira.py @@ -1,5 +1,6 @@ from myutils.config import globalconfig, static_data from traceback import print_exc +from myutils.proxy import getproxy class basehira: @@ -25,6 +26,10 @@ class basehira: def config(self): return globalconfig["hirasetting"][self.typename]["args"] + @property + def proxy(self): + return getproxy(("cishu", self.typename)) + def parseparse(self, text): hira = [] try: diff --git a/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py b/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py index dfb6ea75..9cd61da6 100644 --- a/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py +++ b/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py @@ -1,4 +1,3 @@ -from myutils.proxy import getproxy import requests from hiraparse.basehira import basehira @@ -19,7 +18,7 @@ class mojinlt(basehira): "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", }, - proxies=getproxy(), + proxies=self.proxy, ) return [ diff --git a/LunaTranslator/LunaTranslator/myutils/commonbase.py b/LunaTranslator/LunaTranslator/myutils/commonbase.py index ff34cf81..434803fa 100644 --- a/LunaTranslator/LunaTranslator/myutils/commonbase.py +++ b/LunaTranslator/LunaTranslator/myutils/commonbase.py @@ -96,7 +96,7 @@ class commonbase: self.level2init() def renewsesion(self): - self.session = proxysession(self._globalconfig_key, self.typename) + self.proxysession = proxysession(self._globalconfig_key, self.typename) def level2init(self): pass diff --git a/LunaTranslator/LunaTranslator/myutils/config.py b/LunaTranslator/LunaTranslator/myutils/config.py index 860f1341..757d2e3e 100644 --- a/LunaTranslator/LunaTranslator/myutils/config.py +++ b/LunaTranslator/LunaTranslator/myutils/config.py @@ -57,8 +57,6 @@ except: translatorsetting = tryreadconfig("translatorsetting.json") ocrsetting = tryreadconfig("ocrsetting.json") -vndbtagdata = tryreadconfig("vndbtagdata.json") - def getdefaultsavehook(gamepath, title=None): default = { @@ -67,14 +65,6 @@ def getdefaultsavehook(gamepath, title=None): "onloadautoswitchsrclang": 0, "needinserthookcode": [], "embedablehook": [], - "imagepath": None, - "imagepath_much2": [], - "isimagepathusersetted": False, - "isimagepathusersetted_much": False, - "istitlesetted": False, - "infopath": None, - "vid": 0, - "namemap": {}, "statistic_playtime": 0, "statistic_wordcount": 0, "statistic_wordcount_nodump": 0, @@ -86,24 +76,42 @@ def getdefaultsavehook(gamepath, title=None): "needinserthookcode": [], "removeuseless": False, "codepage_index": 0, - # "allow_tts_auto_names": "", + # "allow_tts_auto_names": "",#->v4 "allow_tts_auto_names_v4": [], "tts_repair": False, "tts_repair_regex": [], "hooktypeasname": {}, "use_saved_text_process": False, - "searchnoresulttime": 0, - "relationlinks": [], + # "searchnoresulttime": 0, "gamejsonfile": "", "gamesqlitefile": "", - "vndbtags": [], + "relationlinks": [], + # "vndbtags": [],#->webtags "usertags": [], - "traceplaytime_v2": [], # [[start,end]] + # "traceplaytime_v2": [], # [[start,end]]->db.traceplaytime_v4,这个东西增加到太快了,有点膨胀 "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": [], + "webtags": [], # 标签 + "infopath": None, # 离线存储的主页 } if title and len(title): - default["title"] = title + default["title"] = title # metadata else: default["title"] = ( os.path.basename(os.path.dirname(gamepath)) @@ -116,15 +124,6 @@ def getdefaultsavehook(gamepath, title=None): _dfsavehook = getdefaultsavehook("") 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 ( ("allow_tts_auto_names_v4" not in savehook_new_data[game]) and ("allow_tts_auto_names" in savehook_new_data[game]) @@ -335,16 +334,18 @@ def _TRL(kk): return x -def saveallconfig(): - def safesave(fname, js): - # 有时保存时意外退出,会导致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) - +def safesave(fname, js): + # 有时保存时意外退出,会导致config文件被清空 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/magpie_config.json", magpie_config) safesave("./userconfig/postprocessconfig.json", postprocessconfig) @@ -353,7 +354,6 @@ def saveallconfig(): safesave("./userconfig/translatorsetting.json", translatorsetting) safesave("./userconfig/ocrerrorfix.json", ocrerrorfix) safesave("./userconfig/ocrsetting.json", ocrsetting) - safesave("./userconfig/vndbtagdata.json", vndbtagdata) safesave( "./userconfig/savehook_new_1.39.4.json", [savehook_new_list, savehook_new_data, savegametaged], diff --git a/LunaTranslator/LunaTranslator/myutils/githubupdate.py b/LunaTranslator/LunaTranslator/myutils/githubupdate.py index 2482c621..ba522206 100644 --- a/LunaTranslator/LunaTranslator/myutils/githubupdate.py +++ b/LunaTranslator/LunaTranslator/myutils/githubupdate.py @@ -22,6 +22,7 @@ def getvesionmethod(): "https://api.github.com/repos/HIllya51/LunaTranslator/releases/latest", headers=headers, verify=False, + proxies=getproxy(("github", "versioncheck")), ).json() # print(res) _version = res["tag_name"] @@ -89,13 +90,17 @@ def updatemethod(_version, progresscallback): return False 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"]) if checkalready(size): return with open(savep, "wb") as file: 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 for i in r.iter_content(chunk_size=1024): if globalconfig["autoupdate"] == False: diff --git a/LunaTranslator/LunaTranslator/myutils/metadata/abstract.py b/LunaTranslator/LunaTranslator/myutils/metadata/abstract.py new file mode 100644 index 00000000..a2cd6742 --- /dev/null +++ b/LunaTranslator/LunaTranslator/myutils/metadata/abstract.py @@ -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() diff --git a/LunaTranslator/LunaTranslator/myutils/metadata/bangumi.py b/LunaTranslator/LunaTranslator/myutils/metadata/bangumi.py new file mode 100644 index 00000000..56481272 --- /dev/null +++ b/LunaTranslator/LunaTranslator/myutils/metadata/bangumi.py @@ -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, + } diff --git a/LunaTranslator/LunaTranslator/myutils/metadata/dlsite.py b/LunaTranslator/LunaTranslator/myutils/metadata/dlsite.py new file mode 100644 index 00000000..6d94c0cc --- /dev/null +++ b/LunaTranslator/LunaTranslator/myutils/metadata/dlsite.py @@ -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", + '
(.*?)', response.text + ).groups()[0] + print(title) + devp = re.search( + '([\\s\\S]*?)(.*?)([\\s\\S]*?)', + response.text, + ).groups()[2] + print(devp) + tags = re.search( + '
([\\s\\S]*?)
', response.text + ).groups()[0] + + tags = [_[1] for _ in re.findall('(.*?)', tags)] + print(tags) + + inner = simplehtmlparser( + response.text, + "div", + '
', + ) + + imags2 = ["https:" + _[0] for _ in re.findall('', inner)] + print(imags2) + + inner = simplehtmlparser(response.text, "div", '
', inner) + ] + print(imags1) + + return { + # "namemap": namemap, + "title": title, + # "infopath": parsehtmlmethod(vndbdowloadinfo(vid)), + "imagepath_all": [self.dispatchdownloadtask(_) for _ in imags1 + imags2], + "webtags": tags, + "developers": [devp], + } diff --git a/LunaTranslator/LunaTranslator/myutils/vndb.py b/LunaTranslator/LunaTranslator/myutils/metadata/vndb.py similarity index 59% rename from LunaTranslator/LunaTranslator/myutils/vndb.py rename to LunaTranslator/LunaTranslator/myutils/metadata/vndb.py index 237ff42b..c2d391c7 100644 --- a/LunaTranslator/LunaTranslator/myutils/vndb.py +++ b/LunaTranslator/LunaTranslator/myutils/metadata/vndb.py @@ -1,88 +1,19 @@ -import time, requests, re, os, hashlib -from myutils.proxy import getproxy -from myutils.config import globalconfig, vndbtagdata +import time, requests, re, os +from myutils.config import globalconfig, tryreadconfig, safesave from threading import Thread import gzip, json import shutil - -def b64string(a): - return hashlib.md5(a.encode("utf8")).hexdigest() +from myutils.metadata.abstract import common -def vndbdownloadimg(url, wait=True): - 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): +def safegetvndbjson(proxy, url, json, getter): try: print(url, json) _ = requests.post( url, json=json, - proxies=getproxy(), + proxies=proxy, ) print(_.text) try: @@ -94,7 +25,7 @@ def safegetvndbjson(url, json, getter): return None -def gettitlebyid(vid): +def gettitlebyid(proxy, vid): def _getter(js): try: @@ -110,13 +41,14 @@ def gettitlebyid(vid): return js["results"][0]["title"] return safegetvndbjson( + proxy, "https://api.vndb.org/kana/vn", {"filters": ["id", "=", vid], "fields": "title,titles.title,titles.main"}, _getter, ) -def getscreenshotsbyid(vid): +def getscreenshotsbyid(proxy, vid): def _getter(js): ___ = [] @@ -126,30 +58,34 @@ def getscreenshotsbyid(vid): return ___ return safegetvndbjson( + proxy, "https://api.vndb.org/kana/vn", {"filters": ["id", "=", vid], "fields": "screenshots.url"}, _getter, ) -def getimgbyid(vid): +def getimgbyid(proxy, vid): return safegetvndbjson( + proxy, "https://api.vndb.org/kana/vn", {"filters": ["id", "=", vid], "fields": "image.url"}, lambda js: js["results"][0]["image"]["url"], ) -def getvidbytitle_vn(title): +def getvidbytitle_vn(proxy, title): return safegetvndbjson( + proxy, "https://api.vndb.org/kana/vn", {"filters": ["search", "=", title], "fields": "id", "sort": "searchrank"}, lambda js: js["results"][0]["id"], ) -def getvidbytitle_release(title): +def getvidbytitle_release(proxy, title): return safegetvndbjson( + proxy, "https://api.vndb.org/kana/release", { "filters": ["search", "=", title], @@ -160,7 +96,7 @@ def getvidbytitle_release(title): ) -def getdevelopersbyid(vid): +def getdevelopersbyid(proxy, vid): def _js(js): _ = [] @@ -171,6 +107,7 @@ def getdevelopersbyid(vid): return _ name = safegetvndbjson( + proxy, "https://api.vndb.org/kana/vn", {"filters": ["id", "=", vid], "fields": "developers.name,developers.original"}, _js, @@ -178,15 +115,16 @@ def getdevelopersbyid(vid): return name -def getvidbytitle(title): - vid = getvidbytitle_vn(title) +def getidbytitle_(proxy, title): + vid = getvidbytitle_vn(proxy, title) if vid: return vid - return getvidbytitle_release(title) + return getvidbytitle_release(proxy, title) -def getcharnamemapbyid(vid): +def getcharnamemapbyid(proxy, vid): res = safegetvndbjson( + proxy, "https://api.vndb.org/kana/character", { "filters": [ @@ -213,11 +151,11 @@ def decompress_gzip_file(gzip_file, output_file): shutil.copyfileobj(f_in, f_out) -def safedownload(): +def safedownload(proxy): try: resp = requests.get( "https://dl.vndb.org/dump/vndb-tags-latest.json.gz", - proxies=getproxy(), + proxies=proxy, ) os.makedirs("cache/temp", exist_ok=True) with open("cache/temp/vndb-tags-latest.json.gz", "wb") as ff: @@ -241,7 +179,7 @@ def safedownload(): return None -def getvntagsbyid(vid): +def getvntagsbyid(proxy, vid): res = safegetvndbjson( "https://api.vndb.org/kana/vn", @@ -258,44 +196,26 @@ def getvntagsbyid(vid): if not res: return tags = [] + vndbtagdata = tryreadconfig("vndbtagdata.json") + changed = False try: for r in res: tag = r["id"] - if tag not in vndbtagdata: - js = safedownload() + if tag not in vndbtagdata and not changed: + js = safedownload(proxy) if js: vndbtagdata.update(js) - - tags.append(r["id"]) + changed = True + if tag not in vndbtagdata: + continue + tags.append(vndbtagdata[r["id"]]) except: pass + if changed: + safesave("./userconfig/vndbtagdata.json", vndbtagdata) 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 @@ -324,8 +244,70 @@ def parsehtmlmethod(infopath): text, ) - with open(resavepath, "w", encoding="utf8") as ff: ff.write(text) 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('
([\\s\\S]*?)
', html) + if find: + html = find.groups()[0] + return [_[1] for _ in re.findall("(.*?)", 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, + } diff --git a/LunaTranslator/LunaTranslator/myutils/utils.py b/LunaTranslator/LunaTranslator/myutils/utils.py index 26d09e09..8ccc1171 100644 --- a/LunaTranslator/LunaTranslator/myutils/utils.py +++ b/LunaTranslator/LunaTranslator/myutils/utils.py @@ -20,9 +20,39 @@ from myutils.config import ( from ctypes import c_float, pointer, c_void_p import threading import re, heapq, winsharedutils -from myutils.vndb import searchfordata, getvidbytitle from myutils.wrapper import tryprint + +def findenclose(text, tag): + i = 0 + tags = f"<{tag}" + tage = f"" + 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(): dl = globalconfig["darklight"] if dl == 0: @@ -33,6 +63,7 @@ def nowisdark(): dark = winsharedutils.isDark() return dark + def getimageformatlist(): _ = [_.data().decode() for _ in QImageWriter.supportedImageFormats()] if globalconfig["imageformat"] == -1 or globalconfig["imageformat"] >= len(_): @@ -67,12 +98,6 @@ class 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): return (savehook_new_data[gamepath]["infopath"] is None) or ( (savehook_new_data[gamepath]["infopath"][:4].lower() != "http") @@ -82,120 +107,146 @@ def checkinfo(gamepath): def checkvid(gamepath): - return ( - checkimage(gamepath) - or checkinfo(gamepath) - or ( - (len(savehook_new_data[gamepath]["vndbtags"]) == 0) - and (len(savehook_new_data[gamepath]["developers"]) == 0) - ) + return checkinfo(gamepath) or ( + (len(savehook_new_data[gamepath]["webtags"]) == 0) + and (len(savehook_new_data[gamepath]["developers"]) == 0) ) -def dispatachtask(gamepath): +def guessmaybetitle(gamepath): __t = [] - if savehook_new_data[gamepath]["vid"]: - if not checkvid(gamepath): - return - print(gamepath) - searchvndbqueue.put((1, gamepath, savehook_new_data[gamepath]["vid"])) - else: - if ( - time.time() - < savehook_new_data[gamepath]["searchnoresulttime"] + 3600 * 24 * 7 - ): - return - print(gamepath) - for _ in [ - 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}\]", "", _) + + print(gamepath) + for _ in [ + 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(_) + _ = re.sub(r"\[(.*?)\]", "", _) + if _ != __t[-1]: __t.append(_) - _ = re.sub(r"\[(.*?)\]", "", _) - if _ != __t[-1]: - __t.append(_) - _ = re.sub(r"\((.*?)\)", "", _) - if _ != __t[-1]: - __t.append(_) - lst = [] - for i, t in enumerate(__t): - t = t.strip() - if t in lst: - continue - if (len(t) < 10) and (all(ord(c) < 128 for c in t)): - continue - lst.append(t) - searchvndbqueue.put((0, gamepath, lst)) + _ = re.sub(r"\((.*?)\)", "", _) + if _ != __t[-1]: + __t.append(_) + lst = [] + for i, t in enumerate(__t): + t = t.strip() + if t in lst: + continue + if (len(t) < 10) and (all(ord(c) < 128 for c in t)): + continue + lst.append(t) + return lst -def parsetask(_type, gamepath, arg): - if _type == 2: - dispatachtask(gamepath) - elif _type == 0: - searchargs = arg +targetmod = {} +for k in globalconfig["metadata"]: + targetmod[k] = importlib.import_module(f"myutils.metadata.{k}").searcher(k) + + +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 for arg in searchargs: - vid = getvidbytitle(arg) + vid = targetmod[key].getidbytitle(arg) if vid: break if not vid: - return - savehook_new_data[gamepath]["vid"] = int(vid[1:]) - savehook_new_data[gamepath]["searchnoresulttime"] = time.time() - searchvndbqueue.put((1, gamepath, int(vid[1:]))) + continue + idname = globalconfig["metadata"][key]["target"] + savehook_new_data[gamepath][idname] = vid + 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: - vid = 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 + trysearchforid(gamepath, arg) def everymethodsthread(): while True: _ = searchvndbqueue.get() _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() -def vidchangedtask(gamepath, vid): - try: - vid = int(vid) - except: +def gamdidchangedtask(key, idname, gamepath): + vid = savehook_new_data[gamepath][idname] + if vid == "": return - - savehook_new_data[gamepath]["isimagepathusersetted_much"] = False - savehook_new_data[gamepath]["isimagepathusersetted"] = False - savehook_new_data[gamepath]["vid"] = vid - searchvndbqueue.put((1, gamepath, vid), 1) + else: + try: + if globalconfig["metadata"][key]["idtype"] == 0: + try: + 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): @@ -205,14 +256,14 @@ def titlechangedtask(gamepath, title): def checkifnewgame(targetlist, gamepath, title=None): - if gamepath in targetlist: - return False - targetlist.insert(0, gamepath) - + isnew = gamepath in targetlist + if not isnew: + targetlist.insert(0, gamepath) if gamepath not in savehook_new_data: savehook_new_data[gamepath] = getdefaultsavehook(gamepath, title) - searchvndbqueue.put((2, gamepath, None)) - return True + searchvndbqueue.put((0, gamepath, [title] + guessmaybetitle(gamepath))) + return isnew + kanjichs2ja = str.maketrans(static_data["kanjichs2ja"]) diff --git a/LunaTranslator/LunaTranslator/ocrengines/baiduocr_X.py b/LunaTranslator/LunaTranslator/ocrengines/baiduocr_X.py index c93784c8..1487823b 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/baiduocr_X.py +++ b/LunaTranslator/LunaTranslator/ocrengines/baiduocr_X.py @@ -29,7 +29,7 @@ class OCR(baseocr): self.config["API 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=" + self.appid + "&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", ][interfacetype] - response = self.session.post(url, params=params, headers=headers, data=data) + response = self.proxysession.post(url, params=params, headers=headers, data=data) try: self.countnum() diff --git a/LunaTranslator/LunaTranslator/ocrengines/baiduocr_ts.py b/LunaTranslator/LunaTranslator/ocrengines/baiduocr_ts.py index d0764562..05bb4bee 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/baiduocr_ts.py +++ b/LunaTranslator/LunaTranslator/ocrengines/baiduocr_ts.py @@ -67,7 +67,7 @@ class OCR(baseocr): headers = { "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: js = response.json() diff --git a/LunaTranslator/LunaTranslator/ocrengines/docsumo.py b/LunaTranslator/LunaTranslator/ocrengines/docsumo.py index 6d2bc65c..db5a7fc2 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/docsumo.py +++ b/LunaTranslator/LunaTranslator/ocrengines/docsumo.py @@ -33,7 +33,7 @@ class OCR(baseocr): + "\r\n------WebKitFormBoundaryUjYOv45hug6CFh3t--\r\n".encode("latin-1") ) - response = self.session.post( + response = self.proxysession.post( "https://ocrserver.docsumo.com/api/v1/ocr/extract/", headers=headers, data=data, diff --git a/LunaTranslator/LunaTranslator/ocrengines/feishu.py b/LunaTranslator/LunaTranslator/ocrengines/feishu.py index 635df4de..2cf3bceb 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/feishu.py +++ b/LunaTranslator/LunaTranslator/ocrengines/feishu.py @@ -12,7 +12,7 @@ class OCR(baseocr): app_id = self.config["app_id"] app_secret = self.config["app_secret"] 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", headers={"Content-Type": "application/json; charset=utf-8"}, json={"app_id": app_id, "app_secret": app_secret}, @@ -27,7 +27,7 @@ class OCR(baseocr): def ocr(self, imagebinary): token = self.check() 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", headers={ "Content-Type": "application/json; charset=utf-8", diff --git a/LunaTranslator/LunaTranslator/ocrengines/googlecloudvision.py b/LunaTranslator/LunaTranslator/ocrengines/googlecloudvision.py index 47fff7a6..72581a96 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/googlecloudvision.py +++ b/LunaTranslator/LunaTranslator/ocrengines/googlecloudvision.py @@ -21,7 +21,7 @@ class OCR(baseocr): } ] } - response = self.session.post(ocr_url, json=data) + response = self.proxysession.post(ocr_url, json=data) try: boxs = [] texts = [] diff --git a/LunaTranslator/LunaTranslator/ocrengines/ocrspace.py b/LunaTranslator/LunaTranslator/ocrengines/ocrspace.py index c64b2a71..275fe315 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/ocrspace.py +++ b/LunaTranslator/LunaTranslator/ocrengines/ocrspace.py @@ -48,7 +48,7 @@ class OCR(baseocr): "apikey": apikey, } - response = self.session.post( + response = self.proxysession.post( "https://" + base + "/parse/image", headers=headers, data=data ) # print(response.text) diff --git a/LunaTranslator/LunaTranslator/ocrengines/txocr.py b/LunaTranslator/LunaTranslator/ocrengines/txocr.py index b73c8a29..b8c1dfcf 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/txocr.py +++ b/LunaTranslator/LunaTranslator/ocrengines/txocr.py @@ -55,7 +55,7 @@ class OCR(baseocr): hashed = hmac.new(key, raw, sha1) b64output = base64.encodebytes(hashed.digest()).decode("utf-8") req_para.update({"Signature": b64output}) - r = self.session.get( + r = self.proxysession.get( url="https://ocr.tencentcloudapi.com/", params=req_para, timeout=10 ) # print(r.text) diff --git a/LunaTranslator/LunaTranslator/ocrengines/txocrtrans.py b/LunaTranslator/LunaTranslator/ocrengines/txocrtrans.py index b3f699b8..cbc463c2 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/txocrtrans.py +++ b/LunaTranslator/LunaTranslator/ocrengines/txocrtrans.py @@ -103,7 +103,7 @@ class OCR(baseocr): + signature ) - r = self.session.post( + r = self.proxysession.post( url="https://tmt.tencentcloudapi.com", headers={ "Authorization": authorization, diff --git a/LunaTranslator/LunaTranslator/ocrengines/xunfei.py b/LunaTranslator/LunaTranslator/ocrengines/xunfei.py index 18464c85..6f748c48 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/xunfei.py +++ b/LunaTranslator/LunaTranslator/ocrengines/xunfei.py @@ -120,7 +120,7 @@ class OCR(baseocr): # print("request_url:", request_url) 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 ) diff --git a/LunaTranslator/LunaTranslator/ocrengines/youdaocr.py b/LunaTranslator/LunaTranslator/ocrengines/youdaocr.py index 9884f06d..7665fa0d 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/youdaocr.py +++ b/LunaTranslator/LunaTranslator/ocrengines/youdaocr.py @@ -33,7 +33,7 @@ class OCR(baseocr): "company": "", } - response = self.session.post( + response = self.proxysession.post( "https://aidemo.youdao.com/ocrapi1", headers=headers, data=data ) @@ -82,7 +82,7 @@ class OCR(baseocr): data["sign"] = sign 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() try: _ = [] diff --git a/LunaTranslator/LunaTranslator/ocrengines/youdaocrtrans.py b/LunaTranslator/LunaTranslator/ocrengines/youdaocrtrans.py index feba260b..2f9618db 100644 --- a/LunaTranslator/LunaTranslator/ocrengines/youdaocrtrans.py +++ b/LunaTranslator/LunaTranslator/ocrengines/youdaocrtrans.py @@ -33,7 +33,7 @@ class OCR(baseocr): "company": "", } - response = self.session.post( + response = self.proxysession.post( "https://aidemo.youdao.com/ocrtransapi1", headers=headers, data=data ) @@ -134,9 +134,9 @@ class OCR(baseocr): def doCall(url, header, params, method): if "get" == method: - return self.session.get(url, params) + return self.proxysession.get(url, params) elif "post" == method: - return self.session.post(url, params, header) + return self.proxysession.post(url, params, header) def readFileAsBase64(imagebinary): return str(base64.b64encode(imagebinary), "utf-8") diff --git a/LunaTranslator/LunaTranslator/translator/DeepLX.py b/LunaTranslator/LunaTranslator/translator/DeepLX.py index e9b4d101..fb6ff85b 100644 --- a/LunaTranslator/LunaTranslator/translator/DeepLX.py +++ b/LunaTranslator/LunaTranslator/translator/DeepLX.py @@ -17,7 +17,7 @@ class TS(basetrans): "target_lang": self.tgtlang, } - response = self.session.post(self.config["api"], json=payload) + response = self.proxysession.post(self.config["api"], json=payload) try: return response.json()["data"] diff --git a/LunaTranslator/LunaTranslator/translator/ali.py b/LunaTranslator/LunaTranslator/translator/ali.py index b341bcaa..1411485d 100644 --- a/LunaTranslator/LunaTranslator/translator/ali.py +++ b/LunaTranslator/LunaTranslator/translator/ali.py @@ -8,7 +8,7 @@ class TS(basetrans): def inittranslator(self): - self.session.get( + self.proxysession.get( "https://translate.alibaba.com", 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", @@ -34,7 +34,7 @@ class TS(basetrans): }, ).text - self.csrf = self.session.get( + self.csrf = self.proxysession.get( "https://translate.alibaba.com/api/translate/csrftoken" ).json()["token"] @@ -69,7 +69,7 @@ class TS(basetrans): "query": content, "_csrf": self.csrf, } - r = self.session.post( + r = self.proxysession.post( "https://translate.alibaba.com/api/translate/text", headers=headers, params=form_data, diff --git a/LunaTranslator/LunaTranslator/translator/aliyunapi.py b/LunaTranslator/LunaTranslator/translator/aliyunapi.py index fd7f4f21..23bdd443 100644 --- a/LunaTranslator/LunaTranslator/translator/aliyunapi.py +++ b/LunaTranslator/LunaTranslator/translator/aliyunapi.py @@ -53,7 +53,7 @@ class TS(basetrans): "x-acs-signature-method": "HMAC-SHA1", "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: response = request.json() return response["Data"]["Translated"] diff --git a/LunaTranslator/LunaTranslator/translator/azure.py b/LunaTranslator/LunaTranslator/translator/azure.py index 37b7d9c1..e4e36305 100644 --- a/LunaTranslator/LunaTranslator/translator/azure.py +++ b/LunaTranslator/LunaTranslator/translator/azure.py @@ -30,7 +30,7 @@ class TS(basetrans): # You can pass more than one object in body. body = [{"text": query}] - request = self.session.post( + request = self.proxysession.post( constructed_url, params=params, headers=headers, json=body ) response = request.json() diff --git a/LunaTranslator/LunaTranslator/translator/baidu_ai.py b/LunaTranslator/LunaTranslator/translator/baidu_ai.py index 112c5684..a8076a30 100644 --- a/LunaTranslator/LunaTranslator/translator/baidu_ai.py +++ b/LunaTranslator/LunaTranslator/translator/baidu_ai.py @@ -22,7 +22,7 @@ class TS(basetrans): "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": '"Windows"', } - self.session.get( + self.proxysession.get( "https://fanyi.baidu.com/mtpe-individual/multimodal#/", headers=headers ) @@ -74,7 +74,7 @@ class TS(basetrans): "milliTimestamp": int(time.time() * 1000), } - response = self.session.post( + response = self.proxysession.post( "https://fanyi.baidu.com/ait/text/translate", headers=headers, json=json_data, diff --git a/LunaTranslator/LunaTranslator/translator/baiduapi.py b/LunaTranslator/LunaTranslator/translator/baiduapi.py index 0ffdca5c..4c02760d 100644 --- a/LunaTranslator/LunaTranslator/translator/baiduapi.py +++ b/LunaTranslator/LunaTranslator/translator/baiduapi.py @@ -47,7 +47,7 @@ class TS(basetrans): + sign ) - res = self.session.get("https://api.fanyi.baidu.com" + myurl) + res = self.proxysession.get("https://api.fanyi.baidu.com" + myurl) try: _ = "\n".join([_["dst"] for _ in res.json()["trans_result"]]) diff --git a/LunaTranslator/LunaTranslator/translator/caiyun.py b/LunaTranslator/LunaTranslator/translator/caiyun.py index e736813b..0d72f5b5 100644 --- a/LunaTranslator/LunaTranslator/translator/caiyun.py +++ b/LunaTranslator/LunaTranslator/translator/caiyun.py @@ -61,12 +61,12 @@ class TS(basetrans): json_data = { "browser_id": self.bid, } - self.session.options( + self.proxysession.options( "https://api.interpreter.caiyunai.com/v1/user/jwt/generate", headers=headers, json=json_data, ) - self.jwt = self.session.post( + self.jwt = self.proxysession.post( "https://api.interpreter.caiyunai.com/v1/user/jwt/generate", headers=headers, json=json_data, @@ -108,12 +108,12 @@ class TS(basetrans): "detect": True, "browser_id": self.bid, } - self.session.options( + self.proxysession.options( "https://api.interpreter.caiyunai.com/v1/translator", headers=headers, json=json_data, ) - response = self.session.post( + response = self.proxysession.post( "https://api.interpreter.caiyunai.com/v1/translator", headers=headers, json=json_data, diff --git a/LunaTranslator/LunaTranslator/translator/caiyunapi.py b/LunaTranslator/LunaTranslator/translator/caiyunapi.py index 4b661bbf..82042298 100644 --- a/LunaTranslator/LunaTranslator/translator/caiyunapi.py +++ b/LunaTranslator/LunaTranslator/translator/caiyunapi.py @@ -22,7 +22,7 @@ class TS(basetrans): "content-type": "application/json", "x-authorization": "token " + token, } - response = self.session.request( + response = self.proxysession.request( "POST", url, data=json.dumps(payload), headers=headers ) try: diff --git a/LunaTranslator/LunaTranslator/translator/claude.py b/LunaTranslator/LunaTranslator/translator/claude.py index 43d462ba..eb0784ca 100644 --- a/LunaTranslator/LunaTranslator/translator/claude.py +++ b/LunaTranslator/LunaTranslator/translator/claude.py @@ -88,7 +88,7 @@ class TS(basetrans): temperature=temperature, stream=usingstream, ) - response = self.session.post( + response = self.proxysession.post( self.checkv1(self.config["BASE_URL"]) + "/messages", headers=headers, json=data, diff --git a/LunaTranslator/LunaTranslator/translator/cohere.py b/LunaTranslator/LunaTranslator/translator/cohere.py index 3e442a76..0d85b481 100644 --- a/LunaTranslator/LunaTranslator/translator/cohere.py +++ b/LunaTranslator/LunaTranslator/translator/cohere.py @@ -124,7 +124,7 @@ class TS(basetrans): temperature=temperature, stream=usingstream, ) - response = self.session.post( + response = self.proxysession.post( "https://api.cohere.ai/v1/chat", headers=headers, json=data, diff --git a/LunaTranslator/LunaTranslator/translator/deepl2.py b/LunaTranslator/LunaTranslator/translator/deepl2.py index 4bd1fec5..45c51033 100644 --- a/LunaTranslator/LunaTranslator/translator/deepl2.py +++ b/LunaTranslator/LunaTranslator/translator/deepl2.py @@ -77,7 +77,7 @@ class TS(basetrans): "id": 3266547795, } - response = self.session.post( + response = self.proxysession.post( "https://www2.deepl.com/jsonrpc?client=chrome-extension,1.11.2", headers=headers, json=json_data, diff --git a/LunaTranslator/LunaTranslator/translator/deeplapi-free.py b/LunaTranslator/LunaTranslator/translator/deeplapi-free.py index 481c301a..9f35c5c5 100644 --- a/LunaTranslator/LunaTranslator/translator/deeplapi-free.py +++ b/LunaTranslator/LunaTranslator/translator/deeplapi-free.py @@ -28,7 +28,7 @@ class TS(basetrans): + self.srclang ) - response = self.session.post( + response = self.proxysession.post( "https://api-free.deepl.com/v2/translate", headers=headers, verify=False, diff --git a/LunaTranslator/LunaTranslator/translator/deeplapi.py b/LunaTranslator/LunaTranslator/translator/deeplapi.py index f2fdef26..bdb26101 100644 --- a/LunaTranslator/LunaTranslator/translator/deeplapi.py +++ b/LunaTranslator/LunaTranslator/translator/deeplapi.py @@ -28,7 +28,7 @@ class TS(basetrans): + self.srclang ) - response = self.session.post( + response = self.proxysession.post( "https://api.deepl.com/v2/translate", headers=headers, verify=False, diff --git a/LunaTranslator/LunaTranslator/translator/feishu.py b/LunaTranslator/LunaTranslator/translator/feishu.py index 1e083c16..5d56ecec 100644 --- a/LunaTranslator/LunaTranslator/translator/feishu.py +++ b/LunaTranslator/LunaTranslator/translator/feishu.py @@ -14,7 +14,7 @@ class TS(basetrans): app_id = self.multiapikeycurrent["app_id"] app_secret = self.multiapikeycurrent["app_secret"] 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", headers={"Content-Type": "application/json; charset=utf-8"}, json={"app_id": app_id, "app_secret": app_secret}, @@ -29,7 +29,7 @@ class TS(basetrans): def translate(self, query): token = self.check() - res = self.session.post( + res = self.proxysession.post( "https://open.feishu.cn/open-apis/translation/v1/text/translate", headers={ "Content-Type": "application/json; charset=utf-8", diff --git a/LunaTranslator/LunaTranslator/translator/gemini.py b/LunaTranslator/LunaTranslator/translator/gemini.py index 2bbd9a98..5b5b6876 100644 --- a/LunaTranslator/LunaTranslator/translator/gemini.py +++ b/LunaTranslator/LunaTranslator/translator/gemini.py @@ -86,9 +86,9 @@ class TS(basetrans): payload= {**contents, **safety, **sys_message, **gen_config } - res = self.session.post( + res = self.proxysession.post( f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent", - params={"key": self.config["SECRET_KEY"]}, + params={"key": self.multiapikeycurrent["SECRET_KEY"]}, json=payload ) try: diff --git a/LunaTranslator/LunaTranslator/translator/google.py b/LunaTranslator/LunaTranslator/translator/google.py index 0f7483b8..28c154bd 100644 --- a/LunaTranslator/LunaTranslator/translator/google.py +++ b/LunaTranslator/LunaTranslator/translator/google.py @@ -11,7 +11,7 @@ class TS(basetrans): def inittranslator(self): - _ = self.session.get( + _ = self.proxysession.get( "https://translate.google.com/", headers={ "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", } - response = self.session.post( + response = self.proxysession.post( "https://translate.google.com/_/TranslateWebserverUi/data/batchexecute", verify=False, headers=headers, diff --git a/LunaTranslator/LunaTranslator/translator/google2.py b/LunaTranslator/LunaTranslator/translator/google2.py index 30289120..409df559 100644 --- a/LunaTranslator/LunaTranslator/translator/google2.py +++ b/LunaTranslator/LunaTranslator/translator/google2.py @@ -39,7 +39,7 @@ class TS(basetrans): "q": content, } - response = self.session.get( + response = self.proxysession.get( "https://translate.google.com/m", params=params, verify=False, diff --git a/LunaTranslator/LunaTranslator/translator/googleapi.py b/LunaTranslator/LunaTranslator/translator/googleapi.py index 4ef4ac10..6d04038b 100644 --- a/LunaTranslator/LunaTranslator/translator/googleapi.py +++ b/LunaTranslator/LunaTranslator/translator/googleapi.py @@ -16,7 +16,7 @@ class TS(basetrans): "target": self.tgtlang, "q": (query), } - response = self.session.get( + response = self.proxysession.get( "https://translation.googleapis.com/language/translate/v2/", params=params ) diff --git a/LunaTranslator/LunaTranslator/translator/gptcommon.py b/LunaTranslator/LunaTranslator/translator/gptcommon.py index 48d3d3e6..c135930c 100644 --- a/LunaTranslator/LunaTranslator/translator/gptcommon.py +++ b/LunaTranslator/LunaTranslator/translator/gptcommon.py @@ -91,7 +91,7 @@ class gptcommon(basetrans): frequency_penalty=self.config["frequency_penalty"], stream=usingstream, ) - response = self.session.post( + response = self.proxysession.post( self.createurl(), headers=self.createheaders(), params=self.createparam(), diff --git a/LunaTranslator/LunaTranslator/translator/huoshan.py b/LunaTranslator/LunaTranslator/translator/huoshan.py index 67a5e345..439e166f 100644 --- a/LunaTranslator/LunaTranslator/translator/huoshan.py +++ b/LunaTranslator/LunaTranslator/translator/huoshan.py @@ -28,7 +28,7 @@ class TS(basetrans): "glossary_list": [], "category": "", } - response = self.session.post( + response = self.proxysession.post( "https://translate.volcengine.com/crx/translate/v1/", headers=headers, json=json_data, diff --git a/LunaTranslator/LunaTranslator/translator/ibm.py b/LunaTranslator/LunaTranslator/translator/ibm.py index a2c149c0..9354a9df 100644 --- a/LunaTranslator/LunaTranslator/translator/ibm.py +++ b/LunaTranslator/LunaTranslator/translator/ibm.py @@ -12,7 +12,7 @@ class TS(basetrans): headers = {"Content-Type": "application/json"} 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) ) try: diff --git a/LunaTranslator/LunaTranslator/translator/lingva.py b/LunaTranslator/LunaTranslator/translator/lingva.py index dae3b1c7..9a7fb8ac 100644 --- a/LunaTranslator/LunaTranslator/translator/lingva.py +++ b/LunaTranslator/LunaTranslator/translator/lingva.py @@ -22,7 +22,7 @@ class TS(basetrans): def translate(self, content): # print(self.url%(self.srclang,self.tgtlang,urllib.parse.quote(content))) - x = self.session.get( + x = self.proxysession.get( "https://" + self.config["host"] + "/api/v1/%s/%s/%s" % (self.srclang, self.tgtlang, quote_plus(content)), diff --git a/LunaTranslator/LunaTranslator/translator/microsoft.py b/LunaTranslator/LunaTranslator/translator/microsoft.py index 997f55c6..062d8924 100644 --- a/LunaTranslator/LunaTranslator/translator/microsoft.py +++ b/LunaTranslator/LunaTranslator/translator/microsoft.py @@ -91,7 +91,7 @@ def translate_async(text, to_language, from_language=None, self=None): "Content-Type": "application/json", } json_data = [{"Text": text}] - response = self.session.post( + response = self.proxysession.post( "https://{}".format(url), headers=headers, data=json.dumps(json_data).encode("utf-8"), diff --git a/LunaTranslator/LunaTranslator/translator/papago.py b/LunaTranslator/LunaTranslator/translator/papago.py index 760e17cd..632a7fa5 100644 --- a/LunaTranslator/LunaTranslator/translator/papago.py +++ b/LunaTranslator/LunaTranslator/translator/papago.py @@ -22,10 +22,10 @@ class TS(basetrans): "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", } - 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() 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.uuid = uuid.uuid4().__str__() @@ -80,7 +80,7 @@ class TS(basetrans): "text": content, } - r = self.session.post( + r = self.proxysession.post( "https://papago.naver.com/apis/n2mt/translate", headers=headers, data=data ) diff --git a/LunaTranslator/LunaTranslator/translator/qqimt.py b/LunaTranslator/LunaTranslator/translator/qqimt.py index fccce355..22db891a 100644 --- a/LunaTranslator/LunaTranslator/translator/qqimt.py +++ b/LunaTranslator/LunaTranslator/translator/qqimt.py @@ -32,7 +32,7 @@ class TS(basetrans): "target": {"lang": self.tgtlang}, } - response = self.session.post( + response = self.proxysession.post( "https://transmart.qq.com/api/imt", headers=headers, json=data ) return response.json()["auto_translation"] diff --git a/LunaTranslator/LunaTranslator/translator/sougou2.py b/LunaTranslator/LunaTranslator/translator/sougou2.py index c2af4f07..a1bfdf83 100644 --- a/LunaTranslator/LunaTranslator/translator/sougou2.py +++ b/LunaTranslator/LunaTranslator/translator/sougou2.py @@ -25,7 +25,7 @@ class TS(basetrans): "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": '"Windows"', } - res = self.session.get( + res = self.proxysession.get( "https://fanyi.sogou.com/text?keyword=" + quote(content) + "&transfrom=" diff --git a/LunaTranslator/LunaTranslator/translator/sugoix.py b/LunaTranslator/LunaTranslator/translator/sugoix.py index 01a5e238..cbe0413a 100644 --- a/LunaTranslator/LunaTranslator/translator/sugoix.py +++ b/LunaTranslator/LunaTranslator/translator/sugoix.py @@ -11,7 +11,7 @@ class TS(basetrans): "message": "translate sentences", } - response = self.session.post(self.config["api"], json=json_data) + response = self.proxysession.post(self.config["api"], json=json_data) try: return response.json() except: diff --git a/LunaTranslator/LunaTranslator/translator/tencentapi.py b/LunaTranslator/LunaTranslator/translator/tencentapi.py index 10cff287..7dceedad 100644 --- a/LunaTranslator/LunaTranslator/translator/tencentapi.py +++ b/LunaTranslator/LunaTranslator/translator/tencentapi.py @@ -61,7 +61,7 @@ class TS(basetrans): 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()) return r diff --git a/LunaTranslator/LunaTranslator/translator/xiaoniu.py b/LunaTranslator/LunaTranslator/translator/xiaoniu.py index e3136097..89b221d7 100644 --- a/LunaTranslator/LunaTranslator/translator/xiaoniu.py +++ b/LunaTranslator/LunaTranslator/translator/xiaoniu.py @@ -28,7 +28,7 @@ class TS(basetrans): "src_text": query, "apikey": apikey, } - response = self.session.post( + response = self.proxysession.post( "https://api.niutrans.com/NiuTransServer/translation", headers=headers, params=params, diff --git a/LunaTranslator/LunaTranslator/translator/yandexapi.py b/LunaTranslator/LunaTranslator/translator/yandexapi.py index c3d4ffcb..56efb042 100644 --- a/LunaTranslator/LunaTranslator/translator/yandexapi.py +++ b/LunaTranslator/LunaTranslator/translator/yandexapi.py @@ -16,7 +16,7 @@ class TS(basetrans): "text": content, } - response = self.session.get(url, params=params) + response = self.proxysession.get(url, params=params) try: return response.json()["text"][0] diff --git a/LunaTranslator/LunaTranslator/translator/youdao.py b/LunaTranslator/LunaTranslator/translator/youdao.py index e0187f63..c833576d 100644 --- a/LunaTranslator/LunaTranslator/translator/youdao.py +++ b/LunaTranslator/LunaTranslator/translator/youdao.py @@ -45,9 +45,9 @@ class TS(basetrans): } # proxies = { "http": None, "https": None} - self.session.trust_env = False - self.session.headers.update(self.headers) - self.session.get("https://fanyi.youdao.com") + self.proxysession.trust_env = False + self.proxysession.headers.update(self.headers) + self.proxysession.get("https://fanyi.youdao.com") def translate(self, content): @@ -91,7 +91,7 @@ class TS(basetrans): "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": '"Windows"', } - response = self.session.post( + response = self.proxysession.post( "https://fanyi.youdao.com/translate_o", params=params, headers=headers, diff --git a/LunaTranslator/LunaTranslator/translator/youdao3.py b/LunaTranslator/LunaTranslator/translator/youdao3.py index bf979af1..21e35595 100644 --- a/LunaTranslator/LunaTranslator/translator/youdao3.py +++ b/LunaTranslator/LunaTranslator/translator/youdao3.py @@ -14,7 +14,7 @@ class TS(basetrans): } def inittranslator(self): - self.session.get( + self.proxysession.get( "https://m.youdao.com/translate", 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", @@ -61,7 +61,7 @@ class TS(basetrans): "sec-ch-ua-platform": '"Windows"', } - response = self.session.post( + response = self.proxysession.post( "https://m.youdao.com/translate", data=data, headers=headers, diff --git a/LunaTranslator/LunaTranslator/translator/youdao5.py b/LunaTranslator/LunaTranslator/translator/youdao5.py index bb46b594..d2d6db07 100644 --- a/LunaTranslator/LunaTranslator/translator/youdao5.py +++ b/LunaTranslator/LunaTranslator/translator/youdao5.py @@ -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", } - self.session.trust_env = False - self.session.headers.update(self.headers) - self.session.get("https://ai.youdao.com/product-fanyi-text.s") + self.proxysession.trust_env = False + self.proxysession.headers.update(self.headers) + self.proxysession.get("https://ai.youdao.com/product-fanyi-text.s") def translate(self, content): @@ -50,7 +50,7 @@ class TS(basetrans): "to": self.tgtlang, } - response = self.session.post( + response = self.proxysession.post( "https://aidemo.youdao.com/trans", data=data, headers=headers ) try: diff --git a/LunaTranslator/LunaTranslator/translator/youdaoapi.py b/LunaTranslator/LunaTranslator/translator/youdaoapi.py index a96cd69a..e2dd4c60 100644 --- a/LunaTranslator/LunaTranslator/translator/youdaoapi.py +++ b/LunaTranslator/LunaTranslator/translator/youdaoapi.py @@ -41,7 +41,7 @@ class TS(basetrans): "signType": "v3", # 签名类型,固定值 "curtime": time_curtime, # 秒级时间戳 } - r = self.session.get(youdao_url, params=data) # 获取返回的json()内容 + r = self.proxysession.get(youdao_url, params=data) # 获取返回的json()内容 try: self.countnum(content) diff --git a/LunaTranslator/LunaTranslator/translator/youdaodict.py b/LunaTranslator/LunaTranslator/translator/youdaodict.py index f0efc68c..ceb56931 100644 --- a/LunaTranslator/LunaTranslator/translator/youdaodict.py +++ b/LunaTranslator/LunaTranslator/translator/youdaodict.py @@ -118,7 +118,7 @@ class TS(basetrans): "appVersion": "8.10.8.0", "product": "deskdict", } - response = self.session.post( + response = self.proxysession.post( "https://dict.youdao.com/dicttranslate", params=param, cookies=cookies, diff --git a/LunaTranslator/LunaTranslator/translator/yunyi2.py b/LunaTranslator/LunaTranslator/translator/yunyi2.py index 164fc1ab..ff3d463d 100644 --- a/LunaTranslator/LunaTranslator/translator/yunyi2.py +++ b/LunaTranslator/LunaTranslator/translator/yunyi2.py @@ -25,7 +25,7 @@ class TS(basetrans): "sec-ch-ua-platform": '"Windows"', } - response = self.session.post( + response = self.proxysession.post( "https://online.cloudtranslation.com/api/v1.0/request_translate/try_translate", data={ "type": "text", diff --git a/LunaTranslator/LunaTranslator/tts/basettsclass.py b/LunaTranslator/LunaTranslator/tts/basettsclass.py index 125880d1..ea80630a 100644 --- a/LunaTranslator/LunaTranslator/tts/basettsclass.py +++ b/LunaTranslator/LunaTranslator/tts/basettsclass.py @@ -2,9 +2,12 @@ from myutils.config import globalconfig import threading, os, functools from myutils.wrapper import threader from traceback import print_exc +from myutils.proxy import getproxy class TTSbase: + typename = None + def init(self): pass @@ -19,6 +22,10 @@ class TTSbase: #################### # 一些可能需要的属性 + @property + def proxy(self): + return getproxy(("reader", self.typename)) + @property def config(self): return self.privateconfig["args"] diff --git a/LunaTranslator/LunaTranslator/tts/edgetts.py b/LunaTranslator/LunaTranslator/tts/edgetts.py index 2c389a5f..ae35d013 100644 --- a/LunaTranslator/LunaTranslator/tts/edgetts.py +++ b/LunaTranslator/LunaTranslator/tts/edgetts.py @@ -1,5 +1,4 @@ import requests -from myutils.proxy import getproxy import websocket from datetime import datetime @@ -17,12 +16,12 @@ class TTS(TTSbase): def getvoicelist(self): self.alllist = requests.get( "https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=6A5AA1D4EAFF4E9FB37E23D68491D6F4", - proxies=getproxy(), + proxies=self.proxy, ).json() return [_["ShortName"] for _ in self.alllist] 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 @@ -123,7 +122,7 @@ def connect_id() -> str: 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" headers = { @@ -144,7 +143,7 @@ def transferMsTTSData(rate, content, voice): "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", ] - proxy = getproxy()["https"] + proxy = proxy["https"] if proxy: ip, port = proxy.split(":") diff --git a/LunaTranslator/LunaTranslator/tts/gtts.py b/LunaTranslator/LunaTranslator/tts/gtts.py index 55ca0153..eeb7ff56 100644 --- a/LunaTranslator/LunaTranslator/tts/gtts.py +++ b/LunaTranslator/LunaTranslator/tts/gtts.py @@ -4,7 +4,6 @@ import json, time import logging, os import re import urllib -from myutils.proxy import getproxy import requests _langs = { @@ -379,6 +378,7 @@ class gTTS: def __init__( self, + ref, text, tld="com", lang="en", @@ -400,7 +400,7 @@ class gTTS: ).run, timeout=None, ): - + self.ref = ref # Debug for k, v in dict(locals()).items(): if k == "self": @@ -492,7 +492,7 @@ class gTTS: url=translate_url, data=data, headers=self.GOOGLE_TTS_HEADERS, - proxies=getproxy(), + proxies=self.ref.proxy, ) # Prepare request @@ -597,6 +597,7 @@ class gTTSError(Exception): from tts.basettsclass import TTSbase + from myutils.config import getlangsrc @@ -605,5 +606,5 @@ class TTS(TTSbase): return [""] def speak(self, content, rate, voice, voiceidx): - tts = gTTS(content, lang=getlangsrc()) + tts = gTTS(self, content, lang=getlangsrc()) return tts.save() diff --git a/LunaTranslator/LunaTranslator/tts/huoshantts.py b/LunaTranslator/LunaTranslator/tts/huoshantts.py index d675b696..4780a10b 100644 --- a/LunaTranslator/LunaTranslator/tts/huoshantts.py +++ b/LunaTranslator/LunaTranslator/tts/huoshantts.py @@ -1,7 +1,6 @@ from traceback import print_exc import requests import base64 -import time, os from tts.basettsclass import TTSbase @@ -43,7 +42,7 @@ class TTS(TTSbase): "https://translate.volcengine.com/crx/tts/v1/", headers=headers, json=json_data, - proxies={"http": None, "https": None}, + proxies=self.proxy, ) b64 = base64.b64decode(response.json()["audio"]["data"]) diff --git a/LunaTranslator/LunaTranslator/tts/youdaotts.py b/LunaTranslator/LunaTranslator/tts/youdaotts.py index 02fab944..23107b41 100644 --- a/LunaTranslator/LunaTranslator/tts/youdaotts.py +++ b/LunaTranslator/LunaTranslator/tts/youdaotts.py @@ -36,6 +36,6 @@ class TTS(TTSbase): "https://dict.youdao.com/dictvoice", params=params, headers=headers, - proxies={"http": None, "https": None}, + proxies=self.proxy, ).content return response diff --git a/LunaTranslator/files/defaultconfig/config.json b/LunaTranslator/files/defaultconfig/config.json index b5c441cd..e29154d9 100644 --- a/LunaTranslator/files/defaultconfig/config.json +++ b/LunaTranslator/files/defaultconfig/config.json @@ -17,6 +17,30 @@ "network": 1, "hookmagpie": true, "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": [ [ "LunaTranslator", @@ -715,7 +739,8 @@ "huoshantts": { "use": false, "voice": "", - "name": "火山TTS" + "name": "火山TTS", + "useproxy": false }, "edgetts": { "use": false, @@ -725,22 +750,26 @@ "youdaotts": { "use": false, "voice": "", - "name": "有道TTS" + "name": "有道TTS", + "useproxy": false }, "windowstts": { "use": false, "voice": "", - "name": "WindowsTTS" + "name": "WindowsTTS", + "type": "offline" }, "NeoSpeech": { "use": false, "voice": "", - "name": "NeoSpeech" + "name": "NeoSpeech", + "type": "offline" }, "voiceroid2": { "use": false, "voice": "", "name": "VoiceRoid2/VoiceRoid+", + "type": "offline", "args": { "path": "" }, @@ -756,6 +785,7 @@ "use": false, "voice": "", "name": "VOICEVOX", + "type": "offline", "args": { "path": "", "Port": 50021 @@ -779,6 +809,7 @@ "use": false, "voice": "", "name": "vits-simple-api", + "type": "offline", "args": { "Port": 23456, "preset": "" @@ -802,6 +833,14 @@ "voice": "" } }, + "github": { + "versioncheck": { + "useproxy": false + }, + "download": { + "useproxy": true + } + }, "hirasetting": { "mecab": { "use": false, @@ -824,18 +863,21 @@ "shiftjis" ] } - } + }, + "type": "offline" }, "mojinlt": { "use": false, "name": "mojinlt", "args": { "Moji NLT Token": "" - } + }, + "useproxy": false }, "latin": { "use": false, "name": "标点", + "type": "offline", "args": { "punctuations": [ " ", @@ -909,7 +951,8 @@ } }, "use": false, - "name": "小学馆" + "name": "小学馆", + "type": "offline" }, "edict": { "use": false, @@ -940,7 +983,8 @@ "max": 10000, "step": 1 } - } + }, + "type": "offline" }, "edict2": { "use": false, @@ -970,7 +1014,8 @@ "max": 10000, "step": 1 } - } + }, + "type": "offline" }, "linggesi": { "use": false, @@ -1000,7 +1045,8 @@ "max": 10000, "step": 1 } - } + }, + "type": "offline" }, "mojidict": { "use": false, @@ -1016,7 +1062,8 @@ "max": 10000, "step": 1 } - } + }, + "useproxy": false }, "youdao": { "use": false, @@ -1032,7 +1079,8 @@ "max": 10000, "step": 1 } - } + }, + "useproxy": false }, "jisho": { "use": false, @@ -1127,7 +1175,8 @@ "Flow" ] } - } + }, + "type": "offline" } }, "darklight": 0, @@ -1159,15 +1208,18 @@ "ocr": { "local": { "use": true, - "name": "本地OCR" + "name": "本地OCR", + "type": "offline" }, "windowsocr": { "use": false, - "name": "WindowsOCR" + "name": "WindowsOCR", + "type": "offline" }, "tesseract5": { "use": false, - "name": "Tesseract5" + "name": "Tesseract5", + "type": "offline" }, "baiduocr_X": { "use": false, @@ -1219,7 +1271,8 @@ }, "mangaocr": { "use": false, - "name": "manga-ocr" + "name": "manga-ocr", + "type": "offline" } }, "fanyi": { diff --git a/LunaTranslator/files/lang/ar.json b/LunaTranslator/files/lang/ar.json index 58a6ab36..335fa18a 100644 --- a/LunaTranslator/files/lang/ar.json +++ b/LunaTranslator/files/lang/ar.json @@ -9,7 +9,6 @@ "获取失败": "الحصول على فشل", "助動詞": "فعل مساعد", "添加行": "إضافة صف", - "在线OCR": "التعرف الضوئي على الحروف على الانترنت", "图标": "أيقونات", "首选翻译": "يفضل الترجمة", "移除非选定hook": "إزالة غير اختيار هوك", @@ -498,7 +497,6 @@ "云译": "سحابة ترجمة", "普通字体": "الخط العادي", "3D游戏模式": "لعبة وسائط 3D", - "统计信息": "معلومات إحصائية", "合并多行识别结果": "دمج نتائج تحديد خط متعددة", "空心线宽": "جوفاء خط العرض", "显示": "عرض .", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "امتيازات غير كافية ، يرجى تشغيل مع امتيازات المسؤول !", "标点": "علامات الترقيم", "添加到列表": "إضافة إلى قائمة", - "目标": "الهدف" + "目标": "الهدف", + "统计": "إحصائيات", + "元数据": "البيانات الوصفية", + "来源": "المصدر", + "首选的": "مفضل", + "设为封面": "مجموعة غطاء", + "复制": "نسخ", + "画廊": "معرض", + "删除图片": "حذف الصور" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/cht.json b/LunaTranslator/files/lang/cht.json index faa3d15f..3d59c5d2 100644 --- a/LunaTranslator/files/lang/cht.json +++ b/LunaTranslator/files/lang/cht.json @@ -440,7 +440,6 @@ "失败": "失敗", "仅使用激活的翻译": "僅使用啟動的翻譯", "云译": "雲譯", - "在线OCR": "線上OCR", "使用代理的项目": "使用代理的項目", "相关说明": "相關說明", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "如果你感覺該軟件對你有幫助,歡迎微信掃碼贊助,謝謝~", @@ -485,7 +484,6 @@ "打开目录": "打開目錄", "标题": "標題", "封面": "封面", - "统计信息": "統計資訊", "游戏时间": "遊戲時間", "未开始": "未開始", "秒": "秒", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "許可權不足,請以管理員許可權運行!", "标点": "標點", "添加到列表": "添加到清單", - "目标": "目標" + "目标": "目標", + "统计": "統計", + "元数据": "中繼資料", + "来源": "來源", + "首选的": "首選的", + "设为封面": "設為封面", + "复制": "複製", + "画廊": "畫廊", + "删除图片": "删除圖片" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/en.json b/LunaTranslator/files/lang/en.json index ebb01bfe..3e52d24d 100644 --- a/LunaTranslator/files/lang/en.json +++ b/LunaTranslator/files/lang/en.json @@ -440,7 +440,6 @@ "失败": "fail", "仅使用激活的翻译": "Use only active translations", "云译": "Cloud translation", - "在线OCR": "Online OCR", "使用代理的项目": "Projects using proxies", "相关说明": "Related instructions", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "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", "标题": "title", "封面": "cover", - "统计信息": "statistical information ", "游戏时间": "Game time", "未开始": "Not Started", "秒": "second", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Insufficient permissions, please run with administrator privileges!", "标点": "punctuation", "添加到列表": "Add to list", - "目标": "target" + "目标": "target", + "统计": "statistics", + "元数据": "metadata", + "来源": "source", + "首选的": "Preferred", + "设为封面": "Set as Cover", + "复制": "copy", + "画廊": "gallery", + "删除图片": "Delete image" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/es.json b/LunaTranslator/files/lang/es.json index 684a4d06..6a61fee9 100644 --- a/LunaTranslator/files/lang/es.json +++ b/LunaTranslator/files/lang/es.json @@ -440,7 +440,6 @@ "失败": "Fracaso", "仅使用激活的翻译": "Solo se utilizan traducciones activadas", "云译": "Traducción en la nube", - "在线OCR": "OCR en línea", "使用代理的项目": "Proyectos con agentes", "相关说明": "Instrucciones pertinentes", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Si sientes que el software te ayuda, Bienvenido al patrocinio de escaneo de wechat, Gracias.", @@ -485,7 +484,6 @@ "打开目录": "Abrir catálogo", "标题": "Título", "封面": "Portada", - "统计信息": "Información Estadística", "游戏时间": "Tiempo de juego", "未开始": "Sin empezar", "秒": "Segundos", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "¡Permisos insuficientes, ¡ por favor, ejecute con permisos de administrador!", "标点": "Puntuación", "添加到列表": "Añadir a la lista", - "目标": "Objetivo" + "目标": "Objetivo", + "统计": "Estadísticas", + "元数据": "Metadata", + "来源": "Fuente", + "首选的": "Preferido", + "设为封面": "Como portada", + "复制": "Copiar", + "画廊": "Galería", + "删除图片": "Eliminar imagen" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/fr.json b/LunaTranslator/files/lang/fr.json index 8d868779..323b776e 100644 --- a/LunaTranslator/files/lang/fr.json +++ b/LunaTranslator/files/lang/fr.json @@ -440,7 +440,6 @@ "失败": "L'échec", "仅使用激活的翻译": "Utiliser uniquement les traductions activées", "云译": "Traduction Cloud", - "在线OCR": "OCR en ligne", "使用代理的项目": "Projets utilisant des agents", "相关说明": "Instructions connexes", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Si vous sentez que le logiciel vous aide, bienvenue Wechat scan code sponsoring, merci ~", @@ -485,7 +484,6 @@ "打开目录": "Ouvrir le catalogue", "标题": "Titre", "封面": "Couverture", - "统计信息": "Informations statistiques", "游戏时间": "Temps de jeu", "未开始": "Pas commencé", "秒": "Secondes", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Autorisations insuffisantes, exécutez avec des privilèges d'administrateur!", "标点": "Ponctuation", "添加到列表": "Ajouter à la Liste", - "目标": "Objectifs" + "目标": "Objectifs", + "统计": "Statistiques", + "元数据": "Métadonnées", + "来源": "Sources", + "首选的": "Préféré", + "设为封面": "Faire la couverture", + "复制": "Copier", + "画廊": "Galerie", + "删除图片": "Supprimer une image" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/it.json b/LunaTranslator/files/lang/it.json index 9a0ca7b5..c862d0dc 100644 --- a/LunaTranslator/files/lang/it.json +++ b/LunaTranslator/files/lang/it.json @@ -428,7 +428,6 @@ "失败": "fail", "仅使用激活的翻译": "Usa solo traduzioni attive", "云译": "Traduzione cloud", - "在线OCR": "OCR online", "使用代理的项目": "Progetti che utilizzano proxy", "相关说明": "Istruzioni correlate", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Se ritieni che questo software sia utile per te, sei il benvenuto a scansionare WeChat per la sponsorizzazione.", @@ -485,7 +484,6 @@ "打开目录": "Apri directory", "标题": "titolo", "封面": "cover", - "统计信息": "informazioni statistiche", "游戏时间": "Tempo di gioco", "未开始": "Non iniziato", "秒": "secondo", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Permessi insufficienti, si prega di eseguire con privilegi di amministratore!", "标点": "punteggiatura", "添加到列表": "Aggiungi alla lista", - "目标": "obiettivo" + "目标": "obiettivo", + "统计": "statistiche", + "元数据": "metadati", + "来源": "fonte", + "首选的": "Preferito", + "设为封面": "Imposta come copertina", + "复制": "copia", + "画廊": "gallery", + "删除图片": "Elimina immagine" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/ja.json b/LunaTranslator/files/lang/ja.json index 3870648a..2626c9be 100644 --- a/LunaTranslator/files/lang/ja.json +++ b/LunaTranslator/files/lang/ja.json @@ -440,7 +440,6 @@ "失败": "に失敗", "仅使用激活的翻译": "アクティブな翻訳のみを使用", "云译": "クラウド翻訳", - "在线OCR": "オンラインOCR", "使用代理的项目": "エージェントを使用したアイテム", "相关说明": "関連説明", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "もしあなたがこのソフトウェアがあなたに役立つと感じたら、微信スキャンコードの協賛を歓迎します、ありがとうございます~", @@ -485,7 +484,6 @@ "打开目录": "ディレクトリを開く", "标题": "タイトル", "封面": "カバー枚", - "统计信息": "統計#トウケイ#", "游戏时间": "ゲーム時間", "未开始": "開始していません", "秒": "秒", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "権限が不足しています。管理者権限で実行してください。", "标点": "ひょうてん", "添加到列表": "リストに追加", - "目标": "ターゲット" + "目标": "ターゲット", + "统计": "統計#トウケイ#", + "元数据": "メタデータ", + "来源": "ソース", + "首选的": "優先", + "设为封面": "表紙にする", + "复制": "レプリケーション", + "画廊": "ギャラリー", + "删除图片": "画像を削除" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/ko.json b/LunaTranslator/files/lang/ko.json index 785c1287..6c187236 100644 --- a/LunaTranslator/files/lang/ko.json +++ b/LunaTranslator/files/lang/ko.json @@ -440,7 +440,6 @@ "失败": "실패", "仅使用激活的翻译": "활성화된 번역만 사용", "云译": "클라우드 번역", - "在线OCR": "온라인 OCR", "使用代理的项目": "프록시 사용 항목", "相关说明": "관련 설명", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "만약 당신이 이 소프트웨어가 당신에게 도움이 된다고 느낀다면, 위챗 스캔 협찬을 환영합니다. 감사합니다~", @@ -485,7 +484,6 @@ "打开目录": "디렉토리 열기", "标题": "제목", "封面": "표지", - "统计信息": "통계 정보", "游戏时间": "게임 시간", "未开始": "시작하지 않음", "秒": "초", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "권한이 부족합니다. 관리자 권한으로 실행하십시오!", "标点": "구두점", "添加到列表": "목록에 추가", - "目标": "목표" + "目标": "목표", + "统计": "통계", + "元数据": "메타데이터", + "来源": "출처", + "首选的": "선호", + "设为封面": "표지로 설정하다", + "复制": "복제", + "画廊": "갤러리", + "删除图片": "그림 삭제" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/pl.json b/LunaTranslator/files/lang/pl.json index 0fd79e0b..51670e24 100644 --- a/LunaTranslator/files/lang/pl.json +++ b/LunaTranslator/files/lang/pl.json @@ -440,7 +440,6 @@ "失败": "niepowodzenie", "仅使用激活的翻译": "Używaj tylko aktywnych tłumaczeń", "云译": "Tłumaczenie chmury", - "在线OCR": "OCR online", "使用代理的项目": "Projekty wykorzystujące serwery proxy", "相关说明": "Powiązane instrukcje", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "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", "标题": "tytuł", "封面": "osłona", - "统计信息": "informacje statystyczne", "游戏时间": "Czas gry", "未开始": "Nie uruchomiono", "秒": "drugie", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Niewystarczające uprawnienia, proszę uruchomić z uprawnieniami administratora!", "标点": "interpunkcja", "添加到列表": "Dodaj do listy", - "目标": "cel" + "目标": "cel", + "统计": "statystyki", + "元数据": "metadane", + "来源": "źródło", + "首选的": "Preferowane", + "设为封面": "Ustaw jako okładka", + "复制": "kopia", + "画廊": "galeria", + "删除图片": "Usuń obraz" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/ru.json b/LunaTranslator/files/lang/ru.json index 52bdcc55..91031f4e 100644 --- a/LunaTranslator/files/lang/ru.json +++ b/LunaTranslator/files/lang/ru.json @@ -440,7 +440,6 @@ "失败": "Неудача", "仅使用激活的翻译": "Использовать только активный перевод", "云译": "Облачный перевод", - "在线OCR": "Онлайн OCR", "使用代理的项目": "Использовать прокси - проекты", "相关说明": "Примечания", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Если вы чувствуете, что программное обеспечение помогает вам, добро пожаловать в спонсорскую поддержку WeChat подметания, спасибо", @@ -485,7 +484,6 @@ "打开目录": "Открыть каталог", "标题": "Заголовок", "封面": "Обложка", - "统计信息": "Статистическая информация", "游戏时间": "Время игры", "未开始": "Не началось", "秒": "Секунда", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Недостаточные права, пожалуйста, запустите с правами администратора!", "标点": "Пунктуация", "添加到列表": "Добавить в список", - "目标": "Цель" + "目标": "Цель", + "统计": "Статистика", + "元数据": "Метаданные", + "来源": "Источник", + "首选的": "Предпочтительный", + "设为封面": "Установить обложку", + "复制": "Копирование", + "画廊": "Галерея", + "删除图片": "Удалить изображение" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/th.json b/LunaTranslator/files/lang/th.json index c8cea7a9..fe4d77e9 100644 --- a/LunaTranslator/files/lang/th.json +++ b/LunaTranslator/files/lang/th.json @@ -156,7 +156,6 @@ "标题": "ชื่อเรื่อง", "过滤尖括号<>": "กรองวงเล็บแหลม <>", "繁简转换": "การแปลงที่ง่ายดาย", - "统计信息": "ข้อมูลสถิติ", "设置": "การตั้งค่า", "接受的编码": "การเข้ารหัสที่ยอมรับ", "OCR自动化方法": "วิธีการอัตโนมัติ OCR", @@ -269,7 +268,6 @@ "自动检测": "การตรวจจับอัตโนมัติ", "繁体中文(BIG5)": "ภาษาจีนดั้งเดิม (BIG5)", "翻译等待时间(s)": "เวลารอการแปล (s)", - "在线OCR": "ออนไลน์ OCR", "词性": "คำพูด เพศ", "收到翻译结果时才刷新": "รีเฟรชเมื่อได้รับผลการแปล", "禁用DirectFlip": "ปิดใช้งาน DirectFlip", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "สิทธิ์ไม่เพียงพอโปรดเรียกใช้ด้วยสิทธิ์ของผู้ดูแลระบบ!", "标点": "เครื่องหมายวรรคตอน", "添加到列表": "เพิ่มลงในรายการ", - "目标": "วัตถุประสงค์" + "目标": "วัตถุประสงค์", + "统计": "สถิติ", + "元数据": "ข้อมูลกำกับภาพ", + "来源": "แหล่งที่มา", + "首选的": "ตัวเลือกแรก", + "设为封面": "ตั้งค่าเป็นปก", + "复制": "คัดลอก", + "画廊": "แกลเลอรี่", + "删除图片": "ลบรูปภาพ" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/tr.json b/LunaTranslator/files/lang/tr.json index 7e61bfce..eaa3a357 100644 --- a/LunaTranslator/files/lang/tr.json +++ b/LunaTranslator/files/lang/tr.json @@ -440,7 +440,6 @@ "失败": "başarısız", "仅使用激活的翻译": "Sadece aktif çevirimleri kullan", "云译": "Bulud çevirimi", - "在线OCR": "Online OCR", "使用代理的项目": "Proksiler kullanarak projeler", "相关说明": "İ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 ~", @@ -485,7 +484,6 @@ "打开目录": "Dizini Aç", "标题": "isim", "封面": "cover", - "统计信息": "istatistik bilgi", "游戏时间": "Oyun zamanı", "未开始": "Başlanmadı", "秒": "saniye", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Insufficient permissions, please run with administrator privileges!", "标点": "noqtalama", "添加到列表": "Listeye ekle", - "目标": "hedef" + "目标": "hedef", + "统计": "istatistikler", + "元数据": "metadata", + "来源": "kaynak", + "首选的": "Tercih et", + "设为封面": "Kapağı olarak ayarlayın", + "复制": "kopyalama", + "画廊": "Galeri", + "删除图片": "Resimi sil" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/uk.json b/LunaTranslator/files/lang/uk.json index b2cb02c3..bc85d6f1 100644 --- a/LunaTranslator/files/lang/uk.json +++ b/LunaTranslator/files/lang/uk.json @@ -428,7 +428,6 @@ "失败": "невдачі", "仅使用激活的翻译": "Використовувати лише активні переклади", "云译": "Переклад хмар", - "在线OCR": "В мережі OCR", "使用代理的项目": "Projects using proxies", "相关说明": "Пов’ язані інструкції", "如果你感觉该软件对你有帮助,欢迎微信扫码赞助,谢谢~": "Якщо ви відчуваєте, що це програмне забезпечення допомагає вам, ви можете сканувати WeChat для спонсорування. Дякую ~", @@ -485,7 +484,6 @@ "打开目录": "Відкрити каталог", "标题": "заголовок", "封面": "обкладинка", - "统计信息": "статистична інформація", "游戏时间": "Час гри", "未开始": "Не запущено", "秒": "second", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Недостатньо прав доступу, будь ласка, запускайте привілеї адміністратора!", "标点": "пунктуація", "添加到列表": "Додати до списку", - "目标": "мета" + "目标": "мета", + "统计": "статистика", + "元数据": "метадані", + "来源": "джерело", + "首选的": "Найбільше", + "设为封面": "Встановити як обкладинку", + "复制": "копіювати", + "画廊": "галерія", + "删除图片": "Вилучити зображення" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/vi.json b/LunaTranslator/files/lang/vi.json index 9dc860ff..67281159 100644 --- a/LunaTranslator/files/lang/vi.json +++ b/LunaTranslator/files/lang/vi.json @@ -440,7 +440,6 @@ "失败": "Thất bại", "仅使用激活的翻译": "Chỉ sử dụng bản dịch kích hoạt", "云译": "Dịch Mây", - "在线OCR": "Trực tuyến OCR", "使用代理的项目": "Các dự án sử dụng proxy", "相关说明": "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~", @@ -485,7 +484,6 @@ "打开目录": "Mở thư mục", "标题": "Tiêu đề", "封面": "Trang chủ", - "统计信息": "Thống kê", "游戏时间": "Thời gian chơi", "未开始": "Chưa bắt đầu", "秒": "giây", @@ -820,5 +818,13 @@ "权限不足,请以管理员权限运行!": "Không đủ quyền, hãy chạy với quyền quản trị viên!", "标点": "Chấm câu", "添加到列表": "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" } \ No newline at end of file diff --git a/LunaTranslator/files/lang/zh.json b/LunaTranslator/files/lang/zh.json index 404e3c0b..b67a8a91 100644 --- a/LunaTranslator/files/lang/zh.json +++ b/LunaTranslator/files/lang/zh.json @@ -155,7 +155,7 @@ "标题": "", "过滤尖括号<>": "", "繁简转换": "", - "统计信息": "", + "统计": "", "设置": "", "接受的编码": "", "OCR自动化方法": "", @@ -266,7 +266,6 @@ "自动检测": "", "繁体中文(BIG5)": "", "翻译等待时间(s)": "", - "在线OCR": "", "词性": "", "收到翻译结果时才刷新": "", "禁用DirectFlip": "", @@ -820,5 +819,12 @@ "权限不足,请以管理员权限运行!": "", "标点": "", "添加到列表": "", - "目标": "" + "目标": "", + "元数据": "", + "来源": "", + "首选的": "", + "设为封面": "", + "复制": "", + "画廊": "", + "删除图片": "" } \ No newline at end of file diff --git a/LunaTranslator/trans_lang.py b/LunaTranslator/trans_lang.py index 272e3560..fa62330c 100644 --- a/LunaTranslator/trans_lang.py +++ b/LunaTranslator/trans_lang.py @@ -39,12 +39,13 @@ if __name__=='__main__': js.pop(k) with open(f'./files/lang/'+f,'w',encoding='utf8') as ff: ff.write( json.dumps(js,ensure_ascii=False,sort_keys=False, indent=4)) + a=TS1('baiduapi') for kk in xxx: with open(f'./files/lang/{kk}.json','r',encoding='utf8') as ff: jsen=json.loads(ff.read()) - a=TS1('baiduapi') + a.tgtlang=xxx[kk] needpop=[] diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 5a0e29f1..06a73d59 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -28,8 +28,8 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/version) include(generate_product_version) set(VERSION_MAJOR 3) -set(VERSION_MINOR 2) -set(VERSION_PATCH 3) +set(VERSION_MINOR 5) +set(VERSION_PATCH 0) add_library(pch pch.cpp) target_precompile_headers(pch PUBLIC pch.h)