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.
@@ -0,0 +1,27 @@
1
+ def inference_backend_parts(path: str) -> list[str]:
2
+ """
3
+ Utility for splitting the inference_backend to the module and object parts
4
+
5
+ Parameters
6
+ ----------
7
+ path : str
8
+ The path to the backend to load. Notation should follow 'module.submodule:object'
9
+
10
+ Returns
11
+ -------
12
+ list[str]
13
+ Parts the first will be the path to the module and the second will be the object
14
+ within the module that will be loaded.
15
+
16
+ Example
17
+ -------
18
+ 'foo.bar:baz' would return ['foo.bar', 'baz'] and can be interpreted as:
19
+ from foo.bar import baz
20
+ """
21
+ parts = path.split(":")
22
+
23
+ if len(parts) != 2:
24
+ raise ValueError(
25
+ "Path must contain exactly one colon separating module and object"
26
+ )
27
+ return parts
packflow/logger.py ADDED
@@ -0,0 +1,5 @@
1
+ from loguru import logger
2
+
3
+
4
+ def get_logger():
5
+ return logger
packflow/project.py ADDED
@@ -0,0 +1,72 @@
1
+ import importlib.resources
2
+ import shutil
3
+ import zipfile
4
+ from pathlib import Path
5
+ from typing import Union
6
+
7
+ import packflow.constants as constants
8
+
9
+ from .loaders.config import PackflowConfig
10
+
11
+
12
+ class PackflowProject:
13
+ def __init__(self, base_dir: Union[str, Path]):
14
+ self.base_dir = Path(base_dir).resolve()
15
+
16
+ @property
17
+ def has_packflow_config(self):
18
+ return self.base_dir.joinpath(constants.PACKAGING_CONFIG_NAME).exists()
19
+
20
+ def __repr__(self):
21
+ return f"{self.__class__.__name__} @ {self.base_dir}"
22
+
23
+ @classmethod
24
+ def create(cls, project_name: str, force: bool = False, template: str = "minimal"):
25
+ """
26
+ Create a new project and then return the PackflowProject controller
27
+ for the new project
28
+ """
29
+ config = PackflowConfig(name=project_name)
30
+
31
+ base_path = Path(config.name).resolve()
32
+
33
+ base_path.mkdir(parents=True, exist_ok=force)
34
+
35
+ # HARD CODED SINCE THERE'S ONLY ONE TEMPLATE RIGHT NOW
36
+ templates_dir = (
37
+ importlib.resources.files("packflow")
38
+ .joinpath("data/templates")
39
+ .joinpath(template)
40
+ )
41
+
42
+ shutil.copytree(str(templates_dir), str(base_path), dirs_exist_ok=True)
43
+
44
+ config.write_yaml(base_path)
45
+
46
+ config.write_requirements(base_path)
47
+
48
+ return cls(base_path)
49
+
50
+ def load_config(self):
51
+ return PackflowConfig.from_project_path(self.base_dir)
52
+
53
+ def export(self, output_directory: str = ".") -> Path:
54
+ """
55
+ Save the loaded project as a package.zip with schema `{name}-{version}-pkg.zip`
56
+ """
57
+ config = PackflowConfig.from_project_path(self.base_dir)
58
+ export_file_name = config.archive_file_name(output_directory)
59
+
60
+ try:
61
+ with zipfile.ZipFile(export_file_name, "w") as zip_file:
62
+ for file_path in self.base_dir.rglob("*"):
63
+ if (
64
+ file_path.is_file()
65
+ and file_path.resolve() != export_file_name.resolve()
66
+ ):
67
+ relative_path = file_path.relative_to(self.base_dir)
68
+ zip_file.write(str(file_path), str(relative_path))
69
+ return export_file_name
70
+ except Exception as e:
71
+ # TODO: Create custom exception
72
+ raise Exception(f"An error occurred: {e}")
@@ -0,0 +1,2 @@
1
+ from .data import flatten_dict, flatten_records, records_to_ndarray
2
+ from .normalize import ensure_native_types, ensure_valid_output
packflow/utils/data.py ADDED
@@ -0,0 +1,152 @@
1
+ import functools
2
+ from typing import Any, List, Optional
3
+
4
+ import numpy as np
5
+ from flatten_dict import flatten, unflatten
6
+ from flatten_dict.reducers import make_reducer
7
+
8
+
9
+ def get_nested_field(obj: dict, field: str, delimiter: Optional[str] = None) -> Any:
10
+ """
11
+ Retrieves a single nested field from a dictionary given a field name.
12
+
13
+ Example: get_nested_field({"foo": {"bar": 5}}, 'foo.bar') -> 5
14
+
15
+ Parameters
16
+ ----------
17
+ obj : dict
18
+ An arbitrary dictionary of data
19
+
20
+ field : str
21
+ The key name to retrieve where subfields are split by $delimiter
22
+
23
+ Returns
24
+ -------
25
+ Any
26
+ The value retrieved from the nested key
27
+ """
28
+ if field in obj:
29
+ return obj[field]
30
+
31
+ flattened = flatten(
32
+ obj, reducer=make_reducer(delimiter or "."), keep_empty_types=(dict, list)
33
+ )
34
+ return flattened.get(field, None)
35
+
36
+
37
+ def records_to_ndarray(
38
+ records: List[dict],
39
+ feature_names: List[str],
40
+ dtype: Optional[str] = None,
41
+ delimiter: Optional[str] = None,
42
+ ) -> np.ndarray:
43
+ """
44
+ Converts records to a numpy nd array
45
+
46
+ Example
47
+ -------
48
+ in: [{"num": 1, "num2": 1}, {"num": 2, "num": 2}]
49
+ args: feature_names=["num", "num2"]
50
+ out: np.array([[1, 1], [2, 2]])
51
+
52
+ Parameters
53
+ ----------
54
+ records : List[Dict]
55
+ A list of dictionary items to be converted
56
+
57
+ feature_names : List[str]
58
+ The values to extract for each row
59
+
60
+ dtype : str
61
+ The numpy data type to coerce the array to. Defaults to 'float32'
62
+
63
+ Returns
64
+ -------
65
+ numpy.ndarray
66
+ """
67
+ if not isinstance(records, list):
68
+ raise ValueError(
69
+ f"Value for `records` must be a list of dictionaries. Received type: {type(records)}"
70
+ )
71
+
72
+ # Pre-allocate list with None values for better performance
73
+ arr_data = [[None] * len(feature_names) for _ in range(len(records))]
74
+
75
+ for index, row in enumerate(records):
76
+ if not isinstance(row, dict):
77
+ raise ValueError(
78
+ f"Value at index {index} is not a dictionary. Received type: {type(row)}"
79
+ )
80
+
81
+ # Use list comprehension with direct assignment
82
+ arr_data[index] = [
83
+ get_nested_field(row, feature, delimiter=delimiter)
84
+ for feature in feature_names
85
+ ]
86
+
87
+ return np.array(arr_data, dtype=dtype)
88
+
89
+
90
+ def flatten_dict(obj: dict, delimiter: str = ".", flatten_lists: bool = False) -> dict:
91
+ """
92
+ Create a flattened dictionary from a nested object.
93
+
94
+ Parameters
95
+ ----------
96
+ obj: dict
97
+
98
+ delimiter: str
99
+ Default '.'
100
+
101
+ flatten_lists: bool
102
+ Default False
103
+
104
+ Returns
105
+ -------
106
+ dict
107
+ Flattened dictionary.
108
+ """
109
+ if not isinstance(obj, dict):
110
+ raise TypeError(
111
+ f"Value for `obj` must be a dictionary-like object. Received type: {type(obj)}"
112
+ )
113
+
114
+ return flatten(
115
+ obj,
116
+ reducer=make_reducer(delimiter),
117
+ enumerate_types=(list,) if flatten_lists else (),
118
+ keep_empty_types=(dict, list),
119
+ )
120
+
121
+
122
+ def flatten_records(
123
+ records: List[dict], delimiter: str = ".", flatten_lists: bool = False
124
+ ) -> List[dict]:
125
+ """
126
+ Flatten a list of dictionaries
127
+
128
+ Parameters
129
+ ----------
130
+ records: List[dict]
131
+
132
+ delimiter: str
133
+ Default '.'
134
+
135
+ flatten_lists: bool
136
+ Default False
137
+
138
+ Returns
139
+ -------
140
+ List[dict]
141
+ Flattened records.
142
+ """
143
+ if not isinstance(records, list):
144
+ raise TypeError(
145
+ f"Value for `records` must be a list. Received type: {type(records)}"
146
+ )
147
+
148
+ flatten_func = functools.partial(
149
+ flatten_dict, delimiter=delimiter, flatten_lists=flatten_lists
150
+ )
151
+
152
+ return list(map(flatten_func, records))
@@ -0,0 +1 @@
1
+ from .normalize import ensure_native_types, ensure_valid_output
@@ -0,0 +1,79 @@
1
+ from abc import ABC, abstractmethod
2
+ import importlib
3
+ from types import ModuleType
4
+ from typing import Any, Union
5
+
6
+ from packflow.logger import get_logger
7
+
8
+
9
+ logger = get_logger()
10
+
11
+
12
+ class TypeConversionHandler(ABC):
13
+ def __init__(self):
14
+ self.module = self._import_module()
15
+
16
+ def __repr__(self): # pragma: no cover
17
+ return self.__class__.__name__
18
+
19
+ def _import_module(self) -> Union[ModuleType, None]:
20
+ """
21
+ Attempts to import the required module.
22
+
23
+ Returns
24
+ -------
25
+ ModuleType
26
+ """
27
+ try:
28
+ return importlib.import_module(self.package_name)
29
+ except Exception as e:
30
+ logger.debug(
31
+ f"{self.__class__.__name__} Type Converter is not available. Reason: {e}"
32
+ )
33
+ return None
34
+
35
+ def available(self) -> bool:
36
+ """
37
+ Returns if the type conversion handler is available.
38
+
39
+ Returns
40
+ -------
41
+ bool
42
+ """
43
+ return self.module is not None
44
+
45
+ @property
46
+ @abstractmethod
47
+ def package_name(self) -> str: # pragma: no cover
48
+ """
49
+ The name of the required package to attempt to import
50
+ """
51
+ pass
52
+
53
+ @abstractmethod
54
+ def is_type(self, obj: Any) -> bool: # pragma: no cover
55
+ """
56
+ Check if the object is the proper type for the converter
57
+
58
+ Returns
59
+ -------
60
+ bool
61
+ """
62
+ pass
63
+
64
+ @abstractmethod
65
+ def convert(self, obj: Any) -> object: # pragma: no cover
66
+ """
67
+ Logic to convert the type to a native, json-serializable Python type.
68
+
69
+ Parameters
70
+ ----------
71
+ obj: Any
72
+ The object to convert
73
+
74
+ Returns
75
+ -------
76
+ object
77
+ Any python native type that is JSON serializable
78
+ """
79
+ pass
@@ -0,0 +1,93 @@
1
+ import base64
2
+ import io
3
+ from typing import Any
4
+
5
+ from .base import TypeConversionHandler
6
+
7
+ # -- NUMPY --
8
+
9
+
10
+ class NumpyTypeHandler(TypeConversionHandler):
11
+ @property
12
+ def package_name(self) -> str:
13
+ return "numpy"
14
+
15
+ def is_type(self, obj: Any) -> bool:
16
+ return isinstance(obj, (self.module.ndarray, self.module.generic))
17
+
18
+ def convert(self, obj: Any) -> object:
19
+ return obj.tolist()
20
+
21
+
22
+ # -- PANDAS --
23
+
24
+
25
+ class PandasSeriesHandler(TypeConversionHandler):
26
+ @property
27
+ def package_name(self) -> str:
28
+ return "pandas"
29
+
30
+ def is_type(self, obj: Any) -> bool:
31
+ return isinstance(obj, self.module.Series)
32
+
33
+ def convert(self, obj: Any) -> object:
34
+ return obj.to_list()
35
+
36
+
37
+ class PandasDataFrameHandler(TypeConversionHandler):
38
+ @property
39
+ def package_name(self) -> str:
40
+ return "pandas"
41
+
42
+ def is_type(self, obj: Any) -> bool:
43
+ return isinstance(obj, self.module.DataFrame)
44
+
45
+ def convert(self, obj: Any) -> object:
46
+ return obj.to_dict("split")
47
+
48
+
49
+ # -- TORCH --
50
+
51
+
52
+ class TorchScalarHandler(TypeConversionHandler):
53
+ @property
54
+ def package_name(self) -> str:
55
+ return "torch"
56
+
57
+ def is_type(self, obj: Any) -> bool:
58
+ return (
59
+ isinstance(obj, (self.module.FloatTensor, self.module.IntTensor))
60
+ and obj.numel() == 1
61
+ )
62
+
63
+ def convert(self, obj: Any) -> object:
64
+ return obj.item()
65
+
66
+
67
+ class TorchTensorHandler(TypeConversionHandler):
68
+ @property
69
+ def package_name(self) -> str:
70
+ return "torch"
71
+
72
+ def is_type(self, obj: Any) -> bool:
73
+ return isinstance(obj, self.module.Tensor)
74
+
75
+ def convert(self, obj: Any) -> object:
76
+ return obj.detach().cpu().numpy().tolist()
77
+
78
+
79
+ # -- PILLOW/PIL --
80
+
81
+
82
+ class PillowImageHandler(TypeConversionHandler):
83
+ @property
84
+ def package_name(self) -> str:
85
+ return "PIL.Image"
86
+
87
+ def is_type(self, obj: Any) -> bool:
88
+ return isinstance(obj, self.module.Image)
89
+
90
+ def convert(self, obj: Any) -> object:
91
+ buffer = io.BytesIO()
92
+ obj.save(buffer, format="PNG")
93
+ return base64.b64encode(buffer.getvalue()).decode("utf-8")
@@ -0,0 +1,87 @@
1
+ from typing import Any, Dict, Iterable
2
+
3
+ from .handlers import (
4
+ NumpyTypeHandler,
5
+ PandasSeriesHandler,
6
+ PandasDataFrameHandler,
7
+ TorchScalarHandler,
8
+ TorchTensorHandler,
9
+ PillowImageHandler,
10
+ )
11
+
12
+ # Prioritized list (most likely to be encountered first) of TypeConversionHandlers
13
+ _ALL_HANDLERS = [
14
+ NumpyTypeHandler(),
15
+ PandasSeriesHandler(),
16
+ PandasDataFrameHandler(),
17
+ TorchScalarHandler(),
18
+ TorchTensorHandler(),
19
+ PillowImageHandler(),
20
+ ]
21
+
22
+ # Filtered list of which handlers are available in the current environment
23
+ _AVAILABLE_HANDLERS = [handler for handler in _ALL_HANDLERS if handler.available()]
24
+
25
+
26
+ def ensure_native_types(obj: Any):
27
+ """Converts any non-native data types to ensure JSON serialization is possible.
28
+
29
+ Parameters
30
+ ----------
31
+ obj : Any
32
+ the object to convert to a native data type
33
+
34
+ Returns
35
+ -------
36
+ A scalar or object with all-native Python data types
37
+ """
38
+ # Bypass handlers if the obj is already a native scalar type
39
+ if isinstance(obj, (int, float, str, bool, type(None))):
40
+ return obj
41
+
42
+ # If not, loop through available handlers and convert to an allowed type
43
+ for handler in _AVAILABLE_HANDLERS:
44
+ if handler.is_type(obj):
45
+ return handler.convert(obj)
46
+
47
+ # Handle containers
48
+ if isinstance(obj, dict):
49
+ return {k: ensure_native_types(v) for k, v in obj.items()}
50
+
51
+ if isinstance(obj, (list, tuple, set)):
52
+ return [ensure_native_types(v) for v in obj]
53
+
54
+ # Throw an error if there's an unknown type
55
+ raise TypeError(
56
+ f'Returned type "{type(obj)}" is not supported. Please convert this object to a native Python type in your app.'
57
+ )
58
+
59
+
60
+ def ensure_valid_output(
61
+ output: Iterable[Any], parent_key: str = "output"
62
+ ) -> Iterable[Dict[str, Any]]:
63
+ """
64
+ Coerces outputs to native Python types and correct formats.
65
+
66
+ Parameters
67
+ ----------
68
+ output : Iterable[Any]
69
+ Model outputs to be cleaned
70
+
71
+ parent_key : str
72
+ Default 'output'. Used when the output is not a dictionary type.
73
+ Ex: Output of [0, 1] would be wrapped to {f'{parent_key}': [0, 1]}
74
+
75
+ Returns
76
+ -------
77
+ List[Dict[str, Any]]
78
+ """
79
+ valid_output = []
80
+ for v in output:
81
+ v = ensure_native_types(v)
82
+ if not isinstance(v, dict):
83
+ if isinstance(v, list) and len(v) == 1:
84
+ v = v[0]
85
+ v = {parent_key: v}
86
+ valid_output.append(v)
87
+ return valid_output