dataset-inspector 0.0.1__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.
@@ -0,0 +1,3 @@
1
+ """Dataset Inspector – lightweight CSV dataset inspector for ML workflows."""
2
+
3
+ __version__ = "0.0.1"
@@ -0,0 +1,5 @@
1
+ """Allow running as: python -m dataset_inspector"""
2
+
3
+ from dataset_inspector.cli import main
4
+
5
+ main()
@@ -0,0 +1,223 @@
1
+ """Core analysis logic for dataset inspection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ # ---------------------------------------------------------------------------
16
+ # Result containers
17
+ # ---------------------------------------------------------------------------
18
+
19
+ @dataclass
20
+ class ColumnStats:
21
+ """Descriptive statistics for a single numeric column."""
22
+ name: str
23
+ mean: float
24
+ std: float
25
+ min: float
26
+ max: float
27
+ median: float
28
+ q25: float
29
+ q75: float
30
+
31
+
32
+ @dataclass
33
+ class MissingInfo:
34
+ """Missing-value summary for a single column."""
35
+ column: str
36
+ count: int
37
+ percentage: float
38
+
39
+
40
+ @dataclass
41
+ class AnomalyInfo:
42
+ """Rows flagged as potential anomalies in a column."""
43
+ column: str
44
+ row_indices: list[int]
45
+ method: str # "iqr" or "zscore"
46
+
47
+
48
+ @dataclass
49
+ class AnalysisResult:
50
+ """Aggregated result of a full dataset analysis."""
51
+ shape: tuple[int, int]
52
+ dtypes: dict[str, str]
53
+ basic_stats: list[ColumnStats] = field(default_factory=list)
54
+ missing: list[MissingInfo] = field(default_factory=list)
55
+ duplicate_row_count: int = 0
56
+ duplicate_pairs: list[tuple[int, int]] = field(default_factory=list)
57
+ class_imbalance: dict[str, dict[str, Any]] | None = None
58
+ anomalies: list[AnomalyInfo] = field(default_factory=list)
59
+
60
+ # ----- serialisation helpers ----- #
61
+ def to_dict(self) -> dict[str, Any]:
62
+ """Return a plain-dict representation suitable for JSON export."""
63
+ return {
64
+ "shape": list(self.shape),
65
+ "dtypes": self.dtypes,
66
+ "basic_stats": [vars(s) for s in self.basic_stats],
67
+ "missing": [vars(m) for m in self.missing],
68
+ "duplicate_row_count": self.duplicate_row_count,
69
+ "duplicate_pairs": self.duplicate_pairs,
70
+ "class_imbalance": self.class_imbalance,
71
+ "anomalies": [
72
+ {**vars(a), "row_indices": a.row_indices[:20]} # cap for readability
73
+ for a in self.anomalies
74
+ ],
75
+ }
76
+
77
+
78
+ # ---------------------------------------------------------------------------
79
+ # Public analysis API
80
+ # ---------------------------------------------------------------------------
81
+
82
+ def load_csv(path: str) -> pd.DataFrame:
83
+ """Read a CSV file into a DataFrame."""
84
+ logger.info("Loading CSV from %s", path)
85
+ df = pd.read_csv(path)
86
+ logger.info("Loaded %d rows x %d columns", *df.shape)
87
+ return df
88
+
89
+
90
+ def compute_basic_stats(df: pd.DataFrame) -> list[ColumnStats]:
91
+ """Compute descriptive statistics for every numeric column."""
92
+ stats: list[ColumnStats] = []
93
+ numeric = df.select_dtypes(include="number")
94
+ for col in numeric.columns:
95
+ s = numeric[col]
96
+ stats.append(ColumnStats(
97
+ name=col,
98
+ mean=float(s.mean()),
99
+ std=float(s.std()),
100
+ min=float(s.min()),
101
+ max=float(s.max()),
102
+ median=float(s.median()),
103
+ q25=float(s.quantile(0.25)),
104
+ q75=float(s.quantile(0.75)),
105
+ ))
106
+ return stats
107
+
108
+
109
+ def detect_missing(df: pd.DataFrame) -> list[MissingInfo]:
110
+ """Return missing-value counts for columns that have any."""
111
+ result: list[MissingInfo] = []
112
+ for col in df.columns:
113
+ n_missing = int(df[col].isna().sum())
114
+ if n_missing > 0:
115
+ result.append(MissingInfo(
116
+ column=col,
117
+ count=n_missing,
118
+ percentage=round(n_missing / len(df) * 100, 2),
119
+ ))
120
+ return result
121
+
122
+
123
+ def detect_duplicates(df: pd.DataFrame) -> tuple[int, list[tuple[int, int]]]:
124
+ """Return the count of duplicated rows and the (original, duplicate) index pairs."""
125
+ pairs: list[tuple[int, int]] = []
126
+ seen: dict[int, int] = {} # hash -> first-seen positional index
127
+ for pos, row_hash in enumerate(pd.util.hash_pandas_object(df, index=False)):
128
+ h = int(row_hash)
129
+ if h in seen:
130
+ pairs.append((seen[h], pos))
131
+ else:
132
+ seen[h] = pos
133
+ return len(pairs), pairs
134
+
135
+
136
+ def detect_class_imbalance(
137
+ df: pd.DataFrame, target: str | None = None, threshold: float = 0.4
138
+ ) -> dict[str, dict[str, Any]] | None:
139
+ """Check for class imbalance on the *target* column.
140
+
141
+ If *target* is ``None`` the function scans object / category columns with
142
+ low cardinality (<= 20 unique values) and reports any that look imbalanced.
143
+
144
+ *threshold* is the maximum acceptable ratio of the minority class count to
145
+ the majority class count. A ratio below this value is flagged.
146
+ """
147
+ candidates = [target] if target else [
148
+ c for c in df.select_dtypes(include=["object", "category", "bool"]).columns
149
+ if df[c].nunique() <= 20
150
+ ]
151
+
152
+ results: dict[str, dict[str, Any]] = {}
153
+ for col in candidates:
154
+ if col not in df.columns:
155
+ logger.warning("Target column '%s' not found – skipping imbalance check.", col)
156
+ continue
157
+ counts = df[col].value_counts()
158
+ if len(counts) < 2:
159
+ continue
160
+ ratio = float(counts.min() / counts.max())
161
+ if ratio < threshold:
162
+ results[col] = {
163
+ "value_counts": counts.to_dict(),
164
+ "minority_majority_ratio": round(ratio, 4),
165
+ "imbalanced": True,
166
+ }
167
+
168
+ return results if results else None
169
+
170
+
171
+ def detect_anomalies(
172
+ df: pd.DataFrame, method: str = "iqr", z_threshold: float = 3.0
173
+ ) -> list[AnomalyInfo]:
174
+ """Flag rows with potential anomalies in numeric columns.
175
+
176
+ Supports two methods:
177
+ - ``iqr``: values outside [Q1 - 1.5*IQR, Q3 + 1.5*IQR]
178
+ - ``zscore``: absolute z-score > *z_threshold*
179
+ """
180
+ anomalies: list[AnomalyInfo] = []
181
+ numeric = df.select_dtypes(include="number")
182
+
183
+ for col in numeric.columns:
184
+ s = numeric[col].dropna()
185
+ if s.empty:
186
+ continue
187
+
188
+ if method == "iqr":
189
+ q1, q3 = float(s.quantile(0.25)), float(s.quantile(0.75))
190
+ iqr = q3 - q1
191
+ lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
192
+ mask = (s < lower) | (s > upper)
193
+ elif method == "zscore":
194
+ z = np.abs((s - s.mean()) / s.std())
195
+ mask = z > z_threshold
196
+ else:
197
+ raise ValueError(f"Unknown anomaly method: {method!r}")
198
+
199
+ flagged = s[mask].index.tolist()
200
+ if flagged:
201
+ anomalies.append(AnomalyInfo(column=col, row_indices=flagged, method=method))
202
+
203
+ return anomalies
204
+
205
+
206
+ def analyze(
207
+ df: pd.DataFrame,
208
+ target: str | None = None,
209
+ anomaly_method: str = "iqr",
210
+ ) -> AnalysisResult:
211
+ """Run the full analysis pipeline on *df* and return an ``AnalysisResult``."""
212
+ logger.info("Starting analysis …")
213
+ dup_count, dup_pairs = detect_duplicates(df)
214
+ return AnalysisResult(
215
+ shape=df.shape,
216
+ dtypes={c: str(d) for c, d in df.dtypes.items()},
217
+ basic_stats=compute_basic_stats(df),
218
+ missing=detect_missing(df),
219
+ duplicate_row_count=dup_count,
220
+ duplicate_pairs=dup_pairs,
221
+ class_imbalance=detect_class_imbalance(df, target=target),
222
+ anomalies=detect_anomalies(df, method=anomaly_method),
223
+ )
@@ -0,0 +1,69 @@
1
+ """Command-line interface for Dataset Inspector."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from dataset_inspector.analyzer import analyze, load_csv
9
+ from dataset_inspector.report import export_json, print_report
10
+ from dataset_inspector.utils import setup_logging
11
+
12
+
13
+ def build_parser() -> argparse.ArgumentParser:
14
+ parser = argparse.ArgumentParser(
15
+ prog="dataset-inspector",
16
+ description="Analyze a CSV dataset and detect common data issues before ML training.",
17
+ )
18
+ parser.add_argument(
19
+ "-i", "--input",
20
+ required=True,
21
+ help="Path to the CSV file to analyze.",
22
+ )
23
+ parser.add_argument(
24
+ "-t", "--target",
25
+ default=None,
26
+ help="Name of the target column (for class-imbalance check).",
27
+ )
28
+ parser.add_argument(
29
+ "--anomaly-method",
30
+ choices=["iqr", "zscore"],
31
+ default="iqr",
32
+ help="Method used for anomaly detection (default: iqr).",
33
+ )
34
+ parser.add_argument(
35
+ "--json",
36
+ default=None,
37
+ metavar="PATH",
38
+ help="Export the report as JSON to the given path.",
39
+ )
40
+ parser.add_argument(
41
+ "-v", "--verbose",
42
+ action="store_true",
43
+ help="Enable debug logging.",
44
+ )
45
+ return parser
46
+
47
+
48
+ def main(argv: list[str] | None = None) -> None:
49
+ """Entry point for the CLI."""
50
+ args = build_parser().parse_args(argv)
51
+ logger = setup_logging(verbose=args.verbose)
52
+
53
+ try:
54
+ df = load_csv(args.input)
55
+ except FileNotFoundError:
56
+ print(f"Error: file not found – {args.input}", file=sys.stderr)
57
+ sys.exit(1)
58
+ except Exception as exc:
59
+ logger.debug("Failed to load CSV", exc_info=True)
60
+ print(f"Error: could not read CSV – {exc}", file=sys.stderr)
61
+ sys.exit(1)
62
+
63
+ result = analyze(df, target=args.target, anomaly_method=args.anomaly_method)
64
+
65
+ print_report(result)
66
+
67
+ if args.json:
68
+ export_json(result, args.json)
69
+ print(f"JSON report saved to {args.json}")
@@ -0,0 +1,110 @@
1
+ """Human-readable terminal report and JSON export."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import TextIO
7
+ import sys
8
+
9
+ from dataset_inspector.analyzer import AnalysisResult
10
+
11
+ # ---------------------------------------------------------------------------
12
+ # Terminal colours (disabled when stdout is not a TTY)
13
+ # ---------------------------------------------------------------------------
14
+ _USE_COLOR = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
15
+
16
+ BOLD = "\033[1m" if _USE_COLOR else ""
17
+ GREEN = "\033[92m" if _USE_COLOR else ""
18
+ YELLOW = "\033[93m" if _USE_COLOR else ""
19
+ RED = "\033[91m" if _USE_COLOR else ""
20
+ RESET = "\033[0m" if _USE_COLOR else ""
21
+
22
+ SEPARATOR = "─" * 60
23
+
24
+
25
+ def _header(title: str) -> str:
26
+ return f"\n{BOLD}{title}{RESET}\n{SEPARATOR}"
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Terminal report
31
+ # ---------------------------------------------------------------------------
32
+
33
+ def print_report(result: AnalysisResult, file: TextIO | None = None) -> None:
34
+ """Print a formatted analysis report to *file* (default stdout)."""
35
+ out = file or sys.stdout
36
+
37
+ def p(*args: object, **kw: object) -> None: # noqa: ANN401
38
+ print(*args, file=out, **kw) # type: ignore[arg-type]
39
+
40
+ p(f"\n{BOLD}{'═' * 60}{RESET}")
41
+ p(f"{BOLD} Dataset Inspector – Analysis Report{RESET}")
42
+ p(f"{BOLD}{'═' * 60}{RESET}")
43
+
44
+ # --- Shape & dtypes ---
45
+ p(_header("Dataset Overview"))
46
+ p(f" Rows : {result.shape[0]}")
47
+ p(f" Columns: {result.shape[1]}")
48
+ p(f" Column types:")
49
+ for col, dtype in result.dtypes.items():
50
+ p(f" • {col}: {dtype}")
51
+
52
+ # --- Basic stats ---
53
+ if result.basic_stats:
54
+ p(_header("Basic Statistics (numeric columns)"))
55
+ for s in result.basic_stats:
56
+ p(f" {BOLD}{s.name}{RESET}")
57
+ p(f" mean={s.mean:.4f} std={s.std:.4f} "
58
+ f"min={s.min:.4f} max={s.max:.4f} median={s.median:.4f}")
59
+
60
+ # --- Missing values ---
61
+ p(_header("Missing Values"))
62
+ if result.missing:
63
+ for m in result.missing:
64
+ colour = RED if m.percentage > 20 else YELLOW
65
+ p(f" {colour}{m.column}: {m.count} ({m.percentage}%){RESET}")
66
+ else:
67
+ p(f" {GREEN}No missing values detected.{RESET}")
68
+
69
+ # --- Duplicates ---
70
+ p(_header("Duplicate Rows"))
71
+ if result.duplicate_row_count:
72
+ p(f" {YELLOW}{result.duplicate_row_count} duplicate row(s) found:{RESET}")
73
+ for orig, dup in result.duplicate_pairs:
74
+ p(f" row {dup} is a duplicate of row {orig}")
75
+ else:
76
+ p(f" {GREEN}No duplicate rows.{RESET}")
77
+
78
+ # --- Class imbalance ---
79
+ p(_header("Class Imbalance"))
80
+ if result.class_imbalance:
81
+ for col, info in result.class_imbalance.items():
82
+ p(f" {YELLOW}Column '{col}' is imbalanced "
83
+ f"(minority/majority ratio = {info['minority_majority_ratio']}):{RESET}")
84
+ for val, cnt in info["value_counts"].items():
85
+ p(f" {val}: {cnt}")
86
+ else:
87
+ p(f" {GREEN}No class imbalance detected.{RESET}")
88
+
89
+ # --- Anomalies ---
90
+ p(_header("Anomalies"))
91
+ if result.anomalies:
92
+ for a in result.anomalies:
93
+ n = len(a.row_indices)
94
+ preview = a.row_indices[:10]
95
+ p(f" {YELLOW}{a.column}: {n} outlier(s) [{a.method}] "
96
+ f"– rows {preview}{'…' if n > 10 else ''}{RESET}")
97
+ else:
98
+ p(f" {GREEN}No anomalies detected.{RESET}")
99
+
100
+ p(f"\n{BOLD}{'═' * 60}{RESET}\n")
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # JSON export
105
+ # ---------------------------------------------------------------------------
106
+
107
+ def export_json(result: AnalysisResult, path: str) -> None:
108
+ """Write the analysis result as JSON to *path*."""
109
+ with open(path, "w", encoding="utf-8") as f:
110
+ json.dump(result.to_dict(), f, indent=2, default=str)
@@ -0,0 +1,13 @@
1
+ """Shared utility helpers."""
2
+
3
+ import logging
4
+ import sys
5
+
6
+ LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
7
+
8
+
9
+ def setup_logging(verbose: bool = False) -> logging.Logger:
10
+ """Configure and return the package-level logger."""
11
+ level = logging.DEBUG if verbose else logging.WARNING
12
+ logging.basicConfig(format=LOG_FORMAT, level=level, stream=sys.stderr)
13
+ return logging.getLogger("dataset_inspector")
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: dataset-inspector
3
+ Version: 0.0.1
4
+ Summary: Lightweight CLI tool to analyze CSV datasets and detect common ML data issues.
5
+ Author: Quentin
6
+ Project-URL: Homepage, https://github.com/mqtin/dataset-inspector
7
+ Project-URL: Repository, https://github.com/mqtin/dataset-inspector
8
+ Project-URL: Issues, https://github.com/mqtin/dataset-inspector/issues
9
+ Keywords: machine-learning,data-quality,csv,cli,data-validation
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: pandas>=1.5
24
+ Requires-Dist: numpy>=1.23
25
+
26
+ # dataset-inspector
27
+
28
+ A lightweight CLI tool to quickly analyze CSV datasets and detect common issues before training ML models.
29
+
30
+ ## Features
31
+
32
+ - **Basic statistics** – mean, std, min, max, median, quartiles for every numeric column
33
+ - **Missing values** – per-column count and percentage
34
+ - **Duplicate rows** – exact duplicate detection
35
+ - **Class imbalance** – minority/majority ratio check for categorical columns
36
+ - **Anomaly detection** – IQR or z-score based outlier flagging
37
+ - **Terminal report** – clean, colour-coded output
38
+ - **JSON export** – optional machine-readable report
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install -r requirements.txt
44
+ ```
45
+
46
+ ## Quick start
47
+
48
+ ```bash
49
+ # Analyse the included example dataset
50
+ python -m dataset_inspector --input examples/sample.csv
51
+
52
+ # Specify a target column for class-imbalance check
53
+ python -m dataset_inspector --input data.csv --target label
54
+
55
+ # Use z-score anomaly detection and export JSON
56
+ python -m dataset_inspector --input data.csv --anomaly-method zscore --json report.json
57
+
58
+ # Enable verbose / debug logging
59
+ python -m dataset_inspector --input data.csv -v
60
+ ```
61
+
62
+ ## Project structure
63
+
64
+ ```
65
+ dataset_inspector/
66
+ ├── __init__.py # package metadata
67
+ ├── __main__.py # python -m entry point
68
+ ├── cli.py # argument parsing (argparse)
69
+ ├── analyzer.py # core analysis logic
70
+ ├── report.py # terminal + JSON report formatting
71
+ └── utils.py # logging helpers
72
+ examples/
73
+ └── sample.csv # small demo dataset
74
+ ```
@@ -0,0 +1,11 @@
1
+ dataset_inspector/__init__.py,sha256=T9AqcXeoB0TBpNp2sO9emdPhoJXc3WePZcoJTARCH4Y,103
2
+ dataset_inspector/__main__.py,sha256=EZSwAre9F8LZKrDL4rShErWkvPe6E5UJvUMi2Vl8Sjw,100
3
+ dataset_inspector/analyzer.py,sha256=BVkxPrYxMb6-ZXyGiqOeMFeBWvsiY9yYh1T_qFNf1_c,7267
4
+ dataset_inspector/cli.py,sha256=KUTFAU9lb-tlsUnr27bPAfMN3bIr-2aTadDfIg4-NAM,2010
5
+ dataset_inspector/report.py,sha256=hBh4qjje0Q-L2ZhBv7--XwPmuuESISzPFBfM1GjV7T4,3939
6
+ dataset_inspector/utils.py,sha256=qRKGhLyyjxYjRe96QoqhOPv8U0XPm2ZdDbyxv6gyJ-k,425
7
+ dataset_inspector-0.0.1.dist-info/METADATA,sha256=kJ1mC8RpjfERkMLMYwrycpITbDCLDwAW_Jpk_O1IKgg,2673
8
+ dataset_inspector-0.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
9
+ dataset_inspector-0.0.1.dist-info/entry_points.txt,sha256=tFv37btNZjdfOjy9v2R5sN8CRJjMLszrCH0bZ4aNb2I,65
10
+ dataset_inspector-0.0.1.dist-info/top_level.txt,sha256=zd8_OK3nUGTHe4WYPLQ8alRINVWU-d27J4mClMJducg,18
11
+ dataset_inspector-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dataset-inspector = dataset_inspector.cli:main
@@ -0,0 +1 @@
1
+ dataset_inspector