tricklepy 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.
- trickle/__init__.py +0 -0
- trickle/adapters.py +80 -0
- trickle/cli.py +153 -0
- trickle/exceptions.py +38 -0
- trickle/inference.py +26 -0
- trickle/load.py +65 -0
- trickle/pipeline.py +13 -0
- trickle/protocols.py +15 -0
- trickle/schema.py +68 -0
- trickle/transforms.py +91 -0
- trickle/validation.py +97 -0
- tricklepy-0.1.0.dist-info/METADATA +9 -0
- tricklepy-0.1.0.dist-info/RECORD +17 -0
- tricklepy-0.1.0.dist-info/WHEEL +5 -0
- tricklepy-0.1.0.dist-info/entry_points.txt +2 -0
- tricklepy-0.1.0.dist-info/licenses/LICENSE +21 -0
- tricklepy-0.1.0.dist-info/top_level.txt +1 -0
trickle/__init__.py
ADDED
|
File without changes
|
trickle/adapters.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from trickle.exceptions import ConfigurationError
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from typing import Any
|
|
4
|
+
from trickle.exceptions import PredictionError
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BaseAdapter(ABC):
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
predictor: Callable[[Any], Any],
|
|
12
|
+
name: str,
|
|
13
|
+
adapter_type
|
|
14
|
+
):
|
|
15
|
+
super().__init__()
|
|
16
|
+
if callable(predictor):
|
|
17
|
+
self.predictor = predictor
|
|
18
|
+
else:
|
|
19
|
+
raise ConfigurationError(
|
|
20
|
+
message="Predictor is not callable.",
|
|
21
|
+
error_code="INVALID_PREDICTOR"
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
if isinstance(name, str) and name.strip():
|
|
25
|
+
self.name = name
|
|
26
|
+
else:
|
|
27
|
+
raise ConfigurationError(
|
|
28
|
+
message="Invalid model name.",
|
|
29
|
+
error_code="INVALID_MODEL_NAME"
|
|
30
|
+
)
|
|
31
|
+
if isinstance(adapter_type, str) and adapter_type.strip():
|
|
32
|
+
self.adapter_type = adapter_type
|
|
33
|
+
else:
|
|
34
|
+
raise ConfigurationError(
|
|
35
|
+
message="Invalid adapter type.",
|
|
36
|
+
error_code="INVALID_ADAPTER_TYPE"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
def metadata(self) -> dict[str, Any]:
|
|
40
|
+
return {
|
|
41
|
+
"name": self.name,
|
|
42
|
+
"adapter": self.adapter_type
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
@abstractmethod
|
|
46
|
+
def predict(self, batch: list[Any]) -> list[Any]:
|
|
47
|
+
...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CallableAdapter(BaseAdapter):
|
|
51
|
+
def __init__(self, predictor: Callable[[Any], Any], name: str):
|
|
52
|
+
super().__init__(predictor, name, "callable")
|
|
53
|
+
|
|
54
|
+
def predict(self, batch: list[Any]) -> list[Any]:
|
|
55
|
+
predictions = []
|
|
56
|
+
for x in batch:
|
|
57
|
+
predictions.append(self.predictor(x))
|
|
58
|
+
|
|
59
|
+
return predictions
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class BatchPredictAdapter(BaseAdapter):
|
|
63
|
+
def __init__(self, predictor: Callable[[list[Any]], list[Any]], name: str):
|
|
64
|
+
super().__init__(predictor, name, "batch")
|
|
65
|
+
|
|
66
|
+
def predict(self, batch: list[Any]) -> list[Any]:
|
|
67
|
+
prediction = self.predictor(batch)
|
|
68
|
+
if not isinstance(prediction, list):
|
|
69
|
+
raise PredictionError(
|
|
70
|
+
message="Prediction must be a list.",
|
|
71
|
+
error_code="INVALID_PREDICTION_TYPE"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
if len(prediction) != len(batch):
|
|
75
|
+
raise PredictionError(
|
|
76
|
+
message="Prediction count does not match batch size.",
|
|
77
|
+
error_code="PREDICTION_COUNT_MISMATCH"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
return prediction
|
trickle/cli.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from contextlib import closing
|
|
7
|
+
from itertools import combinations
|
|
8
|
+
|
|
9
|
+
from trickle.schema import load_schema
|
|
10
|
+
from trickle.exceptions import ConfigurationError
|
|
11
|
+
from trickle.validation import validate_config
|
|
12
|
+
from trickle.load import load_jsonl
|
|
13
|
+
from trickle.pipeline import Pipeline
|
|
14
|
+
from trickle.transforms import Batch
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog="trickle",
|
|
23
|
+
description="Stream and validate large JSONL files."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"--input", type=str, required=True,
|
|
28
|
+
help="Input JSONL file."
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"--output", type=str, required=True,
|
|
33
|
+
help="Output JSONL file."
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
parser.add_argument(
|
|
37
|
+
"--errors", type=str, required=True,
|
|
38
|
+
help="Rejected records file."
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"--batch-size", type=int, default=32,
|
|
43
|
+
help="Number of records per batch."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"--max-record-size", type=int, default=65536,
|
|
48
|
+
help="Maximum record size in bytes."
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"--schema", type=str, default=None,
|
|
53
|
+
help="Optional JSON schema file."
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
return parser
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _validate_paths(args: argparse.Namespace) -> None:
|
|
60
|
+
paths = [
|
|
61
|
+
Path(args.input),
|
|
62
|
+
Path(args.output),
|
|
63
|
+
Path(args.errors)
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
if args.schema is not None:
|
|
67
|
+
paths.append(Path(args.schema))
|
|
68
|
+
|
|
69
|
+
for first, second in combinations(paths, 2):
|
|
70
|
+
if first.resolve() == second.resolve() or (
|
|
71
|
+
first.exists()
|
|
72
|
+
and second.exists()
|
|
73
|
+
and first.samefile(second)
|
|
74
|
+
):
|
|
75
|
+
raise ConfigurationError(
|
|
76
|
+
message=f"Conflicting paths: {first} and {second}",
|
|
77
|
+
error_code="FILE_PATH_CONFLICT"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def main(argv: list[str] | None = None) -> int:
|
|
82
|
+
logging.basicConfig(
|
|
83
|
+
level=logging.INFO,
|
|
84
|
+
format="%(levelname)s: %(message)s"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
parser = _build_parser()
|
|
88
|
+
args = parser.parse_args(argv)
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
_validate_paths(args)
|
|
92
|
+
|
|
93
|
+
schema = load_schema(args.schema)
|
|
94
|
+
|
|
95
|
+
validate_config(
|
|
96
|
+
max_record_size=args.max_record_size,
|
|
97
|
+
schema=schema,
|
|
98
|
+
data_path=args.input,
|
|
99
|
+
error_path=args.errors
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
validate_config(
|
|
103
|
+
max_record_size=args.max_record_size,
|
|
104
|
+
schema=schema,
|
|
105
|
+
data_path=args.input,
|
|
106
|
+
error_path=args.output
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
pipeline = Pipeline([
|
|
110
|
+
Batch(batch_size=args.batch_size)
|
|
111
|
+
])
|
|
112
|
+
|
|
113
|
+
records = load_jsonl(
|
|
114
|
+
args.input,
|
|
115
|
+
args.errors,
|
|
116
|
+
args.max_record_size,
|
|
117
|
+
schema
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
written = 0
|
|
121
|
+
|
|
122
|
+
logger.info("Processing started.")
|
|
123
|
+
|
|
124
|
+
with closing(records) as source:
|
|
125
|
+
with open(args.output, "w", encoding="utf-8") as output:
|
|
126
|
+
for batch in pipeline.transform(source):
|
|
127
|
+
for record in batch:
|
|
128
|
+
output.write(
|
|
129
|
+
json.dumps(record, ensure_ascii=False) + "\n"
|
|
130
|
+
)
|
|
131
|
+
written += 1
|
|
132
|
+
|
|
133
|
+
with open(args.errors, "r", encoding="utf-8") as errors:
|
|
134
|
+
rejected = sum(1 for _ in errors)
|
|
135
|
+
|
|
136
|
+
logger.info("Processing completed.")
|
|
137
|
+
logger.info("Total records: %d", written + rejected)
|
|
138
|
+
logger.info("Accepted records: %d", written)
|
|
139
|
+
logger.info("Rejected records: %d", rejected)
|
|
140
|
+
|
|
141
|
+
return 0
|
|
142
|
+
|
|
143
|
+
except ConfigurationError as exc:
|
|
144
|
+
logger.error("%s: %s", exc.error_code, exc)
|
|
145
|
+
return 1
|
|
146
|
+
|
|
147
|
+
except (OSError, ValueError) as exc:
|
|
148
|
+
logger.error("Processing failed: %s", exc)
|
|
149
|
+
return 1
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
if __name__ == "__main__":
|
|
153
|
+
raise SystemExit(main())
|
trickle/exceptions.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class TrickleError(Exception):
|
|
5
|
+
def __init__(self, message: str, value: Any) -> None:
|
|
6
|
+
super().__init__()
|
|
7
|
+
self.message = message
|
|
8
|
+
self.value = value
|
|
9
|
+
|
|
10
|
+
def __str__(self):
|
|
11
|
+
return f"{self.message} (Value: {self.value})"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SchemaValidationError(TrickleError):
|
|
15
|
+
def __init__(self, message: str, error_code: Any):
|
|
16
|
+
super().__init__(message, error_code)
|
|
17
|
+
self.error_code = error_code
|
|
18
|
+
|
|
19
|
+
def __str__(self):
|
|
20
|
+
return super().__str__()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ConfigurationError(TrickleError):
|
|
24
|
+
def __init__(self, message, error_code):
|
|
25
|
+
super().__init__(message, error_code)
|
|
26
|
+
self.error_code = error_code
|
|
27
|
+
|
|
28
|
+
def __str__(self):
|
|
29
|
+
return super().__str__()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PredictionError(TrickleError):
|
|
33
|
+
def __init__(self, message: str, error_code):
|
|
34
|
+
super().__init__(message, error_code)
|
|
35
|
+
self.error_code = error_code
|
|
36
|
+
|
|
37
|
+
def __str__(self):
|
|
38
|
+
return super().__str__()
|
trickle/inference.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from trickle.protocols import ModelProtocol
|
|
2
|
+
from collections.abc import Iterable, Iterator
|
|
3
|
+
from typing import Any
|
|
4
|
+
from trickle.exceptions import PredictionError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class InferenceEngine():
|
|
8
|
+
def __init__(self, model: ModelProtocol):
|
|
9
|
+
self.model = model
|
|
10
|
+
|
|
11
|
+
def predict(self, batches: Iterable[list[Any]]) -> Iterator[list[Any]]:
|
|
12
|
+
for batch in batches:
|
|
13
|
+
prediction = self.model.predict(batch)
|
|
14
|
+
if not isinstance(prediction, list):
|
|
15
|
+
raise PredictionError(
|
|
16
|
+
message="Prediction must be a list.",
|
|
17
|
+
error_code="INVALID_PREDICTION_TYPE"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
if len(prediction) != len(batch):
|
|
21
|
+
raise PredictionError(
|
|
22
|
+
message="Prediction count does not match batch size.",
|
|
23
|
+
error_code="PREDICTION_COUNT_MISMATCH"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
yield prediction
|
trickle/load.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from .validation import validate_schema, validate_config
|
|
3
|
+
from .exceptions import SchemaValidationError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def load_jsonl(
|
|
7
|
+
data_path: str,
|
|
8
|
+
error_path: str,
|
|
9
|
+
max_record_size: int,
|
|
10
|
+
schema: dict
|
|
11
|
+
):
|
|
12
|
+
validate_config(max_record_size, schema, data_path, error_path)
|
|
13
|
+
with open(data_path, "rb") as df:
|
|
14
|
+
with open(error_path, "w") as ef:
|
|
15
|
+
line = 1
|
|
16
|
+
raw_data = None
|
|
17
|
+
while raw_data := df.readline(max_record_size + 1):
|
|
18
|
+
if len(raw_data) == max_record_size + 1:
|
|
19
|
+
total_size = len(raw_data)
|
|
20
|
+
if not raw_data.endswith(b'\n'):
|
|
21
|
+
while tmp := df.readline(max_record_size):
|
|
22
|
+
total_size += len(tmp)
|
|
23
|
+
if tmp.endswith(b'\n'):
|
|
24
|
+
break
|
|
25
|
+
json.dump({
|
|
26
|
+
"line_number": line,
|
|
27
|
+
"actual_size": total_size,
|
|
28
|
+
"max_record_size": max_record_size,
|
|
29
|
+
"error_code": "RECORD_TOO_LARGE",
|
|
30
|
+
}, ef)
|
|
31
|
+
ef.write("\n")
|
|
32
|
+
else:
|
|
33
|
+
try:
|
|
34
|
+
record = json.loads(raw_data.decode("utf-8"))
|
|
35
|
+
validate_schema(record, schema)
|
|
36
|
+
yield record
|
|
37
|
+
except json.JSONDecodeError as e:
|
|
38
|
+
json.dump(
|
|
39
|
+
{
|
|
40
|
+
"line_number": line,
|
|
41
|
+
"error_code": "INVALID_JSON",
|
|
42
|
+
"error": str(e)
|
|
43
|
+
}, ef
|
|
44
|
+
)
|
|
45
|
+
ef.write("\n")
|
|
46
|
+
except UnicodeDecodeError as e:
|
|
47
|
+
json.dump(
|
|
48
|
+
{
|
|
49
|
+
"line_number": line,
|
|
50
|
+
"error_code": "INVALID_ENCODING",
|
|
51
|
+
"error": str(e)
|
|
52
|
+
}, ef
|
|
53
|
+
)
|
|
54
|
+
ef.write("\n")
|
|
55
|
+
except SchemaValidationError as e:
|
|
56
|
+
json.dump(
|
|
57
|
+
{
|
|
58
|
+
"line_number": line,
|
|
59
|
+
"raw_data": record,
|
|
60
|
+
"error_code": e.error_code,
|
|
61
|
+
"error": str(e)
|
|
62
|
+
}, ef
|
|
63
|
+
)
|
|
64
|
+
ef.write("\n")
|
|
65
|
+
line += 1
|
trickle/pipeline.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from trickle.protocols import Transform
|
|
2
|
+
from typing import Iterator, Iterable
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Pipeline():
|
|
6
|
+
def __init__(self, transforms: list[Transform]):
|
|
7
|
+
self.transforms = transforms.copy()
|
|
8
|
+
|
|
9
|
+
def transform(self, records: Iterable) -> Iterator:
|
|
10
|
+
records = iter(records)
|
|
11
|
+
for transform in self.transforms:
|
|
12
|
+
records = transform.transform(records)
|
|
13
|
+
return records
|
trickle/protocols.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from typing import Protocol, Any
|
|
2
|
+
from collections.abc import Iterable, Iterator
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Transform(Protocol):
|
|
6
|
+
def transform(self, records: Iterable) -> Iterator:
|
|
7
|
+
...
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ModelProtocol(Protocol):
|
|
11
|
+
def predict(self, batch: list[Any]) -> list[Any]:
|
|
12
|
+
...
|
|
13
|
+
|
|
14
|
+
def metadata() -> dict[str, Any]:
|
|
15
|
+
...
|
trickle/schema.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from trickle.exceptions import ConfigurationError
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
TYPE_REGISTRY = {
|
|
6
|
+
"int": int,
|
|
7
|
+
"str": str,
|
|
8
|
+
"float": float,
|
|
9
|
+
"bool": bool,
|
|
10
|
+
"list": list,
|
|
11
|
+
"dict": dict,
|
|
12
|
+
"null": type(None)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_schema(path: str | None) -> dict[str, type]:
|
|
17
|
+
if path is None:
|
|
18
|
+
return {}
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
22
|
+
schema = json.load(f)
|
|
23
|
+
|
|
24
|
+
if not isinstance(schema, dict):
|
|
25
|
+
raise ConfigurationError(
|
|
26
|
+
message="Schema must be a JSON object.",
|
|
27
|
+
error_code="INVALID_SCHEMA"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
for k, v in schema.items():
|
|
31
|
+
if not isinstance(v, str) or v not in TYPE_REGISTRY:
|
|
32
|
+
raise ConfigurationError(
|
|
33
|
+
message="Invalid schema type.",
|
|
34
|
+
error_code="INVALID_SCHEMA_TYPE"
|
|
35
|
+
)
|
|
36
|
+
schema[k] = TYPE_REGISTRY[v]
|
|
37
|
+
|
|
38
|
+
return schema
|
|
39
|
+
|
|
40
|
+
except TypeError:
|
|
41
|
+
raise ConfigurationError(
|
|
42
|
+
message="Invalid path of schema file.",
|
|
43
|
+
error_code="INVALID_PATH"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
except FileNotFoundError:
|
|
47
|
+
raise ConfigurationError(
|
|
48
|
+
message="Schema file not found.",
|
|
49
|
+
error_code="SCHEMA_FILE_NOT_FOUND"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
except json.JSONDecodeError:
|
|
53
|
+
raise ConfigurationError(
|
|
54
|
+
message="Invalid schema json.",
|
|
55
|
+
error_code="INVALID_SCHEMA_JSON"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
except UnicodeDecodeError:
|
|
59
|
+
raise ConfigurationError(
|
|
60
|
+
message="Schema cannot read.",
|
|
61
|
+
error_code="SCHEMA_READ_ERROR"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
except OSError:
|
|
65
|
+
raise ConfigurationError(
|
|
66
|
+
message="Schema cannot read.",
|
|
67
|
+
error_code="SCHEMA_READ_ERROR"
|
|
68
|
+
)
|
trickle/transforms.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from collections.abc import Callable, Iterable, Iterator, Hashable
|
|
2
|
+
from typing import Any
|
|
3
|
+
from trickle.exceptions import ConfigurationError
|
|
4
|
+
from collections import deque
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Filter():
|
|
8
|
+
def __init__(self, predicate: Callable[[Any], bool]):
|
|
9
|
+
if callable(predicate):
|
|
10
|
+
self.predicate = predicate
|
|
11
|
+
else:
|
|
12
|
+
raise ConfigurationError(
|
|
13
|
+
message="Predicate is not callable.",
|
|
14
|
+
error_code="INVALID_PREDICATE"
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
def transform(self, records: Iterable) -> Iterator:
|
|
18
|
+
for record in records:
|
|
19
|
+
if self.predicate(record):
|
|
20
|
+
yield record
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Map():
|
|
24
|
+
def __init__(self, mapper: Callable[[Any], Any]):
|
|
25
|
+
if callable(mapper):
|
|
26
|
+
self.mapper = mapper
|
|
27
|
+
else:
|
|
28
|
+
raise ConfigurationError(
|
|
29
|
+
message="Mapper is not callable.",
|
|
30
|
+
error_code="INVALID_MAPPER"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def transform(self, records: Iterable) -> Iterator:
|
|
34
|
+
for record in records:
|
|
35
|
+
yield self.mapper(record)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Batch():
|
|
39
|
+
def __init__(self, batch_size: int):
|
|
40
|
+
if type(batch_size) is int and batch_size > 0:
|
|
41
|
+
self.batch_size = batch_size
|
|
42
|
+
else:
|
|
43
|
+
raise ConfigurationError(
|
|
44
|
+
message="Batch size must be positive integer.",
|
|
45
|
+
error_code="INVALID_BATCH_SIZE"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def transform(self, records: Iterable) -> Iterator:
|
|
49
|
+
batch = []
|
|
50
|
+
for record in records:
|
|
51
|
+
batch.append(record)
|
|
52
|
+
if len(batch) == self.batch_size:
|
|
53
|
+
yield batch
|
|
54
|
+
batch = []
|
|
55
|
+
if batch:
|
|
56
|
+
yield batch
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Dedup():
|
|
60
|
+
def __init__(self, key: Callable[[Any], Hashable], window_size):
|
|
61
|
+
if callable(key):
|
|
62
|
+
self.key = key
|
|
63
|
+
else:
|
|
64
|
+
raise ConfigurationError(
|
|
65
|
+
message="Key is not callable.",
|
|
66
|
+
error_code="INVALID_KEY"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
if type(window_size) is int and window_size > 0:
|
|
70
|
+
self.window_size = window_size
|
|
71
|
+
else:
|
|
72
|
+
raise ConfigurationError(
|
|
73
|
+
message="Window size must be positive integer.",
|
|
74
|
+
error_code="INVALID_WINDOW_SIZE"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
def transform(self, records: Iterable) -> Iterator:
|
|
78
|
+
seen = set()
|
|
79
|
+
window = deque()
|
|
80
|
+
|
|
81
|
+
for record in records:
|
|
82
|
+
record_key = self.key(record)
|
|
83
|
+
if record_key in seen:
|
|
84
|
+
continue
|
|
85
|
+
if len(window) >= self.window_size:
|
|
86
|
+
old_key = window.popleft()
|
|
87
|
+
seen.remove(old_key)
|
|
88
|
+
|
|
89
|
+
window.append(record_key)
|
|
90
|
+
seen.add(record_key)
|
|
91
|
+
yield record
|
trickle/validation.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from .exceptions import SchemaValidationError, ConfigurationError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def validate_schema(record, schema):
|
|
8
|
+
items = schema.keys()
|
|
9
|
+
|
|
10
|
+
if type(record) is not dict:
|
|
11
|
+
raise SchemaValidationError(
|
|
12
|
+
message="Record must be a dictionary.",
|
|
13
|
+
error_code="INVALID_RECORD_TYPE"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
if not (set(items).issubset(record)):
|
|
17
|
+
raise SchemaValidationError(
|
|
18
|
+
message="Missing field in record.",
|
|
19
|
+
error_code="MISSING_FIELD"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
if not (all(type(record[k]) is schema[k] for k in items)):
|
|
23
|
+
raise SchemaValidationError(
|
|
24
|
+
message="Field type mismatch in record.",
|
|
25
|
+
error_code="INVALID_TYPE",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def validate_config(
|
|
30
|
+
max_record_size,
|
|
31
|
+
schema,
|
|
32
|
+
data_path,
|
|
33
|
+
error_path
|
|
34
|
+
):
|
|
35
|
+
try:
|
|
36
|
+
data_file = Path(data_path)
|
|
37
|
+
error_file = Path(error_path)
|
|
38
|
+
except TypeError:
|
|
39
|
+
raise ConfigurationError(
|
|
40
|
+
message="Invalid path of data or error file.",
|
|
41
|
+
error_code="INVALID_PATH"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
if type(max_record_size) is not int or max_record_size <= 0:
|
|
45
|
+
raise ConfigurationError(
|
|
46
|
+
message="Invalid max record size.",
|
|
47
|
+
error_code="INVALID_MAX_RECORD_SIZE"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
if type(schema) is not dict:
|
|
51
|
+
raise ConfigurationError(
|
|
52
|
+
message="Invalid schema.",
|
|
53
|
+
error_code="INVALID_SCHEMA"
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
if not all(type(k) is str for k in schema.keys()):
|
|
57
|
+
raise ConfigurationError(
|
|
58
|
+
message="Invalid schema key.",
|
|
59
|
+
error_code="INVALID_SCHEMA_KEY"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
if not all(isinstance(v, type) for v in schema.values()):
|
|
63
|
+
raise ConfigurationError(
|
|
64
|
+
message="Invalid schema type.",
|
|
65
|
+
error_code="INVALID_SCHEMA_TYPE"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
if not data_file.exists():
|
|
69
|
+
raise ConfigurationError(
|
|
70
|
+
message="Input file path not found.",
|
|
71
|
+
error_code="INPUT_FILE_NOT_FOUND"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
if not data_file.is_file():
|
|
75
|
+
raise ConfigurationError(
|
|
76
|
+
message="Invalid input file.",
|
|
77
|
+
error_code="INVALID_INPUT_PATH"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
if not error_file.parent.is_dir():
|
|
81
|
+
raise ConfigurationError(
|
|
82
|
+
message="Invalid output file path.",
|
|
83
|
+
error_code="INVALID_OUTPUT_PATH"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
if error_file.exists():
|
|
87
|
+
if not (error_file.is_file()):
|
|
88
|
+
raise ConfigurationError(
|
|
89
|
+
message="Invalid output file.",
|
|
90
|
+
error_code="INVALID_OUTPUT_FILE"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
if os.path.samefile(error_file, data_file):
|
|
94
|
+
raise ConfigurationError(
|
|
95
|
+
message="Output file path and input file path are same.",
|
|
96
|
+
error_code="FILE_PATH_CONFLICT"
|
|
97
|
+
)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tricklepy
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight library for memory-efficient data processing and AI model contracts.
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Provides-Extra: dev
|
|
8
|
+
Requires-Dist: pytest; extra == "dev"
|
|
9
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
trickle/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
trickle/adapters.py,sha256=-o_WJwPJnsVjSDI9ripAo75748Z3rbn1O_Nmlh2hCc8,2411
|
|
3
|
+
trickle/cli.py,sha256=pyuQ8n4hYsEBnMtA7bgibkufCnTQgNSvbVa1OpmZTSM,3899
|
|
4
|
+
trickle/exceptions.py,sha256=2IjeGV2PP6wTwtpXN13Iqkm7wFvE_iybUj2iyJjJI3g,974
|
|
5
|
+
trickle/inference.py,sha256=Q84nLyphYZuu162lZp0fTfvHjY8dBU2J8xjFhq1SfQQ,908
|
|
6
|
+
trickle/load.py,sha256=fMOw2-Ok1h7DiLlwEs9M84uEDReV9d1yCpNa1jMMKa4,2586
|
|
7
|
+
trickle/pipeline.py,sha256=XH5L1pPi-gqSLlRye-dtgZA2w-txOjwggN596yFhtuc,400
|
|
8
|
+
trickle/protocols.py,sha256=5qf6C3BJ_IddNADd1QWE-doJghh72CQ3e3aePPH9lWU,327
|
|
9
|
+
trickle/schema.py,sha256=HqCpKZerqLNE7LncbRI0yw0olu0HviEix4vdFz9Ln3E,1736
|
|
10
|
+
trickle/transforms.py,sha256=L8G6xHrqKezrySj-dRzsi8EeyrlGwdiHHA_PswXiGJ8,2710
|
|
11
|
+
trickle/validation.py,sha256=OB2bvJTwzhBVVDqqS2EJHcDrqji4sXHrGwWWBN6gdh8,2766
|
|
12
|
+
tricklepy-0.1.0.dist-info/licenses/LICENSE,sha256=FK5FHyoMXPGUxPDrGeAQDdzThyCkkyULk4ydIvxW6R4,1070
|
|
13
|
+
tricklepy-0.1.0.dist-info/METADATA,sha256=fYZ8L5rv1fh9c932YxcqOk6BfixNSZo2y2zT6wzeLvo,271
|
|
14
|
+
tricklepy-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
15
|
+
tricklepy-0.1.0.dist-info/entry_points.txt,sha256=COAlSeXJEOIDreeLiOJWCDX13HYAJEDLuhbMiBP6YVo,45
|
|
16
|
+
tricklepy-0.1.0.dist-info/top_level.txt,sha256=3rBtoJyH9ZBqOXTnPZa_c2RtW-X2eOpV__MXXwAue2M,8
|
|
17
|
+
tricklepy-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Caner Çakır
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
trickle
|