python-corekit 0.1.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.
- corekit/__init__.py +0 -0
- corekit/api/__init__.py +9 -0
- corekit/api/handler.py +76 -0
- corekit/api/responses.py +40 -0
- corekit/api/routers.py +115 -0
- corekit/concurrency/__init__.py +9 -0
- corekit/concurrency/decorators.py +72 -0
- corekit/concurrency/thread_local.py +99 -0
- corekit/concurrency/worker.py +65 -0
- corekit/config/__init__.py +47 -0
- corekit/config/loader.py +153 -0
- corekit/config/settings.py +161 -0
- corekit/config/sources.py +125 -0
- corekit/connections/__init__.py +31 -0
- corekit/connections/connectable.py +212 -0
- corekit/connections/decorators.py +92 -0
- corekit/connections/redis/__init__.py +7 -0
- corekit/connections/redis/connection.py +239 -0
- corekit/connections/registry.py +80 -0
- corekit/connections/sql/__init__.py +10 -0
- corekit/connections/sql/connection.py +342 -0
- corekit/connections/sql/fields/__init__.py +7 -0
- corekit/connections/sql/fields/jsonb.py +67 -0
- corekit/connections/sql/migration/__init__.py +57 -0
- corekit/connections/sql/migration/base.py +40 -0
- corekit/connections/sql/migration/operations.py +416 -0
- corekit/connections/sql/migration/registry.py +166 -0
- corekit/connections/sql/migration/table.py +27 -0
- corekit/connections/sql/query.py +68 -0
- corekit/connections/sql/table.py +96 -0
- corekit/constants.py +45 -0
- corekit/crypto/__init__.py +1 -0
- corekit/crypto/constants.py +7 -0
- corekit/crypto/enum.py +11 -0
- corekit/crypto/hasher.py +89 -0
- corekit/data/__init__.py +81 -0
- corekit/data/dataset.py +340 -0
- corekit/data/expressions/__init__.py +46 -0
- corekit/data/expressions/comparison.py +252 -0
- corekit/data/expressions/expression.py +98 -0
- corekit/data/record.py +147 -0
- corekit/data/stats.py +157 -0
- corekit/decorators/__init__.py +2 -0
- corekit/decorators/exception_handling.py +43 -0
- corekit/decorators/warnings.py +35 -0
- corekit/docker/__init__.py +7 -0
- corekit/docker/watchdog.py +222 -0
- corekit/etl/__init__.py +44 -0
- corekit/etl/connection.py +44 -0
- corekit/etl/extract/__init__.py +0 -0
- corekit/etl/extract/extractor.py +48 -0
- corekit/etl/extract/schemas.py +18 -0
- corekit/etl/load/__init__.py +0 -0
- corekit/etl/load/loader.py +53 -0
- corekit/etl/load/schemas.py +33 -0
- corekit/etl/orchestrator.py +201 -0
- corekit/etl/schemas.py +22 -0
- corekit/etl/transform/__init__.py +0 -0
- corekit/etl/transform/schemas.py +15 -0
- corekit/etl/transform/transformer.py +28 -0
- corekit/events/__init__.py +38 -0
- corekit/events/enum.py +58 -0
- corekit/events/frames.py +51 -0
- corekit/events/models.py +23 -0
- corekit/events/publisher.py +75 -0
- corekit/events/reader.py +132 -0
- corekit/events/sse.py +109 -0
- corekit/events/websocket.py +97 -0
- corekit/exceptions/__init__.py +0 -0
- corekit/exceptions/base.py +45 -0
- corekit/exceptions/custom/__init__.py +0 -0
- corekit/exceptions/http/__init__.py +0 -0
- corekit/exceptions/http/exceptions.py +37 -0
- corekit/exceptions/types.py +17 -0
- corekit/files/__init__.py +25 -0
- corekit/files/base.py +117 -0
- corekit/files/enum.py +30 -0
- corekit/files/json.py +12 -0
- corekit/files/pickle.py +12 -0
- corekit/files/toml.py +43 -0
- corekit/http/__init__.py +0 -0
- corekit/http/client.py +176 -0
- corekit/http/exponential_backoff.py +100 -0
- corekit/http/response.py +12 -0
- corekit/log_monitor/__init__.py +23 -0
- corekit/log_monitor/constants.py +8 -0
- corekit/log_monitor/models.py +150 -0
- corekit/log_monitor/service.py +418 -0
- corekit/notifications/__init__.py +8 -0
- corekit/notifications/base.py +51 -0
- corekit/notifications/models.py +34 -0
- corekit/observability/__init__.py +21 -0
- corekit/observability/benchmarkable.py +12 -0
- corekit/observability/loggable.py +29 -0
- corekit/observability/timing/__init__.py +0 -0
- corekit/observability/timing/constants.py +1 -0
- corekit/observability/timing/split.py +20 -0
- corekit/observability/timing/timer.py +30 -0
- corekit/py.typed +0 -0
- corekit/registry/__init__.py +12 -0
- corekit/registry/registry.py +134 -0
- corekit/schemas/__init__.py +0 -0
- corekit/schemas/dataclasses/__init__.py +0 -0
- corekit/schemas/enum.py +49 -0
- corekit/schemas/models/__init__.py +0 -0
- corekit/schemas/models/arbitrary.py +11 -0
- corekit/schemas/models/date_models.py +18 -0
- corekit/schemas/pydantic/__init__.py +0 -0
- corekit/schemas/pydantic/fields.py +35 -0
- corekit/schemas/types.py +40 -0
- corekit/serialization/__init__.py +0 -0
- corekit/serialization/enum.py +21 -0
- corekit/serialization/serializable.py +42 -0
- corekit/serialization/serializer.py +179 -0
- corekit/utils/__init__.py +5 -0
- corekit/utils/ids.py +5 -0
- corekit/utils/raise_exc.py +8 -0
- corekit/utils/time.py +21 -0
- corekit/utils/validators.py +15 -0
- corekit/utils/void.py +8 -0
- python_corekit-0.1.0.dist-info/METADATA +417 -0
- python_corekit-0.1.0.dist-info/RECORD +125 -0
- python_corekit-0.1.0.dist-info/WHEEL +5 -0
- python_corekit-0.1.0.dist-info/licenses/LICENSE +21 -0
- python_corekit-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Expression:
|
|
5
|
+
"""
|
|
6
|
+
Base class for composable predicates. Subclasses implement __call__
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
def __call__(self, *args: Any, **kwargs: Any) -> bool:
|
|
10
|
+
raise NotImplementedError
|
|
11
|
+
|
|
12
|
+
def __and__(self, other: "Expression") -> "Expression":
|
|
13
|
+
return And(self, other)
|
|
14
|
+
|
|
15
|
+
def __or__(self, other: "Expression") -> "Expression":
|
|
16
|
+
return Or(self, other)
|
|
17
|
+
|
|
18
|
+
def __invert__(self) -> "Expression":
|
|
19
|
+
return Not(self)
|
|
20
|
+
|
|
21
|
+
def to_sql(self, *args: Any, **kwargs: Any) -> str:
|
|
22
|
+
raise NotImplementedError
|
|
23
|
+
|
|
24
|
+
def to_mongo(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
25
|
+
raise NotImplementedError
|
|
26
|
+
|
|
27
|
+
def to_elasticsearch(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
28
|
+
raise NotImplementedError
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class And(Expression):
|
|
32
|
+
def __init__(self, left: Expression, right: Expression) -> None:
|
|
33
|
+
self.left = left
|
|
34
|
+
self.right = right
|
|
35
|
+
|
|
36
|
+
def __call__(self, *args: Any, **kwargs: Any) -> bool:
|
|
37
|
+
return bool(self.left(*args, **kwargs)) and bool(self.right(*args, **kwargs))
|
|
38
|
+
|
|
39
|
+
def __repr__(self) -> str:
|
|
40
|
+
return f"({self.left!r} & {self.right!r})"
|
|
41
|
+
|
|
42
|
+
def to_sql(self, *args: Any, **kwargs: Any) -> str:
|
|
43
|
+
return f"({self.left.to_sql(*args, **kwargs)} AND {self.right.to_sql(*args, **kwargs)})"
|
|
44
|
+
|
|
45
|
+
def to_mongo(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
46
|
+
return {"$and": [self.left.to_mongo(), self.right.to_mongo()]}
|
|
47
|
+
|
|
48
|
+
def to_elasticsearch(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
49
|
+
return {
|
|
50
|
+
"bool": {
|
|
51
|
+
"must": [self.left.to_elasticsearch(*args, **kwargs), self.right.to_elasticsearch(*args, **kwargs)]
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Or(Expression):
|
|
57
|
+
def __init__(self, left: Expression, right: Expression) -> None:
|
|
58
|
+
self.left = left
|
|
59
|
+
self.right = right
|
|
60
|
+
|
|
61
|
+
def __call__(self, *args: Any, **kwargs: Any) -> bool:
|
|
62
|
+
return bool(self.left(*args, **kwargs)) or bool(self.right(*args, **kwargs))
|
|
63
|
+
|
|
64
|
+
def __repr__(self) -> str:
|
|
65
|
+
return f"({self.left!r} | {self.right!r})"
|
|
66
|
+
|
|
67
|
+
def to_sql(self, *args: Any, **kwargs: Any) -> str:
|
|
68
|
+
return f"({self.left.to_sql(*args, **kwargs)} OR {self.right.to_sql(*args, **kwargs)})"
|
|
69
|
+
|
|
70
|
+
def to_mongo(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
71
|
+
return {"$or": [self.left.to_mongo(*args, **kwargs), self.right.to_mongo(*args, **kwargs)]}
|
|
72
|
+
|
|
73
|
+
def to_elasticsearch(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
74
|
+
return {
|
|
75
|
+
"bool": {
|
|
76
|
+
"should": [self.left.to_elasticsearch(*args, **kwargs), self.right.to_elasticsearch(*args, **kwargs)]
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Not(Expression):
|
|
82
|
+
def __init__(self, expr: Expression) -> None:
|
|
83
|
+
self.expr = expr
|
|
84
|
+
|
|
85
|
+
def __call__(self, *args: Any, **kwargs: Any) -> bool:
|
|
86
|
+
return not self.expr(*args, **kwargs)
|
|
87
|
+
|
|
88
|
+
def __repr__(self) -> str:
|
|
89
|
+
return f"~{self.expr!r}"
|
|
90
|
+
|
|
91
|
+
def to_sql(self, *args: Any, **kwargs: Any) -> str:
|
|
92
|
+
return f"NOT ({self.expr.to_sql(*args, **kwargs)})"
|
|
93
|
+
|
|
94
|
+
def to_mongo(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
95
|
+
return {"$not": self.expr.to_mongo(*args, **kwargs)}
|
|
96
|
+
|
|
97
|
+
def to_elasticsearch(self, *args: Any, **kwargs: Any) -> dict[str, Any] | str:
|
|
98
|
+
return {"bool": {"must_not": self.expr.to_elasticsearch(*args, **kwargs)}}
|
corekit/data/record.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import keyword
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any, Callable, Iterator
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def is_valid_key(key: Any) -> bool:
|
|
10
|
+
return isinstance(key, str) and key.isidentifier() and not keyword.iskeyword(key)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def return_constant(value: Any) -> Any:
|
|
14
|
+
return value
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def resolve_default(default: Any, default_factory: Callable[[], Any] | None) -> Callable[[], Any]:
|
|
18
|
+
"""
|
|
19
|
+
Normalize (default, default_factory) into a single zero-arg factory.
|
|
20
|
+
|
|
21
|
+
Raises on a raw mutable default (list/dict/set/bytearray), since that
|
|
22
|
+
object would otherwise be shared by reference across every record;
|
|
23
|
+
use default_factory instead. The non-factory path returns
|
|
24
|
+
functools.partial(_return_constant, default) rather than a lambda,
|
|
25
|
+
since a local lambda can't be pickled.
|
|
26
|
+
"""
|
|
27
|
+
if default_factory is not None:
|
|
28
|
+
if default is not None:
|
|
29
|
+
logger.warning("Both default and default_factory were provided. Prioritizing default_factory.")
|
|
30
|
+
return default_factory
|
|
31
|
+
|
|
32
|
+
if isinstance(default, (list, dict, set, bytearray)):
|
|
33
|
+
raise TypeError(
|
|
34
|
+
f"mutable default {default!r} would be shared by reference across every "
|
|
35
|
+
f"record; use default_factory instead (e.g. default_factory=list)"
|
|
36
|
+
)
|
|
37
|
+
return functools.partial(return_constant, default)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def reconstruct_record(fields: tuple, values: tuple) -> "BaseRecord":
|
|
41
|
+
"""
|
|
42
|
+
Rebuild a record on unpickling. Module-level so pickle can reference
|
|
43
|
+
it by import path -- the record's actual class is generated
|
|
44
|
+
dynamically and has no module path of its own.
|
|
45
|
+
"""
|
|
46
|
+
cls = BaseRecord.create_new(fields)
|
|
47
|
+
instance = cls()
|
|
48
|
+
for key, value in zip(fields, values):
|
|
49
|
+
instance[key] = value
|
|
50
|
+
return instance
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class BaseRecord:
|
|
54
|
+
"""
|
|
55
|
+
Base class for dynamically generated, schema-specific record types.
|
|
56
|
+
|
|
57
|
+
Subclasses are built per-dataset by create_new() with __slots__ for
|
|
58
|
+
each field, so instances carry no per-record __dict__ overhead.
|
|
59
|
+
__slots__ = () here means this base itself adds nothing on top of
|
|
60
|
+
that.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
__slots__ = ()
|
|
64
|
+
__fieldmap__ = {}
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def create_new(fields: tuple) -> type:
|
|
68
|
+
"""
|
|
69
|
+
Build a record class for the given field names.
|
|
70
|
+
|
|
71
|
+
Fields that aren't valid Python identifiers get a synthetic slot
|
|
72
|
+
name (_slot_0, _slot_1, ...) instead, tracked via __fieldmap__
|
|
73
|
+
so dict-style access (record["weird field"]) still works.
|
|
74
|
+
Synthetic names are checked against real field names so a field
|
|
75
|
+
literally named "_slot_0" can't collide with one.
|
|
76
|
+
"""
|
|
77
|
+
fieldmap: dict[Any, str] = {}
|
|
78
|
+
slot_names: list[str] = []
|
|
79
|
+
reserved = {key for key in fields if is_valid_key(key)}
|
|
80
|
+
used: set[str] = set()
|
|
81
|
+
counter = 0
|
|
82
|
+
for key in fields:
|
|
83
|
+
if is_valid_key(key):
|
|
84
|
+
slot = key
|
|
85
|
+
else:
|
|
86
|
+
candidate = f"_slot_{counter}"
|
|
87
|
+
counter += 1
|
|
88
|
+
while candidate in reserved or candidate in used:
|
|
89
|
+
candidate = f"_slot_{counter}"
|
|
90
|
+
counter += 1
|
|
91
|
+
slot = candidate
|
|
92
|
+
used.add(slot)
|
|
93
|
+
fieldmap[key] = slot
|
|
94
|
+
slot_names.append(slot)
|
|
95
|
+
return type("Record", (BaseRecord,), {"__slots__": tuple(slot_names), "__fieldmap__": fieldmap})
|
|
96
|
+
|
|
97
|
+
def __getitem__(self, key: Any) -> Any:
|
|
98
|
+
slot = self.__fieldmap__.get(key, key)
|
|
99
|
+
try:
|
|
100
|
+
return getattr(self, slot)
|
|
101
|
+
except AttributeError:
|
|
102
|
+
raise KeyError(key) from None
|
|
103
|
+
|
|
104
|
+
def __setitem__(self, key: Any, value: Any) -> Any:
|
|
105
|
+
slot = self.__fieldmap__.get(key)
|
|
106
|
+
if slot is None:
|
|
107
|
+
raise KeyError(f"{key!r} does not exist for record: {self}")
|
|
108
|
+
setattr(self, slot, value)
|
|
109
|
+
|
|
110
|
+
def __contains__(self, key: Any) -> bool:
|
|
111
|
+
return key in self.__fieldmap__
|
|
112
|
+
|
|
113
|
+
def __iter__(self) -> Iterator[Any]:
|
|
114
|
+
return iter(self.__fieldmap__)
|
|
115
|
+
|
|
116
|
+
def __len__(self) -> int:
|
|
117
|
+
return len(self.__fieldmap__)
|
|
118
|
+
|
|
119
|
+
def __eq__(self, other: Any) -> bool:
|
|
120
|
+
"""
|
|
121
|
+
Value equality: same fields and values, not same object.
|
|
122
|
+
|
|
123
|
+
Records are mutable, so __hash__ is implicitly disabled once
|
|
124
|
+
__eq__ is defined (Python does this automatically) -- that's
|
|
125
|
+
intentional, not an oversight, since a hashable object whose
|
|
126
|
+
hash can change under mutation is unsafe to use as a dict/set key.
|
|
127
|
+
"""
|
|
128
|
+
if isinstance(other, BaseRecord):
|
|
129
|
+
return self.to_dict() == other.to_dict()
|
|
130
|
+
if isinstance(other, dict):
|
|
131
|
+
return self.to_dict() == other
|
|
132
|
+
return NotImplemented
|
|
133
|
+
|
|
134
|
+
def __repr__(self) -> str:
|
|
135
|
+
fields = ", ".join(f"{key}={self[key]!r}" for key in self.__fieldmap__)
|
|
136
|
+
return f"{type(self).__name__}({fields})"
|
|
137
|
+
|
|
138
|
+
def __reduce__(self) -> tuple:
|
|
139
|
+
"""
|
|
140
|
+
Pickle as (reconstruct_fn, (fields, values)); see _reconstruct_record
|
|
141
|
+
"""
|
|
142
|
+
fields = tuple(self.__fieldmap__.keys())
|
|
143
|
+
values = tuple(self[k] for k in fields)
|
|
144
|
+
return reconstruct_record, (fields, values)
|
|
145
|
+
|
|
146
|
+
def to_dict(self) -> dict[Any, Any]:
|
|
147
|
+
return {k: self[k] for k in self.__fieldmap__}
|
corekit/data/stats.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import statistics
|
|
2
|
+
from collections import Counter
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from dataclasses import field as dataclass_field
|
|
5
|
+
from typing import Any, Iterator
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(slots=True)
|
|
9
|
+
class FieldStats:
|
|
10
|
+
"""
|
|
11
|
+
Common shape shared by every field's statistics
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
field: Any
|
|
15
|
+
count: int
|
|
16
|
+
missing: int
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(slots=True)
|
|
20
|
+
class NumericFieldStats(FieldStats):
|
|
21
|
+
"""
|
|
22
|
+
Stats for a field where every non-missing value is int/float (not bool)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
mean: float
|
|
26
|
+
min: Any
|
|
27
|
+
max: Any
|
|
28
|
+
stdev: float
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(slots=True)
|
|
32
|
+
class CategoricalFieldStats(FieldStats):
|
|
33
|
+
"""
|
|
34
|
+
Stats for any field that isn't purely numeric
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
unique: int
|
|
38
|
+
top: Any
|
|
39
|
+
freq: int
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(slots=True)
|
|
43
|
+
class ValueCounts:
|
|
44
|
+
"""
|
|
45
|
+
How often each distinct value of a field occurs, most frequent first
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
field: Any
|
|
49
|
+
counts: dict[Any, int]
|
|
50
|
+
|
|
51
|
+
def most_common(self, n: int | None = None) -> list[tuple[Any, int]]:
|
|
52
|
+
items = list(self.counts.items())
|
|
53
|
+
return items[:n] if n is not None else items
|
|
54
|
+
|
|
55
|
+
def top(self) -> tuple[Any, int] | None:
|
|
56
|
+
return next(iter(self.counts.items()), None)
|
|
57
|
+
|
|
58
|
+
def __iter__(self) -> Iterator[tuple[Any, int]]:
|
|
59
|
+
return iter(self.counts.items())
|
|
60
|
+
|
|
61
|
+
def __len__(self) -> int:
|
|
62
|
+
return len(self.counts)
|
|
63
|
+
|
|
64
|
+
def __getitem__(self, value: Any) -> int:
|
|
65
|
+
return self.counts[value]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(slots=True)
|
|
69
|
+
class FieldDescription:
|
|
70
|
+
field: Any
|
|
71
|
+
values: list[Any] = dataclass_field(default_factory=list)
|
|
72
|
+
non_missing: list[Any] = dataclass_field(default_factory=list)
|
|
73
|
+
num_values: int = dataclass_field(default=0)
|
|
74
|
+
num_non_missing: int = dataclass_field(default=0)
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def from_data(cls, data: list[Any], field: Any) -> "FieldDescription":
|
|
78
|
+
instance = cls(field)
|
|
79
|
+
for record in data:
|
|
80
|
+
instance.add(record[field])
|
|
81
|
+
return instance
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def missing(self) -> int:
|
|
85
|
+
return self.num_values - self.num_non_missing
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def is_numeric(self) -> bool:
|
|
89
|
+
return all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in self.non_missing)
|
|
90
|
+
|
|
91
|
+
def to_field_stats(self) -> FieldStats:
|
|
92
|
+
if self.is_numeric:
|
|
93
|
+
return NumericFieldStats(
|
|
94
|
+
field=self.field,
|
|
95
|
+
count=self.num_non_missing,
|
|
96
|
+
missing=self.missing,
|
|
97
|
+
mean=statistics.fmean(self.non_missing),
|
|
98
|
+
min=min(self.non_missing),
|
|
99
|
+
max=max(self.non_missing),
|
|
100
|
+
stdev=statistics.stdev(self.non_missing) if self.num_non_missing > 1 else 0.0,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
counts = Counter(self.non_missing)
|
|
104
|
+
top_value, top_count = counts.most_common(1)[0] if counts else (None, 0)
|
|
105
|
+
return CategoricalFieldStats(
|
|
106
|
+
field=self.field,
|
|
107
|
+
count=self.num_non_missing,
|
|
108
|
+
missing=self.missing,
|
|
109
|
+
unique=len(counts),
|
|
110
|
+
top=top_value,
|
|
111
|
+
freq=top_count,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def add(self, value: Any) -> None:
|
|
115
|
+
self.values.append(value)
|
|
116
|
+
self.num_values += 1
|
|
117
|
+
if value is not None:
|
|
118
|
+
self.non_missing.append(value)
|
|
119
|
+
self.num_non_missing += 1
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class DatasetStats:
|
|
123
|
+
"""
|
|
124
|
+
Read-only field statistics for a Dataset's current records.
|
|
125
|
+
|
|
126
|
+
Computed fresh on every call from the dataset's public interface (never
|
|
127
|
+
cached), so there's nothing here that can go stale after a mutation --
|
|
128
|
+
the same reasoning that ruled out persistent secondary indexes applies:
|
|
129
|
+
recomputing is cheap and always correct, caching is not free and can lie.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
def __init__(self, data: list[Any], schema: tuple[Any, ...] | None = None) -> None:
|
|
133
|
+
self._data = data
|
|
134
|
+
self._schema = schema or ()
|
|
135
|
+
|
|
136
|
+
def value_counts(self, field: Any) -> ValueCounts:
|
|
137
|
+
"""
|
|
138
|
+
How often each distinct value of `field` occurs, most frequent first
|
|
139
|
+
"""
|
|
140
|
+
counts = dict(Counter(rec[field] for rec in self._data).most_common())
|
|
141
|
+
return ValueCounts(field=field, counts=counts)
|
|
142
|
+
|
|
143
|
+
def describe(self, field: Any | None = None) -> dict[Any, FieldStats]:
|
|
144
|
+
"""
|
|
145
|
+
Summary statistics per field, pandas-.describe()-style.
|
|
146
|
+
|
|
147
|
+
Numeric fields (int/float, excluding bool) get a NumericFieldStats
|
|
148
|
+
(mean/min/max/stdev). Everything else gets a CategoricalFieldStats
|
|
149
|
+
(unique/top/freq). Pass `field` to describe just one; omit to
|
|
150
|
+
describe every field in the schema.
|
|
151
|
+
"""
|
|
152
|
+
fields = (field,) if field is not None else self._schema
|
|
153
|
+
stats = {}
|
|
154
|
+
for f in fields:
|
|
155
|
+
field_description = FieldDescription.from_data(self._data, f)
|
|
156
|
+
stats[f] = field_description.to_field_stats()
|
|
157
|
+
return stats
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Any, Callable
|
|
4
|
+
|
|
5
|
+
from corekit.utils import raise_exc, void
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def exception_handler(
|
|
11
|
+
ignore: list[type[Exception]] | None = None,
|
|
12
|
+
callback: Callable = raise_exc,
|
|
13
|
+
ignore_callback: Callable = void,
|
|
14
|
+
) -> Any:
|
|
15
|
+
"""
|
|
16
|
+
A decorator to handle exceptions in a class method or function.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
ignore: exception classes to suppress. These do not propagate.
|
|
20
|
+
callback: called when an exception is raised that is not ignored.
|
|
21
|
+
ignore_callback: called when a suppressed exception is raised.
|
|
22
|
+
"""
|
|
23
|
+
exceptions_to_ignore = tuple(ignore) if ignore else tuple()
|
|
24
|
+
|
|
25
|
+
def decorator(func):
|
|
26
|
+
@functools.wraps(func)
|
|
27
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
28
|
+
try:
|
|
29
|
+
return func(*args, **kwargs)
|
|
30
|
+
except Exception as ex:
|
|
31
|
+
# If in ignore list, suppress and invoke the ignore_callback function
|
|
32
|
+
if isinstance(ex, exceptions_to_ignore):
|
|
33
|
+
logger.warning(f"Suppressed exception in {func.__name__}: {ex}")
|
|
34
|
+
logger.info(f"Invoking callback function: {ignore_callback.__name__}")
|
|
35
|
+
return ignore_callback(ex, *args, **kwargs)
|
|
36
|
+
|
|
37
|
+
# Log the exception and invoke the callback function, returning its return value (if any)
|
|
38
|
+
logger.error(f"Exception in {func.__name__}: {ex}", exc_info=True)
|
|
39
|
+
return callback(ex, *args, **kwargs)
|
|
40
|
+
|
|
41
|
+
return wrapper
|
|
42
|
+
|
|
43
|
+
return decorator
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import logging
|
|
3
|
+
import warnings
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def deprecated(
|
|
10
|
+
message: str,
|
|
11
|
+
exception: type[Exception] | None = None,
|
|
12
|
+
) -> Any:
|
|
13
|
+
"""
|
|
14
|
+
A decorator to mark a function as deprecated
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
message (str): The message to display when the function is deprecated
|
|
18
|
+
exception (Exception | None): An optional exception to raise
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def decorator(func):
|
|
22
|
+
@functools.wraps(func)
|
|
23
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
24
|
+
if exception:
|
|
25
|
+
raise exception(message)
|
|
26
|
+
# A real warning, so linters, test runners and -W flags can see
|
|
27
|
+
# it; the log line alone is invisible to all of them. stacklevel=2
|
|
28
|
+
# points at the caller rather than at this wrapper.
|
|
29
|
+
warnings.warn(f"{func.__name__} is deprecated: {message}", DeprecationWarning, stacklevel=2)
|
|
30
|
+
logger.warning(f"[DEPRECATION WARNING]: {func.__name__} is deprecated: {message}")
|
|
31
|
+
return func(*args, **kwargs)
|
|
32
|
+
|
|
33
|
+
return wrapper
|
|
34
|
+
|
|
35
|
+
return decorator
|