Skip to content

Commit

Permalink
Merge branch 'HIllya51:main' into xx
Browse files Browse the repository at this point in the history
  • Loading branch information
test123456654321 authored Oct 18, 2024
2 parents 241c33e + 3dc87ff commit 43e7fc3
Show file tree
Hide file tree
Showing 109 changed files with 535 additions and 504 deletions.
6 changes: 3 additions & 3 deletions .github/ISSUE_TEMPLATE/01_bug.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ body:

- type: textarea
attributes:
label: Log files 日志文件
label: Log file 日志文件
description: >
View log files in the "logs" directory. Please upload the log file as an attachment instead of copying its contents.
Run LunaTranslator_debug.exe to reproduce the error, and then upload the generated log_*.txt file.
在"logs"目录中获取日志文件。请将日志文件以附件的形式上传,而不是将其中的内容复制
运行LunaTranslator_debug.exe复现错误,然后上传产生的log_*.txt文件
validations:
required: true
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@ LunaTranslator/run3832.bat
LunaTranslator/logs
LunaTranslator/LunaTranslator/.vscode/settings.json
.vscode/settings.json
LunaTranslator/translation_record
23 changes: 12 additions & 11 deletions LunaTranslator/LunaTranslator/LunaTranslator.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,16 +310,17 @@ def textgetmethod_1(
currentsignature = uuid.uuid4()
if not waitforresultcallback:
self.currentsignature = currentsignature
try:
origin = text
text = POSTSOLVE(text)
self.settin_ui.showandsolvesig.emit(origin, text)
except Exception as e:
msg = str(type(e))[8:-2] + " " + str(e).replace("\n", "").replace("\r", "")
self.translation_ui.displaystatus.emit(msg, True, True)
return
if not text:
return
# 内嵌&文件翻译不要进行文本预处理
try:
origin = text
text = POSTSOLVE(text)
self.settin_ui.showandsolvesig.emit(origin, text)
if not text:
return
except Exception as e:
self.translation_ui.displaystatus.emit(stringfyerror(e), True, True)
return

if is_auto_run and (
len(text) < globalconfig["minlength"]
or len(text) > globalconfig["maxlength"]
Expand Down Expand Up @@ -368,7 +369,7 @@ def textgetmethod_1(
self.transhis.getnewsentencesignal.emit(text)
self.maybesetedittext(text)

if not globalconfig["showfanyi"]:
if not waitforresultcallback and not globalconfig["showfanyi"]:
return _showrawfunction()

text_solved, optimization_params = self.solvebeforetrans(text)
Expand Down
49 changes: 2 additions & 47 deletions LunaTranslator/LunaTranslator/LunaTranslator_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,60 +188,16 @@ def switchdir():
pass


class Lockedfile:
def __init__(self) -> None:
self.collect = queue.Queue()
threading.Thread(target=self.__write).start()

def __write(self):
data = self.collect.get()
os.makedirs("logs", exist_ok=True)
file = open(
f"logs/{time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())}.txt",
"w",
encoding="utf8",
errors="ignore",
)
while True:
file.write(data)
file.flush()
data = self.collect.get()

def write(self, data):
self.collect.put(data)


lockedfile = Lockedfile()


class debugoutput(io.IOBase):
def __init__(self, file: io.TextIOBase) -> None:
super().__init__()
self.originfile = file

def write(self, data):
self.originfile.write(data)
lockedfile.write(data)

def flush(self):
self.originfile.flush()


def savelogs():
sys.stderr = debugoutput(sys.stderr)
sys.stdout = debugoutput(sys.stdout)


def urlprotocol():
import argparse, gobject, sys
from urllib.parse import urlsplit
from traceback import print_exc

parser = argparse.ArgumentParser()
parser.add_argument("--URLProtocol", required=False)
args = parser.parse_args()
URLProtocol: str = args.URLProtocol
try:
args = parser.parse_args()
URLProtocol: str = args.URLProtocol
if URLProtocol:
print(URLProtocol)
result = urlsplit(URLProtocol)
Expand All @@ -266,7 +222,6 @@ def urlprotocol():
checklang()
checkintegrity()
checkpermission()
savelogs()
urlprotocol()
loadmainui()
app.exit(app.exec())
12 changes: 7 additions & 5 deletions LunaTranslator/LunaTranslator/gui/selecthook.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ def setupUi(self):
self.vboxlayout.addWidget(self.tabwidget)
self.tabwidget.setTabPosition(QTabWidget.TabPosition.East)
self.tabwidget.addTab(self.textOutput, ("文本"))
self.tabwidget.addTab(self.sysOutput, ("系统"))
self.tabwidget.addTab(self.sysOutput, ("日志"))

def showmenu(self, p: QPoint):
r = self.tttable.currentIndex().row()
Expand Down Expand Up @@ -729,14 +729,16 @@ def gethide(self, res):

if self.checkfilt_notcontrol.isChecked():
lres = list(res)

for r in lres:
_ord = ord(r)
if _ord < 0x20 or (_ord > 0x80 and _ord < 0xA0):

if (
(_ord >= 0x21 and _ord <= 0x2F)
or (_ord >= 0x3A and _ord <= 0x40)
or (_ord >= 0x5B and _ord <= 0x60)
or (_ord >= 0x7B and _ord <= 0x7E)
):
hide = True
break

return hide

def searchtextfunc2(self):
Expand Down
12 changes: 8 additions & 4 deletions LunaTranslator/LunaTranslator/gui/setting_display_buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
getIconButton,
makescrollgrid,
D_getsimpleswitch,
getsmalllabel,
)
from gui.dynalang import LDialog

Expand All @@ -33,7 +34,7 @@ def __init__(self, parent, dict, key) -> None:
getIconButton(
functools.partial(self.selectcallback, "fa." + name),
qicon=qtawesome.icon(
"fa." + name, color=globalconfig["buttoncolor"]
"fa." + name, color=globalconfig["buttoncolor2"]
),
),
i // 30,
Expand Down Expand Up @@ -81,7 +82,7 @@ def changerank(item, up, sortlist, savelist, savelay):

def createbuttonwidget(self, lay):
# return table
grids = [["显示", "", "", "对齐", "图标", "图标2", "说明"]]
grids = [["显示", "", "", "对齐", "", "图标", "", "图标2", "", "说明"]]
sortlist = globalconfig["toolbutton"]["rank2"]
savelist = []
savelay = []
Expand Down Expand Up @@ -116,6 +117,7 @@ def createbuttonwidget(self, lay):
callback=doadjust,
fixedsize=True,
),
getsmalllabel(),
D_getIconButton(
functools.partial(
dialog_selecticon,
Expand All @@ -125,9 +127,10 @@ def createbuttonwidget(self, lay):
),
qicon=qtawesome.icon(
globalconfig["toolbutton"]["buttons"][k]["icon"],
color=globalconfig["buttoncolor"],
color=globalconfig["buttoncolor2"],
),
),
getsmalllabel(),
]
if "icon2" in globalconfig["toolbutton"]["buttons"][k]:
l.append(
Expand All @@ -140,12 +143,13 @@ def createbuttonwidget(self, lay):
),
qicon=qtawesome.icon(
globalconfig["toolbutton"]["buttons"][k]["icon2"],
color=globalconfig["buttoncolor"],
color=globalconfig["buttoncolor2"],
),
),
)
else:
l.append("")
l.append(getsmalllabel())
if "belong" in globalconfig["toolbutton"]["buttons"][k]:
belong = (
"_"
Expand Down
5 changes: 4 additions & 1 deletion LunaTranslator/LunaTranslator/gui/setting_textinput_ocr.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def __init__(self, parent) -> None:
table.setSelectionMode((QAbstractItemView.SelectionMode.SingleSelection))
table.setWordWrap(False)
table.setModel(model)

table.getindexdata = self.__getindexwidgetdata
table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
table.customContextMenuRequested.connect(self.showmenu)
self.hctable = table
Expand All @@ -109,6 +109,9 @@ def __init__(self, parent) -> None:
self.resize(600, self.sizeHint().height())
self.show()

def __getindexwidgetdata(self, index: QModelIndex):
return self.hctable.indexWidgetX(index).currentIndex()

def closeEvent(self, a0: QCloseEvent) -> None:
rows = self.hcmodel.rowCount()
self.list.clear()
Expand Down
21 changes: 14 additions & 7 deletions LunaTranslator/LunaTranslator/gui/translatorUI.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@
makehtml,
loadpostsettingwindowmethod_maybe,
)
from myutils.hwnd import mouseselectwindow, grabwindow, getExeIcon, getcurrexe
from myutils.hwnd import (
mouseselectwindow,
grabwindow,
getExeIcon,
getcurrexe,
hwndratex,
)
from gui.setting_about import doupdate
from gui.dialog_memory import dialog_memory
from gui.textbrowser import Textbrowser
Expand Down Expand Up @@ -252,8 +258,8 @@ class TranslatorWindow(resizableframeless):
move_signal = pyqtSignal(QPoint)
closesignal = pyqtSignal()
hotkeyuse_selectprocsignal = pyqtSignal()
changeshowhiderawsig=pyqtSignal()
changeshowhidetranssig=pyqtSignal()
changeshowhiderawsig = pyqtSignal()
changeshowhidetranssig = pyqtSignal()

