Reo324 commited on
Commit
0378cfd
·
verified ·
1 Parent(s): 140b005

Upload secure_launcher_v2.py

Browse files
runtime-patches/5.5.10/runtime/secure_launcher_v2.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ AutoMosaRakku セキュアランチャー(改良版)
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ import shutil
10
+ from pathlib import Path
11
+ import pickle
12
+ import traceback
13
+ from datetime import datetime
14
+ import logging
15
+ import time
16
+
17
+ _STARTUP_TOTAL_START = time.perf_counter()
18
+ _STARTUP_TIMING_ENABLED = os.environ.get('AUTOMOSA_STARTUP_TIMING') == '1'
19
+ APP_DIR_ENV = 'AUTOMOSA_APP_DIR'
20
+ SAM2_CHECKPOINT_PROVIDER_ENV = 'AUTOMOSA_SAM2_CHECKPOINT_PROVIDER'
21
+ SAM2_CHECKPOINT_REL_PATHS = {
22
+ 'tiny': 'sam2/sam2.1_hiera_tiny.pt',
23
+ }
24
+ _sam2_checkpoint_buffers = {}
25
+
26
+ # コンソール出力を抑制(Tritonコンパイル時のちらつき防止)
27
+ try:
28
+ # 物体削除初回推論時のコンソールちらつきを完全に防ぐ
29
+ # pythonw起動ではstdout/stderrがNoneになり、tqdm等がwriteした瞬間に
30
+ # AttributeErrorで落ちるため、必ず書き込み可能なストリームを保証する
31
+ if sys.stdout is None:
32
+ sys.stdout = open(os.devnull, 'w', encoding='utf-8')
33
+ if sys.stderr is None:
34
+ sys.stderr = open(os.devnull, 'w', encoding='utf-8')
35
+ if not hasattr(sys, '_original_stdout'):
36
+ sys._original_stdout = sys.stdout
37
+ sys._original_stderr = sys.stderr
38
+
39
+ # 環境変数でも出力を抑制
40
+ os.environ['PYTHONIOENCODING'] = 'utf-8'
41
+ os.environ['PYTHONUNBUFFERED'] = '0'
42
+
43
+ except:
44
+ pass
45
+
46
+ # CRITICAL: 組み込みPython環境を強制設定(ランチャー起動直後)
47
+ script_dir = Path(__file__).parent.parent
48
+ python_base_dir = script_dir / "python_base"
49
+ os.environ[APP_DIR_ENV] = str(script_dir)
50
+
51
+
52
+ def _normalize_resource_path(relative_path):
53
+ return str(relative_path).replace('\\', '/')
54
+
55
+
56
+ def _register_sam2_checkpoint_buffer(relative_path, content):
57
+ normalized_path = _normalize_resource_path(relative_path)
58
+ for model_size, checkpoint_path in SAM2_CHECKPOINT_REL_PATHS.items():
59
+ if normalized_path == checkpoint_path:
60
+ _sam2_checkpoint_buffers[model_size] = bytes(content)
61
+ return True
62
+ return False
63
+
64
+
65
+ def get_sam2_checkpoint_bytes(model_size='tiny'):
66
+ content = _sam2_checkpoint_buffers.get(model_size)
67
+ if content is None:
68
+ return None
69
+ return bytes(content)
70
+
71
+
72
+ def _startup_log_path(root_dir):
73
+ log_dir = root_dir / "logs"
74
+ return log_dir / f"startup_timing_{datetime.now().strftime('%Y%m%d')}.log"
75
+
76
+
77
+ def _startup_phase_start():
78
+ return time.perf_counter()
79
+
80
+
81
+ def _startup_log_phase(root_dir, phase, phase_start):
82
+ if not _STARTUP_TIMING_ENABLED:
83
+ return
84
+ now = time.perf_counter()
85
+ message = (
86
+ f"[STARTUP] phase={phase} event=end "
87
+ f"elapsed_ms={(now - phase_start) * 1000:.3f} "
88
+ f"total_ms={(now - _STARTUP_TOTAL_START) * 1000:.3f}"
89
+ )
90
+ try:
91
+ log_file = _startup_log_path(root_dir)
92
+ log_file.parent.mkdir(exist_ok=True)
93
+ with open(log_file, "a", encoding="utf-8") as f:
94
+ f.write(message + "\n")
95
+ except Exception:
96
+ pass
97
+
98
+ # 環境変数を強制設定
99
+ if python_base_dir.exists():
100
+ # print(f"[ENVIRONMENT ISOLATION] Configuring embedded Python...")
101
+ # print(f"[ENVIRONMENT CHECK] Python paths:")
102
+ # print(f" PYTHONHOME: {python_base_dir}")
103
+ # print(f" INCLUDE: {python_base_dir / 'include'}")
104
+ # print(f" LIB: {python_base_dir / 'libs'}")
105
+
106
+ # Python関連環境変数を完全にクリア(最初に実行)
107
+ python_env_vars = ['PYTHONPATH', 'PYTHONHOME', 'VIRTUAL_ENV', 'CONDA_DEFAULT_ENV', 'CONDA_PREFIX', 'PYENV_ROOT', 'PYENV_VERSION']
108
+ for env_var in python_env_vars:
109
+ if env_var in os.environ:
110
+ del os.environ[env_var]
111
+ # print(f"[ENV CLEAR] Removed {env_var}")
112
+
113
+ # PATHからPython関連のパスを除去(VC++は保持)
114
+ path_env = os.environ.get('PATH', '')
115
+ filtered_paths = []
116
+ for p in path_env.split(os.pathsep):
117
+ # VC++/MSVCパスは保持
118
+ if 'microsoft visual studio' in p.lower() or 'msvc' in p.lower() or 'windows kits' in p.lower():
119
+ filtered_paths.append(p)
120
+ # print(f"[PATH KEEP] Preserved VC++: {p}")
121
+ # Python関連パスをフィルタリング
122
+ elif any(keyword in p.lower() for keyword in [
123
+ 'pyenv', 'python', 'anaconda', 'miniconda', 'conda', 'venv', 'virtualenv'
124
+ ]):
125
+ # print(f"[PATH FILTER] Excluded: {p}")
126
+ pass
127
+ else:
128
+ filtered_paths.append(p)
129
+
130
+ # 埋め込みPythonパスを先頭に追加
131
+ filtered_paths.insert(0, str(python_base_dir))
132
+ filtered_paths.insert(1, str(python_base_dir / 'Scripts'))
133
+ os.environ['PATH'] = os.pathsep.join(filtered_paths)
134
+ # print(f"[PATH UPDATE] New PATH starts with: {filtered_paths[0]}")
135
+
136
+ # 埋め込みPython環境を強制設定
137
+ os.environ['PYTHONHOME'] = str(python_base_dir)
138
+ os.environ['PYTHONPATH'] = f"{python_base_dir / 'Lib'};{python_base_dir / 'Lib' / 'site-packages'}"
139
+
140
+ # INCLUDE/LIB環境変数を拡張(上書きではなく追加)
141
+ # VC++のヘッダー/ライブラリパスを保持
142
+ existing_include = os.environ.get('INCLUDE', '')
143
+ existing_lib = os.environ.get('LIB', '')
144
+
145
+ # Python埋め込み版のパスを先頭に追加
146
+ os.environ['INCLUDE'] = f"{python_base_dir / 'include'};{existing_include}" if existing_include else str(python_base_dir / 'include')
147
+ os.environ['LIB'] = f"{python_base_dir / 'libs'};{existing_lib}" if existing_lib else str(python_base_dir / 'libs')
148
+
149
+ # MinGW-w64環境を設定(stdlib.h問題の解決)
150
+ mingw_dir = script_dir / "mingw64"
151
+ if mingw_dir.exists():
152
+ # print(f"[MINGW] Configuring MinGW-w64 compiler environment...")
153
+ # MinGWのbinをPATHに追加
154
+ os.environ['PATH'] = f"{mingw_dir / 'bin'};" + os.environ.get('PATH', '')
155
+ # コンパイラの設定
156
+ os.environ['CC'] = str(mingw_dir / 'bin' / 'gcc.exe')
157
+ os.environ['CXX'] = str(mingw_dir / 'bin' / 'g++.exe')
158
+ # インクルードパスの設定(stdlib.hを含む)
159
+ os.environ['C_INCLUDE_PATH'] = f"{mingw_dir / 'include'};{mingw_dir / 'x86_64-w64-mingw32' / 'include'}"
160
+ os.environ['CPLUS_INCLUDE_PATH'] = f"{mingw_dir / 'include'};{mingw_dir / 'x86_64-w64-mingw32' / 'include'}"
161
+ # Python libsディレクトリを最初に追加(libpython311.aのため)
162
+ os.environ['LIBRARY_PATH'] = f"{python_base_dir / 'libs'};{mingw_dir / 'lib'};{mingw_dir / 'x86_64-w64-mingw32' / 'lib'}"
163
+ # Tritonが確実に認識できるよう追加の環境変数も設定
164
+ os.environ['LDFLAGS'] = f"-L{python_base_dir / 'libs'} -L{mingw_dir / 'lib'}"
165
+ # Triton用の設定
166
+ os.environ['TRITON_PTXAS_PATH'] = str(mingw_dir / 'bin')
167
+ os.environ['TRITON_CUOBJDUMP_PATH'] = str(mingw_dir / 'bin')
168
+ # print(f"[MINGW] MinGW-w64 configured at: {mingw_dir}")
169
+
170
+ # sys.pathを調整(完全にクリアせずに必要なパスを前に追加)
171
+ # print(f"[SYS.PATH] Original sys.path length: {len(sys.path)}")
172
+ # 必要なパスを前に追加(標準ライブラリを保持)
173
+ new_paths = [
174
+ str(python_base_dir / 'Lib' / 'site-packages'),
175
+ str(python_base_dir / 'Lib'),
176
+ str(python_base_dir / 'DLLs'),
177
+ str(python_base_dir),
178
+ str(python_base_dir / 'Scripts')
179
+ ]
180
+ # 既存のパスから重複を除去して追加
181
+ for path in new_paths:
182
+ if path not in sys.path:
183
+ sys.path.insert(0, path)
184
+ # print(f"[SYS.PATH] New sys.path length: {len(sys.path)}")
185
+ # print(f"[SYS.PATH] First entry: {sys.path[0]}")
186
+
187
+ # sys属性の強制更新
188
+ original_executable = sys.executable
189
+ sys.executable = str(python_base_dir / 'python.exe')
190
+ sys.prefix = str(python_base_dir)
191
+ sys.exec_prefix = str(python_base_dir)
192
+ sys.base_prefix = str(python_base_dir)
193
+ sys.base_exec_prefix = str(python_base_dir)
194
+
195
+ # print(f"[SYS UPDATE] executable: {original_executable} -> {sys.executable}")
196
+ # print(f"[SYS UPDATE] prefix: {sys.prefix}")
197
+ # print(f"[SYS UPDATE] exec_prefix: {sys.exec_prefix}")
198
+
199
+ # 環境分離完了後のランタイム情報を出力
200
+ # print(f"[RUNTIME] Python: {sys.executable}")
201
+ # print(f"[RUNTIME] sys.prefix: {sys.prefix}")
202
+
203
+ _startup_log_phase(script_dir, "env", _STARTUP_TOTAL_START)
204
+
205
+ # ログ設定(無効化 - 配布版では不要)
206
+ # log_dir = Path(__file__).parent.parent / "logs"
207
+ # log_dir.mkdir(exist_ok=True)
208
+ # log_file = log_dir / f"launcher_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
209
+
210
+ # logging.basicConfig(
211
+ # level=logging.INFO,
212
+ # format='%(asctime)s - %(levelname)s - %(message)s',
213
+ # handlers=[
214
+ # logging.FileHandler(log_file, encoding='utf-8')
215
+ # # StreamHandler()はコンソールウィンドウのちらつきを引き起こすため配布版では無効化
216
+ # ]
217
+ # )
218
+ # logger = logging.getLogger(__name__)
219
+
220
+
221
+ class SplashWindow:
222
+ """起動スプラッシュウィンドウ"""
223
+
224
+ def __init__(self, initial_message="オートモザラック 起動中..."):
225
+ try:
226
+ from PySide6.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
227
+ from PySide6.QtCore import Qt
228
+ from PySide6.QtGui import QFont
229
+
230
+ self.app = QApplication.instance()
231
+ if self.app is None:
232
+ self.app = QApplication([])
233
+
234
+ self.window = QWidget()
235
+ self.window.setWindowTitle("オートモザラック")
236
+ self.window.setFixedSize(300, 120)
237
+ self.window.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
238
+
239
+ # レイアウト
240
+ layout = QVBoxLayout()
241
+
242
+ # タイトル
243
+ title_label = QLabel("オートモザラック")
244
+ title_font = QFont()
245
+ title_font.setPointSize(14)
246
+ title_font.setBold(True)
247
+ title_label.setFont(title_font)
248
+ title_label.setAlignment(Qt.AlignCenter)
249
+
250
+ # メッセージ
251
+ self.message_label = QLabel(initial_message)
252
+ self.message_label.setAlignment(Qt.AlignCenter)
253
+
254
+ layout.addWidget(title_label)
255
+ layout.addWidget(self.message_label)
256
+
257
+ self.window.setLayout(layout)
258
+
259
+ # ウィンドウを中央に配置
260
+ self.center_window()
261
+
262
+ except ImportError:
263
+ # PySide6が利用できない場合は何もしない
264
+ self.window = None
265
+ self.app = None
266
+
267
+ def center_window(self):
268
+ """ウィンドウを画面中央に配置"""
269
+ if self.window:
270
+ from PySide6.QtWidgets import QApplication
271
+ screen = QApplication.primaryScreen()
272
+ if screen:
273
+ screen_geometry = screen.geometry()
274
+ x = (screen_geometry.width() - self.window.width()) // 2
275
+ y = (screen_geometry.height() - self.window.height()) // 2
276
+ self.window.move(x, y)
277
+
278
+ def show(self):
279
+ """ウィンドウを表示"""
280
+ if self.window:
281
+ self.window.show()
282
+ if self.app:
283
+ self.app.processEvents()
284
+
285
+ def update_message(self, message):
286
+ """メッセージを更新"""
287
+ if self.message_label:
288
+ self.message_label.setText(message)
289
+ if self.app:
290
+ self.app.processEvents()
291
+
292
+ def close(self):
293
+ """ウィンドウを閉じる"""
294
+ if self.window:
295
+ self.window.close()
296
+
297
+
298
+ def _g():
299
+ """動的にキーを生成(難読化)"""
300
+ # 難読化されたキーデータ
301
+ _K = [
302
+ ([112, 168, 206, 174], [244, 79, 138, 205]),
303
+ ([8, 221, 134, 194], [103, 94, 24, 115]),
304
+ ([151, 237, 49, 38], [184, 61, 85, 242]),
305
+ ([102, 4, 23, 41], [49, 0, 12, 198]),
306
+ ([168, 53, 47, 55], [171, 147, 249, 73]),
307
+ ([169, 62, 88, 214], [154, 100, 243, 135]),
308
+ ([223, 112, 79, 121], [87, 178, 205, 68]),
309
+ ([122, 185, 192, 39], [32, 16, 99, 61]),
310
+ ]
311
+
312
+ # キーの各部分を復元
313
+ key_bytes = bytearray()
314
+
315
+ for obf, xor in _K:
316
+ # XORで元のデータを復元
317
+ chunk = bytes(a ^ b for a, b in zip(obf, xor))
318
+ key_bytes.extend(chunk)
319
+
320
+ # Base64エンコード
321
+ import base64
322
+ return base64.urlsafe_b64encode(bytes(key_bytes))
323
+
324
+
325
+ class D:
326
+ """復号化クラス"""
327
+
328
+ def __init__(self):
329
+ from cryptography.fernet import Fernet
330
+ self.f = Fernet(_g())
331
+
332
+ def d(self, i, o):
333
+ """ディレクトリを復号化(シンプル版)"""
334
+ with open(i, 'rb') as f:
335
+ e = f.read()
336
+
337
+ # 復号化
338
+ s = self.f.decrypt(e)
339
+
340
+ # デシリアライズ
341
+ data = pickle.loads(s)
342
+
343
+ # ファイル復元
344
+ for rel_path, content in data.items():
345
+ out_path = os.path.join(o, rel_path)
346
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
347
+ with open(out_path, 'wb') as f:
348
+ f.write(content)
349
+
350
+
351
+ def clear_triton_cache():
352
+ """Tritonキャッシュを削除してコンパイル失敗を避ける"""
353
+ import shutil
354
+ try:
355
+ cache_dirs = []
356
+
357
+ # Windows標準キャッシュディレクトリ
358
+ if os.name == 'nt':
359
+ # os.path.expanduser を使用(埋め込み版でも利用可能)
360
+ home = os.path.expanduser('~')
361
+ username = os.environ.get('USERNAME', '')
362
+ localappdata = os.environ.get('LOCALAPPDATA', '')
363
+
364
+ if home:
365
+ cache_dirs.append(os.path.join(home, '.triton', 'cache'))
366
+ if localappdata and username:
367
+ cache_dirs.append(os.path.join(localappdata, 'Temp', f'torchinductor_{username}'))
368
+
369
+ # print("Windows標準キャッシュディレクトリを使用:")
370
+ for cache_dir in cache_dirs:
371
+ cache_dir_name = os.path.basename(os.path.dirname(cache_dir))
372
+ # print(f" {cache_dir_name}: {cache_dir}")
373
+ if os.path.exists(cache_dir):
374
+ try:
375
+ shutil.rmtree(cache_dir, ignore_errors=True)
376
+ # print(f"[CACHE] Cleared: {cache_dir}")
377
+ except Exception as e:
378
+ # print(f"[CACHE] Failed to clear {cache_dir}: {e}")
379
+ pass
380
+ else:
381
+ # print(f"[CACHE] Not found: {cache_dir}")
382
+ pass
383
+ except Exception as e:
384
+ # print(f"[CACHE ERROR] Failed to clear Triton cache: {e}")
385
+ # キャッシュクリアに失敗してもアプリ起動は続行
386
+ pass
387
+
388
+
389
+ def configure_embedded_environment(exe_dir):
390
+ """埋め込みPython環境の再設定とTriton用の追加設定"""
391
+ python_base_dir = exe_dir / "python_base"
392
+ mingw_dir = exe_dir / "mingw64"
393
+ os.environ[APP_DIR_ENV] = str(exe_dir)
394
+
395
+ if not python_base_dir.exists():
396
+ # print(f"[ERROR] Python base directory not found: {python_base_dir}")
397
+ return
398
+
399
+ # 暗号化環境のメモリベースモデルアクセス環境変数を設定
400
+ os.environ['AUTOMOSA_MEMORY_MODELS'] = '1'
401
+
402
+ # Tritonコンパイラ用の環境変数を追加設定
403
+ if mingw_dir.exists():
404
+ # print(f"[MINGW EXTENDED] Configuring extended MinGW-w64 environment for Triton...")
405
+
406
+ # 基本的なMinGW-w64ライブラリパス(標準ランタイムオブジェクト用)
407
+ lib_dirs = [
408
+ mingw_dir / "x86_64-w64-mingw32" / "lib",
409
+ mingw_dir / "lib" / "gcc" / "x86_64-w64-mingw32" / "15.2.0",
410
+ mingw_dir / "lib",
411
+ python_base_dir / "libs" # libpython311.a用
412
+ ]
413
+
414
+ # 存在するライブラリパスのみを環境変数に設定
415
+ valid_lib_paths = [str(lib_dir) for lib_dir in lib_dirs if lib_dir.exists()]
416
+
417
+ # 環境変数の更新
418
+ os.environ['LIBRARY_PATH'] = os.pathsep.join(valid_lib_paths)
419
+ os.environ['LD_LIBRARY_PATH'] = os.pathsep.join(valid_lib_paths) # Linux style too
420
+
421
+ # LDFLAGS更新(-Lフラグを明示的に追加)
422
+ ldflags = " ".join([f"-L{path}" for path in valid_lib_paths])
423
+ os.environ['LDFLAGS'] = ldflags
424
+
425
+ # CFLAGS/CXXFLAGS追加設定
426
+ cflags = f"-I{python_base_dir / 'include'} -I{mingw_dir / 'include'} -I{mingw_dir / 'x86_64-w64-mingw32' / 'include'}"
427
+ os.environ['CFLAGS'] = cflags
428
+ os.environ['CXXFLAGS'] = cflags
429
+
430
+ # print(f"[MINGW EXTENDED] LIBRARY_PATH set to: {os.environ['LIBRARY_PATH']}")
431
+ # print(f"[MINGW EXTENDED] LDFLAGS set to: {os.environ['LDFLAGS']}")
432
+
433
+ # Triton用の追加環境変数
434
+ os.environ['TRITON_CC'] = str(mingw_dir / 'bin' / 'gcc.exe')
435
+ os.environ['TRITON_CXX'] = str(mingw_dir / 'bin' / 'g++.exe')
436
+
437
+ # MinGW-w64用のTriton Windows utilities設定
438
+ os.environ['TRITON_LIBDIR'] = os.pathsep.join(valid_lib_paths)
439
+
440
+ # 【重要】TritonがPythonライブラリを確実に見つけるため、libpython311.aをTritonの期待する場所にコピー
441
+ try:
442
+ import shutil
443
+ site_packages = python_base_dir / "Lib" / "site-packages"
444
+ if site_packages.exists():
445
+ triton_lib_paths = [
446
+ site_packages / "triton" / "backends" / "nvidia" / "lib",
447
+ site_packages / "triton" / "backends" / "nvidia" / "lib" / "x64"
448
+ ]
449
+
450
+ libpython_source = python_base_dir / "libs" / "libpython311.a"
451
+ if libpython_source.exists():
452
+ for target_dir in triton_lib_paths:
453
+ if target_dir.exists():
454
+ target_file = target_dir / "libpython311.a"
455
+ if not target_file.exists():
456
+ shutil.copy2(str(libpython_source), str(target_file))
457
+ # print(f"[TRITON FIX] Copied libpython311.a to: {target_file}")
458
+
459
+ # MinGW-w64ランタイムライブラリもコピー
460
+ mingw_runtime_libs = [
461
+ "libmingw32.a", "libgcc.a", "libgcc_s.a"
462
+ ]
463
+
464
+ for lib_name in mingw_runtime_libs:
465
+ for mingw_lib_dir in [mingw_dir / "lib", mingw_dir / "x86_64-w64-mingw32" / "lib"]:
466
+ source_lib = mingw_lib_dir / lib_name
467
+ if source_lib.exists():
468
+ target_lib = target_dir / lib_name
469
+ if not target_lib.exists():
470
+ shutil.copy2(str(source_lib), str(target_lib))
471
+ # print(f"[TRITON FIX] Copied {lib_name} to: {target_lib}")
472
+ break
473
+
474
+ except Exception as e:
475
+ # print(f"[TRITON FIX] Warning: Could not copy libraries to Triton: {e}")
476
+ pass
477
+
478
+ # print("[ENV CONFIG] Extended Triton compilation environment configured")
479
+
480
+ def main():
481
+ """メイン処理"""
482
+ try:
483
+ # GUI起動前にstdout/stderrを復元(ログ出力のため)
484
+ try:
485
+ if hasattr(sys, '_original_stdout'):
486
+ sys.stdout = sys._original_stdout
487
+ sys.stderr = sys._original_stderr
488
+ except:
489
+ pass
490
+
491
+ # コマンドライン引数をチェック
492
+ cache_only_mode = '--cache-only' in sys.argv
493
+
494
+ # 実行ディレクトリ
495
+ if getattr(sys, 'frozen', False):
496
+ exe_dir = Path(sys.executable).parent
497
+ else:
498
+ exe_dir = Path(__file__).parent.parent
499
+ os.environ[APP_DIR_ENV] = str(exe_dir)
500
+
501
+ # Tritonキャッシュクリアは削除(prebuild_cache.batで事前生成したキャッシュを活用)
502
+ # clear_triton_cache() は呼ばない
503
+
504
+ # 埋め込みPython環境を設定
505
+ configure_embedded_environment(exe_dir)
506
+
507
+ # 暗号化ファイル
508
+ core_dat = exe_dir / "runtime" / "core.dat" # 統合暗号化ファイル
509
+ models_enc = exe_dir / "runtime" / "resources.dat" # resources.datに修正
510
+
511
+ # デバッグ用: スプラッシュウィンドウを無効化
512
+ # logger.info("起動中...")
513
+
514
+ # 一時ディレクトリ
515
+ phase_start = _startup_phase_start()
516
+ temp_dir = tempfile.mkdtemp(prefix="automosa_")
517
+ _startup_log_phase(exe_dir, "temp", phase_start)
518
+
519
+ try:
520
+ d = D()
521
+
522
+ # 統合ファイル(core.dat)から復号化
523
+ # logger.info("初期化しています...")
524
+
525
+ # core.datを読み込み
526
+ phase_start = _startup_phase_start()
527
+ with open(str(core_dat), 'rb') as f:
528
+ encrypted_unified_data = f.read()
529
+ _startup_log_phase(exe_dir, "core_read", phase_start)
530
+
531
+ # 統合データを復号化
532
+ phase_start = _startup_phase_start()
533
+ decrypted_unified = d.f.decrypt(encrypted_unified_data)
534
+ unified_data = pickle.loads(decrypted_unified)
535
+ _startup_log_phase(exe_dir, "core_decrypt", phase_start)
536
+
537
+ # ソース部分を復号化してファイル展開
538
+ phase_start = _startup_phase_start()
539
+ app_dir = os.path.join(temp_dir, "app")
540
+ source_encrypted = unified_data['sections']['source']
541
+ source_decrypted = d.f.decrypt(source_encrypted)
542
+ source_data = pickle.loads(source_decrypted)
543
+
544
+ # ソースファイルを展開
545
+ for rel_path, content in source_data.items():
546
+ out_path = os.path.join(app_dir, rel_path)
547
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
548
+ with open(out_path, 'wb') as f:
549
+ f.write(content)
550
+ _startup_log_phase(exe_dir, "source_unpack", phase_start)
551
+
552
+ # モデル復号化(従来通り)
553
+ # logger.info("AI機能を準備中...")
554
+ models_dir = os.path.join(temp_dir, "models")
555
+ phase_start = _startup_phase_start()
556
+ with open(str(models_enc), 'rb') as f:
557
+ encrypted_models_data = f.read()
558
+ _startup_log_phase(exe_dir, "resources_read", phase_start)
559
+
560
+ phase_start = _startup_phase_start()
561
+ models_decrypted = d.f.decrypt(encrypted_models_data)
562
+ models_data = pickle.loads(models_decrypted)
563
+ _sam2_checkpoint_buffers.clear()
564
+ for rel_path, content in models_data.items():
565
+ if _register_sam2_checkpoint_buffer(rel_path, content):
566
+ continue
567
+ out_path = os.path.join(models_dir, rel_path)
568
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
569
+ with open(out_path, 'wb') as f:
570
+ f.write(content)
571
+ _startup_log_phase(exe_dir, "resources_unpack", phase_start)
572
+
573
+ # パッケージ復号化(統合データからパッケージ部分を復号化)
574
+ # logger.info("パッケージを準備中...")
575
+ phase_start = _startup_phase_start()
576
+ packages_dir = os.path.join(temp_dir, "packages")
577
+ os.makedirs(packages_dir, exist_ok=True)
578
+
579
+ # 統合データからパッケージ部分を取得
580
+ packages_encrypted = unified_data['sections']['packages']
581
+ packages_decrypted = d.f.decrypt(packages_encrypted)
582
+ packages_data = pickle.loads(packages_decrypted)
583
+
584
+ # パッケージファイルを展開
585
+ for rel_path, content in packages_data.items():
586
+ out_path = os.path.join(packages_dir, rel_path)
587
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
588
+ with open(out_path, 'wb') as f:
589
+ f.write(content)
590
+ _startup_log_phase(exe_dir, "packages_unpack", phase_start)
591
+
592
+ # 展開にだけ使うデータを、長寿命のアプリ実行フレームに残さない。
593
+ # SAM2用の重みは _sam2_checkpoint_buffers が必要な分だけ保持する。
594
+ del encrypted_unified_data, decrypted_unified, unified_data
595
+ del source_encrypted, source_decrypted, source_data
596
+ del encrypted_models_data, models_decrypted, models_data
597
+ del packages_encrypted, packages_decrypted, packages_data
598
+ content = None
599
+
600
+ # 起動準備
601
+ # logger.info("起動準備中...")
602
+
603
+ # Pythonパス設定(パッケージパスを最初に追加)
604
+ phase_start = _startup_phase_start()
605
+ sys.path.insert(0, packages_dir)
606
+ sys.path.insert(0, app_dir)
607
+
608
+ # 環境変数設定
609
+ os.environ['AUTOMOSA_MODEL_DIR'] = models_dir
610
+ os.environ['AUTOMOSA_CONFIG_DIR'] = str(exe_dir / "config") # configフォルダを設定ファイル保存場所に
611
+ os.environ['AUTOMOSA_MEMORY_MODELS'] = models_dir # 暗号化環境判定用
612
+ os.environ[APP_DIR_ENV] = str(exe_dir)
613
+ if _sam2_checkpoint_buffers:
614
+ os.environ[SAM2_CHECKPOINT_PROVIDER_ENV] = (
615
+ '__main__:get_sam2_checkpoint_bytes'
616
+ )
617
+ try:
618
+ from video.sam2_checkpoint_locator import (
619
+ set_sam2_checkpoint_bytes_provider,
620
+ )
621
+ set_sam2_checkpoint_bytes_provider(get_sam2_checkpoint_bytes)
622
+ except ImportError:
623
+ pass
624
+
625
+ # subprocess制御を適用(FLA/Tritonコンパイル時のコマンドプロンプトちらつき防止)
626
+ try:
627
+ from utils.subprocess_control import setup_comprehensive_process_suppression
628
+ setup_comprehensive_process_suppression()
629
+ except ImportError:
630
+ # subprocess制御が利用できない場合はスキップ
631
+ pass
632
+ _startup_log_phase(exe_dir, "path_setup", phase_start)
633
+
634
+ # メイン起動
635
+ # logger.info("メインアプリケーション起動中...")
636
+ phase_start = _startup_phase_start()
637
+ import main
638
+ _startup_log_phase(exe_dir, "import_main", phase_start)
639
+
640
+ # キャッシュ専用モードの場合は引数を調整
641
+ if cache_only_mode:
642
+ original_argv = sys.argv.copy()
643
+ sys.argv = [sys.argv[0], '--cache-only']
644
+ try:
645
+ phase_start = _startup_phase_start()
646
+ result = main.main()
647
+ _startup_log_phase(exe_dir, "main_main", phase_start)
648
+ # キャッシュ作成の結果に基づいて終了コードを設定
649
+ sys.exit(0 if result else 1)
650
+ finally:
651
+ sys.argv = original_argv
652
+ else:
653
+ phase_start = _startup_phase_start()
654
+ try:
655
+ main.main()
656
+ finally:
657
+ _startup_log_phase(exe_dir, "main_main", phase_start)
658
+
659
+ finally:
660
+ # クリーンアップ
661
+ if os.path.exists(temp_dir):
662
+ try:
663
+ shutil.rmtree(temp_dir, ignore_errors=True)
664
+ except:
665
+ pass
666
+
667
+ except Exception as e:
668
+ # 配布版では詳細なエラー情報を隠す
669
+ try:
670
+ from PySide6.QtWidgets import QApplication, QMessageBox
671
+ app = QApplication.instance()
672
+ if app is None:
673
+ app = QApplication([])
674
+
675
+ error_msg = "アプリケーションの起動に失敗しました。\n\n"
676
+ error_msg += "以下を確認してください:\n"
677
+ error_msg += "・初回セットアップ.batを実行済みか\n"
678
+ error_msg += "・セキュリティソフトの除外設定\n"
679
+ error_msg += "・管理者権限での実行\n\n"
680
+ # error_msg += f"詳細なエラー情報は以下に保存されました:\n{log_file}"
681
+
682
+ QMessageBox.critical(None, "起動エラー", error_msg)
683
+ except ImportError:
684
+ # PySide6が利用できない場合はtkinterを使用
685
+ import tkinter as tk
686
+ from tkinter import messagebox
687
+
688
+ root = tk.Tk()
689
+ root.withdraw()
690
+
691
+ error_msg = "アプリケーションの起動に失敗しました。\n\n"
692
+ error_msg += "以下を確認してくだ���い:\n"
693
+ error_msg += "・初回セットアップ.batを実行済みか\n"
694
+ error_msg += "・セキュリティソフトの除外設定\n"
695
+ error_msg += "・管理者権限での実行\n\n"
696
+ # error_msg += f"詳細なエラー情報は以下に保存されました:\n{log_file}"
697
+
698
+ messagebox.showerror("起動エラー", error_msg)
699
+ sys.exit(1)
700
+
701
+
702
+ if __name__ == "__main__":
703
+ main()