-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAutoML.py
More file actions
345 lines (294 loc) · 11.3 KB
/
Copy pathAutoML.py
File metadata and controls
345 lines (294 loc) · 11.3 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python3
# Author: Miguel Marina <karel.capek.robotics@gmail.com>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Copyright (C) 2025 Capek System Safety & Robotic Solutions
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Wrapper launcher for AutoML.
This script ensures required third-party packages are available before
executing :mod:`AutoML`. When run inside the PyInstaller-built
executable the dependencies are already bundled so the installation step
is skipped.
"""
import argparse
import importlib
import os
import shutil
import subprocess
import sys
import types
from pathlib import Path
from tkinter import ttk
# Ensure bundled executables can import sibling packages
if getattr(sys, "frozen", False):
_ROOT = Path(sys._MEIPASS)
else:
_ROOT = Path(__file__).resolve().parent
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
# Provide default configuration when the external package is absent or incompatible
try: # pragma: no cover - executed in frozen builds
_prefix = "AutoML." if __package__ and __package__.startswith("AutoML") else ""
_automl_constants = importlib.import_module(f"{_prefix}config.automl_constants")
except ImportError:
_automl_constants = types.SimpleNamespace(
AUTHOR="Miguel Marina",
AUTHOR_EMAIL="karel.capek.robotics@gmail.com",
AUTHOR_LINKEDIN="https://www.linkedin.com/in/progman32/",
PMHF_TARGETS={},
VALID_SUBTYPES=[],
dynamic_recommendations={},
)
_config_module = types.ModuleType("config")
_config_module.automl_constants = _automl_constants
sys.modules.setdefault("config", _config_module)
sys.modules["config.automl_constants"] = _automl_constants
else:
sys.modules.setdefault("config", types.ModuleType("config"))
sys.modules["config.automl_constants"] = _automl_constants
import tools # noqa: F401 # ensure package is bundled
from tools.crash_report_logger import install_best, report_health
from tools.diagnostics_manager import EventDiagnosticsManager
from tools.memory_manager import manager as memory_manager
from tools.model_loader import model_loader
from tools.splash_launcher import SplashLauncher
from tools.trash_eater import manager_eater
from tools.worker_lifecycle import project_workers
from mainappsrc.version import VERSION
from mainappsrc.core.automl_core import (
AutoMLApp,
FaultTreeNode,
AutoML_Helper,
messagebox,
GATE_NODE_TYPES,
)
from mainappsrc.core.safety_analysis import SafetyAnalysis_FTA_FMEA
from mainappsrc.page_diagram import PageDiagram
import tkinter.font as tkFont
from gui.utils.drawing_helper import fta_drawing_helper
if __package__ and __package__.startswith("AutoML"):
from AutoML.config.automl_constants import PMHF_TARGETS
else: # pragma: no cover - running as script
from config.automl_constants import PMHF_TARGETS
from analysis.models import HazopDoc
from gui.dialogs.edit_node_dialog import EditNodeDialog
from analysis.risk_assessment import AutoMLHelper
__all__ = [
"AutoMLApp",
"FaultTreeNode",
"AutoML_Helper",
"messagebox",
"GATE_NODE_TYPES",
"PMHF_TARGETS",
"HazopDoc",
"EditNodeDialog",
"SafetyAnalysis_FTA_FMEA",
"AutoMLHelper",
"PageDiagram",
"tkFont",
"fta_drawing_helper",
]
# Hint PyInstaller to bundle AutoML and its dependencies (e.g. gui package)
if False: # pragma: no cover
import AutoML # noqa: F401
Path(r"C:\\Program Files\\gs\\gs10.04.0\\bin\\gswin64c.exe")
# Distribution names are not always valid Python import names. In particular,
# the ``pillow`` distribution exposes the ``PIL`` package. Keeping both names
# explicit prevents every launch from needlessly invoking pip for an already
# installed dependency.
REQUIRED_PACKAGES = {
"pillow": "PIL",
"openpyxl": "openpyxl",
"networkx": "networkx",
"matplotlib": "matplotlib",
"reportlab": "reportlab",
"adjustText": "adjustText",
}
GS_PATH = Path(r"C:\\Program Files\\gs\\gs10.04.0\\bin\\gswin64c.exe")
_GS_CANDIDATE_BINARIES = ("gswin64c.exe", "gswin32c.exe", "gs.exe")
def _ghostscript_available() -> bool:
"""Return ``True`` when a usable Ghostscript binary or module exists."""
if os.name != "nt":
return True
candidate_paths = [GS_PATH]
for env_key in ("GHOSTSCRIPT_EXE", "GHOSTSCRIPT_PATH"):
env_value = os.environ.get(env_key)
if env_value:
candidate_paths.append(Path(env_value))
for path in candidate_paths:
if isinstance(path, Path) and path.exists():
return True
for binary in _GS_CANDIDATE_BINARIES:
resolved = shutil.which(binary)
if resolved:
return True
try:
import ghostscript # type: ignore[import-not-found]
except Exception:
return False
try:
# ``ghostscript`` initialises a shared library when available. The
# initialisation raises ``OSError`` if the native binary is missing.
ghostscript.Ghostscript("-h") # type: ignore[attr-defined]
except OSError:
return False
except Exception:
# Any other exception indicates the library was found but the
# invocation failed due to arguments; treat it as available.
return True
else:
return True
_diagnostics_manager: EventDiagnosticsManager | None = None
def parse_args() -> None:
"""Handle command line arguments for the launcher."""
parser = argparse.ArgumentParser(
description=(
f"Launch the AutoML application (v{VERSION}) with centralized project "
"configuration management"
)
)
parser.add_argument("--version", action="version", version=VERSION)
parser.parse_args()
def _install_ghostscript_via_winget() -> bool:
"""Attempt installation using winget."""
try:
subprocess.check_call([
"winget",
"install",
"--id",
"Ghostscript.Ghostscript",
"-e",
"--silent",
])
return True
except Exception:
return False
def _install_ghostscript_via_choco() -> bool:
"""Attempt installation using Chocolatey."""
try:
subprocess.check_call(["choco", "install", "ghostscript", "-y"])
return True
except Exception:
return False
def _install_ghostscript_via_powershell() -> bool:
"""Download and install Ghostscript via PowerShell."""
url = "https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs10040/gs10040w64.exe"
script = (
f"Invoke-WebRequest -Uri {url} -OutFile gs.exe;"
"Start-Process gs.exe -ArgumentList '/S' -NoNewWindow -Wait"
)
try:
subprocess.check_call(["powershell", "-Command", script])
return True
except Exception:
return False
def _install_ghostscript_via_pip() -> bool:
"""Fallback installation using pip ghostscript wrapper."""
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "ghostscript"])
return True
except Exception:
return False
def ensure_ghostscript() -> None:
"""Ensure Ghostscript is available on Windows systems.
The function attempts four different installation mechanisms to provide
robustness across environments. If all methods fail, a ``RuntimeError``
is raised to signal the missing dependency.
"""
if os.name != "nt":
return
if _ghostscript_available():
return
installers = [
_install_ghostscript_via_winget,
_install_ghostscript_via_choco,
_install_ghostscript_via_powershell,
_install_ghostscript_via_pip,
]
for installer in installers:
if installer():
if _ghostscript_available():
return
raise RuntimeError("Ghostscript installation failed")
def ensure_packages() -> None:
"""Install any missing runtime dependencies.
When running from a PyInstaller executable, the packages are already
bundled and pip is not available, so the function simply returns.
"""
if getattr(sys, "frozen", False):
return
missing = []
for distribution, import_name in REQUIRED_PACKAGES.items():
# Discovery avoids executing third-party package initializers. An
# installed package can raise ImportError while importing an optional
# dependency; treating that as "not installed" caused redundant pip
# output for adjustText on every launch.
if importlib.util.find_spec(import_name) is None:
missing.append(distribution)
if not missing:
return
def install(pkg: str) -> None:
proc = subprocess.Popen([sys.executable, "-m", "pip", "install", pkg])
memory_manager.register_process(pkg, proc)
proc.wait()
for package in missing:
install(package)
memory_manager.cleanup()
def _bootstrap() -> object:
"""Run startup checks before constructing the GUI.
Returns
-------
Module
The main application module which provides a ``main`` entry point.
"""
import AutoML as automl
global _diagnostics_manager
automl.parse_args()
automl.install_best()
automl.report_health("startup", healthy=True)
_diagnostics_manager = EventDiagnosticsManager()
automl._diagnostics_manager = _diagnostics_manager
# Startup imports and initializers remain sequential because third-party
# packages may create Tk objects or a default root as an import side effect.
automl.ensure_packages()
automl.ensure_ghostscript()
base_path = Path(getattr(sys, "_MEIPASS", Path(__file__).parent))
# Insert both the launcher directory and the 'mainappsrc' module location to ensure
# the project-specific AutoML module is discovered rather than any similarly
# named third-party package that may be installed in the environment.
mainappsrc_path = base_path / "mainappsrc"
for path in (str(mainappsrc_path), str(base_path)):
if path not in sys.path:
sys.path.insert(0, path)
# Cleanup is tied to this completed startup phase rather than a timer.
automl.manager_eater.cleanup()
return importlib.import_module("mainappsrc.automl_core")
def main() -> None:
"""Entry point used by both source and bundled executions."""
try:
# The splash and its animation share the main GUI thread. Bootstrap is
# scheduled only after its event loop starts, and the application root
# is created after the splash interpreter closes.
SplashLauncher(loader=_bootstrap).launch()
finally:
model_loader.cleanup()
manager_eater.cleanup()
if _diagnostics_manager:
_diagnostics_manager.process_events()
_diagnostics_manager.raise_errors()
report_health("shutdown", healthy=True)
project_workers.assert_stopped()
if __name__ == "__main__":
main()