dragon-ml-toolbox 2.3.0__py3-none-any.whl → 2.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dragon-ml-toolbox
3
- Version: 2.3.0
3
+ Version: 2.4.0
4
4
  Summary: A collection of tools for data science and machine learning projects
5
5
  Author-email: Karl Loza <luigiloza@gmail.com>
6
6
  License-Expression: MIT
@@ -37,9 +37,11 @@ Requires-Dist: Pillow
37
37
  Provides-Extra: pytorch
38
38
  Requires-Dist: torch; extra == "pytorch"
39
39
  Requires-Dist: torchvision; extra == "pytorch"
40
+ Provides-Extra: gui
41
+ Requires-Dist: FreeSimpleGUI>=5.2; extra == "gui"
40
42
  Dynamic: license-file
41
43
 
42
- # dragon-ml-tools
44
+ # dragon-ml-toolbox
43
45
 
44
46
  A collection of Python utilities for data science and machine learning, structured as a modular package for easy reuse and installation.
45
47
 
@@ -57,7 +59,7 @@ A collection of Python utilities for data science and machine learning, structur
57
59
  Install the latest stable release from PyPI:
58
60
 
59
61
  ```bash
60
- pip install dragon-ml-tools
62
+ pip install dragon-ml-toolbox
61
63
  ```
62
64
 
63
65
  ### Via GitHub (Editable)
@@ -77,16 +79,26 @@ Install from the conda-forge channel:
77
79
  ```bash
78
80
  conda install -c conda-forge dragon-ml-toolbox
79
81
  ```
80
- **Note:** This version is outdated or broken due to dependency incompatibilities.
82
+ **Note:** This version is outdated or broken due to dependency incompatibilities. Use PyPi instead.
81
83
 
82
84
  ## Optional dependencies
83
85
 
84
- **PyTorch**, which provides different builds depending on the **platform** and **hardware acceleration** (e.g., CUDA for NVIDIA GPUs on Linux/Windows, or MPS for Apple Silicon on macOS).
86
+ ### FreeSimpleGUI
87
+
88
+ Wrapper library used to build powerful GUIs. Requires the tkinter backend.
89
+
90
+ ```bash
91
+ pip install dragon-ml-toolbox[gui]
92
+ ```
93
+
94
+ ### PyTorch
95
+
96
+ Different builds available depending on the **platform** and **hardware acceleration** (e.g., CUDA for NVIDIA GPUs on Linux/Windows, or MPS for Apple Silicon on macOS).
85
97
 
86
98
  Install the default CPU-only version with
87
99
 
88
100
  ```bash
89
- pip install dragon-ml-tools[pytorch]
101
+ pip install dragon-ml-toolbox[pytorch]
90
102
  ```
91
103
 
92
104
  To make use of GPU acceleration use the official PyTorch installation instructions:
@@ -108,6 +120,8 @@ from ml_tools.logger import custom_logger
108
120
  data_exploration
109
121
  datasetmaster
110
122
  ensemble_learning
123
+ ETL_engineering
124
+ GUI_tools
111
125
  handle_excel
112
126
  logger
113
127
  MICE_imputation
@@ -1,6 +1,7 @@
1
- dragon_ml_toolbox-2.3.0.dist-info/licenses/LICENSE,sha256=2uUFNy7D0TLgHim1K5s3DIJ4q_KvxEXVilnU20cWliY,1066
2
- dragon_ml_toolbox-2.3.0.dist-info/licenses/LICENSE-THIRD-PARTY.md,sha256=6cfpIeQ6D4Mcs10nkogQrkVyq1T7i2qXjjNHFoUMOyE,1892
1
+ dragon_ml_toolbox-2.4.0.dist-info/licenses/LICENSE,sha256=2uUFNy7D0TLgHim1K5s3DIJ4q_KvxEXVilnU20cWliY,1066
2
+ dragon_ml_toolbox-2.4.0.dist-info/licenses/LICENSE-THIRD-PARTY.md,sha256=6cfpIeQ6D4Mcs10nkogQrkVyq1T7i2qXjjNHFoUMOyE,1892
3
3
  ml_tools/ETL_engineering.py,sha256=ns8HsLWZhByurvjtUUW10p7If1h1O5-btUfCRXxzkME,31568
