packflow 0.3.0__tar.gz

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.
Files changed (35) hide show
  1. packflow-0.3.0/LICENSE +9 -0
  2. packflow-0.3.0/PKG-INFO +175 -0
  3. packflow-0.3.0/README.md +135 -0
  4. packflow-0.3.0/pyproject.toml +71 -0
  5. packflow-0.3.0/src/packflow/__init__.py +6 -0
  6. packflow-0.3.0/src/packflow/backend/__init__.py +2 -0
  7. packflow-0.3.0/src/packflow/backend/base.py +262 -0
  8. packflow-0.3.0/src/packflow/backend/configuration.py +152 -0
  9. packflow-0.3.0/src/packflow/backend/metrics.py +27 -0
  10. packflow-0.3.0/src/packflow/backend/preprocessors.py +237 -0
  11. packflow-0.3.0/src/packflow/backend/validation.py +98 -0
  12. packflow-0.3.0/src/packflow/cli.py +47 -0
  13. packflow-0.3.0/src/packflow/constants.py +3 -0
  14. packflow-0.3.0/src/packflow/data/templates/minimal/LICENSE.txt +0 -0
  15. packflow-0.3.0/src/packflow/data/templates/minimal/MODEL_CARD.md +91 -0
  16. packflow-0.3.0/src/packflow/data/templates/minimal/README.md +0 -0
  17. packflow-0.3.0/src/packflow/data/templates/minimal/inference.py +75 -0
  18. packflow-0.3.0/src/packflow/data/templates/minimal/packflow.yaml +11 -0
  19. packflow-0.3.0/src/packflow/data/templates/minimal/requirements.txt +0 -0
  20. packflow-0.3.0/src/packflow/data/templates/minimal/validate.py +25 -0
  21. packflow-0.3.0/src/packflow/exceptions.py +26 -0
  22. packflow-0.3.0/src/packflow/loaders/__init__.py +4 -0
  23. packflow-0.3.0/src/packflow/loaders/base.py +86 -0
  24. packflow-0.3.0/src/packflow/loaders/config.py +125 -0
  25. packflow-0.3.0/src/packflow/loaders/local.py +57 -0
  26. packflow-0.3.0/src/packflow/loaders/module.py +29 -0
  27. packflow-0.3.0/src/packflow/loaders/utils.py +27 -0
  28. packflow-0.3.0/src/packflow/logger.py +5 -0
  29. packflow-0.3.0/src/packflow/project.py +72 -0
  30. packflow-0.3.0/src/packflow/utils/__init__.py +2 -0
  31. packflow-0.3.0/src/packflow/utils/data.py +152 -0
  32. packflow-0.3.0/src/packflow/utils/normalize/__init__.py +1 -0
  33. packflow-0.3.0/src/packflow/utils/normalize/base.py +79 -0
  34. packflow-0.3.0/src/packflow/utils/normalize/handlers.py +93 -0
  35. packflow-0.3.0/src/packflow/utils/normalize/normalize.py +87 -0
