packflow 0.3.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.
- packflow/__init__.py +6 -0
- packflow/backend/__init__.py +2 -0
- packflow/backend/base.py +262 -0
- packflow/backend/configuration.py +152 -0
- packflow/backend/metrics.py +27 -0
- packflow/backend/preprocessors.py +237 -0
- packflow/backend/validation.py +98 -0
- packflow/cli.py +47 -0
- packflow/constants.py +3 -0
- packflow/data/templates/minimal/LICENSE.txt +0 -0
- packflow/data/templates/minimal/MODEL_CARD.md +91 -0
- packflow/data/templates/minimal/README.md +0 -0
- packflow/data/templates/minimal/inference.py +75 -0
- packflow/data/templates/minimal/packflow.yaml +11 -0
- packflow/data/templates/minimal/requirements.txt +0 -0
- packflow/data/templates/minimal/validate.py +25 -0
- packflow/exceptions.py +26 -0
- packflow/loaders/__init__.py +4 -0
- packflow/loaders/base.py +86 -0
- packflow/loaders/config.py +125 -0
- packflow/loaders/local.py +57 -0
- packflow/loaders/module.py +29 -0
- packflow/loaders/utils.py +27 -0
- packflow/logger.py +5 -0
- packflow/project.py +72 -0
- packflow/utils/__init__.py +2 -0
- packflow/utils/data.py +152 -0
- packflow/utils/normalize/__init__.py +1 -0
- packflow/utils/normalize/base.py +79 -0
- packflow/utils/normalize/handlers.py +93 -0
- packflow/utils/normalize/normalize.py +87 -0
- packflow-0.3.0.dist-info/METADATA +175 -0
- packflow-0.3.0.dist-info/RECORD +36 -0
- packflow-0.3.0.dist-info/WHEEL +4 -0
- packflow-0.3.0.dist-info/entry_points.txt +3 -0
- packflow-0.3.0.dist-info/licenses/LICENSE +9 -0
packflow/__init__.py
ADDED
packflow/backend/base.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from typing import Any, Callable, Dict, List, Union
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
import packflow.exceptions as exceptions
|
|
8
|
+
from packflow.logger import get_logger
|
|
9
|
+
|
|
10
|
+
from .configuration import BackendConfig, load_backend_configuration
|
|
11
|
+
from .metrics import ExecutionMetrics
|
|
12
|
+
from .preprocessors import get_preprocessor
|
|
13
|
+
from .validation import InferenceBackendValidator
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InferenceBackend(ABC):
|
|
17
|
+
"""Abstract Base Class for the inference backend base"""
|
|
18
|
+
|
|
19
|
+
backend_config_model: BackendConfig | type[BackendConfig] = BackendConfig
|
|
20
|
+
|
|
21
|
+
def __init__(self, **kwargs):
|
|
22
|
+
self.logger = get_logger()
|
|
23
|
+
self.config = load_backend_configuration(self.backend_config_model, **kwargs)
|
|
24
|
+
self._preprocessor = get_preprocessor(self.config)
|
|
25
|
+
self._execution_metrics = dict(execution_times={})
|
|
26
|
+
self._initialize()
|
|
27
|
+
|
|
28
|
+
def __repr__(self): # pragma: no cover
|
|
29
|
+
return f"{self.__class__.__name__}[\n {self.config.__repr__()}\n]"
|
|
30
|
+
|
|
31
|
+
def __call__(self, inputs: Union[dict, List[dict]]) -> Union[dict, List[dict]]:
|
|
32
|
+
"""Execute the entire inference pipeline.
|
|
33
|
+
|
|
34
|
+
Steps are executed in the following order:
|
|
35
|
+
preprocess (internal) --> transform_inputs (optional) --> execute (required) --> transform_outputs (optional)
|
|
36
|
+
|
|
37
|
+
Each step reports execution metrics for debugging and bottleneck identification. Metrics are logged if
|
|
38
|
+
verbose=True is set in the BackendConfig. Otherwise, they can be accessed through the get_metrics() method.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
inputs : Union[dict, List[dict]]
|
|
43
|
+
A single dictionary or a list of dictionaries (Records) to pass through the pipeline
|
|
44
|
+
|
|
45
|
+
Returns
|
|
46
|
+
-------
|
|
47
|
+
Union[dict, List[dict]]
|
|
48
|
+
Object that matches the type and shape of the provided input
|
|
49
|
+
"""
|
|
50
|
+
if not isinstance(inputs, (dict, list)):
|
|
51
|
+
raise exceptions.InferenceBackendRuntimeError(
|
|
52
|
+
f"Inputs must be a dictionary or Records. Type received: {type(inputs)}"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
input_is_dict = isinstance(inputs, dict)
|
|
56
|
+
|
|
57
|
+
inputs = [inputs] if input_is_dict else inputs
|
|
58
|
+
|
|
59
|
+
self._execution_metrics["batch_size"] = len(inputs)
|
|
60
|
+
|
|
61
|
+
preprocessed = self._execute_and_profile_step(self._preprocess, inputs)
|
|
62
|
+
|
|
63
|
+
if hasattr(self, "transform_inputs"):
|
|
64
|
+
features = self._execute_and_profile_step(
|
|
65
|
+
self.transform_inputs, preprocessed
|
|
66
|
+
)
|
|
67
|
+
else:
|
|
68
|
+
features = preprocessed
|
|
69
|
+
|
|
70
|
+
results = self._execute_and_profile_step(self.execute, features)
|
|
71
|
+
|
|
72
|
+
if hasattr(self, "transform_outputs"):
|
|
73
|
+
outputs = self._execute_and_profile_step(self.transform_outputs, results)
|
|
74
|
+
else:
|
|
75
|
+
outputs = results
|
|
76
|
+
|
|
77
|
+
if not isinstance(outputs, list):
|
|
78
|
+
raise exceptions.InferenceBackendRuntimeError(
|
|
79
|
+
f"Output of inference backend is not a list. Received type: {type(outputs)}"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
if input_is_dict:
|
|
83
|
+
outputs = outputs[0]
|
|
84
|
+
|
|
85
|
+
if self.config.verbose:
|
|
86
|
+
self.logger.info(f"{self.get_metrics().__repr__()}")
|
|
87
|
+
|
|
88
|
+
return outputs
|
|
89
|
+
|
|
90
|
+
def _initialize(self):
|
|
91
|
+
"""Metrics wrapper for user-defined initialize function"""
|
|
92
|
+
start = time.perf_counter()
|
|
93
|
+
try:
|
|
94
|
+
self.initialize()
|
|
95
|
+
except Exception as e:
|
|
96
|
+
raise exceptions.InferenceBackendInitializationError(
|
|
97
|
+
f"Failed to initialize inference backend: {e}"
|
|
98
|
+
) from e
|
|
99
|
+
|
|
100
|
+
delta = time.perf_counter() - start
|
|
101
|
+
|
|
102
|
+
if self.config.verbose:
|
|
103
|
+
self.logger.info(
|
|
104
|
+
f"Initialized {self.__class__.__name__} in {delta:,.4f} ms"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
def _preprocess(self, raw_inputs: List[dict]) -> Union[List[dict], "np.array"]:
|
|
108
|
+
"""
|
|
109
|
+
Run the internally configured data preprocessor
|
|
110
|
+
"""
|
|
111
|
+
return self._preprocessor(raw_inputs)
|
|
112
|
+
|
|
113
|
+
def _execute_and_profile_step(self, method: Callable, data: Any) -> Any:
|
|
114
|
+
"""
|
|
115
|
+
Wrap execution of a method with error handling and gather execution time.
|
|
116
|
+
|
|
117
|
+
Parameters
|
|
118
|
+
----------
|
|
119
|
+
method: Callable
|
|
120
|
+
The method to execute
|
|
121
|
+
|
|
122
|
+
data: Any
|
|
123
|
+
The input data for the step
|
|
124
|
+
|
|
125
|
+
Returns
|
|
126
|
+
-------
|
|
127
|
+
Any
|
|
128
|
+
The output of the step
|
|
129
|
+
|
|
130
|
+
Notes
|
|
131
|
+
-----
|
|
132
|
+
This method is not a decorator because subclasses will override the main methods
|
|
133
|
+
(transform_inputs, execute, transform_outputs), and would require users to manually
|
|
134
|
+
specify the decorator at development time. This approach removes that concern and
|
|
135
|
+
reduces redundant code.
|
|
136
|
+
"""
|
|
137
|
+
name = method.__name__.strip("_")
|
|
138
|
+
start = time.perf_counter()
|
|
139
|
+
|
|
140
|
+
try:
|
|
141
|
+
result = method(data)
|
|
142
|
+
except Exception as e:
|
|
143
|
+
raise exceptions.InferenceBackendRuntimeError(
|
|
144
|
+
f"{name}() failed with the following error: {e}"
|
|
145
|
+
) from e
|
|
146
|
+
|
|
147
|
+
time_ms = (time.perf_counter() - start) * 1000
|
|
148
|
+
|
|
149
|
+
self._execution_metrics["execution_times"][name] = round(time_ms, 5)
|
|
150
|
+
|
|
151
|
+
return result
|
|
152
|
+
|
|
153
|
+
def initialize(self) -> None:
|
|
154
|
+
"""User-defined initialization steps. Runs during __init__ for the base class.
|
|
155
|
+
|
|
156
|
+
Notes
|
|
157
|
+
-----
|
|
158
|
+
This function is to simplify initialization steps for an extension of this class
|
|
159
|
+
"""
|
|
160
|
+
return
|
|
161
|
+
|
|
162
|
+
# def transform_inputs(self, inputs: Union[List[dict], Any]) -> Any:
|
|
163
|
+
# """Preprocessing steps or other transformations before running inference.
|
|
164
|
+
#
|
|
165
|
+
# This function should ingest raw records and return inference-ready features.
|
|
166
|
+
# Ex: [{"foo": 5}] -> np.array([[5]])
|
|
167
|
+
#
|
|
168
|
+
# Parameters
|
|
169
|
+
# ----------
|
|
170
|
+
# inputs: List[Dict]
|
|
171
|
+
# A list of dictionary objects
|
|
172
|
+
#
|
|
173
|
+
# Returns
|
|
174
|
+
# -------
|
|
175
|
+
# Any
|
|
176
|
+
# The expected input data for the model or function is.
|
|
177
|
+
#
|
|
178
|
+
# Notes
|
|
179
|
+
# -----
|
|
180
|
+
# This function should *not* filter rows. The input and output batches should
|
|
181
|
+
# have the same length.
|
|
182
|
+
# """
|
|
183
|
+
# return inputs
|
|
184
|
+
|
|
185
|
+
@abstractmethod
|
|
186
|
+
def execute(self, inputs: Any) -> Any: # pragma: no cover
|
|
187
|
+
"""The main execution of inference or analysis for the developed application.
|
|
188
|
+
|
|
189
|
+
This method should remain targeted to passing data through the model/execution
|
|
190
|
+
code for profiling purposes. Minimal pre- or post-processing should occur at this
|
|
191
|
+
step unless completely necessary.
|
|
192
|
+
|
|
193
|
+
Parameters
|
|
194
|
+
----------
|
|
195
|
+
inputs: List[Dict]
|
|
196
|
+
The output of the transform_inputs method. If the transform_inputs method is
|
|
197
|
+
not overridden, the data is formatted as records (list of dictionaries)
|
|
198
|
+
|
|
199
|
+
Returns
|
|
200
|
+
-------
|
|
201
|
+
Any
|
|
202
|
+
Model Outputs
|
|
203
|
+
|
|
204
|
+
Notes
|
|
205
|
+
-----
|
|
206
|
+
The transform_outputs() method should handle all postprocessing including calculating
|
|
207
|
+
metrics, converting outputs back to Python types, and other postprocessing steps. Try
|
|
208
|
+
to keep this method focused purely on inference/analysis.
|
|
209
|
+
"""
|
|
210
|
+
pass
|
|
211
|
+
|
|
212
|
+
# def transform_outputs(self, outputs: Any) -> List[dict]:
|
|
213
|
+
# """The main execution of inference or
|
|
214
|
+
#
|
|
215
|
+
# This method should remain targeted to passing data through the model/execution
|
|
216
|
+
# code for profiling purposes. Minimal
|
|
217
|
+
#
|
|
218
|
+
# Parameters
|
|
219
|
+
# ----------
|
|
220
|
+
# outputs: Any
|
|
221
|
+
# The output of the transform_inputs method. If the transform_inputs method is
|
|
222
|
+
# not overridden, the data is formatted as records (list of dictionaries)
|
|
223
|
+
#
|
|
224
|
+
# Returns
|
|
225
|
+
# -------
|
|
226
|
+
# List[dict]
|
|
227
|
+
# Model Outputs
|
|
228
|
+
#
|
|
229
|
+
# Notes
|
|
230
|
+
# -----
|
|
231
|
+
# The transform_outputs() method *must* output json-serializable data in the form of
|
|
232
|
+
# records (a list of dictionaries).
|
|
233
|
+
# """
|
|
234
|
+
# return outputs
|
|
235
|
+
|
|
236
|
+
def validate(self, inputs: Union[dict, List[dict]]) -> Union[dict, List[dict]]:
|
|
237
|
+
"""
|
|
238
|
+
Run validations against the inference backend to ensure it meets API restrictions
|
|
239
|
+
"""
|
|
240
|
+
validator = InferenceBackendValidator(self)
|
|
241
|
+
|
|
242
|
+
return validator.run(inputs)
|
|
243
|
+
|
|
244
|
+
def get_metrics(self) -> ExecutionMetrics:
|
|
245
|
+
"""
|
|
246
|
+
Utility for collecting user-defined metrics and validating their contents
|
|
247
|
+
|
|
248
|
+
Returns
|
|
249
|
+
-------
|
|
250
|
+
ExecutionMetrics
|
|
251
|
+
"""
|
|
252
|
+
return ExecutionMetrics(**self._execution_metrics)
|
|
253
|
+
|
|
254
|
+
def ready(self) -> bool:
|
|
255
|
+
"""
|
|
256
|
+
Optional function to define when the app is ready to execute
|
|
257
|
+
|
|
258
|
+
Returns
|
|
259
|
+
-------
|
|
260
|
+
bool
|
|
261
|
+
"""
|
|
262
|
+
return self is not None
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import enum
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import List
|
|
6
|
+
|
|
7
|
+
from deepmerge import Merger
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
from packflow import constants
|
|
11
|
+
from packflow.logger import get_logger
|
|
12
|
+
|
|
13
|
+
logger = get_logger()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InputFormats(enum.Enum):
|
|
17
|
+
"""See :ref:`Preprocessors<preprocessors>` for details."""
|
|
18
|
+
|
|
19
|
+
PASSTHROUGH = "passthrough"
|
|
20
|
+
RECORDS = "records"
|
|
21
|
+
NUMPY = "numpy"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BackendConfig(BaseModel):
|
|
25
|
+
"""See :ref:`Backend Configuration<backend-configuration>` for details."""
|
|
26
|
+
|
|
27
|
+
# Base configurations - controls some runtime logging behaviors
|
|
28
|
+
verbose: bool = True
|
|
29
|
+
|
|
30
|
+
# Data Requirements - controls preprocessor behavior.
|
|
31
|
+
input_format: InputFormats = InputFormats.RECORDS
|
|
32
|
+
rename_fields: dict = {}
|
|
33
|
+
feature_names: List[str] = []
|
|
34
|
+
flatten_nested_inputs: bool = False
|
|
35
|
+
flatten_lists: bool = False
|
|
36
|
+
nested_field_delimiter: str = "."
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_backend_configuration(
|
|
40
|
+
backend_config_model: BackendConfig | type[BackendConfig] = BackendConfig,
|
|
41
|
+
**backend_kwargs,
|
|
42
|
+
) -> BackendConfig:
|
|
43
|
+
"""
|
|
44
|
+
Loads, resolves, and validates base configurations and overrides.
|
|
45
|
+
|
|
46
|
+
Parameters
|
|
47
|
+
----------
|
|
48
|
+
backend_config_model : BackendConfig
|
|
49
|
+
An instance of, or a subclass of, a BackendConfig Model to use for validation.
|
|
50
|
+
Defaults to a base BackendConfig
|
|
51
|
+
|
|
52
|
+
**backend_kwargs
|
|
53
|
+
Optional keyword arguments to use as base parameters. These values are overridden by
|
|
54
|
+
any configurations loaded from the environment configuration.
|
|
55
|
+
|
|
56
|
+
Returns
|
|
57
|
+
-------
|
|
58
|
+
BackendConfig
|
|
59
|
+
A validated configuration model
|
|
60
|
+
"""
|
|
61
|
+
dict_config = _resolve_configs(backend_kwargs)
|
|
62
|
+
|
|
63
|
+
logger.debug(f"Loaded raw configuration: {dict_config}")
|
|
64
|
+
|
|
65
|
+
validated_config = backend_config_model.model_validate(dict_config)
|
|
66
|
+
|
|
67
|
+
logger.info(f"Configuration: {validated_config.__repr__()}")
|
|
68
|
+
|
|
69
|
+
return validated_config
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _load_overrides_from_env() -> dict:
|
|
73
|
+
"""
|
|
74
|
+
Load a configuration from the file path passed via environment variable.
|
|
75
|
+
This configuration overrides all in-line or default values in the provided
|
|
76
|
+
BackendConfig or subclass.
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
dict
|
|
81
|
+
|
|
82
|
+
Notes
|
|
83
|
+
-----
|
|
84
|
+
The configuration file must include a top level key named "configs".
|
|
85
|
+
Example:
|
|
86
|
+
{
|
|
87
|
+
"configs": {
|
|
88
|
+
"feature_names": ["foo:bar"]
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
"""
|
|
92
|
+
config_file_path = os.getenv(constants.BACKEND_CONFIG_PATH_ENV_VAR_NAME)
|
|
93
|
+
|
|
94
|
+
if not config_file_path:
|
|
95
|
+
return {}
|
|
96
|
+
|
|
97
|
+
file_path = Path(config_file_path)
|
|
98
|
+
|
|
99
|
+
if not file_path.exists():
|
|
100
|
+
logger.error(
|
|
101
|
+
f"Falling back to empty configuration. Reason: Configuration file does not exist at provided path {file_path}"
|
|
102
|
+
)
|
|
103
|
+
return {}
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
with file_path.open() as f:
|
|
107
|
+
config = json.load(f)
|
|
108
|
+
|
|
109
|
+
logger.debug(f"Loaded Overrides from environment: {config}")
|
|
110
|
+
|
|
111
|
+
if "configs" not in config:
|
|
112
|
+
logger.warning(
|
|
113
|
+
'Falling back to empty configuration. Reason: Loaded config does not contain "configs" parent key.'
|
|
114
|
+
)
|
|
115
|
+
return config.get("configs", {})
|
|
116
|
+
|
|
117
|
+
except Exception as e:
|
|
118
|
+
logger.error(
|
|
119
|
+
f"Falling back to empty configuration. Reason: Exception encountered: {e}"
|
|
120
|
+
)
|
|
121
|
+
return {}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _resolve_configs(backend_kwargs: dict) -> dict:
|
|
125
|
+
"""
|
|
126
|
+
Loads overrides from the environment and merges the configuration
|
|
127
|
+
with the provided backend_kwargs.
|
|
128
|
+
|
|
129
|
+
The Overrides will supersede any base configurations passed as
|
|
130
|
+
keyword arguments or model defaults.
|
|
131
|
+
|
|
132
|
+
Parameters
|
|
133
|
+
----------
|
|
134
|
+
**backend_kwargs
|
|
135
|
+
Any keyword arguments to pass to a BackendModel
|
|
136
|
+
|
|
137
|
+
Returns
|
|
138
|
+
-------
|
|
139
|
+
Deep-merged configuration dictionary
|
|
140
|
+
"""
|
|
141
|
+
merger = Merger(
|
|
142
|
+
[
|
|
143
|
+
(dict, "merge"),
|
|
144
|
+
(list, "override"),
|
|
145
|
+
],
|
|
146
|
+
["override"],
|
|
147
|
+
["override"],
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
overrides = _load_overrides_from_env()
|
|
151
|
+
|
|
152
|
+
return merger.merge(backend_kwargs, overrides)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, model_validator
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ExecutionTimes(BaseModel):
|
|
7
|
+
preprocess: float
|
|
8
|
+
transform_inputs: Optional[float] = None
|
|
9
|
+
execute: float
|
|
10
|
+
transform_outputs: Optional[float] = None
|
|
11
|
+
|
|
12
|
+
def total(self):
|
|
13
|
+
"""
|
|
14
|
+
Return the total execution time based on the sum of each defined field
|
|
15
|
+
"""
|
|
16
|
+
return sum([getattr(self, field) for field in self.model_fields_set])
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ExecutionMetrics(BaseModel):
|
|
20
|
+
batch_size: int
|
|
21
|
+
execution_times: ExecutionTimes
|
|
22
|
+
total_execution_time: float = None
|
|
23
|
+
|
|
24
|
+
@model_validator(mode="after")
|
|
25
|
+
def calculate_total_execution_time(self):
|
|
26
|
+
self.total_execution_time = self.execution_times.total()
|
|
27
|
+
return self
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from flatten_dict import flatten, unflatten
|
|
5
|
+
from flatten_dict.reducers import make_reducer
|
|
6
|
+
from flatten_dict.splitters import make_splitter
|
|
7
|
+
from loguru import logger
|
|
8
|
+
|
|
9
|
+
import packflow.exceptions as exceptions
|
|
10
|
+
import packflow.utils
|
|
11
|
+
|
|
12
|
+
from .configuration import BackendConfig, InputFormats
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_preprocessor(config: BackendConfig):
|
|
16
|
+
"""
|
|
17
|
+
Instantiate a preprocessor based on the provided BackendConfig.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
config : BackendConfig
|
|
22
|
+
The packflow BackendConfig for the inference backend.
|
|
23
|
+
|
|
24
|
+
Returns
|
|
25
|
+
-------
|
|
26
|
+
Preprocessor
|
|
27
|
+
|
|
28
|
+
Raises
|
|
29
|
+
------
|
|
30
|
+
UnknownPreprocessorError
|
|
31
|
+
|
|
32
|
+
Notes
|
|
33
|
+
-----
|
|
34
|
+
This is a general factory function for simpler loading of preprocessor objects.
|
|
35
|
+
All subclasses of the Preprocessor object follow the same API and be executed
|
|
36
|
+
generically.
|
|
37
|
+
"""
|
|
38
|
+
if config.input_format == InputFormats.RECORDS:
|
|
39
|
+
preprocessor = RecordsPreprocessor(config)
|
|
40
|
+
elif config.input_format == InputFormats.NUMPY:
|
|
41
|
+
preprocessor = NumpyPreprocessor(config)
|
|
42
|
+
else:
|
|
43
|
+
preprocessor = PassthroughPreprocessor(config)
|
|
44
|
+
|
|
45
|
+
return preprocessor
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Preprocessor(ABC):
|
|
49
|
+
"""Base class for Packflow preprocessors"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, config: BackendConfig):
|
|
52
|
+
self.config = config
|
|
53
|
+
self.resolve()
|
|
54
|
+
|
|
55
|
+
def __repr__(self): # pragma: no cover
|
|
56
|
+
return f"{self.__class__.__name__}[\n {self.config.__repr__()}\n]"
|
|
57
|
+
|
|
58
|
+
def __call__(self, raw_inputs: list[dict]):
|
|
59
|
+
"""
|
|
60
|
+
Run the preprocessor against raw inputs and return the processed data
|
|
61
|
+
"""
|
|
62
|
+
try:
|
|
63
|
+
return self.process(raw_inputs)
|
|
64
|
+
except Exception as e:
|
|
65
|
+
raise exceptions.PreprocessorRuntimeError(
|
|
66
|
+
f"Failed to preprocess inputs with the following exception: {e}"
|
|
67
|
+
) from e
|
|
68
|
+
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def resolve(self): # pragma: no cover
|
|
71
|
+
"""
|
|
72
|
+
Check the config for required fields or conditions that may not
|
|
73
|
+
be caught by the pydantic model.
|
|
74
|
+
"""
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
@abstractmethod
|
|
78
|
+
def process(self, raw_inputs: list[dict]): # pragma: no cover
|
|
79
|
+
"""
|
|
80
|
+
Run the preprocessor against raw inputs and return the processed data
|
|
81
|
+
"""
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class PassthroughPreprocessor(Preprocessor):
|
|
86
|
+
"""Passthrough preprocessor that does nothing."""
|
|
87
|
+
|
|
88
|
+
def resolve(self):
|
|
89
|
+
"""Ignored, as all data is passed through."""
|
|
90
|
+
return
|
|
91
|
+
|
|
92
|
+
def process(self, raw_inputs: list[dict]) -> list[dict]:
|
|
93
|
+
"""Return inputs without any preprocessing."""
|
|
94
|
+
return raw_inputs
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class RecordsPreprocessor(Preprocessor):
|
|
98
|
+
"""
|
|
99
|
+
Records preprocessor that is highly optimized for:
|
|
100
|
+
- filtering fields
|
|
101
|
+
- ensuring proper order of keys
|
|
102
|
+
- flattening nested fields/lists
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def resolve(self):
|
|
106
|
+
"""
|
|
107
|
+
Resolve the config to ensure that required fields are satisfied.
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
-------
|
|
111
|
+
None
|
|
112
|
+
|
|
113
|
+
Notes
|
|
114
|
+
-----
|
|
115
|
+
This preprocessor may default to being a passthrough if a specific subset of
|
|
116
|
+
config fields are not set. For example, if the config specifies that there are
|
|
117
|
+
no fields to rename, no filtering to be done, or flattening is not enabled, then
|
|
118
|
+
the run() method will default to passing through data for performance.
|
|
119
|
+
"""
|
|
120
|
+
self.passthrough = not any(
|
|
121
|
+
(
|
|
122
|
+
self.config.rename_fields,
|
|
123
|
+
self.config.feature_names,
|
|
124
|
+
self.config.flatten_nested_inputs,
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
if self.passthrough:
|
|
129
|
+
logger.info(
|
|
130
|
+
"Current config does not require preprocessing steps. Defaulting to Passthrough mode."
|
|
131
|
+
)
|
|
132
|
+
return
|
|
133
|
+
|
|
134
|
+
self.reducer = make_reducer(self.config.nested_field_delimiter)
|
|
135
|
+
self.enumerate_types = (list,) if self.config.flatten_lists else ()
|
|
136
|
+
|
|
137
|
+
def process(self, raw_inputs: list[dict]) -> list[dict]:
|
|
138
|
+
"""Process an input batch and make transformations as necessary.
|
|
139
|
+
|
|
140
|
+
This preprocessor focuses on three main transformations:
|
|
141
|
+
1. Renaming input fields
|
|
142
|
+
2. Filtering to only required fields
|
|
143
|
+
3. Flattening objects (dictionaries and/or lists)
|
|
144
|
+
|
|
145
|
+
Parameters
|
|
146
|
+
----------
|
|
147
|
+
raw_inputs : list[dict]
|
|
148
|
+
Raw input records to transform
|
|
149
|
+
|
|
150
|
+
Returns
|
|
151
|
+
-------
|
|
152
|
+
list[dict]
|
|
153
|
+
Transformed records
|
|
154
|
+
"""
|
|
155
|
+
if self.passthrough:
|
|
156
|
+
return raw_inputs
|
|
157
|
+
|
|
158
|
+
records = []
|
|
159
|
+
for obj in raw_inputs:
|
|
160
|
+
obj = obj.copy() # avoid editing input data
|
|
161
|
+
obj = flatten(
|
|
162
|
+
obj,
|
|
163
|
+
reducer=self.reducer,
|
|
164
|
+
enumerate_types=self.enumerate_types,
|
|
165
|
+
keep_empty_types=(dict, list),
|
|
166
|
+
)
|
|
167
|
+
processed_obj = {}
|
|
168
|
+
|
|
169
|
+
for key in self.config.rename_fields:
|
|
170
|
+
processed_obj[self.config.rename_fields[key]] = obj.get(key)
|
|
171
|
+
|
|
172
|
+
if self.config.feature_names:
|
|
173
|
+
for feature in self.config.feature_names:
|
|
174
|
+
if feature not in processed_obj:
|
|
175
|
+
processed_obj[feature] = obj.get(feature)
|
|
176
|
+
else:
|
|
177
|
+
processed_obj.update(obj)
|
|
178
|
+
|
|
179
|
+
if not self.config.flatten_nested_inputs:
|
|
180
|
+
processed_obj = unflatten(
|
|
181
|
+
processed_obj,
|
|
182
|
+
splitter=make_splitter(self.config.nested_field_delimiter),
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
records.append(processed_obj)
|
|
186
|
+
|
|
187
|
+
return records
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class NumpyPreprocessor(Preprocessor):
|
|
191
|
+
"""
|
|
192
|
+
Converts input records to a numpy array.
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
def resolve(self):
|
|
196
|
+
"""
|
|
197
|
+
Check the config for required fields.
|
|
198
|
+
|
|
199
|
+
Returns
|
|
200
|
+
-------
|
|
201
|
+
None
|
|
202
|
+
|
|
203
|
+
Notes
|
|
204
|
+
-----
|
|
205
|
+
This preprocessor will only execute if the user has specified `feature_names`.
|
|
206
|
+
"""
|
|
207
|
+
if not self.config.feature_names:
|
|
208
|
+
raise exceptions.PreprocessorInitError(
|
|
209
|
+
f"This preprocessor requires `feature_names` to be defined. Received config: {self.config.__repr__()}"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
reverse_rename = {v: k for k, v in self.config.rename_fields.items()}
|
|
213
|
+
|
|
214
|
+
self.features = [
|
|
215
|
+
reverse_rename.get(feature, feature)
|
|
216
|
+
for feature in self.config.feature_names
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
def process(self, raw_inputs: list[dict]) -> np.array:
|
|
220
|
+
"""
|
|
221
|
+
Convert the records to a numpy array.
|
|
222
|
+
|
|
223
|
+
Parameters
|
|
224
|
+
----------
|
|
225
|
+
raw_inputs: list[dict]
|
|
226
|
+
|
|
227
|
+
Returns
|
|
228
|
+
-------
|
|
229
|
+
array
|
|
230
|
+
|
|
231
|
+
"""
|
|
232
|
+
return packflow.utils.records_to_ndarray(
|
|
233
|
+
raw_inputs,
|
|
234
|
+
feature_names=self.features,
|
|
235
|
+
dtype=None,
|
|
236
|
+
delimiter=self.config.nested_field_delimiter,
|
|
237
|
+
)
|