damicore-normalizer 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.
@@ -0,0 +1,224 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+
42
+ # Local scratch / generated output (never commit)
43
+ .temp/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py.cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+ cover/
56
+
57
+ # Translations
58
+ *.mo
59
+ *.pot
60
+
61
+ # Django stuff:
62
+ *.log
63
+ local_settings.py
64
+ db.sqlite3
65
+ db.sqlite3-journal
66
+
67
+ # Flask stuff:
68
+ instance/
69
+ .webassets-cache
70
+
71
+ # Scrapy stuff:
72
+ .scrapy
73
+
74
+ # Sphinx documentation
75
+ docs/_build/
76
+
77
+ # PyBuilder
78
+ .pybuilder/
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ # For a library or package, you might want to ignore these files since the code is
90
+ # intended to run in multiple environments; otherwise, check them in:
91
+ # .python-version
92
+
93
+ # pipenv
94
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
96
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
97
+ # install all needed dependencies.
98
+ #Pipfile.lock
99
+
100
+ # UV
101
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
102
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
103
+ # commonly ignored for libraries.
104
+ #uv.lock
105
+
106
+ # poetry
107
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
108
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
109
+ # commonly ignored for libraries.
110
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
111
+ #poetry.lock
112
+ #poetry.toml
113
+
114
+ # pdm
115
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
116
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
117
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
118
+ #pdm.lock
119
+ #pdm.toml
120
+ .pdm-python
121
+ .pdm-build/
122
+
123
+ # pixi
124
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
125
+ #pixi.lock
126
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
127
+ # in the .venv directory. It is recommended not to include this directory in version control.
128
+ .pixi
129
+
130
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
131
+ __pypackages__/
132
+
133
+ # Celery stuff
134
+ celerybeat-schedule
135
+ celerybeat.pid
136
+
137
+ # SageMath parsed files
138
+ *.sage.py
139
+
140
+ # Environments
141
+ .env
142
+ .envrc
143
+ .venv
144
+ env/
145
+ venv/
146
+ ENV/
147
+ env.bak/
148
+ venv.bak/
149
+
150
+ # Spyder project settings
151
+ .spyderproject
152
+ .spyproject
153
+
154
+ # Rope project settings
155
+ .ropeproject
156
+
157
+ # mkdocs documentation
158
+ /site
159
+
160
+ # mypy
161
+ .mypy_cache/
162
+ .dmypy.json
163
+ dmypy.json
164
+
165
+ # Pyre type checker
166
+ .pyre/
167
+
168
+ # pytype static type analyzer
169
+ .pytype/
170
+
171
+ # Cython debug symbols
172
+ cython_debug/
173
+
174
+ # PyCharm
175
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
176
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
177
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
178
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
179
+ #.idea/
180
+
181
+ # Abstra
182
+ # Abstra is an AI-powered process automation framework.
183
+ # Ignore directories containing user credentials, local state, and settings.
184
+ # Learn more at https://abstra.io/docs
185
+ .abstra/
186
+
187
+ # Visual Studio Code
188
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
189
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
190
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
191
+ # you could uncomment the following to ignore the entire vscode folder
192
+ # .vscode/
193
+
194
+ # Ruff stuff:
195
+ .ruff_cache/
196
+
197
+ # PyPI configuration file
198
+ .pypirc
199
+
200
+ # Cursor
201
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
202
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
203
+ # refer to https://docs.cursor.com/context/ignore-files
204
+ .cursorignore
205
+ .cursorindexingignore
206
+
207
+ # Marimo
208
+ marimo/_static/
209
+ marimo/_lsp/
210
+ __marimo__/
211
+
212
+ # LaTeX build artefacts (papers)
213
+ models/**/paper/*.aux
214
+ models/**/paper/*.bbl
215
+ models/**/paper/*.bcf
216
+ models/**/paper/*.blg
217
+ models/**/paper/*.fdb_latexmk
218
+ models/**/paper/*.fls
219
+ models/**/paper/*.log
220
+ models/**/paper/*.out
221
+ models/**/paper/*.run.xml
222
+ models/**/paper/*.synctex.gz
223
+ models/**/paper/*.toc
224
+ models/**/paper/*.pdf
@@ -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.
@@ -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,37 @@
1
+ # damicore-normalizer
2
+
3
+ damicore-normalizer deterministically serializes the columns or rows of a local
4
+ CSV as canonical JSONL objects, recording the size and SHA-256 of every object.
5
+ It is the first stage of the DAMICORE pipeline; most users install the aggregate
6
+ `damicore` distribution, which runs all four stages end to end. Install this
7
+ package alone to normalize datasets without the rest of the pipeline.
8
+
9
+ ```bash
10
+ pip install damicore-normalizer
11
+ ```
12
+
13
+ ## Python
14
+
15
+ ```python
16
+ from damicore_normalizer import NormalizationConfig, normalize_csv
17
+
18
+ result = normalize_csv(
19
+ "dataset.csv",
20
+ "normalization",
21
+ config=NormalizationConfig(split="columns", chunk_rows=50_000),
22
+ )
23
+ ```
24
+
25
+ The call streams through `pandas.read_csv`, bounds open column files with an
26
+ LRU pool, and writes the objects plus a `manifest.json` into the output
27
+ directory. That normalization manifest is the input the sibling
28
+ `damicore-distance` distribution consumes to compute the NCD matrix.
29
+
30
+ ## Links
31
+
32
+ - Repository: <https://github.com/Delbem-Research-and-Innovation/damicore>
33
+ - Issues: <https://github.com/Delbem-Research-and-Innovation/damicore/issues>
34
+ - Documentation:
35
+ <https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md>
36
+
37
+ Licensed under Apache-2.0.
@@ -0,0 +1,63 @@
1
+ [project]
2
+ name = "damicore-normalizer"
3
+ version = "0.1.0"
4
+ description = "Dataset normalization stage for the DAMICORE pipeline."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Ennio Politi Lopes", email = "enniolopes@users.noreply.github.com" }]
9
+ requires-python = ">=3.11,<3.15"
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: Science/Research",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3 :: Only",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Operating System :: OS Independent",
20
+ "Topic :: Scientific/Engineering :: Information Analysis",
21
+ "Typing :: Typed",
22
+ ]
23
+ keywords = ["damicore", "csv", "normalization", "canonical-serialization"]
24
+ dependencies = [
25
+ "pandas>=2.2,<4",
26
+ "pydantic>=2.10,<3",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/Delbem-Research-and-Innovation/damicore"
31
+ Repository = "https://github.com/Delbem-Research-and-Innovation/damicore"
32
+ Issues = "https://github.com/Delbem-Research-and-Innovation/damicore/issues"
33
+ Documentation = "https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/docs/quickstart.md"
34
+ Changelog = "https://github.com/Delbem-Research-and-Innovation/damicore/blob/main/CHANGELOG.md"
35
+
36
+ [build-system]
37
+ requires = ["hatchling>=1.31.0,<2"]
38
+ build-backend = "hatchling.build"
39
+
40
+ # Workspace-only files are excluded on purpose: each package's Makefile only includes
41
+ # ../package.mk, pyrightconfig.json extends ../../pyrightconfig.json, and tests/ depends
42
+ # on the workspace conftest and dev tooling, so none of them work in an sdist unpacked
43
+ # outside the monorepo. The repository .gitignore still ships: hatchling force-includes
44
+ # the located VCS ignore file so an sdist-to-wheel build selects files the same way, and
45
+ # `exclude` deliberately cannot override that.
46
+ [tool.hatch.build.targets.sdist]
47
+ exclude = ["Makefile", "pyrightconfig.json", "tests"]
48
+
49
+ [tool.ruff]
50
+ line-length = 100
51
+ exclude = [".venv", "dist", "__pycache__"]
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "F", "I", "RUF100", "UP"]
55
+
56
+ [tool.pytest.ini_options]
57
+ testpaths = ["tests"]
58
+ pythonpath = ["src"]
59
+ markers = ["unit: fast isolated unit tests"]
60
+ # --cov-branch and the floor mirror the root configuration on purpose: coverage resolves
61
+ # its config from the working directory, so a package-scoped run would otherwise report
62
+ # line coverage with no threshold and read as a stronger result than it is.
63
+ addopts = "--cov=damicore_normalizer --cov-branch --cov-report=term-missing --cov-fail-under=90"
@@ -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, ...]
@@ -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
+ )