tricklepy 0.1.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.
- tricklepy-0.1.0/LICENSE +21 -0
- tricklepy-0.1.0/PKG-INFO +9 -0
- tricklepy-0.1.0/README.md +272 -0
- tricklepy-0.1.0/pyproject.toml +24 -0
- tricklepy-0.1.0/setup.cfg +4 -0
- tricklepy-0.1.0/src/trickle/__init__.py +0 -0
- tricklepy-0.1.0/src/trickle/adapters.py +80 -0
- tricklepy-0.1.0/src/trickle/cli.py +153 -0
- tricklepy-0.1.0/src/trickle/exceptions.py +38 -0
- tricklepy-0.1.0/src/trickle/inference.py +26 -0
- tricklepy-0.1.0/src/trickle/load.py +65 -0
- tricklepy-0.1.0/src/trickle/pipeline.py +13 -0
- tricklepy-0.1.0/src/trickle/protocols.py +15 -0
- tricklepy-0.1.0/src/trickle/schema.py +68 -0
- tricklepy-0.1.0/src/trickle/transforms.py +91 -0
- tricklepy-0.1.0/src/trickle/validation.py +97 -0
- tricklepy-0.1.0/src/tricklepy.egg-info/PKG-INFO +9 -0
- tricklepy-0.1.0/src/tricklepy.egg-info/SOURCES.txt +28 -0
- tricklepy-0.1.0/src/tricklepy.egg-info/dependency_links.txt +1 -0
- tricklepy-0.1.0/src/tricklepy.egg-info/entry_points.txt +2 -0
- tricklepy-0.1.0/src/tricklepy.egg-info/requires.txt +3 -0
- tricklepy-0.1.0/src/tricklepy.egg-info/top_level.txt +1 -0
- tricklepy-0.1.0/tests/test_adapters.py +139 -0
- tricklepy-0.1.0/tests/test_cli.py +153 -0
- tricklepy-0.1.0/tests/test_config.py +139 -0
- tricklepy-0.1.0/tests/test_inference.py +222 -0
- tricklepy-0.1.0/tests/test_pipeline.py +147 -0
- tricklepy-0.1.0/tests/test_reader.py +378 -0
- tricklepy-0.1.0/tests/test_transforms.py +265 -0
- tricklepy-0.1.0/tests/test_validation.py +138 -0
tricklepy-0.1.0/LICENSE
ADDED
|
@@ -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.
|
tricklepy-0.1.0/PKG-INFO
ADDED
|
@@ -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,272 @@
|
|
|
1
|
+
# Trickle
|
|
2
|
+
|
|
3
|
+
Stream, validate and transform large JSONL datasets with bounded
|
|
4
|
+
memory usage.
|
|
5
|
+
|
|
6
|
+
Pure Python. Zero runtime dependencies. Pluggable model contracts.
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Trickle is a lightweight streaming data processing and inference
|
|
11
|
+
library designed for memory-efficient machine learning workflows.
|
|
12
|
+
|
|
13
|
+
Instead of loading entire datasets into memory, Trickle processes
|
|
14
|
+
records lazily through composable transformation pipelines and
|
|
15
|
+
model-independent inference interfaces.
|
|
16
|
+
|
|
17
|
+
## Features
|
|
18
|
+
|
|
19
|
+
- Memory-efficient JSONL streaming
|
|
20
|
+
- Schema and configuration validation
|
|
21
|
+
- Record size limits
|
|
22
|
+
- Structured error reporting
|
|
23
|
+
- Composable transformation pipelines
|
|
24
|
+
- Filter, Map, Batch and bounded Dedup transformations
|
|
25
|
+
- Model-independent batch inference
|
|
26
|
+
- Extensible model adapters
|
|
27
|
+
- Command-line interface
|
|
28
|
+
- Zero third-party runtime dependencies
|
|
29
|
+
- 138 passing automated tests
|
|
30
|
+
|
|
31
|
+
## Architecture
|
|
32
|
+
|
|
33
|
+
```mermaid
|
|
34
|
+
flowchart TD
|
|
35
|
+
A[JSONL Dataset] --> B[Streaming Reader]
|
|
36
|
+
B --> C[Schema Validation]
|
|
37
|
+
C -->|Invalid| D[Error Stream]
|
|
38
|
+
C -->|Valid| E[Transform Pipeline]
|
|
39
|
+
E --> F[Filter]
|
|
40
|
+
F --> G[Map]
|
|
41
|
+
G --> H[Dedup]
|
|
42
|
+
H --> I[Batch]
|
|
43
|
+
I --> J[Inference Engine]
|
|
44
|
+
J --> K[ModelProtocol]
|
|
45
|
+
K --> L[CallableAdapter]
|
|
46
|
+
K --> M[BatchPredictAdapter]
|
|
47
|
+
K --> N[Custom Model]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
Clone the repository and install the package locally:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install .
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
For development:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install -e ".[dev]"
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## CLI Usage
|
|
65
|
+
|
|
66
|
+
Create a schema.json file:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{
|
|
70
|
+
"id": "int",
|
|
71
|
+
"text": "str"
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Run Trickle:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
trickle \
|
|
79
|
+
--input dataset.jsonl \
|
|
80
|
+
--output output.jsonl \
|
|
81
|
+
--errors errors.jsonl \
|
|
82
|
+
--schema schema.json \
|
|
83
|
+
--batch-size 32
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The CLI streams valid records into the output file and writes
|
|
87
|
+
rejected records into a separate error file.
|
|
88
|
+
|
|
89
|
+
## Python API
|
|
90
|
+
|
|
91
|
+
### Streaming and transformation
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from contextlib import closing
|
|
95
|
+
|
|
96
|
+
from trickle.load import load_jsonl
|
|
97
|
+
from trickle.pipeline import Pipeline
|
|
98
|
+
from trickle.transforms import Filter, Map, Dedup, Batch
|
|
99
|
+
|
|
100
|
+
schema = {
|
|
101
|
+
"id": int,
|
|
102
|
+
"text": str
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
pipeline = Pipeline([
|
|
106
|
+
Filter(lambda r: bool(r["text"].strip())),
|
|
107
|
+
Map(lambda r: r["text"].lower()),
|
|
108
|
+
Dedup(key=lambda text: text, window_size=1000),
|
|
109
|
+
Batch(batch_size=32)
|
|
110
|
+
])
|
|
111
|
+
|
|
112
|
+
with closing(
|
|
113
|
+
load_jsonl(
|
|
114
|
+
"dataset.jsonl",
|
|
115
|
+
"errors.jsonl",
|
|
116
|
+
65536,
|
|
117
|
+
schema
|
|
118
|
+
)
|
|
119
|
+
) as records:
|
|
120
|
+
for batch in pipeline.transform(records):
|
|
121
|
+
print(batch)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Model inference
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from trickle.adapters import CallableAdapter
|
|
128
|
+
from trickle.inference import InferenceEngine
|
|
129
|
+
from trickle.pipeline import Pipeline
|
|
130
|
+
from trickle.transforms import Batch
|
|
131
|
+
|
|
132
|
+
model = CallableAdapter(
|
|
133
|
+
predictor=lambda x: x ** 2,
|
|
134
|
+
name="square_model"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
pipeline = Pipeline([
|
|
138
|
+
Batch(batch_size=3)
|
|
139
|
+
])
|
|
140
|
+
|
|
141
|
+
engine = InferenceEngine(model)
|
|
142
|
+
|
|
143
|
+
batches = pipeline.transform(range(1, 9))
|
|
144
|
+
|
|
145
|
+
for predictions in engine.predict(batches):
|
|
146
|
+
print(predictions)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Output:
|
|
150
|
+
|
|
151
|
+
```text
|
|
152
|
+
[1, 4, 9]
|
|
153
|
+
[16, 25, 36]
|
|
154
|
+
[49, 64]
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## API Contract
|
|
158
|
+
|
|
159
|
+
### Transform
|
|
160
|
+
|
|
161
|
+
A transformation consumes an iterable and returns an iterator.
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
transform(records: Iterable) -> Iterator
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Transformations are composed sequentially using Pipeline.
|
|
168
|
+
|
|
169
|
+
### ModelProtocol
|
|
170
|
+
|
|
171
|
+
Models must implement the following methods:
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
predict(batch: list[Any]) -> list[Any]
|
|
175
|
+
metadata() -> dict[str, Any]
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Predictions must preserve input order and contain exactly one
|
|
179
|
+
result per input record.
|
|
180
|
+
|
|
181
|
+
Models do not need to inherit from Trickle's adapter classes.
|
|
182
|
+
|
|
183
|
+
### Error Handling
|
|
184
|
+
|
|
185
|
+
Trickle uses structured exceptions and machine-readable
|
|
186
|
+
error codes for configuration, schema validation and
|
|
187
|
+
prediction contract failures.
|
|
188
|
+
|
|
189
|
+
Invalid input records are written into a separate JSONL
|
|
190
|
+
error stream.
|
|
191
|
+
|
|
192
|
+
## Benchmarks
|
|
193
|
+
|
|
194
|
+
Benchmarks were executed on Apple Silicon using Python 3.14.7.
|
|
195
|
+
|
|
196
|
+
| Metric | 100K Records | 1M Records |
|
|
197
|
+
|---|---:|---:|
|
|
198
|
+
| Dataset size | 4.28 MiB | 43.59 MiB |
|
|
199
|
+
| Execution time | 0.285 s | 2.695 s |
|
|
200
|
+
| Peak traced memory | 0.659 MiB | 0.754 MiB |
|
|
201
|
+
| Records per second | 351,323 | 371,020 |
|
|
202
|
+
| Accepted records | 80,000 | 800,000 |
|
|
203
|
+
| Rejected records | 20,000 | 200,000 |
|
|
204
|
+
|
|
205
|
+
Increasing the record count by 10x resulted in:
|
|
206
|
+
|
|
207
|
+
- 1.14x peak traced memory
|
|
208
|
+
- 9.47x execution time
|
|
209
|
+
- Exact agreement with expected record counts
|
|
210
|
+
|
|
211
|
+
These results support bounded-memory and approximately
|
|
212
|
+
linear-time processing under fixed configuration.
|
|
213
|
+
|
|
214
|
+
Memory was measured using tracemalloc and represents traced
|
|
215
|
+
Python allocations, not total process RSS.
|
|
216
|
+
|
|
217
|
+
Timing and memory measurements were performed separately.
|
|
218
|
+
Results are based on a single benchmark execution using
|
|
219
|
+
deterministic synthetic datasets.
|
|
220
|
+
|
|
221
|
+
Raw results are available in benchmarks/results.json.
|
|
222
|
+
|
|
223
|
+
Reproduce the benchmark:
|
|
224
|
+
|
|
225
|
+
```bash
|
|
226
|
+
python benchmarks/benchmark.py
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## Testing
|
|
230
|
+
|
|
231
|
+
```bash
|
|
232
|
+
python -m pytest -v
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Current test suite:
|
|
236
|
+
|
|
237
|
+
138 passed
|
|
238
|
+
|
|
239
|
+
Tests cover:
|
|
240
|
+
|
|
241
|
+
- JSONL streaming and error recovery
|
|
242
|
+
- Schema and configuration validation
|
|
243
|
+
- Generator cleanup
|
|
244
|
+
- Lazy evaluation
|
|
245
|
+
- Transformation composition
|
|
246
|
+
- Mutable state isolation
|
|
247
|
+
- Model interchangeability
|
|
248
|
+
- Prediction contract enforcement
|
|
249
|
+
- CLI and end-to-end integration
|
|
250
|
+
|
|
251
|
+
## Known Limitations
|
|
252
|
+
|
|
253
|
+
- JSONL is the only supported dataset format.
|
|
254
|
+
- Schema validation supports basic Python types.
|
|
255
|
+
- Deduplication uses a bounded FIFO window rather than
|
|
256
|
+
global deduplication.
|
|
257
|
+
- Processing is synchronous.
|
|
258
|
+
- CLI inference is not currently supported.
|
|
259
|
+
- Model inference is available through the Python API.
|
|
260
|
+
- Output files may contain partial results after failures.
|
|
261
|
+
- Existing output files may be overwritten.
|
|
262
|
+
- Memory usage also depends on user-defined transformations
|
|
263
|
+
and model implementations.
|
|
264
|
+
|
|
265
|
+
## Data Sources
|
|
266
|
+
|
|
267
|
+
Benchmark datasets are generated synthetically.
|
|
268
|
+
No external datasets are required.
|
|
269
|
+
|
|
270
|
+
## License
|
|
271
|
+
|
|
272
|
+
See LICENSE for details.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tricklepy"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A lightweight library for memory-efficient data processing and AI model contracts."
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
dependencies = []
|
|
11
|
+
|
|
12
|
+
[project.optional-dependencies]
|
|
13
|
+
dev = ["pytest"]
|
|
14
|
+
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
where = ["src"]
|
|
17
|
+
|
|
18
|
+
[tool.pytest.ini_options]
|
|
19
|
+
testpaths = ["tests"]
|
|
20
|
+
python_files = ["test_*.py"]
|
|
21
|
+
python_functions = ["test_*"]
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
trickle = "trickle.cli:main"
|
|
File without changes
|
|
@@ -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
|
|
@@ -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())
|
|
@@ -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__()
|
|
@@ -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
|
|
@@ -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
|