damicore-normalizer 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.
- damicore_normalizer/__init__.py +12 -0
- damicore_normalizer/api.py +99 -0
- damicore_normalizer/config.py +31 -0
- damicore_normalizer/csv_reader.py +251 -0
- damicore_normalizer/errors.py +10 -0
- damicore_normalizer/manifest.py +52 -0
- damicore_normalizer/py.typed +0 -0
- damicore_normalizer/serializer.py +14 -0
- damicore_normalizer-0.1.0.dist-info/METADATA +66 -0
- damicore_normalizer-0.1.0.dist-info/RECORD +12 -0
- damicore_normalizer-0.1.0.dist-info/WHEEL +4 -0
- damicore_normalizer-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from damicore_normalizer.api import normalize_csv
|
|
2
|
+
from damicore_normalizer.config import NormalizationConfig
|
|
3
|
+
from damicore_normalizer.errors import NormalizerError
|
|
4
|
+
from damicore_normalizer.manifest import NormalizationResult, ObjectDescriptor
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"normalize_csv",
|
|
8
|
+
"NormalizationConfig",
|
|
9
|
+
"NormalizationResult",
|
|
10
|
+
"ObjectDescriptor",
|
|
11
|
+
"NormalizerError",
|
|
12
|
+
]
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from damicore_normalizer.config import NormalizationConfig
|
|
10
|
+
from damicore_normalizer.csv_reader import scan_csv
|
|
11
|
+
from damicore_normalizer.errors import NormalizerError
|
|
12
|
+
from damicore_normalizer.manifest import (
|
|
13
|
+
NormalizationInput,
|
|
14
|
+
NormalizationManifest,
|
|
15
|
+
NormalizationResult,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _sha256(path: Path, chunk_size: int = 4_194_304) -> str:
|
|
20
|
+
digest = hashlib.sha256()
|
|
21
|
+
with path.open("rb") as stream:
|
|
22
|
+
while chunk := stream.read(chunk_size):
|
|
23
|
+
digest.update(chunk)
|
|
24
|
+
return digest.hexdigest()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _atomic_json(path: Path, value: object) -> None:
|
|
28
|
+
payload = (
|
|
29
|
+
json.dumps(
|
|
30
|
+
value,
|
|
31
|
+
ensure_ascii=False,
|
|
32
|
+
indent=2,
|
|
33
|
+
sort_keys=True,
|
|
34
|
+
allow_nan=False,
|
|
35
|
+
)
|
|
36
|
+
+ "\n"
|
|
37
|
+
)
|
|
38
|
+
descriptor, temporary_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
|
|
39
|
+
try:
|
|
40
|
+
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
|
|
41
|
+
stream.write(payload)
|
|
42
|
+
stream.flush()
|
|
43
|
+
os.fsync(stream.fileno())
|
|
44
|
+
os.replace(temporary_name, path)
|
|
45
|
+
finally:
|
|
46
|
+
if os.path.exists(temporary_name):
|
|
47
|
+
os.unlink(temporary_name)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def normalize_csv(
|
|
51
|
+
csv_path: str | Path,
|
|
52
|
+
output_dir: str | Path,
|
|
53
|
+
*,
|
|
54
|
+
config: NormalizationConfig | None = None,
|
|
55
|
+
) -> NormalizationResult:
|
|
56
|
+
"""Normalize a local CSV into deterministic versioned object artifacts."""
|
|
57
|
+
settings = config or NormalizationConfig()
|
|
58
|
+
source = Path(csv_path).resolve()
|
|
59
|
+
if not source.is_file():
|
|
60
|
+
raise NormalizerError(
|
|
61
|
+
f"CSV path is not a regular file: {source}",
|
|
62
|
+
code="input_validation_error",
|
|
63
|
+
)
|
|
64
|
+
before = source.stat()
|
|
65
|
+
destination = Path(output_dir).resolve()
|
|
66
|
+
if destination.exists() and (not destination.is_dir() or any(destination.iterdir())):
|
|
67
|
+
raise NormalizerError("output_dir must be absent or empty", code="output_conflict_error")
|
|
68
|
+
destination.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
scan = scan_csv(source, settings, objects_dir=destination / "objects")
|
|
70
|
+
after = source.stat()
|
|
71
|
+
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
|
72
|
+
raise NormalizerError("CSV changed during normalization", code="input_drift")
|
|
73
|
+
for item in scan.objects:
|
|
74
|
+
object_path = destination / item.relative_path
|
|
75
|
+
if object_path.stat().st_size != item.size_bytes or _sha256(object_path) != item.sha256:
|
|
76
|
+
raise NormalizerError(
|
|
77
|
+
f"normalized object failed validation: {item.object_id}",
|
|
78
|
+
code="artifact_validation_error",
|
|
79
|
+
)
|
|
80
|
+
manifest_path = destination / "manifest.json"
|
|
81
|
+
manifest = NormalizationManifest(
|
|
82
|
+
schema_version=1,
|
|
83
|
+
input=NormalizationInput(
|
|
84
|
+
path=str(source),
|
|
85
|
+
sha256=_sha256(source),
|
|
86
|
+
size_bytes=before.st_size,
|
|
87
|
+
delimiter=settings.delimiter,
|
|
88
|
+
encoding=settings.encoding,
|
|
89
|
+
split=settings.split,
|
|
90
|
+
),
|
|
91
|
+
objects=scan.objects,
|
|
92
|
+
)
|
|
93
|
+
_atomic_json(manifest_path, manifest.model_dump(mode="json"))
|
|
94
|
+
return NormalizationResult(
|
|
95
|
+
manifest_path=manifest_path,
|
|
96
|
+
object_count=len(scan.objects),
|
|
97
|
+
total_bytes=scan.total_bytes,
|
|
98
|
+
objects=scan.objects,
|
|
99
|
+
)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import codecs
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class NormalizationConfig(BaseModel):
|
|
10
|
+
"""Configuration for deterministic CSV normalization."""
|
|
11
|
+
|
|
12
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
13
|
+
|
|
14
|
+
split: Literal["columns", "rows"] = "columns"
|
|
15
|
+
delimiter: str = ","
|
|
16
|
+
encoding: str = "utf-8"
|
|
17
|
+
chunk_rows: int = Field(default=50_000, gt=0)
|
|
18
|
+
max_open_files: int = Field(default=64, gt=0)
|
|
19
|
+
|
|
20
|
+
@field_validator("delimiter")
|
|
21
|
+
@classmethod
|
|
22
|
+
def _validate_delimiter(cls, value: str) -> str:
|
|
23
|
+
if len(value) != 1:
|
|
24
|
+
raise ValueError("delimiter must contain exactly one Unicode character")
|
|
25
|
+
return value
|
|
26
|
+
|
|
27
|
+
@field_validator("encoding")
|
|
28
|
+
@classmethod
|
|
29
|
+
def _validate_encoding(cls, value: str) -> str:
|
|
30
|
+
codecs.lookup(value)
|
|
31
|
+
return value
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import codecs
|
|
4
|
+
import csv
|
|
5
|
+
import hashlib
|
|
6
|
+
from collections import OrderedDict
|
|
7
|
+
from collections.abc import Generator
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import BinaryIO
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from damicore_normalizer.config import NormalizationConfig
|
|
16
|
+
from damicore_normalizer.errors import NormalizerError
|
|
17
|
+
from damicore_normalizer.manifest import ObjectDescriptor
|
|
18
|
+
from damicore_normalizer.serializer import serialize_cell, serialize_row
|
|
19
|
+
|
|
20
|
+
# A single field may be this many characters during the csv.reader passes. csv defaults to
|
|
21
|
+
# 131072, which pandas does not impose, so without this a well-formed wide cell would be
|
|
22
|
+
# reported as malformed. The value is a bound the C long behind field_size_limit accepts on
|
|
23
|
+
# every supported platform, not a contract: section 10.1 sets no field-size limit.
|
|
24
|
+
_MAX_FIELD_CHARS = 2**31 - 1
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _strip_bom(header: list[str], encoding: str) -> list[str]:
|
|
28
|
+
"""Drop a leading UTF-8 BOM from the first column name, as pandas' C parser does.
|
|
29
|
+
|
|
30
|
+
Python's ``utf-8`` codec keeps the BOM, so without this the two readers disagree on the
|
|
31
|
+
first name and the per-chunk header check rejects a well-formed file. Decoding through
|
|
32
|
+
``utf-8-sig`` instead would buffer past the header, which would misreport an undecodable
|
|
33
|
+
data row as a header failure.
|
|
34
|
+
"""
|
|
35
|
+
if not header or codecs.lookup(encoding).name != "utf-8":
|
|
36
|
+
return header
|
|
37
|
+
return [header[0].removeprefix("\ufeff"), *header[1:]]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@contextmanager
|
|
41
|
+
def _relaxed_field_size_limit() -> Generator[None]:
|
|
42
|
+
"""Lift csv's field-size cap for the duration of a validation pass.
|
|
43
|
+
|
|
44
|
+
The cap is process-global state, so it is restored on exit; the passes it wraps are
|
|
45
|
+
synchronous and do not run user code.
|
|
46
|
+
"""
|
|
47
|
+
previous = csv.field_size_limit(_MAX_FIELD_CHARS)
|
|
48
|
+
try:
|
|
49
|
+
yield
|
|
50
|
+
finally:
|
|
51
|
+
csv.field_size_limit(previous)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class ScanResult:
|
|
56
|
+
objects: tuple[ObjectDescriptor, ...]
|
|
57
|
+
total_bytes: int
|
|
58
|
+
max_serialized_chunk_bytes: int
|
|
59
|
+
row_count: int
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _FilePool:
|
|
63
|
+
def __init__(self, root: Path, limit: int) -> None:
|
|
64
|
+
self._root = root
|
|
65
|
+
self._limit = limit
|
|
66
|
+
self._streams: OrderedDict[str, BinaryIO] = OrderedDict()
|
|
67
|
+
|
|
68
|
+
def write(self, name: str, payload: bytes) -> None:
|
|
69
|
+
stream = self._streams.pop(name, None)
|
|
70
|
+
if stream is None:
|
|
71
|
+
if len(self._streams) >= self._limit:
|
|
72
|
+
_, oldest = self._streams.popitem(last=False)
|
|
73
|
+
oldest.close()
|
|
74
|
+
stream = (self._root / name).open("ab")
|
|
75
|
+
self._streams[name] = stream
|
|
76
|
+
stream.write(payload)
|
|
77
|
+
|
|
78
|
+
def close(self) -> None:
|
|
79
|
+
for stream in self._streams.values():
|
|
80
|
+
stream.close()
|
|
81
|
+
self._streams.clear()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _read_header(path: Path, config: NormalizationConfig) -> list[str]:
|
|
85
|
+
try:
|
|
86
|
+
with (
|
|
87
|
+
_relaxed_field_size_limit(),
|
|
88
|
+
path.open("r", encoding=config.encoding, errors="strict", newline="") as stream,
|
|
89
|
+
):
|
|
90
|
+
header = _strip_bom(
|
|
91
|
+
next(csv.reader(stream, delimiter=config.delimiter)), config.encoding
|
|
92
|
+
)
|
|
93
|
+
except (OSError, UnicodeError, csv.Error, StopIteration) as exc:
|
|
94
|
+
raise NormalizerError("Could not read a valid CSV header", code="csv_format_error") from exc
|
|
95
|
+
if not header or any(name == "" for name in header):
|
|
96
|
+
raise NormalizerError("CSV header names must be non-empty", code="csv_format_error")
|
|
97
|
+
if len(set(header)) != len(header):
|
|
98
|
+
raise NormalizerError("CSV header names must be unique", code="csv_format_error")
|
|
99
|
+
return header
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _validate_record_widths(path: Path, config: NormalizationConfig, width: int) -> None:
|
|
103
|
+
"""Reject any record whose field count disagrees with the mandatory header.
|
|
104
|
+
|
|
105
|
+
``on_bad_lines="error"`` cannot express this rule on its own. When every data row carries
|
|
106
|
+
surplus fields, the C parser reads the leading ones as an index and those cells disappear;
|
|
107
|
+
when only a later row does, the surplus is dropped or reported depending on where the chunk
|
|
108
|
+
boundary falls; a short row is padded with a cell the input never contained. The canonical
|
|
109
|
+
bytes would then depend on ``chunk_rows``, which section 24.1 forbids.
|
|
110
|
+
|
|
111
|
+
``csv.reader`` agrees with pandas on record boundaries and field counts once the two are
|
|
112
|
+
configured to match, so one streaming pass over the raw records makes the check total.
|
|
113
|
+
Two axes had to be aligned deliberately and are handled above: the BOM, which pandas
|
|
114
|
+
strips and this codec does not, and the field-size cap, which pandas does not impose. A
|
|
115
|
+
blank line is a third: ``skip_blank_lines=False`` defines it as a full-width empty row,
|
|
116
|
+
and pandas materializes it as one.
|
|
117
|
+
"""
|
|
118
|
+
try:
|
|
119
|
+
with (
|
|
120
|
+
_relaxed_field_size_limit(),
|
|
121
|
+
path.open("r", encoding=config.encoding, errors="strict", newline="") as stream,
|
|
122
|
+
):
|
|
123
|
+
reader = csv.reader(stream, delimiter=config.delimiter)
|
|
124
|
+
next(reader, None)
|
|
125
|
+
for number, record in enumerate(reader, start=2):
|
|
126
|
+
if record and len(record) != width:
|
|
127
|
+
raise NormalizerError(
|
|
128
|
+
f"CSV line {number} has {len(record)} fields but the header declares "
|
|
129
|
+
f"{width}",
|
|
130
|
+
code="csv_format_error",
|
|
131
|
+
)
|
|
132
|
+
except (OSError, UnicodeError, csv.Error) as exc:
|
|
133
|
+
raise NormalizerError("CSV parsing failed", code="csv_format_error") from exc
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def scan_csv(
|
|
137
|
+
csv_path: str | Path,
|
|
138
|
+
config: NormalizationConfig,
|
|
139
|
+
*,
|
|
140
|
+
objects_dir: Path | None = None,
|
|
141
|
+
) -> ScanResult:
|
|
142
|
+
"""Scan canonical object bytes; optionally persist them through the same path."""
|
|
143
|
+
path = Path(csv_path).resolve()
|
|
144
|
+
if not path.is_file():
|
|
145
|
+
raise NormalizerError(
|
|
146
|
+
f"CSV path is not a regular file: {path}",
|
|
147
|
+
code="input_validation_error",
|
|
148
|
+
)
|
|
149
|
+
header = _read_header(path, config)
|
|
150
|
+
if config.split == "columns" and len(header) < 2:
|
|
151
|
+
raise NormalizerError(
|
|
152
|
+
"columns split requires at least two columns",
|
|
153
|
+
code="csv_format_error",
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
# Structure is settled before anything is created, so a malformed CSV never leaves a
|
|
157
|
+
# partially written objects directory behind.
|
|
158
|
+
_validate_record_widths(path, config, len(header))
|
|
159
|
+
|
|
160
|
+
if objects_dir is not None:
|
|
161
|
+
objects_dir.mkdir(parents=True, exist_ok=False)
|
|
162
|
+
|
|
163
|
+
column_hashes = [hashlib.sha256() for _ in header]
|
|
164
|
+
column_sizes = [0 for _ in header]
|
|
165
|
+
row_objects: list[ObjectDescriptor] = []
|
|
166
|
+
max_chunk_bytes = 0
|
|
167
|
+
row_count = 0
|
|
168
|
+
pool = _FilePool(objects_dir, config.max_open_files) if objects_dir is not None else None
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
chunks = pd.read_csv(
|
|
172
|
+
path,
|
|
173
|
+
sep=config.delimiter,
|
|
174
|
+
encoding=config.encoding,
|
|
175
|
+
dtype=str,
|
|
176
|
+
keep_default_na=False,
|
|
177
|
+
na_filter=False,
|
|
178
|
+
skip_blank_lines=False,
|
|
179
|
+
chunksize=config.chunk_rows,
|
|
180
|
+
on_bad_lines="error",
|
|
181
|
+
quotechar='"',
|
|
182
|
+
doublequote=True,
|
|
183
|
+
comment=None,
|
|
184
|
+
# No inference of any kind, including an index inferred from row width. Records
|
|
185
|
+
# are already known to match the header, so this only pins the parser's contract.
|
|
186
|
+
index_col=False,
|
|
187
|
+
)
|
|
188
|
+
for chunk in chunks:
|
|
189
|
+
if list(chunk.columns) != header:
|
|
190
|
+
raise NormalizerError("CSV header changed while parsing", code="csv_format_error")
|
|
191
|
+
chunk_bytes = 0
|
|
192
|
+
for values in chunk.itertuples(index=False, name=None):
|
|
193
|
+
text_values = tuple(str(value) for value in values)
|
|
194
|
+
row_count += 1
|
|
195
|
+
if config.split == "rows":
|
|
196
|
+
payload = serialize_row(text_values)
|
|
197
|
+
object_id = f"row_{row_count:06d}"
|
|
198
|
+
relative_path = f"objects/{object_id}.jsonl"
|
|
199
|
+
digest = hashlib.sha256(payload).hexdigest()
|
|
200
|
+
row_objects.append(
|
|
201
|
+
ObjectDescriptor(
|
|
202
|
+
object_id=object_id,
|
|
203
|
+
label=object_id,
|
|
204
|
+
relative_path=relative_path,
|
|
205
|
+
size_bytes=len(payload),
|
|
206
|
+
sha256=digest,
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
if objects_dir is not None:
|
|
210
|
+
(objects_dir / f"{object_id}.jsonl").write_bytes(payload)
|
|
211
|
+
chunk_bytes += len(payload)
|
|
212
|
+
else:
|
|
213
|
+
for index, value in enumerate(text_values):
|
|
214
|
+
payload = serialize_cell(value)
|
|
215
|
+
column_hashes[index].update(payload)
|
|
216
|
+
column_sizes[index] += len(payload)
|
|
217
|
+
chunk_bytes += len(payload)
|
|
218
|
+
if pool is not None:
|
|
219
|
+
pool.write(f"column_{index + 1:06d}.jsonl", payload)
|
|
220
|
+
max_chunk_bytes = max(max_chunk_bytes, chunk_bytes)
|
|
221
|
+
except NormalizerError:
|
|
222
|
+
raise
|
|
223
|
+
except (OSError, UnicodeError, ValueError) as exc:
|
|
224
|
+
# pd.errors.ParserError is a ValueError subclass, already caught above.
|
|
225
|
+
raise NormalizerError("CSV parsing failed", code="csv_format_error") from exc
|
|
226
|
+
finally:
|
|
227
|
+
if pool is not None:
|
|
228
|
+
pool.close()
|
|
229
|
+
|
|
230
|
+
if row_count == 0 or (config.split == "rows" and row_count < 2):
|
|
231
|
+
raise NormalizerError("CSV does not contain enough data rows", code="csv_format_error")
|
|
232
|
+
|
|
233
|
+
if config.split == "columns":
|
|
234
|
+
objects = tuple(
|
|
235
|
+
ObjectDescriptor(
|
|
236
|
+
object_id=f"column_{index + 1:06d}",
|
|
237
|
+
label=label,
|
|
238
|
+
relative_path=f"objects/column_{index + 1:06d}.jsonl",
|
|
239
|
+
size_bytes=column_sizes[index],
|
|
240
|
+
sha256=column_hashes[index].hexdigest(),
|
|
241
|
+
)
|
|
242
|
+
for index, label in enumerate(header)
|
|
243
|
+
)
|
|
244
|
+
else:
|
|
245
|
+
objects = tuple(row_objects)
|
|
246
|
+
return ScanResult(
|
|
247
|
+
objects=objects,
|
|
248
|
+
total_bytes=sum(item.size_bytes for item in objects),
|
|
249
|
+
max_serialized_chunk_bytes=max_chunk_bytes,
|
|
250
|
+
row_count=row_count,
|
|
251
|
+
)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class NormalizerError(Exception):
|
|
5
|
+
"""Base error raised by the standalone normalizer package."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, message: str, *, code: str = "normalizer_error", **context: object) -> None:
|
|
8
|
+
super().__init__(message)
|
|
9
|
+
self.code = code
|
|
10
|
+
self.context = context
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ObjectDescriptor(BaseModel):
|
|
10
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
11
|
+
|
|
12
|
+
object_id: str
|
|
13
|
+
label: str
|
|
14
|
+
relative_path: str
|
|
15
|
+
size_bytes: int = Field(ge=0)
|
|
16
|
+
sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
|
17
|
+
|
|
18
|
+
@field_validator("relative_path")
|
|
19
|
+
@classmethod
|
|
20
|
+
def _relative_path_is_contained(cls, value: str) -> str:
|
|
21
|
+
path = Path(value)
|
|
22
|
+
if path.is_absolute() or ".." in path.parts or path.as_posix() != value:
|
|
23
|
+
raise ValueError("relative_path must be a contained POSIX path")
|
|
24
|
+
return value
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class NormalizationInput(BaseModel):
|
|
28
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
29
|
+
|
|
30
|
+
path: str
|
|
31
|
+
sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
|
32
|
+
size_bytes: int = Field(ge=0)
|
|
33
|
+
delimiter: str = Field(min_length=1, max_length=1)
|
|
34
|
+
encoding: str
|
|
35
|
+
split: Literal["columns", "rows"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NormalizationManifest(BaseModel):
|
|
39
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
40
|
+
|
|
41
|
+
schema_version: Literal[1]
|
|
42
|
+
input: NormalizationInput
|
|
43
|
+
objects: tuple[ObjectDescriptor, ...]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class NormalizationResult(BaseModel):
|
|
47
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
48
|
+
|
|
49
|
+
manifest_path: Path
|
|
50
|
+
object_count: int = Field(ge=0)
|
|
51
|
+
total_bytes: int = Field(ge=0)
|
|
52
|
+
objects: tuple[ObjectDescriptor, ...]
|
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def serialize_cell(value: str) -> bytes:
|
|
8
|
+
return (json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def serialize_row(values: Sequence[str]) -> bytes:
|
|
12
|
+
return (json.dumps(list(values), ensure_ascii=False, separators=(",", ":")) + "\n").encode(
|
|
13
|
+
"utf-8"
|
|
14
|
+
)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: damicore-normalizer
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Dataset normalization stage for the DAMICORE pipeline.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Delbem-Research-and-Innovation/damicore
|
|
6
|
+
Project-URL: Repository, https://github.com/Delbem-Research-and-Innovation/damicore
|
|
7
|
+
Project-URL: Issues, https://github.com/Delbem-Research-and-Innovation/damicore/issues
|
|
8
|
+
Project-URL: Documentation, https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md
|
|
9
|
+
Project-URL: Changelog, https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Ennio Politi Lopes <enniolopes@users.noreply.github.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: canonical-serialization,csv,damicore,normalization
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: <3.15,>=3.11
|
|
26
|
+
Requires-Dist: pandas<4,>=2.2
|
|
27
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# damicore-normalizer
|
|
31
|
+
|
|
32
|
+
damicore-normalizer deterministically serializes the columns or rows of a local
|
|
33
|
+
CSV as canonical JSONL objects, recording the size and SHA-256 of every object.
|
|
34
|
+
It is the first stage of the DAMICORE pipeline; most users install the aggregate
|
|
35
|
+
`damicore` distribution, which runs all four stages end to end. Install this
|
|
36
|
+
package alone to normalize datasets without the rest of the pipeline.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install damicore-normalizer
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Python
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from damicore_normalizer import NormalizationConfig, normalize_csv
|
|
46
|
+
|
|
47
|
+
result = normalize_csv(
|
|
48
|
+
"dataset.csv",
|
|
49
|
+
"normalization",
|
|
50
|
+
config=NormalizationConfig(split="columns", chunk_rows=50_000),
|
|
51
|
+
)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The call streams through `pandas.read_csv`, bounds open column files with an
|
|
55
|
+
LRU pool, and writes the objects plus a `manifest.json` into the output
|
|
56
|
+
directory. That normalization manifest is the input the sibling
|
|
57
|
+
`damicore-distance` distribution consumes to compute the NCD matrix.
|
|
58
|
+
|
|
59
|
+
## Links
|
|
60
|
+
|
|
61
|
+
- Repository: <https://github.com/Delbem-Research-and-Innovation/damicore>
|
|
62
|
+
- Issues: <https://github.com/Delbem-Research-and-Innovation/damicore/issues>
|
|
63
|
+
- Documentation:
|
|
64
|
+
<https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md>
|
|
65
|
+
|
|
66
|
+
Licensed under Apache-2.0.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
damicore_normalizer/__init__.py,sha256=KL6169L666EX2aTysDJD2SyvSKjqG0e8y1FIHHyWsc0,380
|
|
2
|
+
damicore_normalizer/api.py,sha256=JoHwE8YoAn-pqFLYaeA_zNLA_6vJHToN-9UeQccIslY,3402
|
|
3
|
+
damicore_normalizer/config.py,sha256=QI0JLlyHKlciKToV6QAJWmD62iRkeRIWyBR9MBGaDxQ,902
|
|
4
|
+
damicore_normalizer/csv_reader.py,sha256=PcmCkvku4dEfHFlDfztfepNLVdwbtuusZcT013rlong,10304
|
|
5
|
+
damicore_normalizer/errors.py,sha256=_RZ1FFA8dItVb6bDXdqAg9LGlerZZPgxeqMlaQozHt4,328
|
|
6
|
+
damicore_normalizer/manifest.py,sha256=gPfkSiBZ06ceMHqE-cOgA4dzOc9NC5d7cm7o-VoZSlg,1521
|
|
7
|
+
damicore_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
damicore_normalizer/serializer.py,sha256=F_qAQD7Hr0zMSadp_9rTxvdlkpjLthmT2lmnakv7Kgs,396
|
|
9
|
+
damicore_normalizer-0.1.0.dist-info/METADATA,sha256=Lgp1kEBWMxnPIONJfeT4zAzSl7tMTQ7GW9Taj1REEuY,2733
|
|
10
|
+
damicore_normalizer-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
11
|
+
damicore_normalizer-0.1.0.dist-info/licenses/LICENSE,sha256=BmVNessiu1YyCBRQp38foYZDCX9oXG_nwFqjbV7ueBA,11348
|
|
12
|
+
damicore_normalizer-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Ennio Politi Lopes
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|