4
+ ml_tools/GUI_tools.py,sha256=sKLBWRhwGax3QSVICEduQiTbGhQdwvW0eeHPQMiyOF0,20150
4
5
  ml_tools/MICE_imputation.py,sha256=1fovHycZMdZ6OgVh_bk8-r3wGi4rqf6rS10LOEWYaQo,11177
5
6
  ml_tools/PSO_optimization.py,sha256=gi56mF-q6BApYwhAd9jix0xiYz595WTPcUh7afZsRJ4,25378
6
7
  ml_tools/VIF_factor.py,sha256=lpM3Z2X_iZfXUWbCbURoeI0Tb196lU0bAsRo7q6AzBM,10235
@@ -15,7 +16,7 @@ ml_tools/pytorch_models.py,sha256=bpWZsrSwCvHJQkR6UfoPpElsMv9AvmiNErNHC8NYB_I,10
15
16
  ml_tools/trainer.py,sha256=WAZ4EdrZuTOAnGXRWV3XcLNce4s7EKGf2-qchLC08Ik,15702
16
17
  ml_tools/utilities.py,sha256=T6AnNEQjUDnMAMSIJ8yZqToAVESIlEKK0bGBEm3sAUU,20670
17
18
  ml_tools/vision_helpers.py,sha256=idQ-Ugp1IdsvwXiYyhYa9G3rTRTm37YRpkQDLEpANHM,7701
