universal-data-cleaner 2.5.2__tar.gz → 2.6.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 (28) hide show
  1. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/PKG-INFO +5 -1
  2. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/README.md +4 -0
  3. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/pyproject.toml +1 -1
  4. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/__init__.py +4 -0
  5. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/_version.py +1 -1
  6. universal_data_cleaner-2.6.0/src/data_cleaner/ingestion.py +712 -0
  7. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/universal_data_cleaner.egg-info/PKG-INFO +5 -1
  8. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/universal_data_cleaner.egg-info/SOURCES.txt +2 -0
  9. universal_data_cleaner-2.6.0/tests/test_ingestion.py +246 -0
  10. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/LICENSE +0 -0
  11. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/setup.cfg +0 -0
  12. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/_roles.py +0 -0
  13. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/artifacts.py +0 -0
  14. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/cleaner.py +0 -0
  15. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/config.py +0 -0
  16. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/contract.py +0 -0
  17. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/decisions.py +0 -0
  18. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/integration.py +0 -0
  19. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/ml_audit.py +0 -0
  20. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/profiling.py +0 -0
  21. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/py.typed +0 -0
  22. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/data_cleaner/validation.py +0 -0
  23. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/universal_data_cleaner.egg-info/dependency_links.txt +0 -0
  24. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/universal_data_cleaner.egg-info/requires.txt +0 -0
  25. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/src/universal_data_cleaner.egg-info/top_level.txt +0 -0
  26. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/tests/test_data_cleaner.py +0 -0
  27. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.0}/tests/test_ml_audit.py +0 -0
  28. {universal_data_cleaner-2.5.2 → universal_data_cleaner-2.6.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.5.2
3
+ Version: 2.6.0
4
4
  Summary: Production-ready, scikit-learn-compatible data cleaning transformer for pandas.
5
5
  Author: Haseeb Khan
6
6
  License-Expression: MIT
@@ -58,12 +58,14 @@ The docs site is the central reference. This README is the short entry point.
58
58
  | [Leak-safe workflow](https://devlprkhan.github.io/universal-data-cleaner/leak-safe-workflow/) | The fit/transform contract and common mistakes |
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
+ | [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads and ingestion reports |
61
62
  | [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
62
63
  | [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
63
64
  | [Artifacts & reproducibility](https://devlprkhan.github.io/universal-data-cleaner/artifacts/) | Decision log, manifests, fingerprints, save/load |
64
65
  | [Production guide](https://devlprkhan.github.io/universal-data-cleaner/production/) | Deployment checklist and failure modes |
65
66
  | [API reference](https://devlprkhan.github.io/universal-data-cleaner/api/) | Generated from the package docstrings |
66
67
  | [Changelog](https://devlprkhan.github.io/universal-data-cleaner/changelog/) | Release notes |
68
+ | [Upcoming](https://devlprkhan.github.io/universal-data-cleaner/upcoming/) | What ships next and what is out of scope |
67
69
 
68
70
  ## Install
69
71
 
@@ -131,6 +133,8 @@ for the full explanation.
131
133
  - boolean coercion and imputation
132
134
  - datetime parsing plus calendar feature extraction
133
135
  - optional missing-value indicators and constant-column dropping
136
+ - safe CSV ingestion with contract-driven coercion, identifier protection, date
137
+ and boolean guards, and an audit report
134
138
  - declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
135
139
  - automatic train-schema contract inference and transform-time drift reports
136
140
  - expectation checks and validation reports
@@ -24,12 +24,14 @@ The docs site is the central reference. This README is the short entry point.
24
24
  | [Leak-safe workflow](https://devlprkhan.github.io/universal-data-cleaner/leak-safe-workflow/) | The fit/transform contract and common mistakes |
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
+ | [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads and ingestion reports |
27
28
  | [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
28
29
  | [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
29
30
  | [Artifacts & reproducibility](https://devlprkhan.github.io/universal-data-cleaner/artifacts/) | Decision log, manifests, fingerprints, save/load |
30
31
  | [Production guide](https://devlprkhan.github.io/universal-data-cleaner/production/) | Deployment checklist and failure modes |
31
32
  | [API reference](https://devlprkhan.github.io/universal-data-cleaner/api/) | Generated from the package docstrings |
32
33
  | [Changelog](https://devlprkhan.github.io/universal-data-cleaner/changelog/) | Release notes |
34
+ | [Upcoming](https://devlprkhan.github.io/universal-data-cleaner/upcoming/) | What ships next and what is out of scope |
33
35
 
34
36
  ## Install
35
37
 
@@ -97,6 +99,8 @@ for the full explanation.
97
99
  - boolean coercion and imputation
98
100
  - datetime parsing plus calendar feature extraction
99
101
  - optional missing-value indicators and constant-column dropping
102
+ - safe CSV ingestion with contract-driven coercion, identifier protection, date
103
+ and boolean guards, and an audit report
100
104
  - declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
101
105
  - automatic train-schema contract inference and transform-time drift reports
102
106
  - 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.5.2"
7
+ version = "2.6.0"
8
8
  description = "Production-ready, scikit-learn-compatible data cleaning transformer for pandas."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -22,6 +22,7 @@ from .cleaner import DataCleaner
22
22
  from .config import CleanerConfig
23
23
  from .contract import ColumnSpec, Contract, DataContract, DriftReport
24
24
  from .decisions import CleaningDecision
25
+ from .ingestion import IngestionError, IngestionReport, read_csv_safe
25
26
  from .integration import (
26
27
  DeduplicationReport,
27
28
  JoinDiagnosis,
@@ -61,6 +62,8 @@ __all__ = [
61
62
  "DeduplicationReport",
62
63
  "DriftReport",
63
64
  "Expectation",
65
+ "IngestionError",
66
+ "IngestionReport",
64
67
  "JoinDiagnosis",
65
68
  "ReferentialIntegrityReport",
66
69
  "SplitAudit",
@@ -83,6 +86,7 @@ __all__ = [
83
86
  "matches_pattern",
84
87
  "not_null",
85
88
  "profile_dataframe",
89
+ "read_csv_safe",
86
90
  "row_count_between",
87
91
  "unique",
88
92
  "validate",
@@ -1,4 +1,4 @@
1
1
  """Single source of truth for the package version."""
2
2
 
3
- __version__ = "2.5.2"
3
+ __version__ = "2.6.0"
4
4
  _ARTIFACT_VERSION = 2
@@ -0,0 +1,712 @@
1
+ """Safe CSV ingestion with explicit coercion and an audit report.
2
+
3
+ The reader starts by loading every field as text. It then applies either the
4
+ supplied :class:`~data_cleaner.DataContract` or a conservative inference pass,
5
+ recording every normalization it performs. The goal is not to guess silently:
6
+ the returned frame is typed, and the :class:`IngestionReport` explains what was
7
+ changed and why.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import os
14
+ import re
15
+ from collections import Counter
16
+ from dataclasses import dataclass
17
+ from typing import IO, Any, Literal
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+ from ._roles import _ROLE_TO_KIND, _normalize_kind, _series_kind
23
+ from .contract import ColumnSpec, DataContract
24
+
25
+ LOGGER = logging.getLogger(__name__)
26
+
27
+ IngestionPolicy = Literal["warn", "raise", "ignore"]
28
+ IngestionSeverity = Literal["error", "warning"]
29
+
30
+ _INGESTION_COLUMNS = ["column", "check", "severity", "message", "count"]
31
+ _COLUMN_COLUMNS = [
32
+ "column",
33
+ "detected_kind",
34
+ "output_kind",
35
+ "output_dtype",
36
+ "non_null",
37
+ "missing",
38
+ ]
39
+
40
+ _RESERVED_READ_KWARGS = {
41
+ "converters",
42
+ "decimal",
43
+ "dtype",
44
+ "keep_default_na",
45
+ "na_filter",
46
+ "na_values",
47
+ "parse_dates",
48
+ "thousands",
49
+ }
50
+
51
+ _CURRENCY_CHARS = "€£¥₹₽₩¢$"
52
+ _NUMBER_RE = re.compile(r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?")
53
+ _THOUSANDS_RE = re.compile(r"^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$")
54
+ _DECIMAL_COMMA_RE = re.compile(r"^[+-]?\d+,\d{1,6}$")
55
+ _AMBIGUOUS_DATE_RE = re.compile(r"^(\d{1,2})[/-](\d{1,2})[/-]\d{2,4}$")
56
+ _DATE_STRUCTURE_RE = re.compile(
57
+ r"(?:\d{1,4}[-/]\d{1,2}[-/]\d{1,4})|(?:[T:])|"
58
+ r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)",
59
+ re.IGNORECASE,
60
+ )
61
+ _DATE_VALUE_RE = re.compile(
62
+ r"^(?:\d{1,4}[-/]\d{1,2}[-/]\d{1,4})|"
63
+ r"^(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)",
64
+ re.IGNORECASE,
65
+ )
66
+
67
+ _TEXT_BOOLEAN_TOKENS = {
68
+ "true": True,
69
+ "t": True,
70
+ "yes": True,
71
+ "y": True,
72
+ "false": False,
73
+ "f": False,
74
+ "no": False,
75
+ "n": False,
76
+ }
77
+ _NUMERIC_BOOLEAN_TOKENS = {"1": True, "0": False}
78
+ _NONSTANDARD_BOOLEAN_TOKENS = {"t", "f", "yes", "no", "y", "n"}
79
+
80
+ _NUMERIC_FLAG_MESSAGES = {
81
+ "currency_symbol": "column '{column}' had {count} value(s) with currency "
82
+ "symbols; symbols were removed",
83
+ "thousands_separator": "column '{column}' had {count} value(s) with thousands "
84
+ "separators; separators were removed",
85
+ "percent_symbol": "column '{column}' had {count} value(s) with percent signs; "
86
+ "values were divided by 100",
87
+ "parentheses_negative": "column '{column}' had {count} value(s) in accounting "
88
+ "parentheses; values were treated as negative",
89
+ "decimal_comma": "column '{column}' had {count} value(s) with decimal commas; "
90
+ "commas were treated as decimal points",
91
+ }
92
+ _DATE_FLAG_MESSAGES = {
93
+ "ambiguous_date_format": "column '{column}' had {count} date(s) with an "
94
+ "ambiguous day/month order; pass ColumnSpec.date_format to make it explicit",
95
+ "compact_date": "column '{column}' had {count} date(s) in YYYYMMDD form; "
96
+ "values were parsed as dates",
97
+ "excel_serial_date": "column '{column}' had {count} date(s) stored as Excel "
98
+ "serial numbers; values were parsed as dates",
99
+ }
100
+ _BOOLEAN_FLAG_MESSAGES = {
101
+ "boolean_tokens": "column '{column}' had {count} value(s) using Y/N-style "
102
+ "boolean tokens; values were parsed as booleans",
103
+ }
104
+
105
+
106
+ @dataclass(eq=False)
107
+ class IngestionReport:
108
+ """Audit report returned by :func:`read_csv_safe`.
109
+
110
+ ``findings`` is a tidy DataFrame with ``column``, ``check``, ``severity``,
111
+ ``message``, and ``count`` columns. ``columns`` summarizes how each input
112
+ column was detected and typed. Neither table includes raw cell values.
113
+ """
114
+
115
+ source: str
116
+ rows: int
117
+ columns: pd.DataFrame
118
+ findings: pd.DataFrame
119
+
120
+ @property
121
+ def success(self) -> bool:
122
+ """Whether ingestion found no error-severity issues."""
123
+ if self.findings.empty:
124
+ return True
125
+ return bool((self.findings["severity"] == "error").sum() == 0)
126
+
127
+ @property
128
+ def errors(self) -> pd.DataFrame:
129
+ """Findings with error severity."""
130
+ if self.findings.empty:
131
+ return self.findings.copy()
132
+ return self.findings[self.findings["severity"] == "error"]
133
+
134
+ @property
135
+ def warnings(self) -> pd.DataFrame:
136
+ """Findings with warning severity."""
137
+ if self.findings.empty:
138
+ return self.findings.copy()
139
+ return self.findings[self.findings["severity"] == "warning"]
140
+
141
+ @property
142
+ def has_errors(self) -> bool:
143
+ """Whether at least one error-severity finding exists."""
144
+ return not self.errors.empty
145
+
146
+ @property
147
+ def has_warnings(self) -> bool:
148
+ """Whether at least one warning-severity finding exists."""
149
+ return not self.warnings.empty
150
+
151
+ def summary(self) -> str:
152
+ """Return a short human-readable description of the findings."""
153
+ if self.findings.empty:
154
+ return "no ingestion issues detected"
155
+ lines = [
156
+ f"- [{row['severity']}] {row['column']}: {row['message']}"
157
+ for _, row in self.findings.iterrows()
158
+ ]
159
+ return "\n".join(lines)
160
+
161
+ def to_markdown(self) -> str:
162
+ """Render the findings as a Markdown table (falls back to text)."""
163
+ status = "PASS" if self.success else "FAIL"
164
+ if self.findings.empty:
165
+ return f"**{status}** — no ingestion issues detected."
166
+ lines = [
167
+ f"**{status}** — {len(self.findings)} finding(s): "
168
+ f"{len(self.errors)} error(s), {len(self.warnings)} warning(s)."
169
+ ]
170
+ try:
171
+ lines.append(self.findings.to_markdown(index=False))
172
+ except ImportError: # tabulate is optional
173
+ lines.append(self.findings.to_string(index=False))
174
+ return "\n".join(lines)
175
+
176
+ def to_dict(self) -> dict[str, object]:
177
+ """Return a JSON-friendly representation of the report."""
178
+ return {
179
+ "source": self.source,
180
+ "rows": self.rows,
181
+ "success": self.success,
182
+ "columns": [dict(record) for record in self.columns.to_dict("records")],
183
+ "findings": [dict(record) for record in self.findings.to_dict("records")],
184
+ }
185
+
186
+ def raise_if_failed(self, message: str = "CSV ingestion failed") -> None:
187
+ """Raise ``IngestionError`` when an error-severity finding exists."""
188
+ if not self.success:
189
+ raise IngestionError(f"{message}:\n{self.summary()}", self)
190
+
191
+
192
+ class IngestionError(ValueError):
193
+ """Raised when ingestion finds error-severity issues and policy is ``raise``."""
194
+
195
+ def __init__(self, message: str, report: IngestionReport) -> None:
196
+ super().__init__(message)
197
+ self.report = report
198
+
199
+
200
+ def _add_finding(
201
+ findings: list[dict[str, object]],
202
+ column: str,
203
+ check: str,
204
+ severity: IngestionSeverity,
205
+ message: str,
206
+ count: int,
207
+ ) -> None:
208
+ findings.append(
209
+ {
210
+ "column": column,
211
+ "check": check,
212
+ "severity": severity,
213
+ "message": message,
214
+ "count": count,
215
+ }
216
+ )
217
+
218
+
219
+ def _add_flag_findings(
220
+ findings: list[dict[str, object]],
221
+ column: str,
222
+ flags: dict[str, int],
223
+ messages: dict[str, str],
224
+ ) -> None:
225
+ for flag, count in flags.items():
226
+ if count:
227
+ _add_finding(
228
+ findings,
229
+ column,
230
+ flag,
231
+ "warning",
232
+ messages[flag].format(column=column, count=count),
233
+ count,
234
+ )
235
+
236
+
237
+ def _source_label(source: object) -> str:
238
+ if isinstance(source, (str, os.PathLike)):
239
+ return str(source)
240
+ name = getattr(source, "name", None)
241
+ return str(name) if name else "<stream>"
242
+
243
+
244
+ def _blank_to_na(frame: pd.DataFrame) -> pd.DataFrame:
245
+ """Turn empty or whitespace-only text fields into missing values."""
246
+ result = frame.copy(deep=True)
247
+ for column in result.columns:
248
+ series = result[column]
249
+ blank = series.map(lambda value: isinstance(value, str) and not value.strip())
250
+ result[column] = series.mask(blank, pd.NA)
251
+ return result
252
+
253
+
254
+ def _normalize_numeric_text(value: str) -> tuple[str, set[str]]:
255
+ """Normalize spreadsheet number spellings and report the changes made."""
256
+ text = value.strip().replace("\u2212", "-")
257
+ flags: set[str] = set()
258
+ if not text:
259
+ return "", flags
260
+
261
+ if text.startswith("(") and text.endswith(")"):
262
+ text = "-" + text[1:-1].strip()
263
+ flags.add("parentheses_negative")
264
+
265
+ if text.endswith("%"):
266
+ text = text[:-1].strip()
267
+ flags.add("percent_symbol")
268
+
269
+ if any(character in text for character in _CURRENCY_CHARS):
270
+ text = "".join(
271
+ character for character in text if character not in _CURRENCY_CHARS
272
+ ).strip()
273
+ flags.add("currency_symbol")
274
+
275
+ if "," in text and "." in text:
276
+ if text.rfind(",") > text.rfind("."):
277
+ text = text.replace(".", "").replace(",", ".")
278
+ flags.add("decimal_comma")
279
+ flags.add("thousands_separator")
280
+ else:
281
+ text = text.replace(",", "")
282
+ flags.add("thousands_separator")
283
+ elif "," in text:
284
+ if _THOUSANDS_RE.fullmatch(text):
285
+ text = text.replace(",", "")
286
+ flags.add("thousands_separator")
287
+ elif _DECIMAL_COMMA_RE.fullmatch(text):
288
+ text = text.replace(",", ".")
289
+ flags.add("decimal_comma")
290
+
291
+ return text, flags
292
+
293
+
294
+ def _parse_numeric(
295
+ series: pd.Series,
296
+ ) -> tuple[pd.Series, dict[str, int], int, int]:
297
+ """Parse numeric-looking text and return values, flags, invalid, infinite."""
298
+ flags = dict.fromkeys(_NUMERIC_FLAG_MESSAGES, 0)
299
+ normalized: list[str | float] = []
300
+ percent_mask: list[bool] = []
301
+ for value in series:
302
+ if pd.isna(value):
303
+ normalized.append(np.nan)
304
+ percent_mask.append(False)
305
+ continue
306
+ text, value_flags = _normalize_numeric_text(str(value))
307
+ for flag in value_flags:
308
+ flags[flag] += 1
309
+ normalized.append(text)
310
+ percent_mask.append("percent_symbol" in value_flags)
311
+
312
+ parsed = pd.to_numeric(
313
+ pd.Series(normalized, index=series.index), errors="coerce"
314
+ ).astype("float64")
315
+ if any(percent_mask):
316
+ parsed = parsed.mask(
317
+ pd.Series(percent_mask, index=series.index), parsed / 100.0
318
+ )
319
+
320
+ non_finite = int((parsed.notna() & ~np.isfinite(parsed)).sum())
321
+ unparseable = int((series.notna() & parsed.isna()).sum())
322
+ parsed = parsed.mask(parsed.notna() & ~np.isfinite(parsed), np.nan)
323
+ return parsed, flags, unparseable, non_finite
324
+
325
+
326
+ def _parse_boolean(
327
+ series: pd.Series, *, allow_numeric: bool
328
+ ) -> tuple[pd.Series, dict[str, int], int, bool]:
329
+ flags = {"boolean_tokens": 0}
330
+ mapping = dict(_TEXT_BOOLEAN_TOKENS)
331
+ if allow_numeric:
332
+ mapping.update(_NUMERIC_BOOLEAN_TOKENS)
333
+
334
+ values: list[object] = []
335
+ has_alpha = False
336
+ unparseable = 0
337
+ for value in series:
338
+ if pd.isna(value):
339
+ values.append(pd.NA)
340
+ continue
341
+ token = str(value).strip().lower()
342
+ if token in _TEXT_BOOLEAN_TOKENS:
343
+ has_alpha = True
344
+ if token in _NONSTANDARD_BOOLEAN_TOKENS:
345
+ flags["boolean_tokens"] += 1
346
+ if token in mapping:
347
+ values.append(mapping[token])
348
+ else:
349
+ values.append(pd.NA)
350
+ unparseable += 1
351
+
352
+ parsed = pd.Series(values, index=series.index, dtype="boolean")
353
+ return parsed, flags, unparseable, has_alpha
354
+
355
+
356
+ def _parse_datetime(
357
+ series: pd.Series,
358
+ *,
359
+ date_format: str | None,
360
+ allow_serial: bool,
361
+ ) -> tuple[pd.Series, dict[str, int], int]:
362
+ flags = dict.fromkeys(_DATE_FLAG_MESSAGES, 0)
363
+ raw = series.map(lambda value: "" if pd.isna(value) else str(value).strip())
364
+ present = raw != ""
365
+ if not present.any():
366
+ return (
367
+ pd.Series(pd.NaT, index=series.index, dtype="datetime64[ns]"),
368
+ flags,
369
+ 0,
370
+ )
371
+
372
+ values = raw[present]
373
+ parsed = pd.Series(pd.NaT, index=series.index, dtype="datetime64[ns]")
374
+
375
+ if date_format is not None:
376
+ parsed = pd.to_datetime(raw.where(present), format=date_format, errors="coerce")
377
+ elif allow_serial and values.str.fullmatch(r"\d{8}").all():
378
+ parsed.loc[values.index] = pd.to_datetime(
379
+ values, format="%Y%m%d", errors="coerce"
380
+ )
381
+ flags["compact_date"] = int(values.size)
382
+ elif allow_serial and values.str.fullmatch(r"\d{5}(?:\.\d+)?").all():
383
+ serial = pd.to_numeric(values, errors="coerce")
384
+ parsed.loc[values.index] = pd.to_datetime(
385
+ serial, unit="D", origin="1899-12-30", errors="coerce"
386
+ )
387
+ flags["excel_serial_date"] = int(values.size)
388
+ else:
389
+ try:
390
+ parsed = pd.to_datetime(raw.where(present), errors="coerce", format="mixed")
391
+ except (TypeError, ValueError):
392
+ parsed = pd.to_datetime(raw.where(present), errors="coerce")
393
+
394
+ ambiguous = values[values.str.fullmatch(_AMBIGUOUS_DATE_RE)]
395
+ if not ambiguous.empty:
396
+ parts = ambiguous.str.extract(_AMBIGUOUS_DATE_RE)
397
+ first = pd.to_numeric(parts[0], errors="coerce")
398
+ second = pd.to_numeric(parts[1], errors="coerce")
399
+ flags["ambiguous_date_format"] = int(((first <= 12) & (second <= 12)).sum())
400
+
401
+ invalid = int((present & parsed.isna()).sum())
402
+ return parsed, flags, invalid
403
+
404
+
405
+ def _looks_like_identifier(values: pd.Series) -> bool:
406
+ if values.empty:
407
+ return False
408
+ digits = values.str.fullmatch(r"\d+").fillna(False)
409
+ return bool(
410
+ digits.all()
411
+ and values.str.startswith("0").any()
412
+ and values.str.len().gt(1).any()
413
+ )
414
+
415
+
416
+ def _leading_zero_count(series: pd.Series) -> int:
417
+ values = series.dropna().astype(str).str.strip()
418
+ return int(values.str.fullmatch(r"0\d+").fillna(False).sum())
419
+
420
+
421
+ def _classify_series(series: pd.Series) -> str:
422
+ values = series.dropna().map(lambda value: str(value).strip())
423
+ if values.empty:
424
+ return "empty"
425
+ if _looks_like_identifier(values):
426
+ return "identifier"
427
+
428
+ _, _, unparseable, _ = _parse_numeric(series)
429
+ if unparseable == 0:
430
+ return "numeric"
431
+
432
+ _, _, invalid_boolean, has_alpha = _parse_boolean(series, allow_numeric=False)
433
+ if invalid_boolean == 0 and has_alpha:
434
+ return "boolean"
435
+
436
+ if values.str.contains(_DATE_STRUCTURE_RE).any():
437
+ _, _, invalid_date = _parse_datetime(
438
+ series, date_format=None, allow_serial=False
439
+ )
440
+ if invalid_date == 0:
441
+ return "datetime"
442
+ return "text"
443
+
444
+
445
+ def _value_category(value: str) -> str:
446
+ text = value.strip()
447
+ if text.lower() in _TEXT_BOOLEAN_TOKENS:
448
+ return "boolean"
449
+ normalized, _ = _normalize_numeric_text(text)
450
+ if _NUMBER_RE.fullmatch(normalized):
451
+ return "numeric"
452
+ if _DATE_VALUE_RE.search(text):
453
+ return "datetime"
454
+ return "text"
455
+
456
+
457
+ def _mixed_value_count(series: pd.Series) -> int:
458
+ categories = Counter(_value_category(str(value)) for value in series.dropna())
459
+ if len(categories) <= 1:
460
+ return 0
461
+ dominant = max(categories.values())
462
+ return int(sum(categories.values()) - dominant)
463
+
464
+
465
+ def _target_kind(spec: ColumnSpec) -> str | None:
466
+ if spec.role == "ignore":
467
+ return "text"
468
+ if spec.role is not None:
469
+ return _ROLE_TO_KIND.get(spec.role)
470
+ if spec.dtype is not None:
471
+ return _normalize_kind(spec.dtype)
472
+ return None
473
+
474
+
475
+ def _ingest_column(
476
+ series: pd.Series,
477
+ spec: ColumnSpec | None,
478
+ findings: list[dict[str, object]],
479
+ ) -> tuple[pd.Series, str]:
480
+ detected = _classify_series(series)
481
+ target = _target_kind(spec) if spec is not None else None
482
+ preserve_zeros = bool(spec is not None and spec.preserve_leading_zeros)
483
+ if preserve_zeros and target in {"numeric", None}:
484
+ target = "text"
485
+ if target is None:
486
+ if detected == "numeric":
487
+ target = "numeric"
488
+ elif detected == "boolean":
489
+ target = "boolean"
490
+ elif detected == "datetime":
491
+ target = "datetime"
492
+ else:
493
+ target = "text"
494
+
495
+ column = str(series.name)
496
+ if target == "numeric":
497
+ parsed, flags, unparseable, non_finite = _parse_numeric(series)
498
+ _add_flag_findings(findings, column, flags, _NUMERIC_FLAG_MESSAGES)
499
+ if unparseable:
500
+ _add_finding(
501
+ findings,
502
+ column,
503
+ "unparseable_values",
504
+ "error",
505
+ f"column '{column}' has {unparseable} value(s) that could not be "
506
+ "parsed as numeric",
507
+ unparseable,
508
+ )
509
+ if non_finite:
510
+ _add_finding(
511
+ findings,
512
+ column,
513
+ "non_finite_values",
514
+ "warning",
515
+ f"column '{column}' has {non_finite} non-finite value(s) that were "
516
+ "set to missing",
517
+ non_finite,
518
+ )
519
+ return parsed, detected
520
+
521
+ if target == "datetime":
522
+ parsed, flags, invalid = _parse_datetime(
523
+ series,
524
+ date_format=spec.date_format if spec is not None else None,
525
+ allow_serial=True,
526
+ )
527
+ _add_flag_findings(findings, column, flags, _DATE_FLAG_MESSAGES)
528
+ if invalid:
529
+ _add_finding(
530
+ findings,
531
+ column,
532
+ "unparseable_values",
533
+ "error",
534
+ f"column '{column}' has {invalid} value(s) that could not be "
535
+ "parsed as dates",
536
+ invalid,
537
+ )
538
+ return parsed, detected
539
+
540
+ if target == "boolean":
541
+ parsed, flags, invalid, _ = _parse_boolean(series, allow_numeric=True)
542
+ _add_flag_findings(findings, column, flags, _BOOLEAN_FLAG_MESSAGES)
543
+ if invalid:
544
+ _add_finding(
545
+ findings,
546
+ column,
547
+ "unparseable_values",
548
+ "error",
549
+ f"column '{column}' has {invalid} value(s) that could not be "
550
+ "parsed as booleans",
551
+ invalid,
552
+ )
553
+ return parsed, detected
554
+
555
+ result = series.astype(object)
556
+ zeros = _leading_zero_count(series)
557
+ if zeros and (detected == "identifier" or preserve_zeros):
558
+ _add_finding(
559
+ findings,
560
+ column,
561
+ "leading_zeros_preserved",
562
+ "warning",
563
+ f"column '{column}' has {zeros} value(s) with leading zeros; values "
564
+ "were kept as text",
565
+ zeros,
566
+ )
567
+ if detected == "empty":
568
+ _add_finding(
569
+ findings,
570
+ column,
571
+ "empty_column",
572
+ "warning",
573
+ f"column '{column}' has no non-missing values",
574
+ 0,
575
+ )
576
+ if detected == "text" and spec is None:
577
+ mixed = _mixed_value_count(series)
578
+ if mixed:
579
+ _add_finding(
580
+ findings,
581
+ column,
582
+ "mixed_types",
583
+ "warning",
584
+ f"column '{column}' has {mixed} value(s) that do not match the "
585
+ "dominant value type; the column was kept as text",
586
+ mixed,
587
+ )
588
+ return result, detected
589
+
590
+
591
+ def read_csv_safe(
592
+ source: str | os.PathLike[str] | IO[Any],
593
+ contract: DataContract | None = None,
594
+ *,
595
+ on_error: IngestionPolicy = "warn",
596
+ **read_csv_kwargs: Any,
597
+ ) -> tuple[pd.DataFrame, IngestionReport]:
598
+ """Read a CSV as text, coerce it under an optional contract, and audit it.
599
+
600
+ Parameters
601
+ ----------
602
+ source:
603
+ Path or file-like object accepted by :func:`pandas.read_csv`.
604
+ contract:
605
+ Optional :class:`~data_cleaner.DataContract`. Declared columns use their
606
+ role, dtype, and date format. Undeclared columns are kept as text and
607
+ reported instead of being silently typed.
608
+ on_error:
609
+ ``"warn"`` logs error findings and returns the frame (default),
610
+ ``"raise"`` raises :class:`IngestionError` when an error finding exists,
611
+ and ``"ignore"`` suppresses logging while still returning the report.
612
+ **read_csv_kwargs:
613
+ Extra options passed to :func:`pandas.read_csv`. Options that would
614
+ bypass the string-first read (``dtype``, ``na_filter``,
615
+ ``keep_default_na``, ``na_values``, ``parse_dates``, ``converters``,
616
+ ``decimal``, or ``thousands``) are rejected.
617
+
618
+ Returns
619
+ -------
620
+ tuple[pandas.DataFrame, IngestionReport]
621
+ The typed frame and an audit report. String columns are kept as
622
+ ``object`` dtype for consistency across pandas 2.x and 3.x.
623
+
624
+ Notes
625
+ -----
626
+ The reader recognizes common spreadsheet spellings: thousands separators,
627
+ currency symbols, percent signs, accounting parentheses, decimal commas,
628
+ ``YYYYMMDD`` dates, Excel serial dates, and Y/N-style booleans. Normalization
629
+ is reported, never performed silently. Values that cannot be parsed in a
630
+ declared numeric/date/boolean column become missing values and produce an
631
+ error finding.
632
+
633
+ Identifier columns and columns with leading zeros are kept as text. Passing
634
+ a contract is the safest way to protect identifiers and to make date formats
635
+ unambiguous.
636
+ """
637
+ if contract is not None and not isinstance(contract, DataContract):
638
+ raise TypeError("contract must be a DataContract instance or None")
639
+ if on_error not in {"warn", "raise", "ignore"}:
640
+ raise ValueError("on_error must be one of: warn, raise, ignore")
641
+
642
+ conflicts = sorted(_RESERVED_READ_KWARGS.intersection(read_csv_kwargs))
643
+ if conflicts:
644
+ raise TypeError(
645
+ "read_csv_safe manages these read_csv options itself: "
646
+ f"{', '.join(conflicts)}"
647
+ )
648
+
649
+ raw = pd.read_csv(
650
+ source,
651
+ dtype=str,
652
+ keep_default_na=False,
653
+ na_filter=False,
654
+ **read_csv_kwargs,
655
+ )
656
+ frame = _blank_to_na(raw)
657
+
658
+ findings: list[dict[str, object]] = []
659
+ specs = {spec.name: spec for spec in contract.columns} if contract else {}
660
+ if contract is not None:
661
+ for spec in contract.columns:
662
+ if spec.role != "ignore" and spec.name not in frame.columns:
663
+ _add_finding(
664
+ findings,
665
+ spec.name,
666
+ "missing_column",
667
+ "error",
668
+ f"expected column '{spec.name}' is missing from the CSV",
669
+ 1,
670
+ )
671
+ for column in frame.columns:
672
+ if column not in specs:
673
+ _add_finding(
674
+ findings,
675
+ str(column),
676
+ "undeclared_column",
677
+ "warning",
678
+ f"column '{column}' is not declared in the contract; kept as text",
679
+ 1,
680
+ )
681
+
682
+ parsed_columns: dict[str, pd.Series] = {}
683
+ column_rows: list[dict[str, object]] = []
684
+ for column in frame.columns:
685
+ parsed, detected = _ingest_column(frame[column], specs.get(column), findings)
686
+ parsed_columns[str(column)] = parsed
687
+ column_rows.append(
688
+ {
689
+ "column": str(column),
690
+ "detected_kind": detected,
691
+ "output_kind": _series_kind(parsed),
692
+ "output_dtype": str(parsed.dtype),
693
+ "non_null": int(parsed.notna().sum()),
694
+ "missing": int(parsed.isna().sum()),
695
+ }
696
+ )
697
+
698
+ result = pd.DataFrame(parsed_columns, index=frame.index)
699
+ report = IngestionReport(
700
+ source=_source_label(source),
701
+ rows=len(frame),
702
+ columns=pd.DataFrame(column_rows, columns=_COLUMN_COLUMNS),
703
+ findings=pd.DataFrame(findings, columns=_INGESTION_COLUMNS),
704
+ )
705
+
706
+ if on_error == "raise" and not report.success:
707
+ raise IngestionError(f"CSV ingestion failed:\n{report.summary()}", report)
708
+ if on_error == "warn" and not report.findings.empty:
709
+ LOGGER.warning(
710
+ "CSV ingestion issues for %s:\n%s", report.source, report.summary()
711
+ )
712
+ return result, report
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: universal-data-cleaner
3
- Version: 2.5.2
3
+ Version: 2.6.0
4
4
  Summary: Production-ready, scikit-learn-compatible data cleaning transformer for pandas.
5
5
  Author: Haseeb Khan
6
6
  License-Expression: MIT
@@ -58,12 +58,14 @@ The docs site is the central reference. This README is the short entry point.
58
58
  | [Leak-safe workflow](https://devlprkhan.github.io/universal-data-cleaner/leak-safe-workflow/) | The fit/transform contract and common mistakes |
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
+ | [Safe ingestion](https://devlprkhan.github.io/universal-data-cleaner/ingestion/) | Contract-driven CSV reads and ingestion reports |
61
62
  | [Validation, joins & dedup](https://devlprkhan.github.io/universal-data-cleaner/validation-joins/) | Expectations, join diagnostics, integrity, dedup |
62
63
  | [ML split audit](https://devlprkhan.github.io/universal-data-cleaner/ml-split-audit/) | Duplicate, group, temporal, and target leakage |
63
64
  | [Artifacts & reproducibility](https://devlprkhan.github.io/universal-data-cleaner/artifacts/) | Decision log, manifests, fingerprints, save/load |
64
65
  | [Production guide](https://devlprkhan.github.io/universal-data-cleaner/production/) | Deployment checklist and failure modes |
65
66
  | [API reference](https://devlprkhan.github.io/universal-data-cleaner/api/) | Generated from the package docstrings |
66
67
  | [Changelog](https://devlprkhan.github.io/universal-data-cleaner/changelog/) | Release notes |
68
+ | [Upcoming](https://devlprkhan.github.io/universal-data-cleaner/upcoming/) | What ships next and what is out of scope |
67
69
 
68
70
  ## Install
69
71
 
@@ -131,6 +133,8 @@ for the full explanation.
131
133
  - boolean coercion and imputation
132
134
  - datetime parsing plus calendar feature extraction
133
135
  - optional missing-value indicators and constant-column dropping
136
+ - safe CSV ingestion with contract-driven coercion, identifier protection, date
137
+ and boolean guards, and an audit report
134
138
  - declarative contracts with roles, allowed values, ranges, patterns, and uniqueness
135
139
  - automatic train-schema contract inference and transform-time drift reports
136
140
  - expectation checks and validation reports
@@ -9,6 +9,7 @@ src/data_cleaner/cleaner.py
9
9
  src/data_cleaner/config.py
10
10
  src/data_cleaner/contract.py
11
11
  src/data_cleaner/decisions.py
12
+ src/data_cleaner/ingestion.py
12
13
  src/data_cleaner/integration.py
13
14
  src/data_cleaner/ml_audit.py
14
15
  src/data_cleaner/profiling.py
@@ -20,5 +21,6 @@ src/universal_data_cleaner.egg-info/dependency_links.txt
20
21
  src/universal_data_cleaner.egg-info/requires.txt
21
22
  src/universal_data_cleaner.egg-info/top_level.txt
22
23
  tests/test_data_cleaner.py
24
+ tests/test_ingestion.py
23
25
  tests/test_ml_audit.py
24
26
  tests/test_validation.py
@@ -0,0 +1,246 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+ from pandas.api import types as ptypes
10
+
11
+ from data_cleaner import (
12
+ ColumnSpec,
13
+ DataContract,
14
+ IngestionError,
15
+ IngestionReport,
16
+ read_csv_safe,
17
+ )
18
+
19
+
20
+ class SafeCsvIngestionTests(unittest.TestCase):
21
+ def test_contract_controls_coercion_and_reports_normalization(self) -> None:
22
+ csv = (
23
+ "customer_id,amount,signup,active,plan,notes\n"
24
+ '00123,"$1,234.50",2024-01-02,Y,pro,hello\n'
25
+ "00456,12%,2024-02-03,N,free,\n"
26
+ )
27
+ contract = DataContract(
28
+ columns=(
29
+ ColumnSpec("customer_id", role="id", preserve_leading_zeros=True),
30
+ ColumnSpec("amount", role="numeric"),
31
+ ColumnSpec("signup", role="datetime"),
32
+ ColumnSpec("active", role="boolean"),
33
+ ColumnSpec("plan", role="category"),
34
+ ColumnSpec("notes", role="text"),
35
+ )
36
+ )
37
+
38
+ frame, report = read_csv_safe(io.StringIO(csv), contract=contract)
39
+
40
+ self.assertIsInstance(report, IngestionReport)
41
+ self.assertEqual(report.rows, 2)
42
+ self.assertTrue(report.success)
43
+ self.assertFalse(report.has_errors)
44
+ self.assertTrue(report.has_warnings)
45
+ self.assertEqual(frame["customer_id"].tolist(), ["00123", "00456"])
46
+ self.assertTrue(ptypes.is_object_dtype(frame["customer_id"]))
47
+ self.assertEqual(frame["amount"].tolist(), [1234.5, 0.12])
48
+ self.assertTrue(ptypes.is_datetime64_any_dtype(frame["signup"]))
49
+ self.assertEqual(frame["active"].tolist(), [True, False])
50
+ self.assertTrue(ptypes.is_bool_dtype(frame["active"]))
51
+ self.assertEqual(frame["plan"].tolist(), ["pro", "free"])
52
+ self.assertEqual(frame["notes"].iloc[0], "hello")
53
+ self.assertTrue(pd.isna(frame["notes"].iloc[1]))
54
+
55
+ checks = set(report.findings["check"])
56
+ self.assertIn("leading_zeros_preserved", checks)
57
+ self.assertIn("currency_symbol", checks)
58
+ self.assertIn("thousands_separator", checks)
59
+ self.assertIn("percent_symbol", checks)
60
+ self.assertIn("boolean_tokens", checks)
61
+ self.assertNotIn("00123", report.findings.to_string())
62
+ self.assertIn("PASS", report.to_markdown())
63
+ self.assertEqual(report.to_dict()["rows"], 2)
64
+
65
+ def test_infers_types_without_a_contract(self) -> None:
66
+ csv = (
67
+ "id,qty,when,flag,note,mixed\n"
68
+ "001,1,2024-01-01,yes,alpha,1\n"
69
+ "002,2,2024-02-01,no,beta,two\n"
70
+ )
71
+
72
+ frame, report = read_csv_safe(io.StringIO(csv), on_error="ignore")
73
+
74
+ self.assertTrue(ptypes.is_object_dtype(frame["id"]))
75
+ self.assertTrue(ptypes.is_numeric_dtype(frame["qty"]))
76
+ self.assertTrue(ptypes.is_datetime64_any_dtype(frame["when"]))
77
+ self.assertTrue(ptypes.is_bool_dtype(frame["flag"]))
78
+ self.assertTrue(ptypes.is_object_dtype(frame["note"]))
79
+ self.assertTrue(ptypes.is_object_dtype(frame["mixed"]))
80
+ self.assertTrue(report.success)
81
+ self.assertIn("leading_zeros_preserved", set(report.findings["check"]))
82
+ self.assertIn("boolean_tokens", set(report.findings["check"]))
83
+ self.assertIn("mixed_types", set(report.findings["check"]))
84
+
85
+ detected = report.columns.set_index("column")["detected_kind"].to_dict()
86
+ self.assertEqual(detected["id"], "identifier")
87
+ self.assertEqual(detected["qty"], "numeric")
88
+ self.assertEqual(detected["when"], "datetime")
89
+ self.assertEqual(detected["flag"], "boolean")
90
+ self.assertEqual(detected["mixed"], "text")
91
+
92
+ def test_unparseable_contract_values_become_missing_and_can_raise(self) -> None:
93
+ csv = "amount,event\nN/A,2024-01-01\n1,bad-date\n"
94
+ contract = DataContract(
95
+ columns=(
96
+ ColumnSpec("amount", role="numeric"),
97
+ ColumnSpec("event", role="datetime"),
98
+ )
99
+ )
100
+
101
+ frame, report = read_csv_safe(
102
+ io.StringIO(csv), contract=contract, on_error="ignore"
103
+ )
104
+
105
+ self.assertFalse(report.success)
106
+ self.assertEqual(len(report.errors), 2)
107
+ self.assertTrue(pd.isna(frame["amount"].iloc[0]))
108
+ self.assertTrue(pd.isna(frame["event"].iloc[1]))
109
+ self.assertEqual(int(report.findings["count"].sum()), 2)
110
+ with self.assertRaises(IngestionError) as caught:
111
+ read_csv_safe(io.StringIO(csv), contract=contract, on_error="raise")
112
+ self.assertIsInstance(caught.exception.report, IngestionReport)
113
+ self.assertFalse(caught.exception.report.success)
114
+ with self.assertRaises(IngestionError):
115
+ report.raise_if_failed()
116
+
117
+ def test_date_guards_and_explicit_formats(self) -> None:
118
+ csv = (
119
+ "compact,excel,custom,ambiguous\n"
120
+ "20240101,45292,31/12/2024,01/02/2024\n"
121
+ "20240102,45293,01/01/2025,02/03/2024\n"
122
+ )
123
+ contract = DataContract(
124
+ columns=(
125
+ ColumnSpec("compact", role="datetime"),
126
+ ColumnSpec("excel", role="datetime"),
127
+ ColumnSpec("custom", role="datetime", date_format="%d/%m/%Y"),
128
+ ColumnSpec("ambiguous", role="datetime"),
129
+ )
130
+ )
131
+
132
+ frame, report = read_csv_safe(
133
+ io.StringIO(csv), contract=contract, on_error="ignore"
134
+ )
135
+
136
+ self.assertEqual(frame["compact"].iloc[0], pd.Timestamp("2024-01-01"))
137
+ self.assertEqual(frame["excel"].iloc[0], pd.Timestamp("2024-01-01"))
138
+ self.assertEqual(frame["custom"].iloc[0], pd.Timestamp("2024-12-31"))
139
+ self.assertEqual(frame["ambiguous"].iloc[0], pd.Timestamp("2024-01-02"))
140
+ checks = set(report.findings["check"])
141
+ self.assertIn("compact_date", checks)
142
+ self.assertIn("excel_serial_date", checks)
143
+ self.assertIn("ambiguous_date_format", checks)
144
+
145
+ def test_numeric_spellings_are_normalized(self) -> None:
146
+ csv = 'amount\n"$1,234.50"\n(42)\n12.5%\n"1.234,56"\n'
147
+
148
+ frame, report = read_csv_safe(io.StringIO(csv), on_error="ignore")
149
+
150
+ self.assertEqual(frame["amount"].tolist(), [1234.5, -42.0, 0.125, 1234.56])
151
+ checks = set(report.findings["check"])
152
+ self.assertIn("currency_symbol", checks)
153
+ self.assertIn("thousands_separator", checks)
154
+ self.assertIn("parentheses_negative", checks)
155
+ self.assertIn("percent_symbol", checks)
156
+ self.assertIn("decimal_comma", checks)
157
+
158
+ def test_blank_fields_are_missing_but_na_text_is_preserved(self) -> None:
159
+ csv = "notes,amount\nNA,1\n,2\n"
160
+
161
+ frame, report = read_csv_safe(io.StringIO(csv), on_error="ignore")
162
+
163
+ self.assertEqual(frame["notes"].iloc[0], "NA")
164
+ self.assertTrue(pd.isna(frame["notes"].iloc[1]))
165
+ self.assertEqual(frame["amount"].tolist(), [1.0, 2.0])
166
+ self.assertTrue(report.success)
167
+
168
+ def test_empty_column_and_empty_file_are_reported(self) -> None:
169
+ csv = "empty,value\n,\n,\n"
170
+
171
+ frame, report = read_csv_safe(io.StringIO(csv), on_error="ignore")
172
+
173
+ self.assertTrue(frame["empty"].isna().all())
174
+ self.assertIn("empty_column", set(report.findings["check"]))
175
+ self.assertEqual(report.rows, 2)
176
+
177
+ empty_frame, empty_report = read_csv_safe(
178
+ io.StringIO("a,b\n"), on_error="ignore"
179
+ )
180
+ self.assertTrue(empty_frame.empty)
181
+ self.assertEqual(empty_report.rows, 0)
182
+ self.assertEqual(list(empty_frame.columns), ["a", "b"])
183
+
184
+ def test_path_input_and_reserved_options(self) -> None:
185
+ with tempfile.TemporaryDirectory() as directory:
186
+ path = Path(directory) / "data.csv"
187
+ path.write_text("id,value\n001,1\n002,2\n", encoding="utf-8")
188
+
189
+ frame, report = read_csv_safe(path, on_error="ignore")
190
+
191
+ self.assertEqual(report.source, str(path))
192
+ self.assertEqual(frame["id"].tolist(), ["001", "002"])
193
+
194
+ with self.assertRaises(TypeError):
195
+ read_csv_safe(io.StringIO("a\n1\n"), dtype="int64")
196
+ with self.assertRaises(TypeError):
197
+ read_csv_safe(io.StringIO("a\n1\n"), parse_dates=["a"])
198
+ with self.assertRaises(ValueError):
199
+ read_csv_safe(io.StringIO("a\n1\n"), on_error="unknown") # type: ignore[arg-type]
200
+ with self.assertRaises(TypeError):
201
+ read_csv_safe(io.StringIO("a\n1\n"), contract=object()) # type: ignore[arg-type]
202
+
203
+ def test_contract_reports_missing_and_undeclared_columns(self) -> None:
204
+ csv = "id,extra\n001,x\n"
205
+ contract = DataContract(columns=(ColumnSpec("id", role="id"),))
206
+
207
+ frame, report = read_csv_safe(
208
+ io.StringIO(csv), contract=contract, on_error="ignore"
209
+ )
210
+
211
+ self.assertEqual(frame["id"].tolist(), ["001"])
212
+ checks = set(report.findings["check"])
213
+ self.assertIn("undeclared_column", checks)
214
+ self.assertNotIn("missing_column", checks)
215
+
216
+ contract = DataContract(
217
+ columns=(ColumnSpec("id", role="id"), ColumnSpec("missing"))
218
+ )
219
+ _, report = read_csv_safe(
220
+ io.StringIO("id\n001\n"), contract=contract, on_error="ignore"
221
+ )
222
+ self.assertIn("missing_column", set(report.findings["check"]))
223
+ self.assertFalse(report.success)
224
+
225
+ def test_preserve_leading_zeros_without_an_id_role(self) -> None:
226
+ csv = "code\n001\n002\n"
227
+ contract = DataContract(
228
+ columns=(ColumnSpec("code", role="numeric", preserve_leading_zeros=True),)
229
+ )
230
+
231
+ frame, report = read_csv_safe(
232
+ io.StringIO(csv), contract=contract, on_error="ignore"
233
+ )
234
+
235
+ self.assertEqual(frame["code"].tolist(), ["001", "002"])
236
+ self.assertTrue(ptypes.is_object_dtype(frame["code"]))
237
+ self.assertIn("leading_zeros_preserved", set(report.findings["check"]))
238
+
239
+ def test_on_error_warn_logs_but_returns_frame(self) -> None:
240
+ csv = "amount\nnot-a-number\n"
241
+ contract = DataContract(columns=(ColumnSpec("amount", role="numeric"),))
242
+ with self.assertLogs("data_cleaner.ingestion", level="WARNING") as captured:
243
+ frame, report = read_csv_safe(io.StringIO(csv), contract=contract)
244
+ self.assertTrue(pd.isna(frame["amount"].iloc[0]))
245
+ self.assertFalse(report.success)
246
+ self.assertTrue(any("ingestion" in message for message in captured.output))