@threader
def tracewindowposthread(self):
Expand Down Expand Up @@ -284,11 +290,12 @@ def tracewindowposthread(self):
if not rect:
lastpos = None
continue
rate = hwndratex(hwnd)
rect = QRect(
int(rect[0] / self.devicePixelRatioF()),
int(rect[1] / self.devicePixelRatioF()),
int((rect[2] - rect[0]) / self.devicePixelRatioF()),
int((rect[3] - rect[1]) / self.devicePixelRatioF()),
int(rect[0] / rate),
int(rect[1] / rate),
int((rect[2] - rect[0]) / rate),
int((rect[3] - rect[1]) / rate),
)
if not lastpos:
lastpos = rect
Expand Down
2 changes: 1 addition & 1 deletion LunaTranslator/LunaTranslator/gui/usefulwidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -1016,7 +1016,7 @@ def __getsmalllabel(text):
return __


def getsmalllabel(text):
def getsmalllabel(text=""):
return lambda: __getsmalllabel(text)


Expand Down
4 changes: 2 additions & 2 deletions LunaTranslator/LunaTranslator/myutils/commonbase.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from myutils.proxy import getproxy
from myutils.utils import getlangtgt, getlangsrc
from myutils.utils import getlangtgt, getlangsrc, getlanguagespace
from myutils.config import _TR, static_data
from myutils.wrapper import stripwrapper
import requests