18
- dragon_ml_toolbox-2.3.0.dist-info/METADATA,sha256=4wivV_JKPd83xNzf6xzSfCwxiZgvYL5uW4yE6Da8tnU,2974
19
- dragon_ml_toolbox-2.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
20
- dragon_ml_toolbox-2.3.0.dist-info/top_level.txt,sha256=wm-oxax3ciyez6VoO4zsFd-gSok2VipYXnbg3TH9PtU,9
21
- dragon_ml_toolbox-2.3.0.dist-info/RECORD,,
19
+ dragon_ml_toolbox-2.4.0.dist-info/METADATA,sha256=LewdCOSOEeCNVLrB37FD39hnESJ7lPt2voeO-nFG-es,3232
20
+ dragon_ml_toolbox-2.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
21
+ dragon_ml_toolbox-2.4.0.dist-info/top_level.txt,sha256=wm-oxax3ciyez6VoO4zsFd-gSok2VipYXnbg3TH9PtU,9
22
+ dragon_ml_toolbox-2.4.0.dist-info/RECORD,,
ml_tools/GUI_tools.py ADDED
@@ -0,0 +1,496 @@
1
+ import configparser
2
+ from pathlib import Path
3
+ from typing import Optional, Callable, Any
4
+ import traceback
5
+ import FreeSimpleGUI as sg
6
+ from functools import wraps
7
+ from typing import Any, Dict, Tuple, List
8
+ from .utilities import _script_info
9
+ import numpy as np
10
+
11
+
12
+ __all__ = [
13
+ "PathManager",
14
+ "ConfigManager",
15
+ "GUIFactory",
16
+ "catch_exceptions",
17
+ "prepare_feature_vector",
18
+ "update_target_fields"
19
+ ]
20
+
21
+
22
+ # --- Path Management ---
23
+ class PathManager:
24
+ """
25
+ Manages paths for a Python application, supporting both development mode and bundled mode via Briefcase.
26
+ """
27
+ def __init__(self, anchor_file: str):
28
+ """
29
+ Initializes the PathManager. The package name is automatically inferred
30
+ from the parent directory of the anchor file.
31
+
32
+ Args:
33
+ anchor_file (str): The absolute path to a file within the project's
34
+ package, typically `__file__` from a module inside
35
+ that package (paths.py).
36
+
37
+ Note:
38
+ This inference assumes that the anchor file's parent directory
39
+ has the same name as the package (e.g., `.../src/my_app/paths.py`).
40
+ This is a standard and recommended project structure.
41
+ """
42
+ resolved_anchor_path = Path(anchor_file).resolve()
43
+ self.package_name = resolved_anchor_path.parent.name
44
+ self._is_bundled, self._resource_path_func = self._check_bundle_status()
45
+
46
+ if self._is_bundled:
47
+ # In a Briefcase bundle, resource_path gives an absolute path
48
+ # to the resource directory.
49
+ self.package_root = self._resource_path_func(self.package_name, "")
50
+ else:
51
+ # In development mode, the package root is the directory
52
+ # containing the anchor file.
53
+ self.package_root = resolved_anchor_path.parent
54
+
55
+ def _check_bundle_status(self) -> tuple[bool, Optional[Callable]]:
56
+ """Checks if the app is running in a bundled environment."""
57
+ try:
58
+ # This is the function Briefcase provides in a bundled app
59
+ from briefcase.platforms.base import resource_path
60
+ return True, resource_path
61
+ except ImportError:
62
+ return False, None
63
+
64
+ def get_path(self, relative_path: str | Path) -> Path:
65
+ """
66
+ Gets the absolute path for a given resource file or directory
67
+ relative to the package root.
68
+
69
+ Args:
70
+ relative_path (str | Path): The path relative to the package root (e.g., 'helpers/icon.png').
71
+
72
+ Returns:
73
+ Path: The absolute path to the resource.
74
+ """
75
+ if self._is_bundled:
76
+ # Briefcase's resource_path handles resolving the path within the app bundle
77
+ return self._resource_path_func(self.package_name, str(relative_path)) # type: ignore
78
+ else:
79
+ # In dev mode, join package root with the relative path.
80
+ return self.package_root / relative_path
81
+
82
+
83
+ # --- Configuration Management ---
84
+ class _SectionProxy:
85
+ """A helper class to represent a section of the .ini file as an object."""
86
+ def __init__(self, parser: configparser.ConfigParser, section_name: str):
87
+ for option, value in parser.items(section_name):
88
+ setattr(self, option.lower(), self._process_value(value))
89
+
90
+ def _process_value(self, value_str: str) -> Any:
91
+ """Automatically converts string values to appropriate types."""
92
+ # Handle None
93
+ if value_str is None or value_str.lower() == 'none':
94
+ return None
95
+ # Handle Booleans
96
+ if value_str.lower() in ['true', 'yes', 'on']:
97
+ return True
98
+ if value_str.lower() in ['false', 'no', 'off']:
99
+ return False
100
+ # Handle Integers
101
+ try:
102
+ return int(value_str)
103
+ except ValueError:
104
+ pass
105
+ # Handle Floats
106
+ try:
107
+ return float(value_str)
108
+ except ValueError:
109
+ pass
110
+ # Handle 'width,height' tuples
111
+ if ',' in value_str:
112
+ try:
113
+ return tuple(map(int, value_str.split(",")))
114
+ except (ValueError, TypeError):
115
+ pass
116
+ # Fallback to the original string
117
+ return value_str
118
+
119
+ class ConfigManager:
120
+ """
121
+ Loads a .ini file and provides access to its values as object attributes.
122
+ Includes a method to generate a default configuration template.
123
+ """
124
+ def __init__(self, config_path: str | Path):
125
+ """
126
+ Initializes the ConfigManager and dynamically creates attributes
127
+ based on the .ini file's sections and options.
128
+ """
129
+ config_path = Path(config_path)
130
+ if not config_path.exists():
131
+ raise FileNotFoundError(f"Configuration file not found at: {config_path}")
132
+
133
+ parser = configparser.ConfigParser(comment_prefixes=('#', ';'), inline_comment_prefixes=('#', ';'))
134
+ parser.read(config_path)
135
+
136
+ for section in parser.sections():
137
+ setattr(self, section.lower(), _SectionProxy(parser, section))
138
+
139
+ @staticmethod
140
+ def generate_template(file_path: str | Path, force_overwrite: bool = False):
141
+ """
142
+ Generates a complete, commented .ini template file that works with the GUIFactory.
143
+
144
+ Args:
145
+ file_path (str | Path): The path where the .ini file will be saved.
146
+ force_overwrite (bool): If True, overwrites the file if it already exists.
147
+ """
148
+ path = Path(file_path)
149
+ if path.exists() and not force_overwrite:
150
+ print(f"Configuration file already exists at {path}. Aborting.")
151
+ return
152
+
153
+ config = configparser.ConfigParser()
154
+
155
+ config['General'] = {
156
+ '; The overall theme for the GUI. Find more at https://www.pysimplegui.org/en/latest/call%20reference/#themes-automatic-coloring-of-elements': '',
157
+ 'theme': 'LightGreen6',
158
+ '; Default font for the application.': '',
159
+ 'font_family': 'Helvetica',
160
+ '; Title of the main window.': '',
161
+ 'window_title': 'My Application',
162
+ '; Can the user resize the window? (true/false)': '',
163
+ 'resizable_window': 'false',
164
+ '; Optional minimum window size (width,height). Leave blank for no minimum.': '',
165
+ 'min_size': '800,600',
166
+ '; Optional maximum window size (width,height). Leave blank for no maximum.': '',
167
+ 'max_size': ''
168
+ }
169
+ config['Layout'] = {
170
+ '; Default size for continuous input boxes (width,height in characters).': '',
171
+ 'input_size_cont': '16,1',
172
+ '; Default size for combo/binary boxes (width,height in characters).': '',
173
+ 'input_size_binary': '14,1',
174
+ '; Default size for buttons (width,height in characters).': '',
175
+ 'button_size': '15,2'
176
+ }
177
+ config['Fonts'] = {
178
+ '; Font settings. Style can be "bold", "italic", "underline", or a combination.': '',
179
+ 'label_size': '11',
180
+ 'label_style': 'bold',
181
+ 'range_size': '9',
182
+ 'range_style': '',
183
+ 'button_size': '14',
184
+ 'button_style': 'bold',
185
+ 'frame_size': '14',
186
+ 'frame_style': ''
187
+ }
188
+ config['Colors'] = {
189
+ '; Use standard hex codes (e.g., #FFFFFF) or color names (e.g., white).': '',
190
+ '; Color for the text inside a disabled target/output box.': '',
191
+ 'target_text': '#0000D0',
192
+ '; Background color for a disabled target/output box.': '',
193
+ 'target_background': '#E0E0E0',
194
+ '; Color for the text on a button.': '',
195
+ 'button_text': '#FFFFFF',
196
+ '; Background color for a button.': '',
197
+ 'button_background': '#3c8a7e',
198
+ '; Background color when the mouse is over a button.': '',
199
+ 'button_background_hover': '#5499C7'
200
+ }
201
+ config['Meta'] = {
202
+ '; Optional application version, displayed in the window title.': '',
203
+ 'version': '1.0.0'
204
+ }
205
+
206
+ with open(path, 'w') as configfile:
207
+ config.write(configfile)
208
+ print(f"Successfully generated config template at: '{path}'")
209
+
210
+
211
+ # --- GUI Factory ---
212
+ class GUIFactory:
213
+ """
214
+ Builds styled FreeSimpleGUI elements and layouts using a "building block"
215
+ approach, driven by a ConfigManager instance.
216
+ """
217
+ def __init__(self, config: ConfigManager):
218
+ """
219
+ Initializes the factory with a configuration object.
220
+ """
221
+ self.config = config
222
+ sg.theme(self.config.general.theme)
223
+ sg.set_options(font=(self.config.general.font_family, 12))
224
+
225
+ # --- Atomic Element Generators ---
226
+ def make_button(self, text: str, key: str, **kwargs) -> sg.Button:
227
+ """
228
+ Creates a single, styled action button.
229
+
230
+ Args:
231
+ text (str): The text displayed on the button.
232
+ key (str): The key for the button element.
233
+ **kwargs: Override default styles or add other sg.Button parameters
234
+ (e.g., `tooltip='Click me'`, `disabled=True`).
235
+ """
236
+ cfg = self.config
237
+ font = (cfg.fonts.font_family, cfg.fonts.button_size, cfg.fonts.button_style)
238
+
239
+ style_args = {
240
+ "size": cfg.layout.button_size,
241
+ "font": font,
242
+ "button_color": (cfg.colors.button_text, cfg.colors.button_background),
243
+ "mouseover_colors": (cfg.colors.button_text, cfg.colors.button_background_hover),
244
+ "border_width": 0,
245
+ **kwargs
246
+ }
247
+ return sg.Button(text.title(), key=key, **style_args)
248
+
249
+ def make_frame(self, title: str, layout: List[List[sg.Element]], **kwargs) -> sg.Frame:
250
+ """
251
+ Creates a styled frame around a given layout.
252
+
253
+ Args:
254
+ title (str): The title displayed on the frame's border.
255
+ layout (list): The layout to enclose within the frame.
256
+ **kwargs: Override default styles or add other sg.Frame parameters
257
+ (e.g., `title_color='red'`, `relief=sg.RELIEF_SUNKEN`).
258
+ """
259
+ cfg = self.config
260
+ font = (cfg.fonts.font_family, cfg.fonts.frame_size)
261
+
262
+ style_args = {
263
+ "font": font,
264
+ "expand_x": True,
265
+ "background_color": sg.theme_background_color(),
266
+ **kwargs
267
+ }
268
+ return sg.Frame(title, layout, **style_args)
269
+
270
+ # --- General-Purpose Layout Generators ---
271
+ def generate_continuous_layout(
272
+ self,
273
+ data_dict: Dict[str, Tuple[float, float]],
274
+ is_target: bool = False,
275
+ layout_mode: str = 'grid',
276
+ columns_per_row: int = 4
277
+ ) -> List[List[sg.Column]]:
278
+ """
279
+ Generates a layout for continuous features or targets.
280
+
281
+ Args:
282
+ data_dict (dict): Keys are feature names, values are (min, max) tuples.
283
+ is_target (bool): If True, creates disabled inputs for displaying results.
284
+ layout_mode (str): 'grid' for a multi-row grid layout, or 'row' for a single horizontal row.
285
+ columns_per_row (int): Number of feature columns per row when layout_mode is 'grid'.
286
+
287
+ Returns:
288
+ A list of lists of sg.Column elements, ready to be used in a window layout.
289
+ """
290
+ cfg = self.config
291
+ bg_color = sg.theme_background_color()
292
+ label_font = (cfg.fonts.font_family, cfg.fonts.label_size, cfg.fonts.label_style)
293
+
294
+ columns = []
295
+ for name, (val_min, val_max) in data_dict.items():
296
+ key = f"TARGET_{name}" if is_target else name
297
+ default_text = "" if is_target else str(val_max)
298
+
299
+ label = sg.Text(name, font=label_font, background_color=bg_color, key=f"_text_{name}")
300
+
301
+ input_style = {"size": cfg.layout.input_size_cont, "justification": "center"}
302
+ if is_target:
303
+ input_style["text_color"] = cfg.colors.target_text
304
+ input_style["disabled_readonly_background_color"] = cfg.colors.target_background
305
+
306
+ element = sg.Input(default_text, key=key, disabled=is_target, **input_style)
307
+
308
+ if is_target:
309
+ layout = [[label], [element]]
310
+ else:
311
+ range_font = (cfg.fonts.font_family, cfg.fonts.range_size)
312
+ range_text = sg.Text(f"Range: {int(val_min)}-{int(val_max)}", font=range_font, background_color=bg_color)
313
+ layout = [[label], [element], [range_text]]
314
+
315
+ layout.append([sg.Text(" ", font=(cfg.fonts.font_family, 2), background_color=bg_color)])
316
+ columns.append(sg.Column(layout, background_color=bg_color))
317
+
318
+ if layout_mode == 'row':
319
+ return [columns] # A single row containing all columns
320
+
321
+ # Default to 'grid' layout
322
+ return [columns[i:i + columns_per_row] for i in range(0, len(columns), columns_per_row)]
323
+
324
+ def generate_combo_layout(
325
+ self,
326
+ data_dict: Dict[str, List[Any]],
327
+ layout_mode: str = 'grid',
328
+ columns_per_row: int = 4
329
+ ) -> List[List[sg.Column]]:
330
+ """
331
+ Generates a layout for categorical or binary features using Combo boxes.
332
+
333
+ Args:
334
+ data_dict (dict): Keys are feature names, values are lists of options.
335
+ layout_mode (str): 'grid' for a multi-row grid layout, or 'row' for a single horizontal row.
336
+ columns_per_row (int): Number of feature columns per row when layout_mode is 'grid'.
337
+
338
+ Returns:
339
+ A list of lists of sg.Column elements, ready to be used in a window layout.
340
+ """
341
+ cfg = self.config
342
+ bg_color = sg.theme_background_color()
343
+ label_font = (cfg.fonts.font_family, cfg.fonts.label_size, cfg.fonts.label_style)
344
+
345
+ columns = []
346
+ for name, values in data_dict.items():
347
+ label = sg.Text(name, font=label_font, background_color=bg_color, key=f"_text_{name}")
348
+ element = sg.Combo(
349
+ values, default_value=values[0], key=name,
350
+ size=cfg.layout.input_size_binary, readonly=True
351
+ )
352
+ layout = [[label], [element]]
353
+ layout.append([sg.Text(" ", font=(cfg.fonts.font_family, 2), background_color=bg_color)])
354
+ columns.append(sg.Column(layout, background_color=bg_color))
355
+
356
+ if layout_mode == 'row':
357
+ return [columns] # A single row containing all columns
358
+
359
+ # Default to 'grid' layout
360
+ return [columns[i:i + columns_per_row] for i in range(0, len(columns), columns_per_row)]
361
+
362
+ # --- Window Creation ---
363
+ def create_window(self, title: str, layout: List[List[sg.Element]], **kwargs) -> sg.Window:
364
+ """
365
+ Creates and finalizes the main application window.
366
+
367
+ Args:
368
+ title (str): The title for the window.
369
+ layout (list): The final, assembled layout for the window.
370
+ **kwargs: Additional arguments to pass to the sg.Window constructor
371
+ (e.g., `location=(100, 100)`, `keep_on_top=True`).
372
+ """
373
+ cfg = self.config.general
374
+ version = getattr(self.config.meta, 'version', None)
375
+ full_title = f"{title} v{version}" if version else title
376
+
377
+ window_args = {
378
+ "resizable": cfg.resizable_window,
379
+ "finalize": True,
380
+ "background_color": sg.theme_background_color(),
381
+ **kwargs
382
+ }
383
+ window = sg.Window(full_title, layout, **window_args)
384
+
385
+ if cfg.min_size: window.TKroot.minsize(*cfg.min_size)
386
+ if cfg.max_size: window.TKroot.maxsize(*cfg.max_size)
387
+
388
+ return window
389
+
390
+
391
+ # --- Exception Handling Decorator ---
392
+ def catch_exceptions(show_popup: bool = True):
393
+ """
394
+ A decorator that wraps a function in a try-except block.
395
+ If an exception occurs, it's caught and displayed in a popup window.
396
+ """
397
+ def decorator(func):
398
+ @wraps(func)
399
+ def wrapper(*args, **kwargs):
400
+ try:
401
+ return func(*args, **kwargs)
402
+ except Exception as e:
403
+ # Format the full traceback to give detailed error info
404
+ error_msg = traceback.format_exc()
405
+ if show_popup:
406
+ sg.popup_error("An error occurred:", error_msg, title="Error")
407
+ else:
408
+ # Fallback for non-GUI contexts or if popup is disabled
409
+ print("--- An exception occurred ---")
410
+ print(error_msg)
411
+ print("-----------------------------")
412
+ return wrapper
413
+ return decorator
414
+
415
+
416
+ # --- Inference Helpers ---
417
+ def _default_categorical_processor(feature_name: str, chosen_value: Any) -> List[float]:
418
+ """
419
+ Default processor for binary 'True'/'False' strings.
420
+ Returns a list containing a single float.
421
+ """
422
+ return [1.0] if str(chosen_value) == 'True' else [0.0]
423
+
424
+ def prepare_feature_vector(
425
+ values: Dict[str, Any],
426
+ feature_order: List[str],
427
+ continuous_features: List[str],
428
+ categorical_features: List[str],
429
+ categorical_processor: Optional[Callable[[str, Any], List[float]]] = None
430
+ ) -> np.ndarray:
431
+ """
432
+ Validates and converts GUI values into a numpy array for a model.
433
+ This function supports label encoding and one-hot encoding via the processor.
434
+
435
+ Args:
436
+ values (dict): The values dictionary from a `window.read()` call.
437
+ feature_order (list): A list of all feature names that have a GUI element.
438
+ For one-hot encoding, this should be the name of the
439
+ single GUI element (e.g., 'material_type'), not the
440
+ expanded feature names (e.g., 'material_is_steel').
441
+ continuous_features (list): A list of names for continuous features.
442
+ categorical_features (list): A list of names for categorical features.
443
+ categorical_processor (callable, optional): A function to process categorical
444
+ values. It should accept (feature_name, chosen_value) and return a
445
+ list of floats (e.g., [1.0] for label encoding, [0.0, 1.0, 0.0] for one-hot).
446
+ If None, a default 'True'/'False' processor is used.
447
+
448
+ Returns:
449
+ A 1D numpy array ready for model inference.
450
+ """
451
+ processed_values: List[float] = []
452
+
453
+ # Use the provided processor or the default one
454
+ processor = categorical_processor or _default_categorical_processor
455
+
456
+ # Create sets for faster lookups
457
+ cont_set = set(continuous_features)
458
+ cat_set = set(categorical_features)
459
+
460
+ for name in feature_order:
461
+ chosen_value = values.get(name)
462
+
463
+ if chosen_value is None or chosen_value == '':
464
+ raise ValueError(f"Feature '{name}' is missing a value.")
465
+
466
+ if name in cont_set:
467
+ try:
468
+ processed_values.append(float(chosen_value))
469
+ except (ValueError, TypeError):
470
+ raise ValueError(f"Invalid input for '{name}'. Please enter a valid number.")
471
+
472
+ elif name in cat_set:
473
+ # The processor returns a list of values (one for label, multiple for one-hot)
474
+ numeric_values = processor(name, chosen_value)
475
+ processed_values.extend(numeric_values)
476
+
477
+ return np.array(processed_values, dtype=np.float32)
478
+
479
+
480
+ def update_target_fields(window: sg.Window, results_dict: Dict[str, Any]):
481
+ """
482
+ Updates the GUI's target fields with inference results.
483
+
484
+ Args:
485
+ window (sg.Window): The application's window object.
486
+ results_dict (dict): A dictionary where keys are target names (without the
487
+ 'TARGET_' prefix) and values are the predicted results.
488
+ """
489
+ for target_name, result in results_dict.items():
490
+ # Format numbers to 2 decimal places, leave other types as-is
491
+ display_value = f"{result:.2f}" if isinstance(result, (int, float)) else result
492
+ window[f'TARGET_{target_name}'].update(display_value)
493
+
494
+
495
+ def info():
496
+ _script_info(__all__)