csvhonest 0.1.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- csvhonest/__init__.py +15 -0
- csvhonest/__main__.py +5 -0
- csvhonest/cli.py +126 -0
- csvhonest/dialect.py +150 -0
- csvhonest/duckdb_verify.py +71 -0
- csvhonest/profiles.py +88 -0
- csvhonest/report.py +218 -0
- csvhonest/rules.py +712 -0
- csvhonest/scan.py +323 -0
- csvhonest/snapshot.py +25 -0
- csvhonest/verify.py +318 -0
- csvhonest-0.1.4.dist-info/METADATA +269 -0
- csvhonest-0.1.4.dist-info/RECORD +17 -0
- csvhonest-0.1.4.dist-info/WHEEL +5 -0
- csvhonest-0.1.4.dist-info/entry_points.txt +2 -0
- csvhonest-0.1.4.dist-info/licenses/LICENSE +21 -0
- csvhonest-0.1.4.dist-info/top_level.txt +1 -0
csvhonest/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""csvhonest: audit what your CSV loader will silently change before you load it.
|
|
2
|
+
|
|
3
|
+
csvhonest scans raw CSV text and reports the values that default loader
|
|
4
|
+
settings (pandas.read_csv, polars.read_csv) would silently mutate: leading
|
|
5
|
+
zeros dropped from IDs, strings like "NA" turned into NaN, large integers
|
|
6
|
+
losing exactness under float64 coercion, ambiguous dates, and lookalike
|
|
7
|
+
keys that collapse when stripped or Unicode-normalized.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .scan import scan_file, ScanResult
|
|
11
|
+
from .report import render_text, render_json
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.4"
|
|
14
|
+
|
|
15
|
+
__all__ = ["scan_file", "ScanResult", "render_text", "render_json", "__version__"]
|
csvhonest/__main__.py
ADDED
csvhonest/cli.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Command line interface: csvhonest FILE... [--format text|json]."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from dataclasses import replace
|
|
8
|
+
from typing import List, Optional
|
|
9
|
+
|
|
10
|
+
from .report import exit_code, render_json, render_text
|
|
11
|
+
from .scan import DEFAULT_DISTINCT_CAP, DEFAULT_MAX_ROWS, scan_file
|
|
12
|
+
from .snapshot import captured_path
|
|
13
|
+
from .verify import VERIFIERS
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
17
|
+
parser = argparse.ArgumentParser(
|
|
18
|
+
prog="csvhonest",
|
|
19
|
+
description=(
|
|
20
|
+
"Audit what your CSV loader will silently change before you "
|
|
21
|
+
"load it: dropped leading zeros, strings turned into NaN, "
|
|
22
|
+
"float64 precision loss, ambiguous dates, lookalike keys."
|
|
23
|
+
),
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument("files", nargs="+", help="CSV file(s) to audit")
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"--format",
|
|
28
|
+
choices=("text", "json"),
|
|
29
|
+
default="text",
|
|
30
|
+
help="output format (default: text)",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument(
|
|
33
|
+
"--max-rows",
|
|
34
|
+
type=int,
|
|
35
|
+
default=DEFAULT_MAX_ROWS,
|
|
36
|
+
help=f"stop after this many data rows (default: {DEFAULT_MAX_ROWS})",
|
|
37
|
+
)
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--distinct-cap",
|
|
40
|
+
type=int,
|
|
41
|
+
default=DEFAULT_DISTINCT_CAP,
|
|
42
|
+
help=(
|
|
43
|
+
"store at most this many distinct values per column "
|
|
44
|
+
f"(default: {DEFAULT_DISTINCT_CAP}); capped columns are named"
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
parser.add_argument("--encoding", help="override encoding detection")
|
|
48
|
+
parser.add_argument("--delimiter", help="override delimiter detection")
|
|
49
|
+
header = parser.add_mutually_exclusive_group()
|
|
50
|
+
header.add_argument(
|
|
51
|
+
"--header",
|
|
52
|
+
dest="has_header",
|
|
53
|
+
action="store_true",
|
|
54
|
+
default=None,
|
|
55
|
+
help="force first row to be the header (default: auto-detect)",
|
|
56
|
+
)
|
|
57
|
+
header.add_argument(
|
|
58
|
+
"--no-header",
|
|
59
|
+
dest="has_header",
|
|
60
|
+
action="store_false",
|
|
61
|
+
help="force first row to be data",
|
|
62
|
+
)
|
|
63
|
+
parser.add_argument(
|
|
64
|
+
"--verify",
|
|
65
|
+
choices=("pandas", "polars", "both", "duckdb"),
|
|
66
|
+
help=(
|
|
67
|
+
"also run the installed loader with defaults and diff raw vs "
|
|
68
|
+
"loaded values, confirming mutations on this exact file"
|
|
69
|
+
),
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--fail-on",
|
|
73
|
+
choices=("high", "medium", "low"),
|
|
74
|
+
default="high",
|
|
75
|
+
help="exit 1 when a finding at or above this severity exists (default: high)",
|
|
76
|
+
)
|
|
77
|
+
return parser
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
81
|
+
args = build_parser().parse_args(argv)
|
|
82
|
+
worst = 0
|
|
83
|
+
for path in args.files:
|
|
84
|
+
try:
|
|
85
|
+
# One capture covers static detection and both loader comparisons.
|
|
86
|
+
with captured_path(path, enabled=bool(args.verify)) as input_path:
|
|
87
|
+
result = scan_file(
|
|
88
|
+
input_path,
|
|
89
|
+
max_rows=args.max_rows,
|
|
90
|
+
distinct_cap=args.distinct_cap,
|
|
91
|
+
encoding=args.encoding,
|
|
92
|
+
delimiter=args.delimiter,
|
|
93
|
+
has_header=args.has_header,
|
|
94
|
+
)
|
|
95
|
+
verifications = []
|
|
96
|
+
if args.verify:
|
|
97
|
+
names = ("pandas", "polars") if args.verify == "both" else (args.verify,)
|
|
98
|
+
for name in names:
|
|
99
|
+
if name == "duckdb":
|
|
100
|
+
from .duckdb_verify import verify_with_duckdb
|
|
101
|
+
report = verify_with_duckdb(result, args.max_rows)
|
|
102
|
+
else:
|
|
103
|
+
report = VERIFIERS[name](result, args.max_rows)
|
|
104
|
+
if report.load_error:
|
|
105
|
+
report.load_error = report.load_error.replace(input_path, str(path))
|
|
106
|
+
verifications.append(report)
|
|
107
|
+
result = replace(result, path=path)
|
|
108
|
+
except OSError as exc:
|
|
109
|
+
print(f"csvhonest: cannot read {path}: {exc}", file=sys.stderr)
|
|
110
|
+
worst = max(worst, 2)
|
|
111
|
+
continue
|
|
112
|
+
if args.format == "json":
|
|
113
|
+
print(render_json(result, verifications))
|
|
114
|
+
else:
|
|
115
|
+
print(render_text(result, verifications))
|
|
116
|
+
print()
|
|
117
|
+
worst = max(
|
|
118
|
+
worst,
|
|
119
|
+
2 if any(v.load_error for v in verifications) else 0,
|
|
120
|
+
exit_code(result, fail_on=args.fail_on),
|
|
121
|
+
)
|
|
122
|
+
return worst
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
if __name__ == "__main__": # pragma: no cover
|
|
126
|
+
sys.exit(main())
|
csvhonest/dialect.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Encoding and dialect detection for raw CSV bytes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import List, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class EncodingInfo:
|
|
13
|
+
encoding: str
|
|
14
|
+
bom: bool
|
|
15
|
+
fell_back: bool # True when utf-8 failed and a legacy codec was used
|
|
16
|
+
decode_errors: int # bytes that did not decode cleanly under `encoding`
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def detect_encoding(raw: bytes) -> EncodingInfo:
|
|
20
|
+
"""Pick an encoding for raw bytes, preferring exact UTF-8.
|
|
21
|
+
|
|
22
|
+
Falls back to cp1252 (the common Windows/Excel export encoding) when
|
|
23
|
+
UTF-8 fails, and records how many bytes still failed to decode.
|
|
24
|
+
"""
|
|
25
|
+
bom = False
|
|
26
|
+
data = raw
|
|
27
|
+
if raw.startswith(b"\xef\xbb\xbf"):
|
|
28
|
+
bom = True
|
|
29
|
+
data = raw[3:]
|
|
30
|
+
try:
|
|
31
|
+
data.decode("utf-8", errors="strict")
|
|
32
|
+
return EncodingInfo("utf-8-sig", bom=True, fell_back=False, decode_errors=0)
|
|
33
|
+
except UnicodeDecodeError:
|
|
34
|
+
pass
|
|
35
|
+
else:
|
|
36
|
+
try:
|
|
37
|
+
data.decode("utf-8", errors="strict")
|
|
38
|
+
return EncodingInfo("utf-8", bom=False, fell_back=False, decode_errors=0)
|
|
39
|
+
except UnicodeDecodeError:
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
errors = 0
|
|
43
|
+
try:
|
|
44
|
+
data.decode("cp1252", errors="strict")
|
|
45
|
+
except UnicodeDecodeError:
|
|
46
|
+
# cp1252 has a few undefined bytes; count them and replace.
|
|
47
|
+
decoded = data.decode("cp1252", errors="replace")
|
|
48
|
+
errors = decoded.count("�")
|
|
49
|
+
return EncodingInfo("cp1252", bom=bom, fell_back=True, decode_errors=errors)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class DialectInfo:
|
|
54
|
+
delimiter: str
|
|
55
|
+
quotechar: str
|
|
56
|
+
sniffer_agreed: bool # False when we fell back to the comma default
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_CANDIDATE_DELIMITERS = [",", ";", "\t", "|"]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _column_count_spread(text: str, delimiter: str) -> Tuple[int, int]:
|
|
63
|
+
"""Return (min, max) field counts per line for a candidate delimiter."""
|
|
64
|
+
counts: List[int] = []
|
|
65
|
+
for line in text.splitlines()[:200]:
|
|
66
|
+
if not line.strip():
|
|
67
|
+
continue
|
|
68
|
+
counts.append(line.count(delimiter) + 1)
|
|
69
|
+
if not counts:
|
|
70
|
+
return (1, 1)
|
|
71
|
+
return (min(counts), max(counts))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def detect_dialect(text: str) -> DialectInfo:
|
|
75
|
+
"""Detect the delimiter and quote character of a text sample.
|
|
76
|
+
|
|
77
|
+
Uses csv.Sniffer first; when the sniffer fails or picks a delimiter
|
|
78
|
+
that produces a single column while another candidate splits the file
|
|
79
|
+
into a consistent multi-column shape, the consistent candidate wins.
|
|
80
|
+
"""
|
|
81
|
+
sample = text[:65536]
|
|
82
|
+
sniffer = csv.Sniffer()
|
|
83
|
+
sniffed: Optional[csv.Dialect] = None
|
|
84
|
+
try:
|
|
85
|
+
sniffed = sniffer.sniff(sample, delimiters="".join(_CANDIDATE_DELIMITERS))
|
|
86
|
+
except csv.Error:
|
|
87
|
+
sniffed = None
|
|
88
|
+
|
|
89
|
+
best_delim = ","
|
|
90
|
+
best_score = None
|
|
91
|
+
for delim in _CANDIDATE_DELIMITERS:
|
|
92
|
+
lo, hi = _column_count_spread(sample, delim)
|
|
93
|
+
if hi <= 1:
|
|
94
|
+
continue
|
|
95
|
+
# Prefer many, consistent columns.
|
|
96
|
+
score = (hi - lo == 0, hi)
|
|
97
|
+
if best_score is None or score > best_score:
|
|
98
|
+
best_score = score
|
|
99
|
+
best_delim = delim
|
|
100
|
+
|
|
101
|
+
if sniffed is not None:
|
|
102
|
+
lo, hi = _column_count_spread(sample, sniffed.delimiter)
|
|
103
|
+
if hi > 1:
|
|
104
|
+
return DialectInfo(
|
|
105
|
+
delimiter=sniffed.delimiter,
|
|
106
|
+
quotechar=sniffed.quotechar or '"',
|
|
107
|
+
sniffer_agreed=True,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
# A single-column file has nothing to disagree about; only flag a
|
|
111
|
+
# guessed dialect when a real multi-column decision was made.
|
|
112
|
+
return DialectInfo(
|
|
113
|
+
delimiter=best_delim, quotechar='"', sniffer_agreed=best_score is None
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def decode(raw: bytes, info: EncodingInfo) -> str:
|
|
118
|
+
"""Decode raw bytes according to a detected encoding."""
|
|
119
|
+
errors = "strict" if info.decode_errors == 0 else "replace"
|
|
120
|
+
return raw.decode(info.encoding, errors=errors)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def sniff_has_header(first_rows: List[List[str]]) -> bool:
|
|
124
|
+
"""Heuristic header check: first row all non-numeric, later rows not."""
|
|
125
|
+
if len(first_rows) < 2:
|
|
126
|
+
return True
|
|
127
|
+
first = first_rows[0]
|
|
128
|
+
rest = first_rows[1:]
|
|
129
|
+
|
|
130
|
+
def numericish(v: str) -> bool:
|
|
131
|
+
v = v.strip()
|
|
132
|
+
if not v:
|
|
133
|
+
return False
|
|
134
|
+
try:
|
|
135
|
+
float(v)
|
|
136
|
+
return True
|
|
137
|
+
except ValueError:
|
|
138
|
+
return False
|
|
139
|
+
|
|
140
|
+
first_numeric = sum(1 for v in first if numericish(v))
|
|
141
|
+
rest_numeric = sum(1 for r in rest for v in r if numericish(v))
|
|
142
|
+
if first and first_numeric == 0:
|
|
143
|
+
return True
|
|
144
|
+
if first and rest and first_numeric < rest_numeric / max(len(rest), 1):
|
|
145
|
+
return True
|
|
146
|
+
return first_numeric == 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def text_stream(text: str) -> io.StringIO:
|
|
150
|
+
return io.StringIO(text)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Verify DuckDB defaults for a conservative CSV subset.
|
|
2
|
+
|
|
3
|
+
Not a static profile. No import, install or database connection until requested.
|
|
4
|
+
The existing 'both' selection deliberately remains pandas plus Polars.
|
|
5
|
+
"""
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import shutil
|
|
9
|
+
import tempfile
|
|
10
|
+
|
|
11
|
+
from .dialect import DialectInfo
|
|
12
|
+
from .verify import VerificationReport, _verify_generic
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def verify_with_duckdb(result, max_rows):
|
|
16
|
+
try:
|
|
17
|
+
import duckdb
|
|
18
|
+
except ImportError:
|
|
19
|
+
return VerificationReport('duckdb', 0, 0, load_error='duckdb is not installed')
|
|
20
|
+
if result.encoding.encoding not in ('utf-8', 'utf-8-sig'):
|
|
21
|
+
return VerificationReport(
|
|
22
|
+
'duckdb', 0, 0,
|
|
23
|
+
load_error='DuckDB verification supports UTF-8 CSV only; no transcoding performed',
|
|
24
|
+
)
|
|
25
|
+
path = str(result.path)
|
|
26
|
+
try:
|
|
27
|
+
# Do not pass the source name to DuckDB: its file arguments accept
|
|
28
|
+
# glob patterns. A fixed name inside a private directory is literal.
|
|
29
|
+
with tempfile.TemporaryDirectory(prefix='csvhonest-duckdb-') as directory:
|
|
30
|
+
path = str(Path(directory) / 'input.csv')
|
|
31
|
+
shutil.copyfile(result.path, path)
|
|
32
|
+
with duckdb.connect(':memory:') as connection:
|
|
33
|
+
cursor = connection.execute('SELECT * FROM sniff_csv(?)', [path])
|
|
34
|
+
options = dict(zip([c[0] for c in cursor.description], cursor.fetchone()))
|
|
35
|
+
quote = options['Quote']
|
|
36
|
+
escape = options['Escape']
|
|
37
|
+
if (
|
|
38
|
+
not options['HasHeader']
|
|
39
|
+
or options['SkipRows'] != 0
|
|
40
|
+
or options['Comment'] not in ('', '(empty)')
|
|
41
|
+
or len(options['Delimiter']) != 1
|
|
42
|
+
or quote not in ('', '(empty)', '"', "'")
|
|
43
|
+
or escape not in ('', '(empty)', quote)
|
|
44
|
+
):
|
|
45
|
+
return VerificationReport(
|
|
46
|
+
'duckdb', 0, 0,
|
|
47
|
+
load_error='DuckDB detected a layout csvhonest cannot align safely',
|
|
48
|
+
)
|
|
49
|
+
relation = connection.read_csv(path).limit(max_rows)
|
|
50
|
+
names = relation.columns
|
|
51
|
+
types = [str(t) for t in relation.types]
|
|
52
|
+
rows = relation.fetchall()
|
|
53
|
+
columns = [
|
|
54
|
+
(name, dtype, [row[i] for row in rows])
|
|
55
|
+
for i, (name, dtype) in enumerate(zip(names, types))
|
|
56
|
+
]
|
|
57
|
+
dialect = DialectInfo(
|
|
58
|
+
options['Delimiter'],
|
|
59
|
+
None if quote in ('', '(empty)') else quote,
|
|
60
|
+
True,
|
|
61
|
+
)
|
|
62
|
+
report = _verify_generic(
|
|
63
|
+
replace(result, path=path, dialect=dialect),
|
|
64
|
+
'duckdb', columns, lambda value: value is None, max_rows,
|
|
65
|
+
skips_blank_lines='empty' if len(columns) > 1 else False,
|
|
66
|
+
)
|
|
67
|
+
if report.load_error:
|
|
68
|
+
report.load_error = report.load_error.replace(path, str(result.path))
|
|
69
|
+
return report
|
|
70
|
+
except Exception as exc:
|
|
71
|
+
return VerificationReport('duckdb', 0, 0, load_error=str(exc).replace(path, str(result.path)))
|
csvhonest/profiles.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Loader profiles: what each CSV loader does by default.
|
|
2
|
+
|
|
3
|
+
A profile records the defaults that decide whether a raw string survives a
|
|
4
|
+
load unchanged. Findings are attributed to the profiles whose defaults
|
|
5
|
+
trigger them, so the report can say "pandas changes this value; polars
|
|
6
|
+
keeps it" instead of guessing at a generic parser.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import FrozenSet
|
|
13
|
+
|
|
14
|
+
# pandas STR_NA_VALUES: strings read_csv converts to NaN by default
|
|
15
|
+
# (keep_default_na=True). Source: pandas/io/parsers/readers.py.
|
|
16
|
+
PANDAS_DEFAULT_NA: FrozenSet[str] = frozenset(
|
|
17
|
+
{
|
|
18
|
+
"",
|
|
19
|
+
"#N/A",
|
|
20
|
+
"#N/A N/A",
|
|
21
|
+
"#NA",
|
|
22
|
+
"-1.#IND",
|
|
23
|
+
"-1.#QNAN",
|
|
24
|
+
"-NaN",
|
|
25
|
+
"-nan",
|
|
26
|
+
"1.#IND",
|
|
27
|
+
"1.#QNAN",
|
|
28
|
+
"<NA>",
|
|
29
|
+
"N/A",
|
|
30
|
+
"NA",
|
|
31
|
+
"NULL",
|
|
32
|
+
"NaN",
|
|
33
|
+
"None",
|
|
34
|
+
"n/a",
|
|
35
|
+
"nan",
|
|
36
|
+
"null",
|
|
37
|
+
}
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# Strings pandas converts to bool when they make up an entire column.
|
|
41
|
+
PANDAS_BOOL_STRINGS: FrozenSet[str] = frozenset({"True", "False"})
|
|
42
|
+
|
|
43
|
+
# Strings polars converts to bool when they make up an entire column
|
|
44
|
+
# (verified against polars 2.0: both cases are accepted).
|
|
45
|
+
POLARS_BOOL_STRINGS: FrozenSet[str] = frozenset({"true", "false", "True", "False"})
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class LoaderProfile:
|
|
50
|
+
"""Defaults of one CSV loader."""
|
|
51
|
+
|
|
52
|
+
name: str
|
|
53
|
+
# Exact strings converted to a missing-value marker by default.
|
|
54
|
+
na_values: FrozenSet[str] = field(default_factory=frozenset)
|
|
55
|
+
# Exact strings converted to booleans when a column is all bool-like.
|
|
56
|
+
bool_strings: FrozenSet[str] = field(default_factory=frozenset)
|
|
57
|
+
# Whether an all-integer column with missing values coerces to float64
|
|
58
|
+
# (and can therefore lose exactness above 2**53).
|
|
59
|
+
int_with_holes_becomes_float: bool = False
|
|
60
|
+
# Whether a digit string with leading zeros is parsed as a number
|
|
61
|
+
# (dropping the zeros) when the column is otherwise numeric.
|
|
62
|
+
drops_leading_zeros: bool = True
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
PANDAS = LoaderProfile(
|
|
66
|
+
name="pandas",
|
|
67
|
+
na_values=PANDAS_DEFAULT_NA,
|
|
68
|
+
bool_strings=PANDAS_BOOL_STRINGS,
|
|
69
|
+
int_with_holes_becomes_float=True,
|
|
70
|
+
drops_leading_zeros=True,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# polars read_csv defaults: no NA string list (null_values=None); an empty
|
|
74
|
+
# string in a column inferred as numeric becomes null; boolean inference
|
|
75
|
+
# accepts "true"/"false"; integers with nulls stay Int64 (exact).
|
|
76
|
+
POLARS = LoaderProfile(
|
|
77
|
+
name="polars",
|
|
78
|
+
na_values=frozenset({""}),
|
|
79
|
+
bool_strings=POLARS_BOOL_STRINGS,
|
|
80
|
+
int_with_holes_becomes_float=False,
|
|
81
|
+
drops_leading_zeros=True,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
PROFILES = {p.name: p for p in (PANDAS, POLARS)}
|
|
85
|
+
|
|
86
|
+
# Tag for findings that do not fire on a default load but make later
|
|
87
|
+
# parsing risky (e.g. dates whose day/month order cannot be known).
|
|
88
|
+
DOWNSTREAM = "downstream-parse"
|
csvhonest/report.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Human and machine reports for a scan, plus suggested loader fixes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Dict, List
|
|
7
|
+
|
|
8
|
+
from .profiles import PANDAS_DEFAULT_NA
|
|
9
|
+
from .rules import Finding
|
|
10
|
+
from .scan import ScanResult
|
|
11
|
+
from .verify import VerificationReport
|
|
12
|
+
|
|
13
|
+
_SEVERITY_BADGE = {"high": "HIGH", "medium": "MED ", "low": "LOW "}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def suggested_overrides(result: ScanResult) -> Dict[str, object]:
|
|
17
|
+
"""Concrete loader arguments that prevent the high-severity mutations."""
|
|
18
|
+
pandas_dtype: Dict[str, str] = {}
|
|
19
|
+
polars_schema: List[str] = []
|
|
20
|
+
na_collision = False
|
|
21
|
+
for f in result.findings:
|
|
22
|
+
if f.code in ("LEADING_ZERO_LOSS", "INT64_OVERFLOW", "SCI_NOTATION_FORM_LOSS") and f.column:
|
|
23
|
+
pandas_dtype[f.column] = "str"
|
|
24
|
+
polars_schema.append(f.column)
|
|
25
|
+
elif f.code == "FLOAT64_PRECISION_LOSS" and f.column:
|
|
26
|
+
if "polars" in f.loaders:
|
|
27
|
+
# Mixed int/float column: Int64 cannot hold the floats
|
|
28
|
+
# (TypeError on load), so only text preserves the big
|
|
29
|
+
# integers. The pandas-only (holes) case can use Int64.
|
|
30
|
+
pandas_dtype[f.column] = "str"
|
|
31
|
+
polars_schema.append(f.column)
|
|
32
|
+
else:
|
|
33
|
+
pandas_dtype[f.column] = "Int64"
|
|
34
|
+
elif f.code == "NA_COLLISION" and "pandas" in f.loaders:
|
|
35
|
+
na_collision = True
|
|
36
|
+
elif f.code == "WHITESPACE_KEY_COLLISION" and f.column:
|
|
37
|
+
pandas_dtype.setdefault(f.column, "str")
|
|
38
|
+
if f.column not in polars_schema:
|
|
39
|
+
polars_schema.append(f.column)
|
|
40
|
+
|
|
41
|
+
pandas_args: Dict[str, object] = {}
|
|
42
|
+
if pandas_dtype:
|
|
43
|
+
pandas_args["dtype"] = pandas_dtype
|
|
44
|
+
if na_collision:
|
|
45
|
+
# The colliding strings are data, not missing markers: turn the
|
|
46
|
+
# default list off entirely and treat only empty cells as missing.
|
|
47
|
+
pandas_args["keep_default_na"] = False
|
|
48
|
+
pandas_args["na_values"] = [""]
|
|
49
|
+
polars_args: Dict[str, object] = {}
|
|
50
|
+
if polars_schema:
|
|
51
|
+
polars_args["schema_overrides"] = {c: "String" for c in sorted(set(polars_schema))}
|
|
52
|
+
if na_collision:
|
|
53
|
+
polars_args["null_values"] = [""]
|
|
54
|
+
return {"pandas": pandas_args, "polars": polars_args}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _format_args(args: Dict[str, object], prefix: str) -> List[str]:
|
|
58
|
+
lines: List[str] = []
|
|
59
|
+
for key, value in args.items():
|
|
60
|
+
lines.append(f" {key}={value!r},")
|
|
61
|
+
return lines
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def render_verification_text(report: VerificationReport) -> str:
|
|
65
|
+
lines: List[str] = []
|
|
66
|
+
lines.append(f"Verified with {report.loader} (actual default load of this file)")
|
|
67
|
+
if report.load_error:
|
|
68
|
+
lines.append(f" VERIFICATION FAILED: {report.load_error}")
|
|
69
|
+
return "\n".join(lines)
|
|
70
|
+
lines.append(
|
|
71
|
+
f" {report.loaded_rows} rows x {report.loaded_columns} columns loaded; "
|
|
72
|
+
f"{report.total_mutated_rows} cell(s) differ from the raw text"
|
|
73
|
+
)
|
|
74
|
+
if report.alignment_note:
|
|
75
|
+
lines.append(f" alignment note: {report.alignment_note}")
|
|
76
|
+
for col in report.columns:
|
|
77
|
+
if not col.mutations:
|
|
78
|
+
continue
|
|
79
|
+
lines.append(f" column '{col.column}' (loaded as {col.loaded_dtype}):")
|
|
80
|
+
for m in col.mutations[:5]:
|
|
81
|
+
lines.append(
|
|
82
|
+
f" {m.raw!r} -> {m.became} ({m.kind.replace('_', ' ')}, "
|
|
83
|
+
f"{m.rows} row(s))"
|
|
84
|
+
)
|
|
85
|
+
return "\n".join(lines)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def render_text(result: ScanResult, verifications: List[VerificationReport] = ()) -> str:
|
|
89
|
+
lines: List[str] = []
|
|
90
|
+
lines.append(f"csvhonest: {result.path}")
|
|
91
|
+
lines.append(
|
|
92
|
+
f" {result.row_count} data rows x {result.column_count} columns, "
|
|
93
|
+
f"encoding {result.encoding.encoding}, delimiter {result.dialect.delimiter!r}"
|
|
94
|
+
+ (" (scan truncated at --max-rows)" if result.truncated else "")
|
|
95
|
+
)
|
|
96
|
+
if result.encoding.bom:
|
|
97
|
+
lines.append(" note: UTF-8 BOM present")
|
|
98
|
+
if result.header_auto is not None:
|
|
99
|
+
lines.append(
|
|
100
|
+
" header: auto-detected as "
|
|
101
|
+
+ ("present" if result.header_auto else "absent")
|
|
102
|
+
+ " (heuristic; override with --header/--no-header)"
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
if result.capped_columns:
|
|
106
|
+
lines.append(
|
|
107
|
+
" note: distinct-value cap hit in column(s): "
|
|
108
|
+
+ ", ".join(result.capped_columns)
|
|
109
|
+
+ " (findings there reflect a partial sample)"
|
|
110
|
+
)
|
|
111
|
+
if not result.findings and not verifications:
|
|
112
|
+
lines.append(" No silent-mutation findings. The file loads as written.")
|
|
113
|
+
return "\n".join(lines)
|
|
114
|
+
if not result.findings:
|
|
115
|
+
lines.append(" No silent-mutation findings from the static scan.")
|
|
116
|
+
|
|
117
|
+
counts = {"high": 0, "medium": 0, "low": 0}
|
|
118
|
+
for f in result.findings:
|
|
119
|
+
counts[f.severity] = counts.get(f.severity, 0) + 1
|
|
120
|
+
lines.append(
|
|
121
|
+
f" {counts['high']} high, {counts['medium']} medium, {counts['low']} low finding(s)"
|
|
122
|
+
)
|
|
123
|
+
lines.append("")
|
|
124
|
+
|
|
125
|
+
for f in result.findings:
|
|
126
|
+
where = f"column '{f.column}'" if f.column else "file"
|
|
127
|
+
loaders = ", ".join(f.loaders)
|
|
128
|
+
lines.append(f" [{_SEVERITY_BADGE.get(f.severity, '?')}] {f.code} ({where}; affects: {loaders})")
|
|
129
|
+
lines.append(f" {f.message}")
|
|
130
|
+
if f.examples:
|
|
131
|
+
lines.append(f" examples: {', '.join(f.examples)}")
|
|
132
|
+
lines.append(f" fix: {f.suggestion}")
|
|
133
|
+
lines.append("")
|
|
134
|
+
|
|
135
|
+
overrides = suggested_overrides(result)
|
|
136
|
+
if overrides["pandas"] or overrides["polars"]:
|
|
137
|
+
lines.append("Suggested load arguments")
|
|
138
|
+
lines.append("------------------------")
|
|
139
|
+
if overrides["pandas"]:
|
|
140
|
+
lines.append("pandas:")
|
|
141
|
+
lines.append(" pd.read_csv(path,")
|
|
142
|
+
lines.extend(_format_args(overrides["pandas"], "pandas"))
|
|
143
|
+
lines.append(" )")
|
|
144
|
+
if overrides["polars"]:
|
|
145
|
+
lines.append("polars:")
|
|
146
|
+
lines.append(" pl.read_csv(path,")
|
|
147
|
+
lines.extend(_format_args(overrides["polars"], "polars"))
|
|
148
|
+
lines.append(" )")
|
|
149
|
+
for verification in verifications:
|
|
150
|
+
lines.append("")
|
|
151
|
+
lines.append(render_verification_text(verification))
|
|
152
|
+
return "\n".join(lines)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _verification_json(v: VerificationReport) -> dict:
|
|
156
|
+
return {
|
|
157
|
+
"loader": v.loader,
|
|
158
|
+
"loaded_rows": v.loaded_rows,
|
|
159
|
+
"loaded_columns": v.loaded_columns,
|
|
160
|
+
"load_error": v.load_error,
|
|
161
|
+
"alignment_note": v.alignment_note,
|
|
162
|
+
"total_mutated_rows": v.total_mutated_rows,
|
|
163
|
+
"columns": [
|
|
164
|
+
{
|
|
165
|
+
"column": c.column,
|
|
166
|
+
"loaded_dtype": c.loaded_dtype,
|
|
167
|
+
"mutated_rows": c.mutated_rows,
|
|
168
|
+
"mutations": [
|
|
169
|
+
{"raw": m.raw, "became": m.became, "kind": m.kind, "rows": m.rows}
|
|
170
|
+
for m in c.mutations
|
|
171
|
+
],
|
|
172
|
+
}
|
|
173
|
+
for c in v.columns
|
|
174
|
+
if c.mutations
|
|
175
|
+
],
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def render_json(result: ScanResult, verifications: List[VerificationReport] = ()) -> str:
|
|
180
|
+
payload = {
|
|
181
|
+
"file": result.path,
|
|
182
|
+
"rows": result.row_count,
|
|
183
|
+
"columns": result.column_count,
|
|
184
|
+
"encoding": result.encoding.encoding,
|
|
185
|
+
"delimiter": result.dialect.delimiter,
|
|
186
|
+
"truncated": result.truncated,
|
|
187
|
+
"header_auto": result.header_auto,
|
|
188
|
+
"capped_columns": result.capped_columns,
|
|
189
|
+
"decode_errors": result.decode_errors,
|
|
190
|
+
"highest_severity": result.highest_severity(),
|
|
191
|
+
"findings": [
|
|
192
|
+
{
|
|
193
|
+
"code": f.code,
|
|
194
|
+
"severity": f.severity,
|
|
195
|
+
"column": f.column,
|
|
196
|
+
"column_index": f.column_index,
|
|
197
|
+
"count": f.count,
|
|
198
|
+
"examples": f.examples,
|
|
199
|
+
"loaders": f.loaders,
|
|
200
|
+
"message": f.message,
|
|
201
|
+
"suggestion": f.suggestion,
|
|
202
|
+
}
|
|
203
|
+
for f in result.findings
|
|
204
|
+
],
|
|
205
|
+
"suggested_overrides": suggested_overrides(result),
|
|
206
|
+
}
|
|
207
|
+
if verifications:
|
|
208
|
+
payload["verification"] = [_verification_json(v) for v in verifications]
|
|
209
|
+
return json.dumps(payload, indent=2, ensure_ascii=False)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def exit_code(result: ScanResult, fail_on: str = "high") -> int:
|
|
213
|
+
order = {"high": 0, "medium": 1, "low": 2}
|
|
214
|
+
threshold = order[fail_on]
|
|
215
|
+
for f in result.findings:
|
|
216
|
+
if order.get(f.severity, 3) <= threshold:
|
|
217
|
+
return 1
|
|
218
|
+
return 0
|