class ArgsEmptyExc(Exception):
def __init__(self, valuelist) -> None:
super().__init__(" , ".join(valuelist) + _TR("不能为空"))
super().__init__(" , ".join(valuelist) + getlanguagespace() + _TR("不能为空"))


class proxysession(requests.Session):
Expand Down
11 changes: 8 additions & 3 deletions LunaTranslator/LunaTranslator/myutils/hwnd.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,16 @@ def safepixmap(bs):
return pixmap


def hwndratex(hwnd):
_dpi = windows.GetDpiForWindow(hwnd)
mdpi = winsharedutils.GetMonitorDpiScaling(hwnd)
return mdpi / _dpi


def gdi_screenshot(x1, y1, x2, y2, hwnd=None):
if hwnd:
_r = QApplication.instance().devicePixelRatio()
_dpi = windows.GetDpiForWindow(hwnd)
x1, y1, x2, y2 = (int(_ * _dpi / 96 / _r) for _ in (x1, y1, x2, y2))
rate = hwndratex(hwnd)
x1, y1, x2, y2 = (int(_ / rate) for _ in (x1, y1, x2, y2))
bs = winsharedutils.gdi_screenshot(x1, y1, x2, y2, hwnd)
return safepixmap(bs)

Expand Down
17 changes: 15 additions & 2 deletions LunaTranslator/LunaTranslator/myutils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ def getlangtgt():
return __internal__getlang("private_tgtlang_2", "tgtlang4")


def getlanguagespace(lang):
def getlanguagespace(lang=None):
if lang is None:
lang = getlanguse()
return "" if (lang in ("zh", "ja", "cht")) else " "


Expand Down Expand Up @@ -917,11 +919,22 @@ def checkv1(api_url: str):
return api_url + "/v1"


def urlpathjoin(*argc):
urlx = []
for i, u in enumerate(argc):
if u.startswith("/") and i != 0:
u = u[1:]
if u.endswith("/") and i != len(argc) - 1:
u = u[:-1]
urlx.append(u)
return "/".join(urlx)


def createurl(url: str):
if url.endswith("/chat/completions"):
pass
else:
url = checkv1(url) + "/chat/completions"
url = urlpathjoin(checkv1(url), "/chat/completions")
return url


Expand Down
Loading

0 comments on commit 43e7fc3

Please sign in to comment.