universal-data-cleaner 2.6.0__tar.gz → 2.7.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.
Files changed (32) hide show
  1. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/PKG-INFO +4 -1
  2. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/README.md +3 -0
  3. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/pyproject.toml +4 -1
  4. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/__init__.py +2 -0
  5. universal_data_cleaner-2.7.0/src/data_cleaner/__main__.py +148 -0
  6. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/_version.py +1 -1
  7. universal_data_cleaner-2.7.0/src/data_cleaner/reporting.py +615 -0
  8. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/universal_data_cleaner.egg-info/PKG-INFO +4 -1
  9. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/universal_data_cleaner.egg-info/SOURCES.txt +4 -0
  10. universal_data_cleaner-2.7.0/src/universal_data_cleaner.egg-info/entry_points.txt +2 -0
  11. universal_data_cleaner-2.7.0/tests/test_reporting.py +319 -0
  12. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/LICENSE +0 -0
  13. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/setup.cfg +0 -0
  14. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/_roles.py +0 -0
  15. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/artifacts.py +0 -0
  16. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/cleaner.py +0 -0
  17. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/config.py +0 -0
  18. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/contract.py +0 -0
  19. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/decisions.py +0 -0
  20. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/ingestion.py +0 -0
  21. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/integration.py +0 -0
  22. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/ml_audit.py +0 -0
  23. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/profiling.py +0 -0
  24. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/py.typed +0 -0
  25. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/data_cleaner/validation.py +0 -0
  26. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/universal_data_cleaner.egg-info/dependency_links.txt +0 -0
  27. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/universal_data_cleaner.egg-info/requires.txt +0 -0
  28. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/src/universal_data_cleaner.egg-info/top_level.txt +0 -0
  29. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/tests/test_data_cleaner.py +0 -0
  30. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/tests/test_ingestion.py +0 -0
  31. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/tests/test_ml_audit.py +0 -0
  32. {universal_data_cleaner-2.6.0 → universal_data_cleaner-2.7.0}/tests/test_validation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: universal-data-cleaner
3
- Version: 2.6.0
3
+ Version: 2.7.0
4
4
  Summary: Production-ready, scikit-learn-compatible data cleaning transformer for pandas.
5
5
  Author: Haseeb Khan
6
6
  License-Expression: MIT