packflow-0.3.0/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 U.S. Federal Government (in countries where recognized)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: packflow
3
+ Version: 0.3.0
4
+ Summary: AI/ML inference SDK for streaming data
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 U.S. Federal Government (in countries where recognized)
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ License-File: LICENSE
15
+ Keywords: AI,artificial intelligence,ML,machine learning,streaming,inference
16
+ Author: CDAO Models as a Service
17
+ Author-email: osd.pentagon.cdao.mbx.perceptor-program-members@mail.mil
18
+ Maintainer: CDAO Models as a Service
19
+ Maintainer-email: osd.pentagon.cdao.mbx.perceptor-program-members@mail.mil
20
+ Requires-Python: >=3.10
21
+ Classifier: License :: Other/Proprietary License
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
28
+ Requires-Dist: PyYaml
29
+ Requires-Dist: click (>=8.0.0)
30
+ Requires-Dist: deepmerge (>=2.0,<3.0)
31
+ Requires-Dist: flatten-dict (>=0.4.2,<1.0.0)
32
+ Requires-Dist: loguru (>=0.7.3,<0.8.0)
33
+ Requires-Dist: numpy (<2.3)
34
+ Requires-Dist: pydantic (>=2.11.0,<3.0.0)
35
+ Project-URL: Documentation, https://github.com/dow-cdao/packflow
36
+ Project-URL: Homepage, https://github.com/dow-cdao/packflow
37
+ Project-URL: Repository, https://github.com/dow-cdao/packflow
38
+ Description-Content-Type: text/markdown
39
+
40
+ <h1 style="text-align: center; border-bottom: none !important;">
41
+ <img src="assets/packflow-logo-white-text.png" width="500" alt="Packflow logo">
42
+ </h1>
43
+
44
+ <p align="center">
45
+ <a href="https://pypi.org/project/packflow/"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/packflow.svg"></a>
46
+ <a href="https://pypi.org/project/packflow/"><img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/packflow.svg"></a>
47
+ <a href="https://github.com/dow-cdao/packflow/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-MIT-blue.svg"></a>
48
+ </p>
49
+
50
+ # Introduction
51
+
52
+ `packflow` is a software development kit (SDK) that simplifies the development process and standardizes packaging of AI/ML
53
+ running on streaming data sources.
54
+
55
+ Many existing packaging frameworks are catered towards inference APIs and often require custom preprocessing steps. This can be particularly challenging when dealing with data sources that typically generate data one row at a time in key-value pairs (e.g., firewall logs or message streams).
56
+
57
+ Packflow, however, is optimized to run models on either individual events or batches of events, streamlining development and reducing the need for additional preprocessing. By leveraging Packflow, teams can focus on building and deploying models with custom out-of-the-box workflows and utilities, significantly reducing the time and effort required to onboard new capabilities.
58
+
59
+ ## Getting Started
60
+
61
+ The following instructions quickly walk through how to install Packflow and serve user documentation.
62
+
63
+ ### Installing Packflow
64
+
65
+ #### Prerequisite Requirements
66
+
67
+ - **Python** (version 3.10+)
68
+
69
+ #### Installation from PyPI
70
+
71
+ 1. Packflow can be installed directly from PyPI:
72
+
73
+ ```bash
74
+ pip install packflow
75
+ ```
76
+
77
+ from the root of the Packflow repo.
78
+
79
+ > [!NOTE]
80
+ > If contributing to Packflow, it is recommended to install `packflow` from source in editable mode: `pip install -e .`
81
+
82
+ ## Packflow Documentation
83
+
84
+ Packflow documentation is available pre-built in the repository and can be viewed immediately, or built from source for development work. Follow the instructions below to get started with serving the documentation.
85
+
86
+ ### Viewing Pre-built Documentation
87
+
88
+ The simplest way to view the Packflow documentation is to serve the pre-built HTML files included in the repository:
89
+
90
+ 1. Navigate to the pre-built docs folder: `cd docs/built/html`
91
+ 2. Start a local web server: `python -m http.server 8000`
92
+ 3. Access the documentation in a web browser by navigating to [http://127.0.0.1:8000/](http://127.0.0.1:8000/)
93
+
94
+ > [!WARNING]
95
+ > If a "Not Found" error page is received when first accessing the documentation, wait a moment for the server to fully start and refresh the page.
96
+
97
+ ### Building Documentation from Source
98
+
99
+ #### Prerequisite Requirements
100
+
101
+ The following are required to build documentation from source:
102
+
103
+ - **Python** (version 3.10+)
104
+ - **Pip**
105
+ - **Packflow** (the version corresponding to the docs being served)
106
+ - **Pandoc**[^1] (see Pandoc.org's [official installation instructions](https://pandoc.org/installing.html))
107
+ - **`make` Command**[^2]
108
+
109
+ #### Steps
110
+
111
+ 1. Navigate to the docs folder: `cd docs`
112
+ 2. Install Python dependencies for building and hosting the documentation: `pip install -r requirements.txt`
113
+ 3. Run `make dev` to serve the documentation from a working tree with live updates, or `make prod-serve` to serve static multi-version documentation (requires `.git` directory with branch/tag history)
114
+ 4. Access the built documentation in a web browser by navigating to [http://127.0.0.1:8000/](http://127.0.0.1:8000/)
115
+
116
+ > [!WARNING]
117
+ > If a "Not Found" error page is received when first accessing the documentation, wait a moment for the server to fully start and refresh the page.
118
+
119
+ ## Usage
120
+
121
+ Packflow provides a flexible base class called an `InferenceBackend` that allows users to build highly scalable platform- and tool-agnostic inference code, enabling simplified sharing across environments.
122
+
123
+ Additionally, Packflow's CLI can assist with creating projects, gathering environmental information, and creating distributable code packages for sharing reproducible inference code between disconnected environments.
124
+
125
+ For detailed information and usage patterns on Packflow, please see the `About Packflow` and `User Guide` sections of the official documentation site.
126
+
127
+ ### Dummy Inference Backend
128
+
129
+ To create a dummy Inference Backend, update the `inference.py` file to the following:
130
+
131
+ ```python
132
+ from packflow import InferenceBackend
133
+
134
+
135
+ class Backend(InferenceBackend):
136
+ def execute(self, inputs):
137
+ """
138
+ Simply print 'Hello, world!' then return the input data
139
+ """
140
+ print('Hello, world!')
141
+ return inputs
142
+ ```
143
+
144
+ ### Load and Run the Inference Backend
145
+
146
+ In a different Python file or from the command line in the same directory, execute the following:
147
+
148
+ ```python
149
+ from packflow.loaders import LocalLoader
150
+
151
+ backend = LocalLoader('inference:Backend').load()
152
+
153
+ backend({"sample": "data"})
154
+ # >> {"sample": "data"}
155
+ ```
156
+
157
+ ## Contributing
158
+
159
+ Contributions to Packflow are welcomed and highly encouraged! Please refer to the [CONTRIBUTE.md](CONTRIBUTE.md) guide for more information and guidelines for contributing to Packflow.
160
+
161
+ ## Authors
162
+
163
+ Packflow is developed and maintained by [Booz Allen Hamilton](https://www.boozallen.com/) on behalf of the Federal Government of the United States of America and the Department of War's Chief Digital and Artificial Intelligence Office (CDAO).
164
+
165
+ ## License
166
+
167
+ `packflow` is distributed under the terms of the [MIT license](https://spdx.org/licenses/MIT.html). Please refer to the [LICENSE.txt](./LICENSE) for more information of acceptable usage and distribution of Packflow.
168
+
169
+
170
+ [^1]: *Pandoc* must be installed separately from the `pandoc` python package in `docs/requirements.txt`.
171
+ [^2]: Installation of `make` varies by operating system. On MacOS, install `xcode-select`. On Windows, it is recommend to use Windows Subsystem for Linux (WSL). On Debian/Ubuntu, `make` can be installed via `apt` package manager: <pre>
172
+ sudo apt update
173
+ sudo apt install make build-essential
174
+ </pre>
175
+
@@ -0,0 +1,135 @@
1
+ <h1 style="text-align: center; border-bottom: none !important;">
2
+ <img src="assets/packflow-logo-white-text.png" width="500" alt="Packflow logo">
3
+ </h1>
4
+
5
+ <p align="center">
6
+ <a href="https://pypi.org/project/packflow/"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/packflow.svg"></a>
7
+ <a href="https://pypi.org/project/packflow/"><img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/packflow.svg"></a>
8
+ <a href="https://github.com/dow-cdao/packflow/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-MIT-blue.svg"></a>
9
+ </p>
10
+
11
+ # Introduction
12
+
13
+ `packflow` is a software development kit (SDK) that simplifies the development process and standardizes packaging of AI/ML
14
+ running on streaming data sources.
15
+
16
+ Many existing packaging frameworks are catered towards inference APIs and often require custom preprocessing steps. This can be particularly challenging when dealing with data sources that typically generate data one row at a time in key-value pairs (e.g., firewall logs or message streams).
17
+
18
+ Packflow, however, is optimized to run models on either individual events or batches of events, streamlining development and reducing the need for additional preprocessing. By leveraging Packflow, teams can focus on building and deploying models with custom out-of-the-box workflows and utilities, significantly reducing the time and effort required to onboard new capabilities.
19
+
20
+ ## Getting Started
21
+
22
+ The following instructions quickly walk through how to install Packflow and serve user documentation.
23
+
24
+ ### Installing Packflow
25
+
26
+ #### Prerequisite Requirements
27
+
28
+ - **Python** (version 3.10+)
29
+
30
+ #### Installation from PyPI
31
+
32
+ 1. Packflow can be installed directly from PyPI:
33
+
34
+ ```bash
35
+ pip install packflow
36
+ ```
37
+
38
+ from the root of the Packflow repo.
39
+
40
+ > [!NOTE]
41
+ > If contributing to Packflow, it is recommended to install `packflow` from source in editable mode: `pip install -e .`
42
+
43
+ ## Packflow Documentation
44
+
45
+ Packflow documentation is available pre-built in the repository and can be viewed immediately, or built from source for development work. Follow the instructions below to get started with serving the documentation.
46
+
47
+ ### Viewing Pre-built Documentation
48
+
49
+ The simplest way to view the Packflow documentation is to serve the pre-built HTML files included in the repository:
50
+
51
+ 1. Navigate to the pre-built docs folder: `cd docs/built/html`
52
+ 2. Start a local web server: `python -m http.server 8000`
53
+ 3. Access the documentation in a web browser by navigating to [http://127.0.0.1:8000/](http://127.0.0.1:8000/)
54
+
55
+ > [!WARNING]
56
+ > If a "Not Found" error page is received when first accessing the documentation, wait a moment for the server to fully start and refresh the page.
57
+
58
+ ### Building Documentation from Source
59
+
60
+ #### Prerequisite Requirements
61
+
62
+ The following are required to build documentation from source:
63
+
64
+ - **Python** (version 3.10+)
65
+ - **Pip**
66
+ - **Packflow** (the version corresponding to the docs being served)
67
+ - **Pandoc**[^1] (see Pandoc.org's [official installation instructions](https://pandoc.org/installing.html))
68
+ - **`make` Command**[^2]
69
+
70
+ #### Steps
71
+
72
+ 1. Navigate to the docs folder: `cd docs`
73
+ 2. Install Python dependencies for building and hosting the documentation: `pip install -r requirements.txt`
74
+ 3. Run `make dev` to serve the documentation from a working tree with live updates, or `make prod-serve` to serve static multi-version documentation (requires `.git` directory with branch/tag history)
75
+ 4. Access the built documentation in a web browser by navigating to [http://127.0.0.1:8000/](http://127.0.0.1:8000/)
76
+
77
+ > [!WARNING]
78
+ > If a "Not Found" error page is received when first accessing the documentation, wait a moment for the server to fully start and refresh the page.
79
+
80
+ ## Usage
81
+
82
+ Packflow provides a flexible base class called an `InferenceBackend` that allows users to build highly scalable platform- and tool-agnostic inference code, enabling simplified sharing across environments.
83
+
84
+ Additionally, Packflow's CLI can assist with creating projects, gathering environmental information, and creating distributable code packages for sharing reproducible inference code between disconnected environments.
85
+
86
+ For detailed information and usage patterns on Packflow, please see the `About Packflow` and `User Guide` sections of the official documentation site.
87
+
88
+ ### Dummy Inference Backend
89
+
90
+ To create a dummy Inference Backend, update the `inference.py` file to the following:
91
+
92
+ ```python
93
+ from packflow import InferenceBackend
94
+
95
+
96
+ class Backend(InferenceBackend):
97
+ def execute(self, inputs):
98
+ """
99
+ Simply print 'Hello, world!' then return the input data
100
+ """
101
+ print('Hello, world!')
102
+ return inputs
103
+ ```
104
+
105
+ ### Load and Run the Inference Backend
106
+
107
+ In a different Python file or from the command line in the same directory, execute the following:
108
+
109
+ ```python
110
+ from packflow.loaders import LocalLoader
111
+
112
+ backend = LocalLoader('inference:Backend').load()
113
+
114
+ backend({"sample": "data"})
115
+ # >> {"sample": "data"}
116
+ ```
117
+
118
+ ## Contributing
119
+
120
+ Contributions to Packflow are welcomed and highly encouraged! Please refer to the [CONTRIBUTE.md](CONTRIBUTE.md) guide for more information and guidelines for contributing to Packflow.
121
+
122
+ ## Authors
123
+
124
+ Packflow is developed and maintained by [Booz Allen Hamilton](https://www.boozallen.com/) on behalf of the Federal Government of the United States of America and the Department of War's Chief Digital and Artificial Intelligence Office (CDAO).
125
+
126
+ ## License
127
+
128
+ `packflow` is distributed under the terms of the [MIT license](https://spdx.org/licenses/MIT.html). Please refer to the [LICENSE.txt](./LICENSE) for more information of acceptable usage and distribution of Packflow.
129
+
130
+
131
+ [^1]: *Pandoc* must be installed separately from the `pandoc` python package in `docs/requirements.txt`.
132
+ [^2]: Installation of `make` varies by operating system. On MacOS, install `xcode-select`. On Windows, it is recommend to use Windows Subsystem for Linux (WSL). On Debian/Ubuntu, `make` can be installed via `apt` package manager: <pre>
133
+ sudo apt update
134
+ sudo apt install make build-essential
135
+ </pre>
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "packflow"
3
+ dynamic = [ "version" ]
4
+ description = "AI/ML inference SDK for streaming data"
5
+ authors = [
6
+ {name = "CDAO Models as a Service",email = "osd.pentagon.cdao.mbx.perceptor-program-members@mail.mil"}
7
+ ]
8
+ maintainers = [
9
+ {name = "CDAO Models as a Service",email = "osd.pentagon.cdao.mbx.perceptor-program-members@mail.mil"}
10
+ ]
11
+ keywords = [
12
+ "AI",
13
+ "artificial intelligence",
14
+ "ML",
15
+ "machine learning",
16
+ "streaming",
17
+ "inference"
18
+ ]
19
+ license = { file = "LICENSE" }
20
+ readme = "README.md"
21
+ requires-python = ">=3.10"
22
+ dependencies = [
23
+ "deepmerge (>=2.0,<3.0)",
24
+ "flatten-dict (>=0.4.2,<1.0.0)",
25
+ "loguru (>=0.7.3,<0.8.0)",
26
+ "numpy (<2.3)",
27
+ "pydantic (>=2.11.0,<3.0.0)",
28
+ "click (>=8.0.0)",
29
+ "PyYaml"
30
+ ]
31
+
32
+ [project.urls]
33
+ homepage = "https://github.com/dow-cdao/packflow"
34
+ repository = "https://github.com/dow-cdao/packflow"
35
+ documentation = "https://github.com/dow-cdao/packflow"
36
+
37
+
38
+ [build-system]
39
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
40
+ build-backend = "poetry.core.masonry.api"
41
+
42
+
43
+ [tool.poetry]
44
+ version = "0.3.0"
45
+ exclude = [
46
+ "tests",
47
+ "docs",
48
+ "examples",
49
+ "assets"
50
+ ]
51
+
52
+
53
+ [tool.poetry.dependencies]
54
+ python = '>=3.10,<4.0'
55
+
56
+
57
+ [tool.poetry.group.dev.dependencies]
58
+ pre-commit = "^4.2.0"
59
+ black = {version = "^25.1.0", extras = ["jupyter"]}
60
+ pytest = "^8.4.1"
61
+ pytest-cov = "^6.2.1"
62
+ pandas = "^2.3.0"
63
+ torch = "^2.7.1"
64
+ tensorflow = "^2.19.0"
65
+ pillow = "^11.3.0"
66
+
67
+
68
+ [tool.poetry.scripts]
69
+ packflow = "packflow.cli:cli"
70
+ [tool.coverage.run]
71
+ omit = ["tests/*"]
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import version as _version
2
+
3
+ from .backend import BackendConfig, InferenceBackend
4
+ from .project import PackflowProject
5
+
6
+ __version__ = _version("packflow")
@@ -0,0 +1,2 @@
1
+ from .base import InferenceBackend
2
+ from .configuration import BackendConfig
@@ -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