forked from dmMaze/BallonsTranslator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaunch.py
285 lines (219 loc) · 9.13 KB
/
launch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
from pathlib import Path
import sys
import argparse
import os.path as osp
import os
import importlib
import re
import subprocess
import importlib.util
import pkg_resources
import time
TIME_LAUNCH = time.time()
python = sys.executable
git = os.environ.get('GIT', "git")
skip_install = False
index_url = os.environ.get('INDEX_URL', "")
QT_APIS = ['pyqt6', 'pyside6']
stored_commit_hash = None
REQ_WIN = [
'pywin32'
]
PATH_ROOT=Path(__file__).parent
PATH_FONTS=PATH_ROOT/'fonts'
parser = argparse.ArgumentParser()
parser.add_argument("--reinstall-torch", action='store_true', help="launch.py argument: install the appropriate version of torch even if you have some version already installed")
parser.add_argument("--proj-dir", default='', type=str, help='Open project directory on startup')
parser.add_argument("--qt-api", default='', choices=QT_APIS, help='Set qt api')
parser.add_argument("--debug", action='store_true')
parser.add_argument("--requirements", default='requirements.txt')
parser.add_argument("--headless", action='store_true', help='run without GUI')
parser.add_argument("--exec_dirs", default='', help='translation queue (project directories) separated by comma')
parser.add_argument("--ldpi", default=None, type=float, help='logical dots perinch')
args, _ = parser.parse_known_args()
def is_installed(package):
try:
spec = importlib.util.find_spec(package)
except ModuleNotFoundError:
return False
return spec is not None
def run(command, desc=None, errdesc=None, custom_env=None, live=False):
if desc is not None:
print(desc)
if live:
result = subprocess.run(command, shell=True, env=os.environ if custom_env is None else custom_env)
if result.returncode != 0:
raise RuntimeError(f"""{errdesc or 'Error running command'}.
Command: {command}
Error code: {result.returncode}""")
return ""
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=os.environ if custom_env is None else custom_env)
if result.returncode != 0:
message = f"""{errdesc or 'Error running command'}.
Command: {command}
Error code: {result.returncode}
stdout: {result.stdout.decode(encoding="utf8", errors="ignore") if len(result.stdout)>0 else '<empty>'}
stderr: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.stderr)>0 else '<empty>'}
"""
raise RuntimeError(message)
return result.stdout.decode(encoding="utf8", errors="ignore")
def run_pip(args, desc=None):
if skip_install:
return
index_url_line = f' --index-url {index_url}' if index_url != '' else ''
return run(f'"{python}" -m pip {args} --prefer-binary{index_url_line} --disable-pip-version-check', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}", live=True)
def commit_hash():
global stored_commit_hash
if stored_commit_hash is not None:
return stored_commit_hash
try:
stored_commit_hash = run(f"{git} rev-parse HEAD").strip()
except Exception:
stored_commit_hash = "<none>"
return stored_commit_hash
TRANSLATOR_DIR = 'modules/translators'
TRANSLATOR_PATTERN = re.compile(r'trans_(.*?).py')
def load_translators(translators = None):
if translators is None:
translators = os.listdir(TRANSLATOR_DIR)
for translator in translators:
if TRANSLATOR_PATTERN.match(translator) is not None:
importlib.import_module('modules.translators.' + translator.replace('.py', ''))
def load_modules():
load_translators()
BT = None
APP = None
def restart():
global BT
print('restarting...\n')
BT.close()
os.execv(sys.executable, ['python'] + sys.argv)
def main():
if args.debug:
os.environ['BALLOONTRANS_DEBUG'] = '1'
if not args.qt_api in QT_APIS:
os.environ['QT_API'] = 'pyqt6'
else:
os.environ['QT_API'] = args.qt_api
from utils import appinfo
commit = commit_hash()
print('py version: ', sys.version)
print('py executable: ', sys.executable)
print(f'version: {appinfo.version}')
print(f'branch: {appinfo.branch}')
print(f"Commit hash: {commit}")
APP_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(APP_DIR)
prepare_environment()
from utils.logger import setup_logging, logger as LOGGER
import utils.shared as shared
from utils import config as program_config
from qtpy.QtCore import QTranslator, QLocale, Qt
shared.DEFAULT_DISPLAY_LANG = QLocale.system().name().replace('en_CN', 'zh_CN')
shared.HEADLESS = args.headless
shared.load_cache()
program_config.load_config()
config = program_config.pcfg
if args.headless:
config.module.load_model_on_demand = True
config.module.empty_runcache = False
from modules.prepare_local_files import prepare_local_files_forall
prepare_local_files_forall()
if sys.platform == 'win32':
import ctypes
myappid = u'BalloonsTranslator' # arbitrary string
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
import qtpy
from qtpy.QtWidgets import QApplication
from qtpy.QtGui import QIcon, QFontDatabase, QGuiApplication, QFont
from qtpy import API, QT_VERSION
LOGGER.info(f'QT_API: {API}, QT Version: {QT_VERSION}')
shared.DEBUG = args.debug
shared.USE_PYSIDE6 = API == 'pyside6'
if qtpy.API_NAME[-1] == '6':
shared.FLAG_QT6 = True
else:
shared.FLAG_QT6 = False
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) #enable highdpi scaling
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True) #use highdpi icons
QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
os.chdir(shared.PROGRAM_PATH)
setup_logging(shared.LOGGING_PATH)
load_modules()
app_args = sys.argv
if args.headless:
app_args = sys.argv + ['-platform', 'offscreen']
app = QApplication(app_args)
lang = config.display_lang
langp = osp.join(shared.TRANSLATE_DIR, lang + '.qm')
if osp.exists(langp):
translator = QTranslator()
translator.load(lang, osp.dirname(osp.abspath(__file__)) + "/translate")
app.installTranslator(translator)
elif lang not in ('en_US', 'English'):
LOGGER.warning(f'target display language file {langp} doesnt exist.')
LOGGER.info(f'set display language to {lang}')
# Fonts
# Load custom fonts if they exist
for font in os.listdir(PATH_FONTS):
if font.lower().endswith(('ttf','otf','ttc','pfb')):
fnt_idx = QFontDatabase.addApplicationFont((PATH_FONTS/font).as_posix())
if fnt_idx >= 0:
shared.CUSTOM_FONTS.append(QFontDatabase.applicationFontFamilies(fnt_idx)[0])
shared.FONT_FAMILIES = set(f for f in QFontDatabase.families())
yahei = QFont('Microsoft YaHei UI')
if yahei.exactMatch() and not sys.platform == 'darwin':
QGuiApplication.setFont(yahei)
shared.DEFAULT_FONT_FAMILY = 'Microsoft YaHei UI'
shared.APP_DEFAULT_FONT = 'Microsoft YaHei UI'
else:
app_font = app.font().family()
shared.DEFAULT_FONT_FAMILY = app_font
shared.APP_DEFAULT_FONT = app_font
shared.APP_DEFAULT_FONT = app.font().defaultFamily()
if args.ldpi:
shared.LDPI = args.ldpi
from ui.mainwindow import MainWindow
ballontrans = MainWindow(app, config, open_dir=args.proj_dir, **vars(args))
global BT
BT = ballontrans
BT.restart_signal.connect(restart)
if not args.headless:
ps = QGuiApplication.primaryScreen()
shared.LDPI = ps.logicalDotsPerInch()
shared.SCREEN_W = ps.geometry().width()
shared.SCREEN_H = ps.geometry().height()
if shared.SCREEN_W > 1707 and sys.platform == 'win32': # higher than 2560 (1440p) / 1.5
# https://github.com/dmMaze/BallonsTranslator/issues/220
BT.comicTransSplitter.setHandleWidth(10)
ballontrans.setWindowIcon(QIcon(shared.ICON_PATH))
ballontrans.show()
ballontrans.resetStyleSheet()
sys.exit(app.exec())
def prepare_environment():
if getattr(sys, 'frozen', False):
print('Running as app, skip dependency installation')
return
req_updated = False
if sys.platform == 'win32':
for req in REQ_WIN:
try:
pkg_resources.require(req)
except Exception:
run_pip(f"install {req}", req)
req_updated = True
torch_command = os.environ.get('TORCH_COMMAND', "pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118 --disable-pip-version-check")
if args.reinstall_torch or not is_installed("torch") or not is_installed("torchvision"):
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch", live=True)
req_updated = True
try:
pkg_resources.require(open(args.requirements,mode='r', encoding='utf8'))
except Exception as e:
print(e)
run_pip(f"install -r {args.requirements}", "requirements")
req_updated = True
if req_updated:
import site
importlib.reload(site)
if __name__ == '__main__':
main()