@@ -59,6 +59,7 @@ The docs site is the central reference. This README is the short entry point.
59
59
  | [Cleaning data](https://devlprkhan.github.io/universal-data-cleaner/cleaning/) | Config, roles, imputation, outliers, datetimes |
60
60
  | [Contracts & drift](https://devlprkhan.github.io/universal-data-cleaner/contracts/) | `ColumnSpec`, `DataContract`, drift checks |
61
61
  | [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads and ingestion reports |
62
+ | [Batch reporting](https://devlprkhan.github.io/universal-data-cleaner/reporting/) | `CleanerReport` and the `data-cleaner audit` CLI |
62
63
  | [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
63
64
  | [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
64
65
  | [Artifacts & reproducibility](https://devlprkhan.github.io/universal-data-cleaner/artifacts/) | Decision log, manifests, fingerprints, save/load |
@@ -135,6 +136,8 @@ for the full explanation.
135
136
  - optional missing-value indicators and constant-column dropping
136
137
  - safe CSV ingestion with contract-driven coercion, identifier protection, date
137
138
  and boolean guards, and an audit report
139
+ - `CleanerReport` combining profile, contract drift, validation, ingestion, and
140
+ cleaner decisions, plus a `data-cleaner audit` CLI
138
141
  - declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
139
142
  - automatic train-schema contract inference and transform-time drift reports
140
143
  - expectation checks and validation reports
@@ -25,6 +25,7 @@ The docs site is the central reference. This README is the short entry point.
25
25
  | [Cleaning data](https://devlprkhan.github.io/universal-data-cleaner/cleaning/) | Config, roles, imputation, outliers, datetimes |
26
26
  | [Contracts & drift](https://devlprkhan.github.io/universal-data-cleaner/contracts/) | `ColumnSpec`, `DataContract`, drift checks |
27
27
  | [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads and ingestion reports |
28
+ | [Batch reporting](https://devlprkhan.github.io/universal-data-cleaner/reporting/) | `CleanerReport` and the `data-cleaner audit` CLI |
28
29
  | [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
29
30
  | [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
30
31
  | [Artifacts & reproducibility](https://devlprkhan.github.io/universal-data-cleaner/artifacts/) | Decision log, manifests, fingerprints, save/load |
@@ -101,6 +102,8 @@ for the full explanation.
101
102
  - optional missing-value indicators and constant-column dropping
102
103
  - safe CSV ingestion with contract-driven coercion, identifier protection, date
103
104
  and boolean guards, and an audit report
105
+ - `CleanerReport` combining profile, contract drift, validation, ingestion, and
106
+ cleaner decisions, plus a `data-cleaner audit` CLI
104
107
  - declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
105
108
  - automatic train-schema contract inference and transform-time drift reports
106
109
  - expectation checks and validation reports
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "universal-data-cleaner"
7
- version = "2.6.0"
7
+ version = "2.7.0"
8
8
  description = "Production-ready, scikit-learn-compatible data cleaning transformer for pandas."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -50,6 +50,9 @@ Repository = "https://github.com/devlprkhan/universal-data-cleaner"
50
50
  Issues = "https://github.com/devlprkhan/universal-data-cleaner/issues"
51
51
  Changelog = "https://github.com/devlprkhan/universal-data-cleaner/blob/main/CHANGELOG.md"
52
52
 
53
+ [project.scripts]
54
+ data-cleaner = "data_cleaner.__main__:main"
55
+
53
56
  [dependency-groups]
54
57
  docs = [
55
58
  "mkdocs-material>=9.5",
@@ -38,6 +38,7 @@ from .profiling import (
38
38
  drop_duplicate_rows,
39
39
  profile_dataframe,
40
40
  )
41
+ from .reporting import CleanerReport
41
42
  from .validation import (
42
43
  Expectation,
43
44
  ValidationReport,
@@ -54,6 +55,7 @@ from .validation import (
54
55
 
55
56
  __all__ = [
56
57
  "CleanerConfig",
58
+ "CleanerReport",
57
59
  "CleaningDecision",
58
60
  "ColumnSpec",
59
61
  "Contract",
@@ -0,0 +1,148 @@
1
+ """Command-line entry point for local batch audits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from ._version import __version__
10
+ from .cleaner import DataCleaner
11
+ from .contract import DataContract
12
+ from .ingestion import read_csv_safe
13
+ from .reporting import CleanerReport
14
+
15
+
16
+ def build_parser() -> argparse.ArgumentParser:
17
+ """Build the ``python -m data_cleaner`` argument parser."""
18
+ parser = argparse.ArgumentParser(
19
+ prog="data-cleaner",
20
+ description="Leak-safe data cleaning and batch audits.",
21
+ )
22
+ parser.add_argument(
23
+ "--version",
24
+ action="version",
25
+ version=f"%(prog)s {__version__}",
26
+ )
27
+ subparsers = parser.add_subparsers(dest="command", required=True)
28
+
29
+ audit = subparsers.add_parser(
30
+ "audit",
31
+ help="Audit a CSV batch and print a report.",
32
+ description=(
33
+ "Read a CSV safely, then report its profile, contract findings, "
34
+ "and cleaner decisions."
35
+ ),
36
+ )
37
+ audit.add_argument("csv", type=Path, help="CSV file to audit.")
38
+ source = audit.add_mutually_exclusive_group()
39
+ source.add_argument(
40
+ "--contract",
41
+ type=Path,
42
+ help="JSON contract file used for ingestion and drift checks.",
43
+ )
44
+ source.add_argument(
45
+ "--cleaner",
46
+ type=Path,
47
+ help="Fitted DataCleaner artifact; uses its contract and decisions.",
48
+ )
49
+ audit.add_argument(
50
+ "--name",
51
+ default=None,
52
+ help="Dataset name shown in the profile (defaults to the file stem).",
53
+ )
54
+ audit.add_argument(
55
+ "--format",
56
+ choices=("markdown", "json"),
57
+ default="markdown",
58
+ help="Report format written to stdout or --output.",
59
+ )
60
+ audit.add_argument(
61
+ "--output",
62
+ type=Path,
63
+ default=None,
64
+ help="Write the report to this file instead of stdout.",
65
+ )
66
+ audit.add_argument(
67
+ "--no-profile",
68
+ action="store_true",
69
+ help="Skip the column-level profile for faster large-file audits.",
70
+ )
71
+ audit.add_argument(
72
+ "--fail-on-warning",
73
+ action="store_true",
74
+ help="Exit with status 1 when warnings are present.",
75
+ )
76
+ return parser
77
+
78
+
79
+ def _load_contract(path: Path) -> DataContract:
80
+ return DataContract.from_json(path.read_text(encoding="utf-8"))
81
+
82
+
83
+ def _run_audit(args: argparse.Namespace) -> int:
84
+ contract: DataContract | None = None
85
+ cleaner: DataCleaner | None = None
86
+ if args.contract is not None:
87
+ contract = _load_contract(args.contract)
88
+ if args.cleaner is not None:
89
+ cleaner = DataCleaner.load(args.cleaner)
90
+ contract = cleaner.fitted_contract()
91
+
92
+ frame, ingestion = read_csv_safe(
93
+ args.csv,
94
+ contract=contract,
95
+ on_error="ignore",
96
+ )
97
+ dataset_name = args.name or args.csv.stem
98
+ if cleaner is not None:
99
+ report = CleanerReport.from_cleaner(
100
+ cleaner,
101
+ frame,
102
+ source=ingestion.source,
103
+ name=dataset_name,
104
+ ingestion=ingestion,
105
+ include_profile=not args.no_profile,
106
+ )
107
+ else:
108
+ report = CleanerReport.from_frame(
109
+ frame,
110
+ source=ingestion.source,
111
+ name=dataset_name,
112
+ contract=contract,
113
+ ingestion=ingestion,
114
+ include_profile=not args.no_profile,
115
+ )
116
+
117
+ rendered = (
118
+ report.to_markdown()
119
+ if args.format == "markdown"
120
+ else report.to_json(indent=2) + "\n"
121
+ )
122
+ if args.output is None:
123
+ print(rendered, end="")
124
+ else:
125
+ args.output.parent.mkdir(parents=True, exist_ok=True)
126
+ args.output.write_text(rendered, encoding="utf-8")
127
+ print(f"Wrote {args.format} report to {args.output}", file=sys.stderr)
128
+
129
+ failed = not report.success or (args.fail_on_warning and report.has_warnings)
130
+ return 1 if failed else 0
131
+
132
+
133
+ def main(argv: list[str] | None = None) -> int:
134
+ """Run the CLI and return a process exit status."""
135
+ parser = build_parser()
136
+ args = parser.parse_args(argv)
137
+ if args.command == "audit":
138
+ try:
139
+ return _run_audit(args)
140
+ except (OSError, ValueError, TypeError) as exc:
141
+ print(f"error: {exc}", file=sys.stderr)
142
+ return 2
143
+ parser.print_help()
144
+ return 2
145
+
146
+
147
+ if __name__ == "__main__": # pragma: no cover - exercised via `python -m`
148
+ raise SystemExit(main())
@@ -1,4 +1,4 @@
1
1
  """Single source of truth for the package version."""
2
2
 
3
- __version__ = "2.6.0"
3
+ __version__ = "2.7.0"
4
4
  _ARTIFACT_VERSION = 2
@@ -0,0 +1,615 @@
1
+ """One audit report for a batch: profile, contract, validation, and decisions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ from collections.abc import Sequence
9
+ from dataclasses import dataclass, field
10
+ from datetime import date, datetime
11
+ from typing import IO, Any
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from ._version import __version__
17
+ from .contract import DataContract, DriftReport
18
+ from .decisions import DECISION_COLUMNS
19
+ from .ingestion import IngestionPolicy, IngestionReport, read_csv_safe
20
+ from .profiling import dataset_summary, profile_dataframe
21
+ from .validation import Expectation, ValidationReport, validate
22
+
23
+ _FINDING_COLUMNS = [
24
+ "source",
25
+ "column",
26
+ "check",
27
+ "severity",
28
+ "message",
29
+ "count",
30
+ ]
31
+ _PROFILE_COLUMNS = [
32
+ "dataset",
33
+ "column",
34
+ "dtype",
35
+ "non_null",
36
+ "missing",
37
+ "missing_pct",
38
+ "unique",
39
+ "top",
40
+ "top_freq",
41
+ ]
42
+
43
+
44
+ def _json_safe(value: Any) -> object:
45
+ """Convert pandas/numpy scalars into JSON-friendly values."""
46
+ if value is None:
47
+ return None
48
+ if isinstance(value, bool):
49
+ return value
50
+ if isinstance(value, (str, int)):
51
+ return value
52
+ if isinstance(value, float):
53
+ return value if math.isfinite(value) else None
54
+ if isinstance(value, np.bool_):
55
+ return bool(value)
56
+ if isinstance(value, np.integer):
57
+ return int(value)
58
+ if isinstance(value, np.floating):
59
+ number = float(value)
60
+ return number if math.isfinite(number) else None
61
+ if isinstance(value, np.datetime64):
62
+ return None if pd.isna(value) else pd.Timestamp(value).isoformat()
63
+ if isinstance(value, np.ndarray):
64
+ return [_json_safe(item) for item in value.tolist()]
65
+ if isinstance(value, dict):
66
+ return {str(key): _json_safe(item) for key, item in value.items()}
67
+ if isinstance(value, (list, tuple, set)):
68
+ return [_json_safe(item) for item in value]
69
+ if isinstance(value, (datetime, date)):
70
+ return value.isoformat()
71
+ if isinstance(value, pd.Timedelta):
72
+ return str(value)
73
+ try:
74
+ if pd.isna(value):
75
+ return None
76
+ except (TypeError, ValueError):
77
+ pass
78
+ return str(value)
79
+
80
+
81
+ def _records(frame: pd.DataFrame) -> list[dict[str, object]]:
82
+ """Return rows with JSON-safe keys and values."""
83
+ return [
84
+ {str(key): _json_safe(value) for key, value in record.items()}
85
+ for record in frame.to_dict("records")
86
+ ]
87
+
88
+
89
+ def _markdown_table(frame: pd.DataFrame) -> str:
90
+ """Render a DataFrame as Markdown, falling back to plain text."""
91
+ if frame.empty:
92
+ return "_No rows._"
93
+ try:
94
+ return frame.to_markdown(index=False)
95
+ except ImportError: # tabulate is optional
96
+ return "```\n" + frame.to_string(index=False) + "\n```"
97
+
98
+
99
+ def _finding(
100
+ source: str,
101
+ column: str,
102
+ check: str,
103
+ severity: str,
104
+ message: str,
105
+ count: int,
106
+ ) -> dict[str, object]:
107
+ return {
108
+ "source": source,
109
+ "column": column,
110
+ "check": check,
111
+ "severity": severity,
112
+ "message": message,
113
+ "count": int(count),
114
+ }
115
+
116
+
117
+ def _as_int(value: object, default: int = 0) -> int:
118
+ """Coerce an overview metric to ``int`` without trusting its declared type."""
119
+ if isinstance(value, (bool, np.bool_)):
120
+ return int(value)
121
+ if isinstance(value, (int, np.integer)):
122
+ return int(value)
123
+ if isinstance(value, float):
124
+ return int(value)
125
+ return default
126
+
127
+
128
+ @dataclass(eq=False)
129
+ class CleanerReport:
130
+ """A single review object for one DataFrame or CSV batch.
131
+
132
+ The report combines the dataset profile with contract findings, validation
133
+ results, ingestion findings, and (when available) the cleaner's decision
134
+ log. It never mutates the input frame and never transforms it.
135
+
136
+ Parameters
137
+ ----------
138
+ source:
139
+ Human-readable label for the batch, usually a file name.
140
+ overview:
141
+ Dataset-level metrics from :func:`dataset_summary`.
142
+ profile:
143
+ Column-level profile from :func:`profile_dataframe`.
144
+ drift:
145
+ Contract findings for the batch, when a contract is available.
146
+ validation:
147
+ Expectation results, when expectations are supplied.
148
+ ingestion:
149
+ CSV ingestion findings, when the batch came from :func:`read_csv_safe`.
150
+ decisions:
151
+ The fitted cleaner's decision log, when auditing with a cleaner.
152
+ high_missing_threshold:
153
+ Missing-percentage at which the profile emits a ``high_missing``
154
+ warning. Set to ``None`` to disable that warning.
155
+ library_version:
156
+ Version of Universal Data Cleaner that produced the report.
157
+ """
158
+
159
+ source: str
160
+ overview: dict[str, object]
161
+ profile: pd.DataFrame
162
+ drift: DriftReport | None = None
163
+ validation: ValidationReport | None = None
164
+ ingestion: IngestionReport | None = None
165
+ decisions: pd.DataFrame = field(
166
+ default_factory=lambda: pd.DataFrame(columns=DECISION_COLUMNS)
167
+ )
168
+ high_missing_threshold: float | None = 50.0
169
+ library_version: str = __version__
170
+
171
+ def __post_init__(self) -> None:
172
+ if self.high_missing_threshold is not None and not (
173
+ 0 <= self.high_missing_threshold <= 100
174
+ ):
175
+ raise ValueError("high_missing_threshold must be between 0 and 100")
176
+
177
+ def __repr__(self) -> str:
178
+ return (
179
+ f"CleanerReport(source={self.source!r}, "
180
+ f"rows={self.overview.get('rows')}, "
181
+ f"columns={self.overview.get('columns')}, "
182
+ f"success={self.success})"
183
+ )
184
+
185
+ @classmethod
186
+ def from_frame(
187
+ cls,
188
+ frame: pd.DataFrame,
189
+ *,
190
+ source: str = "dataset",
191
+ name: str = "dataset",
192
+ contract: DataContract | None = None,
193
+ expectations: Expectation | Sequence[Expectation] | None = None,
194
+ ingestion: IngestionReport | None = None,
195
+ decisions: pd.DataFrame | None = None,
196
+ include_profile: bool = True,
197
+ high_missing_threshold: float | None = 50.0,
198
+ ) -> CleanerReport:
199
+ """Build a report for an in-memory DataFrame.
200
+
201
+ Parameters
202
+ ----------
203
+ frame:
204
+ The batch to inspect. It is never modified.
205
+ source:
206
+ Label recorded in the report.
207
+ name:
208
+ Dataset name used in the column profile.
209
+ contract:
210
+ Optional contract. When provided, its findings become the report's
211
+ contract section.
212
+ expectations:
213
+ Optional expectation or sequence of expectations to evaluate.
214
+ ingestion:
215
+ Optional ingestion report to attach, for example from
216
+ :func:`read_csv_safe`.
217
+ decisions:
218
+ Optional decision log to attach, for example from a fitted cleaner.
219
+ include_profile:
220
+ Compute the column-level profile. Disable it for very large batches
221
+ when only findings are needed.
222
+ high_missing_threshold:
223
+ Missing-percentage threshold for a ``high_missing`` warning.
224
+ """
225
+ if not isinstance(frame, pd.DataFrame):
226
+ raise TypeError("frame must be a pandas DataFrame")
227
+ if contract is not None and not isinstance(contract, DataContract):
228
+ raise TypeError("contract must be a DataContract instance or None")
229
+
230
+ overview = dataset_summary(frame)
231
+ profile = (
232
+ profile_dataframe(frame, name=name)
233
+ if include_profile
234
+ else pd.DataFrame(columns=_PROFILE_COLUMNS)
235
+ )
236
+ drift = contract.check(frame) if contract is not None else None
237
+ validation = validate(frame, expectations) if expectations is not None else None
238
+ decision_log = (
239
+ decisions
240
+ if decisions is not None
241
+ else pd.DataFrame(columns=DECISION_COLUMNS)
242
+ )
243
+ return cls(
244
+ source=source,
245
+ overview=overview,
246
+ profile=profile,
247
+ drift=drift,
248
+ validation=validation,
249
+ ingestion=ingestion,
250
+ decisions=decision_log,
251
+ high_missing_threshold=high_missing_threshold,
252
+ )
253
+
254
+ @classmethod
255
+ def from_csv(
256
+ cls,
257
+ source: str | os.PathLike[str] | IO[Any],
258
+ *,
259
+ contract: DataContract | None = None,
260
+ expectations: Expectation | Sequence[Expectation] | None = None,
261
+ name: str | None = None,
262
+ include_profile: bool = True,
263
+ high_missing_threshold: float | None = 50.0,
264
+ on_error: IngestionPolicy = "ignore",
265
+ **read_csv_kwargs: Any,
266
+ ) -> CleanerReport:
267
+ """Read a CSV with :func:`read_csv_safe` and audit the result.
268
+
269
+ The default ``on_error="ignore"`` always returns a report; error
270
+ findings still make :attr:`success` false. Pass ``"raise"`` to stop at
271
+ the first unparseable value instead.
272
+ """
273
+ frame, ingestion = read_csv_safe(
274
+ source,
275
+ contract=contract,
276
+ on_error=on_error,
277
+ **read_csv_kwargs,
278
+ )
279
+ dataset_name = name or os.path.splitext(os.path.basename(ingestion.source))[0]
280
+ return cls.from_frame(
281
+ frame,
282
+ source=ingestion.source,
283
+ name=dataset_name or "dataset",
284
+ contract=contract,
285
+ expectations=expectations,
286
+ ingestion=ingestion,
287
+ include_profile=include_profile,
288
+ high_missing_threshold=high_missing_threshold,
289
+ )
290
+
291
+ @classmethod
292
+ def from_cleaner(
293
+ cls,
294
+ cleaner: Any,
295
+ frame: pd.DataFrame,
296
+ *,
297
+ source: str = "batch",
298
+ name: str = "batch",
299
+ expectations: Expectation | Sequence[Expectation] | None = None,
300
+ ingestion: IngestionReport | None = None,
301
+ include_profile: bool = True,
302
+ high_missing_threshold: float | None = 50.0,
303
+ ) -> CleanerReport:
304
+ """Audit a batch against a fitted :class:`~data_cleaner.DataCleaner`.
305
+
306
+ The cleaner's fitted contract supplies the drift section and its
307
+ decision log is attached to the report. The cleaner is not re-fitted
308
+ and the batch is not transformed.
309
+ """
310
+ from .cleaner import DataCleaner
311
+
312
+ if not isinstance(cleaner, DataCleaner):
313
+ raise TypeError("cleaner must be a DataCleaner")
314
+ contract = cleaner.fitted_contract()
315
+ decisions = cleaner.decision_log()
316
+ return cls.from_frame(
317
+ frame,
318
+ source=source,
319
+ name=name,
320
+ contract=contract,
321
+ expectations=expectations,
322
+ ingestion=ingestion,
323
+ decisions=decisions,
324
+ include_profile=include_profile,
325
+ high_missing_threshold=high_missing_threshold,
326
+ )
327
+
328
+ def _profile_findings(self) -> list[dict[str, object]]:
329
+ rows = _as_int(self.overview.get("rows"))
330
+ columns = _as_int(self.overview.get("columns"))
331
+ duplicates = _as_int(self.overview.get("duplicate_rows"))
332
+ findings: list[dict[str, object]] = []
333
+
334
+ if rows == 0:
335
+ findings.append(
336
+ _finding(
337
+ "profile",
338
+ "*",
339
+ "empty_dataset",
340
+ "warning",
341
+ "dataset has no rows",
342
+ 0,
343
+ )
344
+ )
345
+ if duplicates:
346
+ findings.append(
347
+ _finding(
348
+ "profile",
349
+ "*",
350
+ "duplicate_rows",
351
+ "warning",
352
+ f"dataset has {duplicates} duplicate row(s)",
353
+ duplicates,
354
+ )
355
+ )
356
+ if self.profile.empty:
357
+ return findings
358
+
359
+ for _, row in self.profile.iterrows():
360
+ column = str(row["column"])
361
+ non_null = int(row["non_null"])
362
+ missing = int(row["missing"])
363
+ missing_pct = float(row["missing_pct"])
364
+ unique = int(row["unique"])
365
+
366
+ if rows and non_null == 0:
367
+ findings.append(
368
+ _finding(
369
+ "profile",
370
+ column,
371
+ "empty_column",
372
+ "warning",
373
+ f"column '{column}' has no non-null values",
374
+ rows,
375
+ )
376
+ )
377
+ elif non_null and unique == 1:
378
+ findings.append(
379
+ _finding(
380
+ "profile",
381
+ column,
382
+ "constant_column",
383
+ "warning",
384
+ f"column '{column}' has a single distinct value",
385
+ non_null,
386
+ )
387
+ )
388
+
389
+ if (
390
+ self.high_missing_threshold is not None
391
+ and rows
392
+ and non_null
393
+ and missing_pct >= self.high_missing_threshold
394
+ ):
395
+ findings.append(
396
+ _finding(
397
+ "profile",
398
+ column,
399
+ "high_missing",
400
+ "warning",
401
+ f"column '{column}' is {missing_pct:.1f}% missing",
402
+ missing,
403
+ )
404
+ )
405
+
406
+ if columns == 0:
407
+ findings.append(
408
+ _finding(
409
+ "profile",
410
+ "*",
411
+ "empty_dataset",
412
+ "warning",
413
+ "dataset has no columns",
414
+ 0,
415
+ )
416
+ )
417
+ return findings
418
+
419
+ @property
420
+ def findings(self) -> pd.DataFrame:
421
+ """A tidy table of every error and warning in the report."""
422
+ rows: list[dict[str, object]] = []
423
+
424
+ if self.ingestion is not None and not self.ingestion.findings.empty:
425
+ for _, row in self.ingestion.findings.iterrows():
426
+ rows.append(
427
+ _finding(
428
+ "ingestion",
429
+ str(row["column"]),
430
+ str(row["check"]),
431
+ str(row["severity"]),
432
+ str(row["message"]),
433
+ int(row["count"]),
434
+ )
435
+ )
436
+
437
+ if self.drift is not None and self.drift.has_drift:
438
+ for _, row in self.drift.findings.iterrows():
439
+ rows.append(
440
+ _finding(
441
+ "contract",
442
+ str(row["column"]),
443
+ str(row["check"]),
444
+ str(row["severity"]),
445
+ str(row["message"]),
446
+ 1,
447
+ )
448
+ )
449
+
450
+ if self.validation is not None and not self.validation.failures.empty:
451
+ for _, row in self.validation.failures.iterrows():
452
+ observed = row["observed"]
453
+ count = (
454
+ int(observed)
455
+ if isinstance(observed, (int, np.integer))
456
+ and not isinstance(observed, (bool, np.bool_))
457
+ else 1
458
+ )
459
+ rows.append(
460
+ _finding(
461
+ "validation",
462
+ str(row["column"]) if row["column"] is not None else "*",
463
+ str(row["expectation"]),
464
+ str(row["severity"]),
465
+ str(row["message"]),
466
+ count,
467
+ )
468
+ )
469
+
470
+ rows.extend(self._profile_findings())
471
+ frame = pd.DataFrame(rows, columns=_FINDING_COLUMNS)
472
+ if frame.empty:
473
+ return frame
474
+ frame = frame.drop_duplicates(
475
+ subset=["column", "check", "severity"], keep="first"
476
+ )
477
+ return frame.sort_values(
478
+ ["severity", "source", "column"], kind="stable"
479
+ ).reset_index(drop=True)
480
+
481
+ @property
482
+ def errors(self) -> pd.DataFrame:
483
+ """Findings with error severity."""
484
+ findings = self.findings
485
+ if findings.empty:
486
+ return findings
487
+ return findings[findings["severity"] == "error"].reset_index(drop=True)
488
+
489
+ @property
490
+ def warnings(self) -> pd.DataFrame:
491
+ """Findings with warning severity."""
492
+ findings = self.findings
493
+ if findings.empty:
494
+ return findings
495
+ return findings[findings["severity"] == "warning"].reset_index(drop=True)
496
+
497
+ @property
498
+ def has_errors(self) -> bool:
499
+ """Whether at least one error-severity finding exists."""
500
+ return not self.errors.empty
501
+
502
+ @property
503
+ def has_warnings(self) -> bool:
504
+ """Whether at least one warning-severity finding exists."""
505
+ return not self.warnings.empty
506
+
507
+ @property
508
+ def success(self) -> bool:
509
+ """Whether the batch has no error-severity findings."""
510
+ return not self.has_errors
511
+
512
+ def _status_line(self) -> str:
513
+ status = "PASS" if self.success else "FAIL"
514
+ return (
515
+ f"{status} — {_as_int(self.overview.get('rows'))} row(s), "
516
+ f"{_as_int(self.overview.get('columns'))} column(s), "
517
+ f"{len(self.errors)} error(s), {len(self.warnings)} warning(s)"
518
+ )
519
+
520
+ def summary(self) -> str:
521
+ """Return a short human-readable description of the report."""
522
+ lines = [self._status_line()]
523
+ for _, row in self.findings.iterrows():
524
+ lines.append(
525
+ f"- [{row['severity']}] {row['source']}/{row['check']} "
526
+ f"on '{row['column']}': {row['message']}"
527
+ )
528
+ return "\n".join(lines)
529
+
530
+ def to_markdown(self) -> str:
531
+ """Render the whole report as Markdown."""
532
+ lines = [f"# Cleaner report: {self.source}", "", self._status_line(), ""]
533
+
534
+ lines.extend(["## Overview", ""])
535
+ overview = pd.DataFrame(
536
+ [
537
+ {"metric": key, "value": _json_safe(value)}
538
+ for key, value in self.overview.items()
539
+ ]
540
+ )
541
+ lines.extend([_markdown_table(overview), ""])
542
+
543
+ lines.extend(["## Findings", ""])
544
+ lines.extend([_markdown_table(self.findings), ""])
545
+
546
+ lines.extend(["## Column profile", ""])
547
+ lines.extend([_markdown_table(self.profile), ""])
548
+
549
+ lines.extend(["## Contract drift", ""])
550
+ if self.drift is None:
551
+ lines.extend(["No contract configured.", ""])
552
+ elif not self.drift.has_drift:
553
+ lines.extend(["No contract drift detected.", ""])
554
+ else:
555
+ lines.extend([_markdown_table(self.drift.findings), ""])
556
+
557
+ lines.extend(["## Validation", ""])
558
+ if self.validation is None:
559
+ lines.extend(["No expectations were evaluated.", ""])
560
+ else:
561
+ lines.extend([_markdown_table(self.validation.results), ""])
562
+
563
+ if self.ingestion is not None:
564
+ lines.extend(["## Ingestion", "", self.ingestion.to_markdown(), ""])
565
+
566
+ lines.extend(["## Decisions", ""])
567
+ if self.decisions.empty:
568
+ lines.extend(["No cleaner decisions available.", ""])
569
+ else:
570
+ lines.extend([_markdown_table(self.decisions), ""])
571
+
572
+ return "\n".join(lines).rstrip() + "\n"
573
+
574
+ def to_dict(self) -> dict[str, object]:
575
+ """Return a JSON-friendly representation of the report."""
576
+ return {
577
+ "source": self.source,
578
+ "library_version": self.library_version,
579
+ "success": self.success,
580
+ "overview": {
581
+ str(key): _json_safe(value) for key, value in self.overview.items()
582
+ },
583
+ "findings": _records(self.findings),
584
+ "profile": _records(self.profile),
585
+ "contract": (
586
+ None
587
+ if self.drift is None
588
+ else {
589
+ "has_drift": self.drift.has_drift,
590
+ "has_errors": self.drift.has_errors,
591
+ "findings": _records(self.drift.findings),
592
+ }
593
+ ),
594
+ "validation": (
595
+ None
596
+ if self.validation is None
597
+ else {
598
+ "source": self.validation.source,
599
+ "success": self.validation.success,
600
+ "results": _records(self.validation.results),
601
+ }
602
+ ),
603
+ "ingestion": (None if self.ingestion is None else self.ingestion.to_dict()),
604
+ "decisions": _records(self.decisions),
605
+ "high_missing_threshold": self.high_missing_threshold,
606
+ }
607
+
608
+ def to_json(self, **kwargs: object) -> str:
609
+ """Serialize the report to JSON."""
610
+ return json.dumps(self.to_dict(), **kwargs) # type: ignore[arg-type]
611
+
612
+ def raise_if_failed(self, message: str = "Batch audit failed") -> None:
613
+ """Raise ``ValueError`` when any error-severity finding exists."""
614
+ if not self.success:
615
+ raise ValueError(f"{message}:\n{self.summary()}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: universal-data-cleaner
3
- Version: 2.6.0
3
+ Version: 2.7.0
4
4
  Summary: Production-ready, scikit-learn-compatible data cleaning transformer for pandas.
5
5
  Author: Haseeb Khan
6
6
  License-Expression: MIT
@@ -59,6 +59,7 @@ The docs site is the central reference. This README is the short entry point.
59
59
  | [Cleaning data](https://devlprkhan.github.io/universal-data-cleaner/cleaning/) | Config, roles, imputation, outliers, datetimes |
60
60
  | [Contracts & drift](https://devlprkhan.github.io/universal-data-cleaner/contracts/) | `ColumnSpec`, `DataContract`, drift checks |
61
61
  | [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads and ingestion reports |
62
+ | [Batch reporting](https://devlprkhan.github.io/universal-data-cleaner/reporting/) | `CleanerReport` and the `data-cleaner audit` CLI |
62
63
  | [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
63
64
  | [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
64
65
  | [Artifacts & reproducibility](https://devlprkhan.github.io/universal-data-cleaner/artifacts/) | Decision log, manifests, fingerprints, save/load |
@@ -135,6 +136,8 @@ for the full explanation.
135
136
  - optional missing-value indicators and constant-column dropping
136
137
  - safe CSV ingestion with contract-driven coercion, identifier protection, date
137
138
  and boolean guards, and an audit report
139
+ - `CleanerReport` combining profile, contract drift, validation, ingestion, and
140
+ cleaner decisions, plus a `data-cleaner audit` CLI
138
141
  - declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
139
142
  - automatic train-schema contract inference and transform-time drift reports
140
143
  - expectation checks and validation reports
@@ -2,6 +2,7 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  src/data_cleaner/__init__.py
5
+ src/data_cleaner/__main__.py
5
6
  src/data_cleaner/_roles.py
6
7
  src/data_cleaner/_version.py
7
8
  src/data_cleaner/artifacts.py
@@ -14,13 +15,16 @@ src/data_cleaner/integration.py
14
15
  src/data_cleaner/ml_audit.py
15
16
  src/data_cleaner/profiling.py
16
17
  src/data_cleaner/py.typed
18
+ src/data_cleaner/reporting.py
17
19
  src/data_cleaner/validation.py
18
20
  src/universal_data_cleaner.egg-info/PKG-INFO
19
21
  src/universal_data_cleaner.egg-info/SOURCES.txt
20
22
  src/universal_data_cleaner.egg-info/dependency_links.txt
23
+ src/universal_data_cleaner.egg-info/entry_points.txt
21
24
  src/universal_data_cleaner.egg-info/requires.txt
22
25
  src/universal_data_cleaner.egg-info/top_level.txt
23
26
  tests/test_data_cleaner.py
24
27
  tests/test_ingestion.py
25
28
  tests/test_ml_audit.py
29
+ tests/test_reporting.py
26
30
  tests/test_validation.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ data-cleaner = data_cleaner.__main__:main
@@ -0,0 +1,319 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import json
5
+ import tempfile
6
+ import unittest
7
+ from contextlib import redirect_stderr, redirect_stdout
8
+ from io import StringIO
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import pandas as pd
13
+
14
+ from data_cleaner import (
15
+ CleanerConfig,
16
+ CleanerReport,
17
+ ColumnSpec,
18
+ DataCleaner,
19
+ DataContract,
20
+ not_null,
21
+ )
22
+ from data_cleaner.__main__ import main
23
+
24
+
25
+ def audit_frame() -> pd.DataFrame:
26
+ return pd.DataFrame(
27
+ {
28
+ "empty": [None, None, None, None],
29
+ "constant": ["x", "x", "x", "x"],
30
+ "sparse": [1.0, None, None, None],
31
+ "value": [1, 2, 3, 4],
32
+ }
33
+ )
34
+
35
+
36
+ class CleanerReportTests(unittest.TestCase):
37
+ def test_profile_findings_and_warning_only_report(self) -> None:
38
+ frame = pd.concat([audit_frame(), audit_frame().iloc[[0]]], ignore_index=True)
39
+
40
+ report = CleanerReport.from_frame(frame, source="batch")
41
+
42
+ self.assertEqual(report.overview["rows"], 5)
43
+ self.assertEqual(report.overview["columns"], 4)
44
+ self.assertTrue(report.success)
45
+ self.assertTrue(report.has_warnings)
46
+ self.assertFalse(report.has_errors)
47
+ checks = set(report.findings["check"])
48
+ for check in {
49
+ "empty_column",
50
+ "constant_column",
51
+ "high_missing",
52
+ "duplicate_rows",
53
+ }:
54
+ self.assertIn(check, checks)
55
+ self.assertIn("PASS", report.summary())
56
+ self.assertIn("# Cleaner report: batch", report.to_markdown())
57
+ self.assertIn("CleanerReport", repr(report))
58
+
59
+ payload: dict[str, Any] = report.to_dict()
60
+ self.assertEqual(payload["source"], "batch")
61
+ self.assertTrue(payload["success"])
62
+ self.assertEqual(payload["library_version"], report.library_version)
63
+ self.assertEqual(payload["overview"]["rows"], 5)
64
+ self.assertTrue(payload["profile"])
65
+ self.assertTrue(payload["findings"])
66
+ json.loads(report.to_json())
67
+
68
+ def test_contract_errors_fail_the_report(self) -> None:
69
+ contract = DataContract(
70
+ columns=(
71
+ ColumnSpec("age", role="numeric", min_value=0, max_value=120),
72
+ ColumnSpec("plan", role="category", allowed_values=("free", "pro")),
73
+ )
74
+ )
75
+ frame = pd.DataFrame({"age": [30, 200], "plan": ["free", "enterprise"]})
76
+
77
+ report = CleanerReport.from_frame(frame, contract=contract)
78
+
79
+ self.assertFalse(report.success)
80
+ self.assertTrue(report.has_errors)
81
+ self.assertIsNotNone(report.drift)
82
+ assert report.drift is not None
83
+ self.assertTrue(report.drift.has_errors)
84
+ checks = set(report.findings["check"])
85
+ self.assertIn("value_out_of_range", checks)
86
+ self.assertIn("unexpected_category", checks)
87
+ self.assertEqual(set(report.errors["source"]), {"contract"})
88
+ with self.assertRaises(ValueError):
89
+ report.raise_if_failed()
90
+ self.assertIn("FAIL", report.to_markdown())
91
+ payload: dict[str, Any] = report.to_dict()
92
+ contract_payload: dict[str, Any] = payload["contract"]
93
+ self.assertTrue(contract_payload["has_errors"])
94
+
95
+ def test_validation_results_fail_the_report(self) -> None:
96
+ frame = pd.DataFrame({"age": [1, None], "name": ["a", "b"]})
97
+
98
+ report = CleanerReport.from_frame(frame, expectations=not_null("age"))
99
+
100
+ self.assertFalse(report.success)
101
+ self.assertIsNotNone(report.validation)
102
+ assert report.validation is not None
103
+ self.assertFalse(report.validation.success)
104
+ self.assertIn("not_null", set(report.findings["check"]))
105
+ self.assertEqual(set(report.errors["source"]), {"validation"})
106
+ payload: dict[str, Any] = report.to_dict()
107
+ validation_payload: dict[str, Any] = payload["validation"]
108
+ self.assertFalse(validation_payload["success"])
109
+
110
+ def test_empty_frame_is_reported(self) -> None:
111
+ frame = pd.DataFrame(
112
+ {
113
+ "a": pd.Series([], dtype=object),
114
+ "b": pd.Series([], dtype=float),
115
+ }
116
+ )
117
+
118
+ report = CleanerReport.from_frame(frame)
119
+
120
+ self.assertEqual(report.overview["rows"], 0)
121
+ self.assertIn("empty_dataset", set(report.findings["check"]))
122
+ self.assertTrue(report.success)
123
+ self.assertNotIn("empty_column", set(report.findings["check"]))
124
+
125
+ def test_high_missing_threshold_can_be_adjusted(self) -> None:
126
+ frame = pd.DataFrame({"sparse": [1.0, None, None, None]})
127
+
128
+ disabled = CleanerReport.from_frame(frame, high_missing_threshold=None)
129
+ self.assertNotIn("high_missing", set(disabled.findings["check"]))
130
+
131
+ strict = CleanerReport.from_frame(frame, high_missing_threshold=10)
132
+ self.assertIn("high_missing", set(strict.findings["check"]))
133
+
134
+ with self.assertRaises(ValueError):
135
+ CleanerReport.from_frame(frame, high_missing_threshold=101)
136
+
137
+ def test_from_csv_attaches_ingestion_and_profile(self) -> None:
138
+ contract = DataContract(
139
+ columns=(
140
+ ColumnSpec("customer_id", role="id", preserve_leading_zeros=True),
141
+ ColumnSpec("amount", role="numeric"),
142
+ )
143
+ )
144
+ csv = 'customer_id,amount\n001,"$1,234.50"\n002,12\n'
145
+
146
+ report = CleanerReport.from_csv(io.StringIO(csv), contract=contract)
147
+
148
+ self.assertIsNotNone(report.ingestion)
149
+ self.assertEqual(report.overview["rows"], 2)
150
+ checks = set(report.findings["check"])
151
+ self.assertIn("leading_zeros_preserved", checks)
152
+ self.assertIn("currency_symbol", checks)
153
+ self.assertTrue(report.success)
154
+ payload: dict[str, Any] = report.to_dict()
155
+ self.assertIsNotNone(payload["ingestion"])
156
+ ingestion_payload: dict[str, Any] = payload["ingestion"]
157
+ self.assertEqual(ingestion_payload["rows"], 2)
158
+ self.assertIn("## Ingestion", report.to_markdown())
159
+
160
+ def test_from_cleaner_uses_contract_and_decisions(self) -> None:
161
+ train = pd.DataFrame(
162
+ {
163
+ "age": [20, 30, 40, 50, 60],
164
+ "dept": ["a", "b", "a", "b", "a"],
165
+ }
166
+ )
167
+ cleaner = DataCleaner(CleanerConfig()).fit(train)
168
+ batch = pd.DataFrame({"age": [25, 35], "dept": ["a", "b"]})
169
+
170
+ report = CleanerReport.from_cleaner(cleaner, batch, source="batch")
171
+
172
+ self.assertFalse(report.decisions.empty)
173
+ self.assertIsNotNone(report.drift)
174
+ self.assertEqual(report.overview["rows"], 2)
175
+ self.assertIn("column", report.decisions.columns)
176
+ self.assertIn("action", report.decisions.columns)
177
+ payload: dict[str, Any] = report.to_dict()
178
+ self.assertTrue(payload["decisions"])
179
+ self.assertIsNotNone(payload["contract"])
180
+
181
+ def test_to_dict_handles_timestamps_and_missing_values(self) -> None:
182
+ frame = pd.DataFrame(
183
+ {
184
+ "when": pd.Series([pd.Timestamp("2024-01-01"), pd.NaT]),
185
+ "value": [1.5, None],
186
+ }
187
+ )
188
+
189
+ report = CleanerReport.from_frame(frame)
190
+ payload = json.loads(report.to_json())
191
+
192
+ self.assertEqual(payload["overview"]["rows"], 2)
193
+ self.assertEqual(len(payload["profile"]), 2)
194
+ self.assertTrue(all(isinstance(item, dict) for item in payload["profile"]))
195
+
196
+
197
+ class AuditCliTests(unittest.TestCase):
198
+ def test_audit_markdown_to_stdout(self) -> None:
199
+ with tempfile.TemporaryDirectory() as directory:
200
+ path = Path(directory) / "data.csv"
201
+ path.write_text("value\n1\n2\n", encoding="utf-8")
202
+ stdout = StringIO()
203
+
204
+ with redirect_stdout(stdout), redirect_stderr(StringIO()):
205
+ code = main(["audit", str(path)])
206
+
207
+ self.assertEqual(code, 0)
208
+ output = stdout.getvalue()
209
+ self.assertIn("# Cleaner report", output)
210
+ self.assertIn("PASS", output)
211
+
212
+ def test_audit_json_output_reports_ingestion_errors(self) -> None:
213
+ with tempfile.TemporaryDirectory() as directory:
214
+ path = Path(directory) / "data.csv"
215
+ path.write_text("amount\nN/A\n1\n", encoding="utf-8")
216
+ contract_path = Path(directory) / "contract.json"
217
+ contract = DataContract(columns=(ColumnSpec("amount", role="numeric"),))
218
+ contract_path.write_text(contract.to_json(), encoding="utf-8")
219
+ output_path = Path(directory) / "report.json"
220
+
221
+ with redirect_stdout(StringIO()), redirect_stderr(StringIO()):
222
+ code = main(
223
+ [
224
+ "audit",
225
+ str(path),
226
+ "--contract",
227
+ str(contract_path),
228
+ "--format",
229
+ "json",
230
+ "--output",
231
+ str(output_path),
232
+ "--no-profile",
233
+ ]
234
+ )
235
+
236
+ self.assertEqual(code, 1)
237
+ payload = json.loads(output_path.read_text(encoding="utf-8"))
238
+ self.assertFalse(payload["success"])
239
+ self.assertTrue(
240
+ any(
241
+ finding["check"] == "unparseable_values"
242
+ for finding in payload["findings"]
243
+ )
244
+ )
245
+
246
+ def test_audit_with_fitted_cleaner(self) -> None:
247
+ with tempfile.TemporaryDirectory() as directory:
248
+ train = pd.DataFrame(
249
+ {
250
+ "age": [20, 30, 40, 50, 60],
251
+ "dept": ["a", "b", "a", "b", "a"],
252
+ }
253
+ )
254
+ cleaner = DataCleaner(CleanerConfig()).fit(train)
255
+ artifact = Path(directory) / "cleaner.joblib"
256
+ cleaner.save(artifact)
257
+
258
+ path = Path(directory) / "batch.csv"
259
+ path.write_text("age,dept\n25,a\n35,b\n", encoding="utf-8")
260
+ output_path = Path(directory) / "report.json"
261
+
262
+ with redirect_stdout(StringIO()), redirect_stderr(StringIO()):
263
+ code = main(
264
+ [
265
+ "audit",
266
+ str(path),
267
+ "--cleaner",
268
+ str(artifact),
269
+ "--format",
270
+ "json",
271
+ "--output",
272
+ str(output_path),
273
+ "--no-profile",
274
+ ]
275
+ )
276
+
277
+ self.assertEqual(code, 0)
278
+ payload = json.loads(output_path.read_text(encoding="utf-8"))
279
+ self.assertTrue(payload["decisions"])
280
+ self.assertIsNotNone(payload["contract"])
281
+
282
+ def test_fail_on_warning_changes_the_exit_code(self) -> None:
283
+ with tempfile.TemporaryDirectory() as directory:
284
+ path = Path(directory) / "data.csv"
285
+ path.write_text("value\n1\n1\n", encoding="utf-8")
286
+ output_path = Path(directory) / "report.json"
287
+
288
+ with redirect_stdout(StringIO()), redirect_stderr(StringIO()):
289
+ code = main(
290
+ [
291
+ "audit",
292
+ str(path),
293
+ "--fail-on-warning",
294
+ "--format",
295
+ "json",
296
+ "--output",
297
+ str(output_path),
298
+ ]
299
+ )
300
+
301
+ self.assertEqual(code, 1)
302
+ payload = json.loads(output_path.read_text(encoding="utf-8"))
303
+ self.assertTrue(payload["success"])
304
+ self.assertTrue(
305
+ any(finding["severity"] == "warning" for finding in payload["findings"])
306
+ )
307
+
308
+ def test_cli_returns_2_for_missing_input_or_bad_contract(self) -> None:
309
+ with tempfile.TemporaryDirectory() as directory:
310
+ missing = Path(directory) / "missing.csv"
311
+ with redirect_stdout(StringIO()), redirect_stderr(StringIO()):
312
+ self.assertEqual(main(["audit", str(missing)]), 2)
313
+
314
+ path = Path(directory) / "data.csv"
315
+ path.write_text("value\n1\n", encoding="utf-8")
316
+ bad = Path(directory) / "contract.json"
317
+ bad.write_text("{not json", encoding="utf-8")
318
+ with redirect_stdout(StringIO()), redirect_stderr(StringIO()):
319
+ self.assertEqual(main(["audit", str(path), "--contract", str(bad)]), 2)