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
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import List, Union, Any, Callable
|
|
3
|
+
|
|
4
|
+
import packflow.exceptions as exceptions
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class InferenceBackendValidator:
|
|
8
|
+
def __init__(self, backend: Callable):
|
|
9
|
+
self.backend = backend
|
|
10
|
+
|
|
11
|
+
def run(self, inputs: Union[dict, List[dict]]) -> Union[dict, List[dict]]:
|
|
12
|
+
"""
|
|
13
|
+
Run all validation checks against the backend.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
inputs : Union[dict, List[dict]]
|
|
18
|
+
Input data to test the backend against.
|
|
19
|
+
|
|
20
|
+
Returns
|
|
21
|
+
-------
|
|
22
|
+
The validated outputs of the inference backend.
|
|
23
|
+
"""
|
|
24
|
+
input_is_dict = isinstance(inputs, dict)
|
|
25
|
+
if input_is_dict:
|
|
26
|
+
inputs = [inputs]
|
|
27
|
+
|
|
28
|
+
_input_is_correct_format(inputs)
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
outputs = self.backend(inputs)
|
|
32
|
+
except Exception as e:
|
|
33
|
+
raise exceptions.InferenceBackendRuntimeError(
|
|
34
|
+
"Error encountered when running the inference backend. This is not a validation issue. "
|
|
35
|
+
"See above stack track for additional information."
|
|
36
|
+
) from e
|
|
37
|
+
|
|
38
|
+
_inputs_and_outputs_match_len(inputs, outputs)
|
|
39
|
+
|
|
40
|
+
_output_is_list_of_dicts(outputs)
|
|
41
|
+
|
|
42
|
+
_output_is_json_serializable(outputs)
|
|
43
|
+
|
|
44
|
+
if input_is_dict:
|
|
45
|
+
outputs = outputs[0]
|
|
46
|
+
|
|
47
|
+
return outputs
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _input_is_correct_format(inputs: Any):
|
|
51
|
+
"""Checks if the input is a list of dictionaries"""
|
|
52
|
+
if not isinstance(inputs, list):
|
|
53
|
+
raise exceptions.InferenceBackendValidationError(
|
|
54
|
+
f"Production inputs will be in a list format. Input type received was {type(inputs)}"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
for i, v in enumerate(inputs):
|
|
58
|
+
if not isinstance(v, dict):
|
|
59
|
+
raise exceptions.InferenceBackendValidationError(
|
|
60
|
+
f"Value at index {i} is not a dictionary. Type found was {type(v)}"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _inputs_and_outputs_match_len(inputs: Any, outputs: Any):
|
|
65
|
+
"""Checks if the inputs and outputs are the same length."""
|
|
66
|
+
|
|
67
|
+
if len(inputs) != len(outputs):
|
|
68
|
+
raise exceptions.InferenceBackendValidationError(
|
|
69
|
+
f"Inputs and Outputs must have matching lengths. Received {len(inputs)} inputs "
|
|
70
|
+
f"and returned {len(outputs)} outputs."
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _output_is_list_of_dicts(outputs: Any):
|
|
75
|
+
"""Checks if the output is a list of dictionaries"""
|
|
76
|
+
if not isinstance(outputs, list):
|
|
77
|
+
raise exceptions.InferenceBackendValidationError(
|
|
78
|
+
f"Outputs must be a Python list. Input type received was {type(outputs)}"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
for i, v in enumerate(outputs):
|
|
82
|
+
if not isinstance(v, dict):
|
|
83
|
+
raise exceptions.InferenceBackendValidationError(
|
|
84
|
+
f"Outputs must be a list of dictionaries. Value at index {i} is not a dictionary. "
|
|
85
|
+
f"Type found was {type(v)}"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _output_is_json_serializable(outputs: Any):
|
|
90
|
+
"""Makes sure every row is json serializable and does not contain bad types"""
|
|
91
|
+
for i, v in enumerate(outputs):
|
|
92
|
+
try:
|
|
93
|
+
json.dumps(v)
|
|
94
|
+
except Exception as e:
|
|
95
|
+
raise exceptions.InferenceBackendValidationError(
|
|
96
|
+
f"Value at index {i} is not JSON Serializable. Please ensure returned values are native Python types. "
|
|
97
|
+
f"Error: {e}"
|
|
98
|
+
)
|
packflow/cli.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import click
|
|
2
|
+
|
|
3
|
+
import packflow
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _success_message(msg: str):
|
|
7
|
+
base = click.style("Success:", fg="green")
|
|
8
|
+
click.echo(f"{base} {msg}")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _error_message(msg: str):
|
|
12
|
+
base = click.style("Error:", fg="red")
|
|
13
|
+
click.echo(f"{base} {msg}")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@click.group()
|
|
17
|
+
def cli():
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@cli.command()
|
|
22
|
+
@click.argument("project_name", type=str)
|
|
23
|
+
@click.option(
|
|
24
|
+
"-f",
|
|
25
|
+
"--force",
|
|
26
|
+
is_flag=True,
|
|
27
|
+
help="Force initialization in a directory that already exists. No files will be deleted, but files may be overwritten.",
|
|
28
|
+
)
|
|
29
|
+
def create(project_name, force):
|
|
30
|
+
"""Initialize a new project from a template in the current working directory"""
|
|
31
|
+
try:
|
|
32
|
+
project = packflow.PackflowProject.create(project_name, force=force)
|
|
33
|
+
_success_message(project)
|
|
34
|
+
except Exception as e:
|
|
35
|
+
_error_message(str(e))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@cli.command()
|
|
39
|
+
@click.argument("project_path", type=str, default=".")
|
|
40
|
+
def export(project_path):
|
|
41
|
+
"""Save the package and export to .zip in the current working directory"""
|
|
42
|
+
try:
|
|
43
|
+
project = packflow.PackflowProject(project_path)
|
|
44
|
+
output_file = project.export()
|
|
45
|
+
_success_message(f"Saved Package to {output_file}")
|
|
46
|
+
except Exception as e:
|
|
47
|
+
_error_message(str(e))
|
packflow/constants.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Model Card
|
|
2
|
+
|
|
3
|
+
{introduction}
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
## Capability Overview
|
|
7
|
+
|
|
8
|
+
**Name:** ...
|
|
9
|
+
|
|
10
|
+
**Description:**
|
|
11
|
+
|
|
12
|
+
...
|
|
13
|
+
|
|
14
|
+
**Version:** ...
|
|
15
|
+
|
|
16
|
+
**Release Date:** ...
|
|
17
|
+
|
|
18
|
+
**Intended Use:**
|
|
19
|
+
...
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## Ownership
|
|
23
|
+
|
|
24
|
+
**Organization:** ...
|
|
25
|
+
|
|
26
|
+
**Points of Contact:**
|
|
27
|
+
|
|
28
|
+
- {POC Name, Email}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
## Implementation Details
|
|
32
|
+
|
|
33
|
+
**External Dependencies:**
|
|
34
|
+
|
|
35
|
+
- {any dependencies not accounted for in the Package, such as those not installable via `pip`}
|
|
36
|
+
|
|
37
|
+
**Data Dictionary:**
|
|
38
|
+
|
|
39
|
+
- Inputs: ...
|
|
40
|
+
- Outputs: ...
|
|
41
|
+
|
|
42
|
+
**Known Limitations:**
|
|
43
|
+
|
|
44
|
+
{Known limitations, assumptions, or constraints associated with the analytic. This should include a description of any known biases and/or constraints that are essential to the proper and responsible deployment of the analytic into production}
|
|
45
|
+
|
|
46
|
+
**Infrastructure Requirements:**
|
|
47
|
+
|
|
48
|
+
{Specify CPU/GPU requirements as well as any additional relevant}
|
|
49
|
+
|
|
50
|
+
**Additional Notes:**
|
|
51
|
+
|
|
52
|
+
...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
## Model Details
|
|
56
|
+
|
|
57
|
+
**Methodology:**
|
|
58
|
+
|
|
59
|
+
{Definition and concise description of the underlying algorithm of the analytic. This algorithm could be heuristic, statistical, and/or mathematical (i.e. rule-based hard-coded logic, Neural Networks, Bayesian classifier, etc.). Include links to reference citations as required.}
|
|
60
|
+
|
|
61
|
+
**Evaluation:**
|
|
62
|
+
|
|
63
|
+
{Evaluation methods, metrics, or other information to quantify training performance}
|
|
64
|
+
|
|
65
|
+
**References:**
|
|
66
|
+
|
|
67
|
+
{Location to cite any papers or references that the model is based off}
|
|
68
|
+
|
|
69
|
+
**Responsible AI Considerations:**
|
|
70
|
+
|
|
71
|
+
{Specify how the model and/or analytic implementation defends against adversarial attacks}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
## Data Details
|
|
75
|
+
|
|
76
|
+
**Dataset Name/ID:** ...
|
|
77
|
+
|
|
78
|
+
**Description:**
|
|
79
|
+
|
|
80
|
+
...
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
**Dataset Version:** ...
|
|
84
|
+
|
|
85
|
+
**Last Updated:** {MM/DD/YYYY}
|
|
86
|
+
|
|
87
|
+
**Dataset Owner:** {If different from capability owner}
|
|
88
|
+
|
|
89
|
+
**Points of Contact:**
|
|
90
|
+
|
|
91
|
+
- {POC Name, Email}
|
|
File without changes
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from typing import Any, List
|
|
2
|
+
|
|
3
|
+
from packflow import InferenceBackend
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Backend(InferenceBackend):
|
|
7
|
+
def transform_inputs(self, inputs: List[dict]) -> Any:
|
|
8
|
+
"""Preprocessing steps or other transformations before running inference.
|
|
9
|
+
|
|
10
|
+
This function should ingest raw records and return inference-ready features.
|
|
11
|
+
Ex: [{"foo": 5}] -> np.array([[5]])
|
|
12
|
+
|
|
13
|
+
Parameters
|
|
14
|
+
----------
|
|
15
|
+
inputs: List[Dict]
|
|
16
|
+
A list of dictionary objects
|
|
17
|
+
|
|
18
|
+
Returns
|
|
19
|
+
-------
|
|
20
|
+
Any
|
|
21
|
+
The expected input data for the model or function is.
|
|
22
|
+
|
|
23
|
+
Notes
|
|
24
|
+
-----
|
|
25
|
+
This function should *not* filter rows. The input and output batches should
|
|
26
|
+
have the same length.
|
|
27
|
+
"""
|
|
28
|
+
return inputs
|
|
29
|
+
|
|
30
|
+
def execute(self, inputs: Any) -> Any:
|
|
31
|
+
"""The main execution of inference or analysis for the developed application.
|
|
32
|
+
|
|
33
|
+
This method should remain targeted to passing data through the model/execution
|
|
34
|
+
code for profiling purposes. Minimal pre- or post-processing should occur at this
|
|
35
|
+
step unless completely necessary.
|
|
36
|
+
|
|
37
|
+
Parameters
|
|
38
|
+
----------
|
|
39
|
+
inputs: List[Dict]
|
|
40
|
+
The output of the transform_inputs method. If the transform_inputs method is
|
|
41
|
+
not overridden, the data is formatted as records (list of dictionaries)
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
Any
|
|
46
|
+
Model Outputs
|
|
47
|
+
|
|
48
|
+
Notes
|
|
49
|
+
-----
|
|
50
|
+
The transform_outputs() method should handle all postprocessing including calculating
|
|
51
|
+
metrics, converting outputs back to Python types, and other postprocessing steps. Try
|
|
52
|
+
to keep this method focused purely on inference/analysis.
|
|
53
|
+
"""
|
|
54
|
+
raise NotImplementedError
|
|
55
|
+
|
|
56
|
+
def transform_outputs(self, outputs):
|
|
57
|
+
"""Postprocessing steps or other transformation steps to be executed prior to
|
|
58
|
+
returning outputs.
|
|
59
|
+
|
|
60
|
+
Parameters
|
|
61
|
+
----------
|
|
62
|
+
outputs: Any
|
|
63
|
+
The output of the execute method.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
-------
|
|
67
|
+
List[dict]
|
|
68
|
+
Model Outputs
|
|
69
|
+
|
|
70
|
+
Notes
|
|
71
|
+
-----
|
|
72
|
+
The transform_outputs() method *must* output json-serializable data in the form of
|
|
73
|
+
records (a list of dictionaries).
|
|
74
|
+
"""
|
|
75
|
+
return outputs
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Import Packflow's dev tools to run validations on the Inference Backend
|
|
2
|
+
from packflow.loaders import LocalLoader
|
|
3
|
+
|
|
4
|
+
# Load the backend in the current directory
|
|
5
|
+
# The path 'inference:Backend' can be interpreted as
|
|
6
|
+
# `from inference import Backend`
|
|
7
|
+
backend = LocalLoader("inference:Backend").load()
|
|
8
|
+
|
|
9
|
+
# Define sample inputs that represent realistic data for your backend.
|
|
10
|
+
# These should exercise the expected input format(s) your backend will receive.
|
|
11
|
+
SAMPLE_INPUTS = [
|
|
12
|
+
{"example_field": "example_value"},
|
|
13
|
+
# Add more sample rows as needed
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
if __name__ == "__main__":
|
|
17
|
+
print("Running validation...")
|
|
18
|
+
print(f"Sample inputs: {SAMPLE_INPUTS}\n")
|
|
19
|
+
|
|
20
|
+
# backend.validate() runs your backend and checks the outputs
|
|
21
|
+
# meet Packflow's API requirements. Returns outputs if valid.
|
|
22
|
+
outputs = backend.validate(SAMPLE_INPUTS)
|
|
23
|
+
|
|
24
|
+
print(f"Outputs: {outputs}")
|
|
25
|
+
print("\nValidation passed!")
|
packflow/exceptions.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
class InferenceBackendInitializationError(Exception):
|
|
2
|
+
pass
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class InferenceBackendRuntimeError(Exception):
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class InferenceBackendValidationError(Exception):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class InferenceBackendLoadError(Exception):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class UnknownPreprocessorError(Exception):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PreprocessorInitError(Exception):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PreprocessorRuntimeError(Exception):
|
|
26
|
+
pass
|
packflow/loaders/base.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
from packflow import InferenceBackend, exceptions
|
|
6
|
+
|
|
7
|
+
from .config import PackflowConfig
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class InferenceBackendLoader(ABC):
|
|
11
|
+
def __init__(self, path: str):
|
|
12
|
+
self.path = path
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
def load_backend_module(self) -> InferenceBackend:
|
|
16
|
+
"""
|
|
17
|
+
Load the backend module from its source.
|
|
18
|
+
This method should not handle instantiation or error handling, as
|
|
19
|
+
it is wrapped with error handling and general validation checks at
|
|
20
|
+
runtime.
|
|
21
|
+
|
|
22
|
+
Returns
|
|
23
|
+
-------
|
|
24
|
+
InferenceBackend
|
|
25
|
+
|
|
26
|
+
Notes
|
|
27
|
+
-----
|
|
28
|
+
The base class handles determining if the loaded object is already
|
|
29
|
+
instantiated and validation checks for if the loaded object is not
|
|
30
|
+
in fact an InferenceBackend object. This method should focus solely
|
|
31
|
+
on loading the object from its source.
|
|
32
|
+
"""
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
def load(self, **backend_kwargs) -> InferenceBackend:
|
|
36
|
+
"""
|
|
37
|
+
Load the inference backend.
|
|
38
|
+
|
|
39
|
+
Parameters
|
|
40
|
+
----------
|
|
41
|
+
**backend_kwargs
|
|
42
|
+
Optional Keyword arguments to pass to the backend if the provided path
|
|
43
|
+
leads to a non-instantiated class.
|
|
44
|
+
|
|
45
|
+
Returns
|
|
46
|
+
-------
|
|
47
|
+
InferenceBackend
|
|
48
|
+
An instantiated InferenceBackend that is ready to produce inferences.
|
|
49
|
+
"""
|
|
50
|
+
try:
|
|
51
|
+
backend = self.load_backend_module()
|
|
52
|
+
except Exception as e:
|
|
53
|
+
raise exceptions.InferenceBackendLoadError(
|
|
54
|
+
f"Unable to load inference backend module with error: {e}"
|
|
55
|
+
) from e
|
|
56
|
+
|
|
57
|
+
if isinstance(backend, type):
|
|
58
|
+
backend = backend(**backend_kwargs)
|
|
59
|
+
|
|
60
|
+
if not isinstance(backend, InferenceBackend):
|
|
61
|
+
raise exceptions.InferenceBackendLoadError(
|
|
62
|
+
f"Loaded object does not appear to be a packflow InferenceBackend. Received type: {type(backend)}"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
return backend
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_project(
|
|
69
|
+
cls, project_path: Union[str, Path] = ".", **backend_kwargs
|
|
70
|
+
) -> InferenceBackend:
|
|
71
|
+
"""Load an InferenceBackend from a Packflow directory/packflow.yaml."""
|
|
72
|
+
# Prevent circular imports
|
|
73
|
+
from .local import LocalLoader
|
|
74
|
+
from .module import ModuleLoader
|
|
75
|
+
|
|
76
|
+
project_path = Path(project_path).resolve()
|
|
77
|
+
config = PackflowConfig.from_project_path(project_path)
|
|
78
|
+
|
|
79
|
+
if config.loader == "local":
|
|
80
|
+
loader = LocalLoader(config.inference_backend)
|
|
81
|
+
elif config.loader == "module":
|
|
82
|
+
loader = ModuleLoader(config.inference_backend)
|
|
83
|
+
else:
|
|
84
|
+
raise ValueError(f"Unknown loader type: {config.loader}")
|
|
85
|
+
|
|
86
|
+
return loader.load(**backend_kwargs)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Annotated, Literal, Optional, Union
|
|
4
|
+
|
|
5
|
+
import yaml
|
|
6
|
+
from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, StringConstraints
|
|
7
|
+
|
|
8
|
+
import packflow.constants as constants
|
|
9
|
+
|
|
10
|
+
METADATA_KEYS = ["name", "version", "description", "maintainers"]
|
|
11
|
+
RUNTIME_CONFIG_KEYS = ["inference_backend", "loader", "python_version"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_python_version():
|
|
15
|
+
"""
|
|
16
|
+
Extract semantic version of the current process' python
|
|
17
|
+
"""
|
|
18
|
+
return f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def normalize_name(value: str) -> str:
|
|
22
|
+
return value.replace("-", "_").strip("_")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
NameStr = Annotated[
|
|
26
|
+
Annotated[str, StringConstraints(pattern=r"^[A-Za-z_]+$")],
|
|
27
|
+
BeforeValidator(normalize_name),
|
|
28
|
+
]
|
|
29
|
+
InferenceBackendStr = Annotated[str, StringConstraints(pattern=r"^[^:]+:[^:]+$")]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PackflowConfig(BaseModel):
|
|
33
|
+
model_config = ConfigDict(extra="allow")
|
|
34
|
+
|
|
35
|
+
name: NameStr
|
|
36
|
+
version: str = ""
|
|
37
|
+
description: str = ""
|
|
38
|
+
maintainers: list[str] = []
|
|
39
|
+
|
|
40
|
+
inference_backend: InferenceBackendStr = "inference:Backend"
|
|
41
|
+
loader: Literal["local", "module"] = "local"
|
|
42
|
+
python_version: str = get_python_version()
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_project_path(cls, base_dir: Union[str, Path]):
|
|
46
|
+
config = _load_raw_packaging_config(base_dir)
|
|
47
|
+
return cls(**config)
|
|
48
|
+
|
|
49
|
+
def archive_file_name(self, base_dir: Union[str, Path]):
|
|
50
|
+
base_dir = Path(base_dir).resolve()
|
|
51
|
+
return base_dir / f"{self.name}-{self.version}.zip"
|
|
52
|
+
|
|
53
|
+
def write_yaml(self, base_dir: Union[str, Path]):
|
|
54
|
+
base_dir = Path(base_dir).resolve()
|
|
55
|
+
packaging_config = base_dir / constants.PACKAGING_CONFIG_NAME
|
|
56
|
+
|
|
57
|
+
with packaging_config.open("w+") as f:
|
|
58
|
+
# Preserve order and comment structure
|
|
59
|
+
config_data = self.model_dump()
|
|
60
|
+
f.write("# === METADATA ===\n")
|
|
61
|
+
yaml.safe_dump(
|
|
62
|
+
{k: config_data[k] for k in METADATA_KEYS if k in config_data},
|
|
63
|
+
f,
|
|
64
|
+
sort_keys=False,
|
|
65
|
+
)
|
|
66
|
+
f.write("\n# === RUNTIME ===\n")
|
|
67
|
+
yaml.safe_dump(
|
|
68
|
+
{k: config_data[k] for k in RUNTIME_CONFIG_KEYS if k in config_data},
|
|
69
|
+
f,
|
|
70
|
+
sort_keys=False,
|
|
71
|
+
)
|
|
72
|
+
remaining_fields = list(
|
|
73
|
+
set(config_data.keys()) - set(METADATA_KEYS) - set(RUNTIME_CONFIG_KEYS)
|
|
74
|
+
)
|
|
75
|
+
if remaining_fields:
|
|
76
|
+
f.write("\n# === CUSTOM ===\n")
|
|
77
|
+
yaml.safe_dump(
|
|
78
|
+
{
|
|
79
|
+
k: config_data[k]
|
|
80
|
+
for k in config_data
|
|
81
|
+
if k not in METADATA_KEYS + RUNTIME_CONFIG_KEYS
|
|
82
|
+
},
|
|
83
|
+
f,
|
|
84
|
+
sort_keys=False,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
return packaging_config
|
|
88
|
+
|
|
89
|
+
def write_requirements(self, base_dir: Union[str, Path]):
|
|
90
|
+
from packflow import __version__ as packflow_version
|
|
91
|
+
|
|
92
|
+
base_dir = Path(base_dir).resolve()
|
|
93
|
+
requirements_text = base_dir / constants.REQUIREMENTS_TEXT_NAME
|
|
94
|
+
|
|
95
|
+
with open(requirements_text, "w") as f:
|
|
96
|
+
f.write(f"packflow=={packflow_version}")
|
|
97
|
+
|
|
98
|
+
return requirements_text
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _load_raw_packaging_config(base_dir: Union[str, Path]) -> dict:
|
|
102
|
+
base_dir = Path(base_dir).resolve()
|
|
103
|
+
packaging_config = base_dir / constants.PACKAGING_CONFIG_NAME
|
|
104
|
+
try:
|
|
105
|
+
with packaging_config.open("r") as f:
|
|
106
|
+
return yaml.safe_load(f)
|
|
107
|
+
except FileNotFoundError:
|
|
108
|
+
raise FileNotFoundError(
|
|
109
|
+
f"Not a valid packflow project: {packaging_config} does not exist"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def load_packflow_config(path_or_module: str):
|
|
114
|
+
"""
|
|
115
|
+
Check for local path FIRST -- fallback is to try to import it
|
|
116
|
+
"""
|
|
117
|
+
project_dir = Path(path_or_module).resolve()
|
|
118
|
+
|
|
119
|
+
if project_dir.exists():
|
|
120
|
+
return PackflowConfig.from_project_path(project_dir)
|
|
121
|
+
else:
|
|
122
|
+
# TODO - possible to load a config from module?
|
|
123
|
+
raise NotADirectoryError(
|
|
124
|
+
f"Could not identify packflow project at {path_or_module}"
|
|
125
|
+
)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import importlib.util
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import sys
|
|
5
|
+
from types import ModuleType
|
|
6
|
+
|
|
7
|
+
from .base import InferenceBackendLoader
|
|
8
|
+
from .. import InferenceBackend
|
|
9
|
+
from .utils import inference_backend_parts
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LocalLoader(InferenceBackendLoader):
|
|
13
|
+
@staticmethod
|
|
14
|
+
def _dot_notation_to_pypath(path: str) -> str:
|
|
15
|
+
"""
|
|
16
|
+
Convert a dotted-path like 'foo.bar' to a file path to a python module
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
path : str
|
|
21
|
+
The path to the module in dot notation
|
|
22
|
+
|
|
23
|
+
"""
|
|
24
|
+
module = path.replace(".", "/")
|
|
25
|
+
|
|
26
|
+
return str(Path(module).with_suffix(".py").resolve())
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def _import_module_from_source(path: str) -> ModuleType:
|
|
30
|
+
"""
|
|
31
|
+
Load a Python module from a local file path.
|
|
32
|
+
"""
|
|
33
|
+
source_path = Path(path).resolve(strict=True)
|
|
34
|
+
|
|
35
|
+
spec = importlib.util.spec_from_file_location(source_path.stem, source_path)
|
|
36
|
+
|
|
37
|
+
if not spec:
|
|
38
|
+
raise ImportError(f"Unable to import Python script from: {path}")
|
|
39
|
+
|
|
40
|
+
module = importlib.util.module_from_spec(spec)
|
|
41
|
+
|
|
42
|
+
sys.modules[spec.name] = module
|
|
43
|
+
|
|
44
|
+
spec.loader.exec_module(module)
|
|
45
|
+
|
|
46
|
+
return module
|
|
47
|
+
|
|
48
|
+
def load_backend_module(self, **backend_kwargs) -> InferenceBackend:
|
|
49
|
+
module_name, obj_name = inference_backend_parts(self.path)
|
|
50
|
+
|
|
51
|
+
module_path = self._dot_notation_to_pypath(module_name)
|
|
52
|
+
|
|
53
|
+
module = self._import_module_from_source(module_path)
|
|
54
|
+
|
|
55
|
+
backend = getattr(module, obj_name)
|
|
56
|
+
|
|
57
|
+
return backend
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
|
|
3
|
+
from packflow import exceptions
|
|
4
|
+
from .base import InferenceBackendLoader
|
|
5
|
+
from .. import InferenceBackend
|
|
6
|
+
from .utils import inference_backend_parts
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ModuleLoader(InferenceBackendLoader):
|
|
10
|
+
def load_backend_module(self) -> InferenceBackend:
|
|
11
|
+
"""
|
|
12
|
+
Load an InferenceBackend from an installed module.
|
|
13
|
+
|
|
14
|
+
Returns
|
|
15
|
+
-------
|
|
16
|
+
InferenceBackend
|
|
17
|
+
"""
|
|
18
|
+
module_name, backend_name = inference_backend_parts(self.path)
|
|
19
|
+
|
|
20
|
+
module = importlib.import_module(module_name)
|
|
21
|
+
|
|
22
|
+
backend = getattr(module, backend_name, None)
|
|
23
|
+
|
|
24
|
+
if not backend:
|
|
25
|
+
raise exceptions.InferenceBackendLoadError(
|
|
26
|
+
f"Backend with name `{backend_name}` does not exist in loaded module `{module}`"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
return backend
|