diff --git a/.github/workflows/dxray.yml b/.github/workflows/dxray.yml new file mode 100644 index 0000000..d356b47 --- /dev/null +++ b/.github/workflows/dxray.yml @@ -0,0 +1,89 @@ +# dxray, the Python data library in python/dxray: tests on every change, and publishing to PyPI by hand. +# +# Publishing uses PyPI Trusted Publishing, so no password or token is stored anywhere. One-time setup on +# https://pypi.org/manage/account/publishing/ ("Add a new pending publisher"): +# PyPI project name: dxray Owner: fcopensource Repository: veyraeditor +# Workflow name: dxray.yml Environment name: pypi +# Then: Actions -> "dxray (Python)" -> Run workflow -> publish: pypi. +# (For a trial run first, add the same pending publisher on https://test.pypi.org with environment "testpypi".) +name: dxray (Python) + +on: + push: + branches: [main] + paths: ["python/dxray/**", ".github/workflows/dxray.yml"] + pull_request: + paths: ["python/dxray/**", ".github/workflows/dxray.yml"] + workflow_dispatch: + inputs: + publish: + description: Publish this version + type: choice + options: [none, testpypi, pypi] + default: none + +permissions: + contents: read + +defaults: + run: + working-directory: python/dxray + +jobs: + test: + name: Python ${{ matrix.python }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, windows-latest, macos-latest] + python: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + allow-prereleases: true + - run: python -m pip install --upgrade pip + - run: python -m pip install ".[all]" pytest + - run: python -m pytest -q -p no:cacheprovider + + build: + name: Build + needs: test + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: python -m pip install build twine + - run: python -m build + - run: python -m twine check --strict dist/* + - uses: actions/upload-artifact@v4 + with: + name: dist + path: python/dxray/dist/ + + publish: + name: Publish to ${{ inputs.publish }} + needs: build + if: github.event_name == 'workflow_dispatch' && inputs.publish != 'none' + runs-on: ubuntu-22.04 + environment: + name: ${{ inputs.publish }} + url: ${{ inputs.publish == 'pypi' && 'https://pypi.org/project/dxray/' || 'https://test.pypi.org/project/dxray/' }} + permissions: + id-token: write # Trusted Publishing + defaults: + run: + working-directory: . + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: ${{ inputs.publish == 'testpypi' && 'https://test.pypi.org/legacy/' || 'https://upload.pypi.org/legacy/' }} + packages-dir: dist/ diff --git a/docs/PUBLISHING-PYTHON-LIBRARIES.md b/docs/PUBLISHING-PYTHON-LIBRARIES.md new file mode 100644 index 0000000..6dddf86 --- /dev/null +++ b/docs/PUBLISHING-PYTHON-LIBRARIES.md @@ -0,0 +1,112 @@ +# Publishing our Python libraries to PyPI + +How `dxray` and `veyra-snap` (in `python/`) get to `pip install`. Read it once top to bottom; after that, a release is +the five steps in [Every release](#every-release). + +## How it fits together + +- **PyPI** (pypi.org) is where `pip install` downloads packages from. Anyone can publish; a name belongs to whoever + publishes it first. +- **A release** is a version number (like `1.0.0`) plus two files built from the code: a **wheel** (`.whl`, ready to + install) and an **sdist** (`.tar.gz`, the source). `pyproject.toml` describes the package: name, description, + dependencies, the README that becomes the PyPI page. +- **A version can be uploaded only once, ever.** If `1.0.0` has a mistake, you publish `1.0.1`. You can't replace or + re-upload a version, even after deleting it. +- **Trusted Publishing** lets GitHub Actions upload to PyPI without a password or token stored anywhere: PyPI trusts a + specific workflow in a specific repository. That's how ours are set up. + +Each library has its own workflow that tests it on every pull request and publishes when you ask: + +| Library | Folder | Workflow | PyPI page | +|---|---|---|---| +| dxray | `python/dxray` | `.github/workflows/dxray.yml` | https://pypi.org/project/dxray/ | +| veyra-snap | `python/veyra-snap` | `.github/workflows/veyra-snap.yml` | https://pypi.org/project/veyra-snap/ | + +## One-time setup (about 10 minutes) + +### 1. A PyPI account + +1. Sign up at https://pypi.org/account/register/ and confirm the email. +2. Turn on **two-factor authentication** (Account settings → Add 2FA). PyPI requires it to publish. +3. Optional, for trial runs: do the same at https://test.pypi.org (a separate practice site with separate accounts). + +### 2. Tell PyPI to trust our workflow (a "pending publisher") + +The project doesn't exist on PyPI yet, so you reserve it for our workflow: + +1. Go to https://pypi.org/manage/account/publishing/ → **Add a new pending publisher** → **GitHub**. +2. Fill it in **exactly** (one entry per library): + + | Field | dxray | veyra-snap | + |---|---|---| + | PyPI Project Name | `dxray` | `veyra-snap` | + | Owner | `fcopensource` | `fcopensource` | + | Repository name | `veyraeditor` | `veyraeditor` | + | Workflow name | `dxray.yml` | `veyra-snap.yml` | + | Environment name | `pypi` | `pypi` | + +3. Click **Add**. The first successful publish turns it into a normal project you own. + +For trial runs on TestPyPI, add the same entries at https://test.pypi.org/manage/account/publishing/ with environment +name `testpypi`. + +### 3. Optional: a safety catch in GitHub + +In the repository: **Settings → Environments → New environment** named `pypi`, then tick **Required reviewers** and +add yourself. A publish then waits until you click **Approve**, so nobody publishes by accident. + +## Every release + +1. **Merge the code.** The library's pull request must be merged into `main`, with its tests green. +2. **Optional practice run:** Actions → **dxray (Python)** (or **veyra-snap (Python)**) → **Run workflow** → + branch `main`, publish: **testpypi**. Then try it: + + ```console + pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ dxray + ``` + +3. **Publish:** Actions → the same workflow → **Run workflow** → publish: **pypi**. + The run tests the library, builds the wheel and sdist, checks them with `twine check`, and uploads. +4. **Check it:** open https://pypi.org/project/dxray/ and, in a fresh terminal: + + ```console + pip install dxray + dxray --version + ``` + +5. **Tell people:** the website pages switch to `pip install …` by themselves within the hour. + +## Releasing a new version + +1. On a new branch, change the code and add tests. +2. Bump the version in the library's `src//__init__.py` (`__version__ = "1.0.1"`). Use + [semantic versioning](https://semver.org): `1.0.1` for fixes, `1.1.0` for new features, `2.0.0` when existing code + using the library would break. +3. Add a section at the top of its `CHANGELOG.md`. +4. Pull request → merge → [Every release](#every-release) from step 2. + +## When something goes wrong + +| What you see | What it means | What to do | +|---|---|---| +| `invalid-publisher` in the upload step | The pending publisher doesn't match the run | Compare every field in step 2 above with the workflow file name and environment, letter by letter | +| `File already exists` | That version is already on PyPI | Bump the version; versions can't be re-uploaded | +| `The name 'x' is too similar to an existing project` | PyPI blocks look-alike names (`data-xray` blocks `dataxray`) | Choose another name in `pyproject.toml` | +| The run waits forever | The `pypi` environment needs your approval | Open the run and click **Review deployments → Approve** | +| `twine check` fails | The README can't be shown on PyPI | Fix the Markdown it names | +| A broken release is out | Users installing it get the bug | Publish a fixed version; on PyPI you can also **yank** the bad one (Manage → Releases), which hides it from new installs without breaking anyone pinned to it | + +## Doing it by hand (to understand it, or without GitHub) + +The workflow does exactly this: + +```console +cd python/dxray +python -m pip install build twine +python -m build # makes dist/dxray-1.0.0-py3-none-any.whl and dist/dxray-1.0.0.tar.gz +python -m twine check dist/* # will PyPI accept it and show the README? +python -m twine upload dist/* # asks for an API token from https://pypi.org/manage/account/token/ +``` + +Use a token (username `__token__`, the token as the password), never your PyPI password, and prefer the workflow so +no token has to live on anyone's machine. diff --git a/python/dxray/.gitignore b/python/dxray/.gitignore new file mode 100644 index 0000000..7c2aac0 --- /dev/null +++ b/python/dxray/.gitignore @@ -0,0 +1,6 @@ +__pycache__/ +*.egg-info/ +dist/ +build/ +.pytest_cache/ +examples/*.html diff --git a/python/dxray/CHANGELOG.md b/python/dxray/CHANGELOG.md new file mode 100644 index 0000000..ddaf329 --- /dev/null +++ b/python/dxray/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +## 1.0.0 + +First release. + +- `dx.scan(data, target=None)`: what each column really is, data problems with the pandas line that fixes each one, + ranked insights in plain English (relationships, group differences, what drives a target, trends and biggest + changes, 80/20 concentration, lopsided averages), and a 0-100 health score. +- Reports in the terminal, as a rich Jupyter view, as one self-contained HTML page with inline SVG charts, as + Markdown and as JSON. +- `dx.clean(data)`: the safe, mechanical fixes, with a log of every change. Never drops outliers or fills gaps. +- `dx.for_llm(data)`: the dataset described for an AI model in compact Markdown. +- `dx.ask(data, question)`: answers from Claude (`pip install "dxray[ai]"`), with the description cached across + questions. +- The `dxray` command for CSV, TSV, Excel, Parquet and JSON files. diff --git a/python/dxray/LICENSE b/python/dxray/LICENSE new file mode 100644 index 0000000..dc4f037 --- /dev/null +++ b/python/dxray/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 FlightCoders + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/dxray/README.md b/python/dxray/README.md new file mode 100644 index 0000000..41eb901 --- /dev/null +++ b/python/dxray/README.md @@ -0,0 +1,129 @@ +# dxray: an X-ray for your data + +**One line tells you what's wrong with a dataset and what stands out in it, in plain English.** Then clean it, share +a report, or ask Claude about it. + +```python +import dxray as dx + +dx.scan(df, target="revenue") +``` + +```text +◆ dxray orders.csv 4,040 rows × 13 columns. Health 53/100: 12 issues, 16 insights. + +What stands out + → What drives 'revenue': 'ad_spend', 'price', 'tier'. + → 'price' differs a lot by 'tier': 'Premium' averages 221, 5.2× 'Basic' (42.4). + → Total 'revenue' rose 122% from 2026-01 to 2026-12 (by month). + → Total 'revenue' dropped 61% in 2026-03 (vs 2026-02), the biggest fall of any month. + → The top 20% of 'customer' values (68 of 338) account for 83% of total 'revenue'. + +Data problems + ● 'price' holds numbers stored as text (like '$46.25', '$95.54'), so you can't sum or average it. + fix: df['price'] = pd.to_numeric(df['price'].astype(str).str.replace(r'[,$€£₹¥%\s]', '', regex=True), errors='coerce') + ● 'region' spells the same value different ways (like 'NORTH', 'North', 'north'). + fix: df['region'] = df['region'].str.strip().str.title() + ● 40 rows (1.0%) are exact duplicates of another row. + fix: df = df.drop_duplicates() +``` + +```console +pip install dxray +``` + +Works with pandas DataFrames (and polars or pyarrow tables, dicts, lists) and with CSV, Excel, Parquet and JSON files. +Python 3.9+. Only needs pandas and numpy. + +## Why dxray + +Every analysis starts the same way: twenty minutes of `df.info()`, `df.describe()`, `value_counts()` and squinting, +before you know whether the data can be trusted or where the story is. dxray does that pass for you, in one line, and +writes it in sentences: + +- **What each column really is.** Not just `object` and `int64`: money stored as text, dates stored as text, yes/no + columns, IDs, emails, categories, free text, constants. +- **What's wrong, and the exact fix.** Missing values (including "N/A", "-", "null" hiding as text), duplicates, + repeated IDs, the same category spelled three ways, stray spaces, numbers stored as text, impossible outliers, + sentinel values like -999. Every problem comes with the pandas line that fixes it. +- **What stands out.** The strongest relationships, the groups that differ, what drives the column you care about, + trends over time and the biggest jumps and drops, 80/20 concentration, and averages that lie. Ranked, so the best + come first. +- **A health score** from 0 to 100, so you can see at a glance whether the data is ready. + +## A report you can share + +```python +report = dx.scan(df, target="revenue") +report # in Jupyter: a rich report with charts +report.to_html("report.html") # one self-contained page: email it, attach it, open it anywhere +report.to_markdown() # for a PR, a wiki, a notebook cell +report.to_json() # for code +``` + +The dxray HTML report for orders.csv: a health score of 53, and insight cards with charts: what drives revenue, price by tier, revenue rising through the year, the March drop, and the top customers bringing 83% of revenue + +## Clean it, safely + +```python +clean_df, log = dx.clean(df) +print(log) +``` + +```text +dxray cleaned 4,040 rows → 4,000 rows, 7 changes + ✓ 'order_date': dates stored as text are now dates + ✓ 'region': merged different spellings of the same value (111 values) + ✓ 'price': 31 values like 'N/A' or '-' are now missing values + ✓ 'price': numbers stored as text are now numbers + ✓ Dropped 40 duplicate rows +``` + +`dx.clean()` only makes mechanical fixes and tells you every one. It never drops outliers or fills in missing values: +those are decisions about your data, so the report tells you about them and you decide. Your original DataFrame is +left untouched. + +## Made for AI + +**Give any AI model your dataset, without pasting a million rows.** `dx.for_llm(df)` describes the data in compact +Markdown: every column with its type and statistics (computed from all rows), a few sample rows, the problems and the +findings. A few thousand tokens instead of your whole table. + +```python +prompt = dx.for_llm(df, target="revenue") +``` + +**Or just ask.** With `pip install "dxray[ai]"` and an +[Anthropic API key](https://console.anthropic.com), `dx.ask()` sends that description to Claude: + +```python +dx.ask(df, "Why did revenue drop in March, and is the data trustworthy enough to report?") +``` + +Claude sees dxray's description, not your rows. Asking several questions about the same data reuses the cached +description, so follow-ups are faster and cheaper. Choose `effort="low"`, `"medium"` (default) or `"high"`, a +`model=`, or pass your own `client=anthropic.Anthropic(...)`. + +## From the command line + +```console +$ dxray sales.csv --target revenue --html report.html +$ dxray sales.csv --clean sales_clean.csv +$ dxray sales.csv --llm > context.md +$ dxray sales.csv --ask "Which region is growing fastest?" +$ dxray sales.csv --json +``` + +## Good to know + +- **Big data:** columns are profiled on every row; the relationship and trend analysis uses a 200,000-row random + sample, so a million-row table still takes seconds. +- **Correlation isn't cause.** dxray tells you what moves together and what differs; deciding why is still your job. +- **Trends** use the table's main date column (it skips birth, signup and join dates), leave out thin periods, and + can't be faked by a few typos like a quantity of 9,999. +- **Private by default.** Everything runs locally. Only `dx.ask()` sends anything anywhere: the description, to the + Anthropic API. + +## License + +MIT. Made by [FlightCoders](https://flightcoders.com), the team behind the [Veyra](https://veyraeditor.com) editor. diff --git a/python/dxray/examples/make_orders.py b/python/dxray/examples/make_orders.py new file mode 100644 index 0000000..a7c7814 --- /dev/null +++ b/python/dxray/examples/make_orders.py @@ -0,0 +1,68 @@ +"""Makes examples/orders.csv: a year of shop orders with the usual mess, and a few things worth finding. + +Planted on purpose (dxray should find all of them): +- price stored as text with "$" and commas; "N/A" and "-" meaning missing; region spelled "North", "north ", "NORTH" +- 40 exact duplicate rows; a few absurd quantities (9,999); signup dates stored as text +- revenue grows through the year, with a sharp drop in March; Premium customers spend far more +- ad_spend goes with revenue; a few big customers bring most of the revenue (80/20) +- churn depends mostly on support_tickets + + python examples/make_orders.py # writes examples/orders.csv +""" + +from pathlib import Path + +import numpy as np +import pandas as pd + + +def make(n: int = 4000, seed: int = 7) -> pd.DataFrame: + r = np.random.default_rng(seed) + days = pd.date_range("2026-01-01", "2026-12-31", freq="D") + growth = np.linspace(0.7, 1.4, len(days)) + weights = growth.copy() + weights[(days.month == 3)] *= 0.45 # March slump + date = r.choice(days, size=n, p=weights / weights.sum()) + customers = [f"C{i:04d}" for i in range(400)] + pareto = 1 / np.arange(1, 401) ** 1.15 + customer = r.choice(customers, size=n, p=pareto / pareto.sum()) + tier = np.where(r.random(n) < 0.25, "Premium", np.where(r.random(n) < 0.5, "Plus", "Basic")) + region = r.choice(["North", "South", "East", "West"], size=n, p=[0.4, 0.25, 0.2, 0.15]) + qty = r.integers(1, 6, size=n) + base = {"Basic": 40, "Plus": 85, "Premium": 210} + price = np.round(np.array([base[t] for t in tier]) * r.lognormal(0, 0.35, n), 2) + ad_spend = np.round(price * qty * r.uniform(0.08, 0.14, n) + r.normal(0, 4, n), 2).clip(0) + revenue = np.round(price * qty, 2) + tickets = r.poisson(1.2, n) + churn = (r.random(n) < (0.05 + 0.13 * tickets)).astype(int) + df = pd.DataFrame({ + "order_id": [f"O{100000 + i}" for i in range(n)], + "order_date": pd.to_datetime(date), + "customer": customer, + "tier": tier, + "region": region, + "quantity": qty, + "price": [f"${p:,.2f}" for p in price], + "revenue": revenue, + "ad_spend": ad_spend, + "support_tickets": tickets, + "signup_date": pd.to_datetime(date) - pd.to_timedelta(r.integers(10, 900, n), unit="D"), + "churned": churn, + "channel": "web", + }) + df["signup_date"] = df["signup_date"].dt.strftime("%Y-%m-%d") + # the mess + idx = r.choice(n, 60, replace=False); df.loc[idx[:30], "price"] = "N/A"; df.loc[idx[30:], "price"] = "-" + for spelling, k in (("north ", 70), ("NORTH", 40)): + hit = df.index[df["region"] == "North"][:k] if spelling == "north " else df.index[df["region"] == "North"][-k:] + df.loc[hit, "region"] = spelling + df.loc[r.choice(n, 8, replace=False), "quantity"] = 9999 + df.loc[r.choice(n, 120, replace=False), "ad_spend"] = np.nan + df = pd.concat([df, df.sample(40, random_state=1)], ignore_index=True) + return df.sort_values("order_date").reset_index(drop=True) + + +if __name__ == "__main__": + out = Path(__file__).with_name("orders.csv") + make().to_csv(out, index=False) + print(f"wrote {out}") diff --git a/python/dxray/media/report.png b/python/dxray/media/report.png new file mode 100644 index 0000000..127b133 Binary files /dev/null and b/python/dxray/media/report.png differ diff --git a/python/dxray/pyproject.toml b/python/dxray/pyproject.toml new file mode 100644 index 0000000..6f7e45b --- /dev/null +++ b/python/dxray/pyproject.toml @@ -0,0 +1,59 @@ +[build-system] +requires = ["hatchling>=1.21"] +build-backend = "hatchling.build" + +[project] +name = "dxray" +dynamic = ["version"] +description = "An X-ray for your data: one line finds what's wrong with a dataset and what stands out, in plain English. Clean it, report it, or ask Claude about it." +readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] +requires-python = ">=3.9" +authors = [{ name = "FlightCoders", email = "hire@flightcoders.com" }] +keywords = ["pandas", "data analysis", "eda", "exploratory data analysis", "data profiling", "data quality", "data cleaning", "insights", "llm", "ai", "claude", "jupyter", "dataframe", "automated eda"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "Intended Audience :: Financial and Insurance Industry", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Framework :: Jupyter", + "Topic :: Scientific/Engineering :: Information Analysis", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Typing :: Typed", +] +dependencies = ["pandas>=1.5", "numpy>=1.23"] + +[project.optional-dependencies] +ai = ["anthropic>=2.13"] +all = ["anthropic>=2.13", "pyarrow>=12", "openpyxl>=3.1"] + +[project.urls] +Homepage = "https://github.com/fcopensource/veyraeditor/tree/main/python/dxray" +Source = "https://github.com/fcopensource/veyraeditor/tree/main/python/dxray" +Issues = "https://github.com/fcopensource/veyraeditor/issues" +Changelog = "https://github.com/fcopensource/veyraeditor/blob/main/python/dxray/CHANGELOG.md" + +[project.scripts] +dxray = "dxray.cli:main" + +[tool.hatch.version] +path = "src/dxray/__init__.py" + +[tool.hatch.build.targets.wheel] +packages = ["src/dxray"] + +[tool.hatch.build.targets.sdist] +include = ["src", "tests", "examples/make_orders.py", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/python/dxray/src/dxray/__init__.py b/python/dxray/src/dxray/__init__.py new file mode 100644 index 0000000..365ccad --- /dev/null +++ b/python/dxray/src/dxray/__init__.py @@ -0,0 +1,21 @@ +"""dxray: an X-ray for your data. + + import dxray as dx + + report = dx.scan(df, target="revenue") # what each column is, what's wrong, what stands out + report # a rich report in Jupyter; print(report) in a terminal + report.to_html("report.html") # a shareable page with charts + + clean_df, log = dx.clean(df) # fix the safe problems, see every change + prompt = dx.for_llm(df) # the dataset described for an AI model + dx.ask(df, "Why did sales drop in March?") # answered by Claude (pip install "dxray[ai]") +""" + +from ._api import CleanLog, clean, for_llm, scan +from ._ask import Answer, AskError, ask +from ._infer import infer +from ._model import Column, Insight, Issue +from ._report import Report + +__version__ = "1.0.0" +__all__ = ["Answer", "AskError", "CleanLog", "Column", "Insight", "Issue", "Report", "__version__", "ask", "clean", "for_llm", "infer", "scan"] diff --git a/python/dxray/src/dxray/__main__.py b/python/dxray/src/dxray/__main__.py new file mode 100644 index 0000000..eb53e2f --- /dev/null +++ b/python/dxray/src/dxray/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +raise SystemExit(main()) diff --git a/python/dxray/src/dxray/_api.py b/python/dxray/src/dxray/_api.py new file mode 100644 index 0000000..1557f2d --- /dev/null +++ b/python/dxray/src/dxray/_api.py @@ -0,0 +1,177 @@ +"""The public functions: scan, clean, for_llm and ask.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from typing import Any + +import numpy as np +import pandas as pd + +from ._infer import is_missing_text, is_text, numeric_values, parse_dates +from ._insights import find_insights, nice +from ._model import Column +from ._profile import profile +from ._quality import find_issues +from ._report import Report + + +def _frame(data: Any) -> tuple[pd.DataFrame, str]: + """Anything table-like, or a path to a CSV / Excel / Parquet / JSON file, as a DataFrame.""" + if isinstance(data, pd.DataFrame): + return data, "dataset" + if isinstance(data, pd.Series): + return data.to_frame(), str(data.name or "series") + if isinstance(data, (str, os.PathLike)): + path = os.fspath(data) + low = path.lower() + name = os.path.basename(path) + if low.endswith((".csv", ".txt", ".tsv")): + return pd.read_csv(path, sep="\t" if low.endswith(".tsv") else ",", low_memory=False), name + if low.endswith((".xlsx", ".xls")): + return pd.read_excel(path), name + if low.endswith(".parquet"): + return pd.read_parquet(path), name + if low.endswith((".json", ".jsonl")): + return pd.read_json(path, lines=low.endswith(".jsonl")), name + raise ValueError(f"dxray can't read {name!r}: use a CSV, Excel, Parquet or JSON file, or a pandas DataFrame.") + if hasattr(data, "to_pandas"): # polars, pyarrow, ... + return data.to_pandas(), "dataset" + return pd.DataFrame(data), "dataset" + + +def scan(data: Any, target: str | None = None, *, name: str | None = None, insights: int = 20) -> Report: + """X-ray a dataset: what each column really is, what's wrong with it, and what stands out. + + ``data`` is a pandas DataFrame (or polars/pyarrow table, dict, list of rows) or a path to a CSV, Excel, Parquet or + JSON file. ``target`` is the column you care about most (sales, churn, price...): dxray then shows what drives it. + """ + df, default_name = _frame(data) + if target is not None and target not in map(str, df.columns): + raise KeyError(f"No column named {target!r}. Columns: {', '.join(map(str, df.columns))}") + cols, kinds = profile(df) + report = Report(rows=len(df), columns=cols, issues=find_issues(df, cols, kinds), insights=find_insights(df, kinds, target, insights), + target=target, name=name or default_name, memory_mb=round(df.memory_usage(deep=True).sum() / 1e6, 2)) + return report + + +@dataclass +class CleanLog: + """What dx.clean() changed, one line per change.""" + changes: list[str] = field(default_factory=list) + rows_before: int = 0 + rows_after: int = 0 + + def __str__(self) -> str: + head = f"dxray cleaned {self.rows_before:,} rows → {self.rows_after:,} rows, {len(self.changes)} change{'s' * (len(self.changes) != 1)}" + return head + ("".join(f"\n ✓ {c}" for c in self.changes) if self.changes else "\n Nothing needed fixing.") + + __repr__ = __str__ + + +def clean(data: Any, *, duplicates: bool = True, drop_empty: bool = True, fix_text: bool = True, convert: bool = True, + inplace: bool = False) -> tuple[pd.DataFrame, CleanLog]: + """Fix the safe, mechanical problems scan() finds, and say exactly what changed. + + Turns "N/A"-style text into real missing values, strips stray spaces, merges spellings of the same category + ("NY", "ny ", "Ny" -> the most common one), converts numbers and dates stored as text, drops exact duplicate rows + and empty columns. It never drops outliers or fills in missing values: those are decisions, not fixes. + """ + df, _ = _frame(data) + df = df if inplace else df.copy() + log = CleanLog(rows_before=len(df)) + if drop_empty: + empty = [c for c in df.columns if df[c].isna().all() or (is_text(df[c]) and is_missing_text(df[c].dropna()).all())] + if empty: + df = df.drop(columns=empty) + log.changes.append(f"Dropped {len(empty)} empty column{'s' * (len(empty) != 1)}: {', '.join(map(str, empty))}") + cols, kinds = profile(df) + for col in df.columns: + k = kinds[str(col)] + s = df[col] + if not is_text(s): + continue + if fix_text: + present = s.notna() + sentinel = present & is_missing_text(s.where(present, "")) + if sentinel.any(): + df[col] = s = s.mask(sentinel) + log.changes.append(f"'{col}': {int(sentinel.sum()):,} values like 'N/A' or '-' are now missing values") + stripped = s.where(s.isna(), s.astype(str).str.strip()) + changed = int((s.notna() & (stripped != s)).fillna(False).sum()) + if changed: + df[col] = s = stripped + log.changes.append(f"'{col}': trimmed spaces from {changed:,} values") + if convert and k.convertible == "numeric": + df[col] = numeric_values(s, k) + log.changes.append(f"'{col}': numbers stored as text are now numbers") + continue + if convert and k.convertible == "datetime": + df[col] = parse_dates(s) + log.changes.append(f"'{col}': dates stored as text are now dates") + continue + if fix_text and k.kind in ("categorical", "boolean"): + text = s.dropna().astype(str) + key = text.str.lower().str.replace(r"\s+", " ", regex=True) + canon = text.groupby(key).agg(lambda v: v.value_counts().index[0]) + merged = key.map(canon) + changed = int((merged != text).sum()) + if changed: + df.loc[merged.index, col] = merged + log.changes.append(f"'{col}': merged different spellings of the same value ({changed:,} values)") + if duplicates: + dupes = int(df.duplicated().sum()) + if dupes: + df = df.drop_duplicates() + log.changes.append(f"Dropped {dupes:,} duplicate rows") + log.rows_after = len(df) + return df, log + + +def for_llm(data: Any, *, target: str | None = None, sample_rows: int = 5, max_chars: int = 12000, report: Report | None = None) -> str: + """The dataset described for an AI model: schema, statistics, a few rows, problems and findings, in compact Markdown. + + Paste it into a prompt (or let dx.ask() do it) so the model knows your data without seeing every row. + """ + df, name = _frame(data) + r = report or scan(df, target, name=name) + lines = [f"# Dataset: {r.name}", f"{r.rows:,} rows, {len(r.columns)} columns. Data health {r.health}/100.", "", "## Columns", + "name | type | missing | unique | summary", "---|---|---|---|---"] + for c in r.columns: + lines.append(f"{c.name} | {c.kind}{' (' + c.note + ')' if c.note else ''} | {c.missing_pct:.1f}% | {c.unique:,} | {_llm_summary(c)}") + if sample_rows and len(df): + sample = df.sample(min(sample_rows, len(df)), random_state=0) if len(df) > sample_rows else df + lines += ["", f"## {len(sample)} sample rows", _rows_text(sample)] + if r.issues: + lines += ["", "## Data problems"] + [f"- [{i.severity}] {i.title}" for i in r.issues[:15]] + if r.insights: + lines += ["", "## Findings (computed from all rows)"] + [f"- {i.title}" + (f" {i.detail}" if i.detail else "") for i in r.insights[:15]] + text = "\n".join(lines) + return text if len(text) <= max_chars else text[: max_chars - 40] + "\n…(trimmed to fit max_chars)" + + +def _llm_summary(c: Column) -> str: + s = c.stats + if c.kind == "numeric" and s: + return f"min {nice(s['min'])}, median {nice(s['median'])}, mean {nice(s['mean'])}, max {nice(s['max'])}, sum {nice(s['sum'])}" + if c.kind == "datetime" and s: + return f"{str(s['min'])[:10]} to {str(s['max'])[:10]}" + if c.top: + return ", ".join(f"{v}={n}" for v, n in c.top[:6]) + return "" + + +def _rows_text(df: pd.DataFrame) -> str: + cols = [str(c) for c in df.columns] + out = [" | ".join(cols), "|".join("---" for _ in cols)] + for _, row in df.iterrows(): + out.append(" | ".join(_cell(v) for v in row.values)) + return "\n".join(out) + + +def _cell(v: Any) -> str: + if v is None or (isinstance(v, float) and np.isnan(v)) or v is pd.NA or v is pd.NaT: + return "" + t = str(v).replace("|", "/").replace("\n", " ") + return t if len(t) <= 40 else t[:37] + "..." diff --git a/python/dxray/src/dxray/_ask.py b/python/dxray/src/dxray/_ask.py new file mode 100644 index 0000000..54a000d --- /dev/null +++ b/python/dxray/src/dxray/_ask.py @@ -0,0 +1,94 @@ +"""dx.ask(): questions about your data, answered by Claude from dxray's description of it. + +Needs the optional extra: ``pip install "dxray[ai]"``, and an Anthropic API key in ANTHROPIC_API_KEY (or an +``ant auth login`` profile). Claude sees dx.for_llm()'s summary (schema, statistics, a few sample rows, problems and +findings), not your whole dataset. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from ._api import _frame, for_llm, scan + +DEFAULT_MODEL = "claude-opus-5-5" + +SYSTEM = ( + "You are a careful data analyst. The user's dataset is described below by dxray: its columns, statistics computed " + "from every row, a few sample rows, data problems and findings. Answer the user's question from this description. " + "Be concrete and cite the numbers you use. If the description doesn't contain enough to answer, say what is " + "missing and give the pandas code that would compute it. Keep answers short unless asked for more.\n\n" +) + + +class AskError(RuntimeError): + """Asking Claude didn't work: missing package or key, a refusal, or an API error. The message says what to do.""" + + +@dataclass +class Answer: + text: str + model: str + input_tokens: int = 0 + output_tokens: int = 0 + cached_tokens: int = 0 + + def __str__(self) -> str: + return self.text + + def _repr_markdown_(self) -> str: + return self.text + + +def ask(data: Any, question: str, *, target: str | None = None, model: str = DEFAULT_MODEL, effort: str = "medium", + client: Any = None, max_tokens: int = 16000) -> Answer: + """Ask a question about a dataset in plain English and get an answer from Claude. + + >>> dx.ask(df, "Which region is growing fastest, and is anything odd about the data?") + + ``effort`` ("low", "medium", "high") trades depth for speed and cost. Pass ``client`` to reuse your own + ``anthropic.Anthropic()`` client. Asking several questions about the same data reuses the cached description. + """ + if not question or not question.strip(): + raise ValueError("Ask a question, like dx.ask(df, 'What drives revenue?')") + try: + import anthropic + except ImportError: + raise AskError('dx.ask() needs the Anthropic SDK. Install it with: pip install "dxray[ai]"') from None + df, name = _frame(data) + context = for_llm(df, target=target, report=scan(df, target, name=name)) + try: + client = client or anthropic.Anthropic() + # Streaming keeps long answers clear of request timeouts. The description sits in a cached system prompt, so a + # second question about the same data is faster and cheaper. If Claude declines, "default" fallbacks retry the + # request on the model Anthropic recommends. + with client.beta.messages.stream( + model=model, + max_tokens=max_tokens, + betas=["server-side-fallback-2026-07-01"], + fallbacks="default", + output_config={"effort": effort}, + system=[{"type": "text", "text": SYSTEM + context, "cache_control": {"type": "ephemeral"}}], + messages=[{"role": "user", "content": question}], + ) as stream: + message = stream.get_final_message() + except anthropic.AuthenticationError: + raise AskError("Anthropic rejected the API key. Set ANTHROPIC_API_KEY (from console.anthropic.com) or run `ant auth login`.") from None + except anthropic.RateLimitError: + raise AskError("Anthropic's rate limit was reached. Wait a moment and ask again.") from None + except anthropic.APIStatusError as e: + raise AskError(f"The Anthropic API returned an error ({e.status_code}): {e.message}") from None + except anthropic.APIConnectionError: + raise AskError("Couldn't reach the Anthropic API. Check your internet connection.") from None + except anthropic.AnthropicError as e: + if isinstance(e, getattr(anthropic, "CredentialsError", ())) or "api_key" in str(e).lower() or "credentials" in str(e).lower(): + raise AskError("No Anthropic API key found. Set ANTHROPIC_API_KEY (from console.anthropic.com) or run `ant auth login`.") from None + raise AskError(str(e)) from None + if message.stop_reason == "refusal": + raise AskError("Claude declined to answer this question.") + text = "".join(b.text for b in message.content if getattr(b, "type", "") == "text").strip() + usage = getattr(message, "usage", None) + return Answer(text=text, model=getattr(message, "model", model), + input_tokens=getattr(usage, "input_tokens", 0) or 0, output_tokens=getattr(usage, "output_tokens", 0) or 0, + cached_tokens=getattr(usage, "cache_read_input_tokens", 0) or 0) diff --git a/python/dxray/src/dxray/_infer.py b/python/dxray/src/dxray/_infer.py new file mode 100644 index 0000000..a9ff87a --- /dev/null +++ b/python/dxray/src/dxray/_infer.py @@ -0,0 +1,125 @@ +"""What each column really is: numbers, money stored as text, dates, categories, IDs, emails, free text... + +pandas only knows storage types (int64, object). ``infer(series)`` looks at the values themselves, so a column of +"$1,200" strings is reported as numbers-in-text, and "2026-03-14" strings as dates-in-text. +""" + +from __future__ import annotations + +import re +import warnings +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +# Values people use to mean "missing". +SENTINELS = {"", "na", "n/a", "nan", "none", "null", "nil", "-", "--", "?", "missing", "unknown", "#n/a", "undefined"} +BOOL_WORDS = {"true", "false", "yes", "no", "y", "n", "t", "f", "1", "0"} +NUMBER_RE = re.compile(r"^\s*[-+(]?\s*[$€£₹¥]?\s*[-+]?(\d{1,3}(,\d{3})+|\d+)(\.\d+)?\s*[%)]?\s*$") +EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$") +URL_RE = re.compile(r"^(https?://|www\.)\S+$", re.I) +ID_NAME_RE = re.compile(r"(^|_|\b)(id|uuid|guid|key|code|sku|number|no)$|id$", re.I) + +KINDS = ("numeric", "boolean", "datetime", "categorical", "text", "id", "email", "url", "empty", "constant") + + +@dataclass +class Kind: + kind: str # one of KINDS + stored_as: str # the pandas dtype + note: str = "" # e.g. "numbers stored as text", "dates stored as text" + convertible: str = "" # "numeric" or "datetime" when the text can be converted + + +def is_text(s: pd.Series) -> bool: + """Text storage: object columns, and the string dtypes of pandas 2 and 3.""" + return s.dtype == object or pd.api.types.is_string_dtype(s.dtype) + + +def _sample(values: pd.Series, n: int = 4000) -> pd.Series: + return values.sample(n, random_state=0) if len(values) > n else values + + +def parse_number_text(s: pd.Series) -> pd.Series: + """'$1,200' -> 1200, '12%' -> 12, '(45)' -> -45. Anything else becomes NaN.""" + t = s.astype("string").str.strip() + neg = (t.str.startswith("(") & t.str.endswith(")")).fillna(False).astype(bool).to_numpy() + t = t.str.replace(r"[,$€£₹¥%()\s]", "", regex=True) + out = pd.to_numeric(t, errors="coerce").astype(float) + return out.where(~neg, -out) + + +def parse_dates(s: pd.Series) -> pd.Series: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + try: + return pd.to_datetime(s, errors="coerce", format="mixed") + except (TypeError, ValueError): + return pd.to_datetime(s, errors="coerce") + + +def is_missing_text(s: pd.Series) -> pd.Series: + """True where a text value is one of the usual stand-ins for missing ("N/A", "null", "-", ...).""" + return s.astype("string").str.strip().str.lower().isin(SENTINELS).fillna(False) + + +def infer(series: pd.Series, name: str | None = None) -> Kind: + name = str(name if name is not None else series.name) + stored = str(series.dtype) + values = series.dropna() + if is_text(values): + values = values[~is_missing_text(values)] + n = len(values) + if n == 0: + return Kind("empty", stored) + unique = values.nunique(dropna=True) + if unique == 1: + return Kind("constant", stored) + + if pd.api.types.is_bool_dtype(series): + return Kind("boolean", stored) + if pd.api.types.is_datetime64_any_dtype(series): + return Kind("datetime", stored) + if pd.api.types.is_numeric_dtype(series): + if unique == 2 and set(pd.unique(values)) <= {0, 1}: + return Kind("boolean", stored) + if pd.api.types.is_integer_dtype(series) and unique == n and ID_NAME_RE.search(name): + return Kind("id", stored) + return Kind("numeric", stored) + if isinstance(series.dtype, pd.CategoricalDtype): + return Kind("categorical", stored) + + text = _sample(values).astype("string").str.strip() + lower = text.str.lower() + if unique <= 2 and set(lower.unique()) <= BOOL_WORDS: + return Kind("boolean", stored, "yes/no stored as text") + if text.str.match(NUMBER_RE).mean() >= 0.95: + return Kind("numeric", stored, "numbers stored as text", "numeric") + if text.str.match(EMAIL_RE).mean() >= 0.9: + return Kind("email", stored) + if text.str.match(URL_RE).mean() >= 0.9: + return Kind("url", stored) + looks_datey = text.str.contains(r"\d", regex=True).mean() > 0.9 and text.str.len().between(6, 32).mean() > 0.9 + if looks_datey and parse_dates(text).notna().mean() >= 0.9: + return Kind("datetime", stored, "dates stored as text", "datetime") + if unique == n and (ID_NAME_RE.search(name) or text.str.len().nunique() <= 2): + return Kind("id", stored) + if unique <= 200 and unique / n <= 0.5: + return Kind("categorical", stored) + return Kind("text", stored) + + +def numeric_values(series: pd.Series, kind: Kind) -> pd.Series: + """The column as numbers (converting numbers-in-text), NaN where it isn't one.""" + if kind.convertible == "numeric": + return parse_number_text(series.where(~is_missing_text(series))) + if kind.kind == "boolean" and kind.note: + return series.astype("string").str.strip().str.lower().map(lambda v: 1.0 if v in {"true", "yes", "y", "t", "1"} else 0.0 if v in {"false", "no", "n", "f", "0"} else np.nan) + return pd.to_numeric(series, errors="coerce") + + +def datetime_values(series: pd.Series, kind: Kind) -> pd.Series: + if pd.api.types.is_datetime64_any_dtype(series): + return series + return parse_dates(series.where(~is_missing_text(series))) diff --git a/python/dxray/src/dxray/_insights.py b/python/dxray/src/dxray/_insights.py new file mode 100644 index 0000000..493c642 --- /dev/null +++ b/python/dxray/src/dxray/_insights.py @@ -0,0 +1,315 @@ +"""What's interesting in the data, written as sentences a person can act on. + +Every finding has a score from 0 to 1 (how strong or surprising it is), so the best ones come first. +""" + +from __future__ import annotations + +import math +import re + +import numpy as np +import pandas as pd + +from ._infer import Kind, datetime_values, numeric_values +from ._model import Insight + +PERSON_DATE = re.compile(r"(birth|dob|signup|sign_up|joined|registered|member_since)", re.I) +MONEY_FIRST = re.compile(r"(revenue|sales|amount|spend|profit|gmv|income|value|total)", re.I) +ADDITIVE = re.compile(r"(amount|revenue|sales|total|cost|qty|quantity|count|units|spend|profit|orders?|bookings|visits|clicks|signups|income|value|volume|gmv)", re.I) +MAX_ROWS = 200_000 + + +def nice(v: float) -> str: + """12345.678 -> '12,346'; 0.1234 -> '0.12'; 2_500_000 -> '2.5M'.""" + if v is None or (isinstance(v, float) and math.isnan(v)): + return "n/a" + v = float(v) + a = abs(v) + if a >= 1e9: + return f"{v / 1e9:.1f}B" + if a >= 1e6: + return f"{v / 1e6:.1f}M" + if a >= 1e4: + return f"{v / 1e3:.1f}k" if a < 1e5 else f"{v / 1e3:.0f}k" + if a >= 100: + return f"{v:,.0f}" + if a >= 1: + return f"{v:,.1f}".rstrip("0").rstrip(".") + if v == 0: + return "0" + return f"{v:.2f}" + + +def _times(a: float, b: float) -> str: + if b == 0: + return "far more than" + r = a / b + return f"{r:.1f}×" if r >= 1.5 else f"{(r - 1) * 100:.0f}% more than" + + +def working_frame(df: pd.DataFrame, kinds: dict[str, Kind]) -> tuple[pd.DataFrame, dict[str, str]]: + """Columns converted to what they really are (numbers, dates, clean categories), sampled if huge.""" + if len(df) > MAX_ROWS: + df = df.sample(MAX_ROWS, random_state=0) + out, roles = {}, {} + for col in df.columns: + name, k = str(col), kinds[str(col)] + s = df[col] + if k.kind == "numeric": + out[name] = numeric_values(s, k).astype(float); roles[name] = "num" + elif k.kind == "boolean": + out[name] = numeric_values(s, k).astype(float) if k.note else pd.to_numeric(s, errors="coerce").astype(float); roles[name] = "bool" + elif k.kind == "datetime": + out[name] = datetime_values(s, k); roles[name] = "date" + elif k.kind == "categorical": + out[name] = s.astype("string").str.strip(); roles[name] = "cat" + elif k.kind in ("text", "id") and s.nunique() <= 0.5 * max(1, s.notna().sum()): + out[name] = s.astype("string").str.strip(); roles[name] = "key" # a repeated key, like a customer ID + return pd.DataFrame(out, index=df.index), roles + + +def label(col: str, value, roles: dict[str, str]) -> str: + """How to name a group in a sentence: 'Premium', or churned=yes for a yes/no column.""" + if roles.get(col) == "bool": + return f"{col}={'yes' if float(value) == 1 else 'no'}" + return f"'{value}'" + + +def _eta_squared(groups: pd.Series, values: pd.Series) -> float: + ok = groups.notna() & values.notna() + g, v = groups[ok], values[ok] + if len(v) < 10 or v.var() == 0: + return 0.0 + means = v.groupby(g).agg(["mean", "count"]) + ss_between = float((means["count"] * (means["mean"] - v.mean()) ** 2).sum()) + ss_total = float(((v - v.mean()) ** 2).sum()) + return ss_between / ss_total if ss_total else 0.0 + + +def _cramers_v(a: pd.Series, b: pd.Series) -> float: + t = pd.crosstab(a, b) + if t.shape[0] < 2 or t.shape[1] < 2: + return 0.0 + n = t.values.sum() + expected = np.outer(t.sum(1), t.sum(0)) / n + chi2 = float(((t.values - expected) ** 2 / np.where(expected == 0, 1, expected)).sum()) + return math.sqrt(chi2 / (n * (min(t.shape) - 1))) + + +def find_insights(df: pd.DataFrame, kinds: dict[str, Kind], target: str | None = None, limit: int = 20) -> list[Insight]: + w, roles = working_frame(df, kinds) + n = len(w) + found: list[Insight] = [] + if n < 5: + return found + nums = [c for c, r in roles.items() if r == "num" and w[c].notna().sum() >= 10 and w[c].nunique() > 2] + cats = [c for c, r in roles.items() if r in ("cat", "bool") and 2 <= w[c].nunique() <= 30] + dates = [c for c, r in roles.items() if r == "date" and w[c].notna().sum() >= 10] + + # --- relationships between numbers + if len(nums) >= 2: + corr = w[nums].corr(method="spearman", min_periods=10) + for i, a in enumerate(nums): + for b in nums[i + 1:]: + r = corr.loc[a, b] + if pd.isna(r) or abs(r) < 0.5 or target in (a, b): + continue + if abs(r) >= 0.97: + found.append(Insight(f"'{a}' and '{b}' carry almost the same information (correlation {r:.2f}): you probably need only one.", "redundant", 0.45, [a, b])) + continue + way = "go up" if r > 0 else "go down" + found.append(Insight(f"When '{a}' is higher, '{b}' tends to {way} too (correlation {r:.2f}).", "correlation", min(1.0, abs(r) * 0.9), [a, b], + "Spearman rank correlation, so it also catches curved relationships. Correlation isn't proof of cause.", + _scatter(w, a, b))) + + # --- groups that differ + for g in cats: + if g == target: + continue + levels = w[g].value_counts() + levels = levels[levels >= max(5, 0.01 * n)] + if len(levels) < 2: + continue + best = None + for m in nums: + if m == target: + continue + sub = w[w[g].isin(levels.index)] + e = _eta_squared(sub[g], sub[m]) + if e >= 0.06 and (best is None or e > best[0]): + best = (e, m, sub) + if best: + e, m, sub = best + means = sub.groupby(g)[m].mean().sort_values(ascending=False) + hi, lo = label(g, means.index[0], roles), label(g, means.index[-1], roles) + found.append(Insight(f"'{m}' differs a lot by '{g}': {hi} averages {nice(means.iloc[0])}, {_times(means.iloc[0], means.iloc[-1])} {lo} ({nice(means.iloc[-1])}).", + "segment", min(1.0, math.sqrt(e) * 1.1), [g, m], f"'{g}' explains {e * 100:.0f}% of the variation in '{m}'.", + {"type": "bar", "labels": [label(g, x, roles).strip("'") for x in means.index[:10]], "values": [round(float(v), 4) for v in means.values[:10]], "title": f"Average {m} by {g}"})) + + # --- one value dominates a column / 80-20 concentration + for g in [c for c, r in roles.items() if r == "cat"]: + vc = w[g].value_counts(normalize=True) + if len(vc) >= 3 and vc.iloc[0] >= 0.5: + found.append(Insight(f"'{g}' is mostly '{vc.index[0]}' ({vc.iloc[0] * 100:.0f}% of rows).", "dominance", 0.25 + 0.3 * (vc.iloc[0] - 0.5), [g])) + for g in [c for c, r in roles.items() if r in ("cat", "key")]: + if w[g].nunique() < 10: + continue + for m in sorted(nums, key=lambda c: 0 if MONEY_FIRST.search(c) else 1): + x = robust(w[m]) + if x.min() < 0 or not ADDITIVE.search(m): + continue + totals = x.groupby(w[g]).sum().sort_values(ascending=False) + if totals.sum() <= 0: + continue + k = max(1, int(round(len(totals) * 0.2))) + share = totals.iloc[:k].sum() / totals.sum() + if share >= 0.6: + found.append(Insight(f"The top 20% of '{g}' values ({k} of {len(totals)}) account for {share * 100:.0f}% of total '{m}'.", "concentration", + min(1.0, 0.3 + (share - 0.6)), [g, m], "An 80/20 pattern: a few account for most of the total.", + {"type": "bar", "labels": [str(v) for v in totals.index[:10]], "values": [round(float(v), 4) for v in totals.values[:10]], "title": f"Total {m} by {g} (top 10)"})) + break + + # --- lopsided numbers + for m in nums: + x = robust(w[m]).dropna() + if len(x) < 30: + continue + mean, med = x.mean(), x.median() + if x.skew() > 2 and med > 0 and mean > 1.5 * med: + found.append(Insight(f"'{m}' is lopsided: the average is {nice(mean)} but the typical value (median) is {nice(med)}. A few very large values pull the average up.", + "skew", 0.3, [m], "Report the median, or look at the large values separately.")) + + # --- over time: on the main date column, with thin periods and extreme values left out so they can't fake a trend + found.extend(time_insights(w, nums, dates, n)) + + # --- what drives the target + if target is not None and target in w.columns: + found = [i for i in found if not (i.kind == "segment" and target in i.columns)] + found.extend(drivers(w, roles, target)) + + found.sort(key=lambda i: -i.score) + seen, out = set(), [] + for i in found: + if i.title not in seen: + seen.add(i.title); out.append(i) + return out[:limit] + + +def robust(x: pd.Series) -> pd.Series: + """Values clipped at 3 IQRs past the quartiles (on a log scale for positive, lopsided data), so a few typos like + 9,999 can't dominate a total or an average.""" + v = x.dropna() + if len(v) < 20: + return x + log = v.min() >= 0 and v.skew() > 1 + t = np.log1p(v) if log else v + q1, q3 = np.percentile(t, [25, 75]) + hi = q3 + 3 * (q3 - q1) + hi = float(np.expm1(hi)) if log else float(hi) + lo = None if log else float(q1 - 3 * (q3 - q1)) + return x.clip(lower=lo, upper=hi) + + +def time_insights(w: pd.DataFrame, nums: list[str], dates: list[str], n: int) -> list[Insight]: + out: list[Insight] = [] + best = None + # The main date column: the first one with enough well-filled periods, skipping dates that describe people + # (birth, signup, joined) rather than the events in the table. + preferred = [d for d in dates if not PERSON_DATE.search(d)] + [d for d in dates if PERSON_DATE.search(d)] + for d in preferred: + col = w[d].dropna() + span = (col.max() - col.min()).days if len(col) else 0 + if span < 14: + continue + freq = "M" if span > 120 else "W" if span > 30 else "D" + counts = col.dt.to_period(freq).value_counts() + good = int((counts >= max(5, 0.005 * n)).sum()) + if good >= 4: + best = (good, d, freq) + break + if not best: + return out + _, d, freq = best + label = {"M": "month", "W": "week", "D": "day"}[freq] + period = w[d].dt.to_period(freq) + counts = period.value_counts().sort_index() + keep = counts[counts >= max(5, 0.005 * n)].index + series = [("rows", counts.loc[keep].astype(float), "number of rows")] + for m in nums[:8]: + agg = "sum" if (w[m].min() >= 0 and ADDITIVE.search(m)) else "mean" + ts = robust(w[m]).groupby(period).agg(agg).sort_index() + series.append((m, ts.reindex(keep), f"{'total' if agg == 'sum' else 'average'} '{m}'")) + trends, changes = [], [] + for m, ts, what in series: + ts = ts.dropna() + if len(ts) < 4: + continue + cols = [d] + ([m] if m != "rows" else []) + chart = {"type": "line", "labels": [str(p) for p in ts.index], "values": [round(float(v), 4) for v in ts.values], "title": f"{what[0].upper() + what[1:]} by {label}"} + k = max(1, len(ts) // 4) + first, last = ts.iloc[:k].mean(), ts.iloc[-k:].mean() + if first > 0 and abs((last - first) / first) >= 0.2: + change = (last - first) / first + trends.append(Insight(f"{what[0].upper() + what[1:]} {'rose' if change > 0 else 'fell'} {abs(change) * 100:.0f}% from {ts.index[0]} to {ts.index[-1]} (by {label}).", + "trend", min(0.95, 0.35 + abs(change) / 3), cols, f"Comparing the first and last quarter of the {label}s.", chart)) + steps = ts.pct_change().replace([np.inf, -np.inf], np.nan).dropna() + if len(steps) >= 3: + worst, top = steps.idxmin(), steps.idxmax() + if steps.loc[worst] <= -0.25: + prev = ts.index[ts.index.get_loc(worst) - 1] + changes.append(Insight(f"{what[0].upper() + what[1:]} dropped {abs(steps.loc[worst]) * 100:.0f}% in {worst} (vs {prev}), the biggest fall of any {label}.", + "change", min(0.95, 0.4 + abs(steps.loc[worst]) / 2), cols, chart=chart)) + if steps.loc[top] >= 0.4: + prev = ts.index[ts.index.get_loc(top) - 1] + changes.append(Insight(f"{what[0].upper() + what[1:]} jumped {steps.loc[top] * 100:.0f}% in {top} (vs {prev}), the biggest rise of any {label}.", + "change", min(0.9, 0.3 + steps.loc[top] / 4), cols, chart=chart)) + trends.sort(key=lambda i: -i.score) + # One biggest fall and one biggest rise, not two versions of the same month from related columns. + picked = [] + for word in ("dropped", "jumped"): + same = [c for c in changes if f" {word} " in c.title] + if same: + picked.append(max(same, key=lambda i: (i.score, any(MONEY_FIRST.search(c) for c in i.columns[1:])))) + return trends[:3] + picked + + +def drivers(w: pd.DataFrame, roles: dict[str, str], target: str) -> list[Insight]: + """How strongly each column relates to the target, strongest first.""" + t = w[target] + numeric_target = roles.get(target) in ("num", "bool") + strengths: list[tuple[float, str, str]] = [] + for c, r in roles.items(): + if c == target or r == "date": + continue + if r in ("num", "bool"): + if numeric_target: + v = w[[c, target]].corr(method="spearman").iloc[0, 1] + if pd.notna(v): + strengths.append((abs(float(v)), c, f"{'higher' if v > 0 else 'lower'} '{c}' goes with {'higher' if numeric_target else ''} '{target}' (correlation {v:.2f})")) + else: + e = _eta_squared(t, w[c]) + strengths.append((math.sqrt(e), c, f"'{c}' differs across '{target}' groups")) + elif r == "cat" and w[c].nunique() <= 30: + if numeric_target: + e = _eta_squared(w[c], t) + means = t.groupby(w[c]).mean().sort_values(ascending=False) + strengths.append((math.sqrt(e), c, f"'{target}' is highest for {label(c, means.index[0], roles)} ({nice(means.iloc[0])}) and lowest for {label(c, means.index[-1], roles)} ({nice(means.iloc[-1])})")) + else: + strengths.append((_cramers_v(w[c], t), c, f"'{target}' depends on '{c}'")) + strengths = sorted((s for s in strengths if s[0] >= 0.1), reverse=True) + if not strengths: + return [Insight(f"No single column clearly predicts '{target}'.", "driver", 0.2, [target])] + out = [Insight(f"What drives '{target}': " + ", ".join(f"'{c}'" for _, c, _ in strengths[:3]) + ".", "driver", min(1.0, 0.5 + strengths[0][0] / 2), + [target] + [c for _, c, _ in strengths[:5]], "Strength of each column's link to the target (0 = none, 1 = perfect).", + {"type": "bar", "labels": [c for _, c, _ in strengths[:8]], "values": [round(s, 3) for s, _, _ in strengths[:8]], "title": f"Link to {target}"})] + for s, c, text in strengths[:3]: + out.append(Insight(text[0].upper() + text[1:] + ".", "driver", min(1.0, 0.4 + s / 2), [target, c])) + return out + + +def _scatter(w: pd.DataFrame, a: str, b: str, n: int = 300) -> dict: + pts = pd.DataFrame({a: robust(w[a]), b: robust(w[b])}).dropna() + if len(pts) > n: + pts = pts.sample(n, random_state=0) + return {"type": "scatter", "x": [round(float(v), 4) for v in pts[a]], "y": [round(float(v), 4) for v in pts[b]], "xlabel": a, "ylabel": b, "title": f"{b} vs {a}"} diff --git a/python/dxray/src/dxray/_model.py b/python/dxray/src/dxray/_model.py new file mode 100644 index 0000000..4d87c23 --- /dev/null +++ b/python/dxray/src/dxray/_model.py @@ -0,0 +1,78 @@ +"""The pieces of a report: what each column is, what's wrong with the data, and what's interesting in it.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +from typing import Any + + +@dataclass +class Column: + name: str + kind: str + stored_as: str + note: str = "" + count: int = 0 + missing: int = 0 + unique: int = 0 + stats: dict[str, Any] = field(default_factory=dict) + top: list[tuple[Any, int]] = field(default_factory=list) + chart: dict[str, Any] = field(default_factory=dict) + + @property + def missing_pct(self) -> float: + total = self.count + self.missing + return 100.0 * self.missing / total if total else 0.0 + + +@dataclass +class Issue: + """Something wrong with the data, and how to fix it.""" + severity: str # "high", "medium" or "low" + title: str # one plain sentence + column: str | None = None + count: int = 0 + examples: list[Any] = field(default_factory=list) + fix: str = "" # a pandas line that fixes it + auto: bool = False # dx.clean() fixes it for you + code: str = "" # a stable id, e.g. "numbers-as-text" + + +@dataclass +class Insight: + """Something worth knowing about the data, in a sentence a person can read.""" + title: str + kind: str # correlation, driver, segment, trend, concentration, dominance, skew, redundant, change + score: float # 0..1: how strong or surprising it is + columns: list[str] = field(default_factory=list) + detail: str = "" + chart: dict[str, Any] = field(default_factory=dict) + + +def plain(obj: Any) -> Any: + """Make dataclasses and numpy/pandas values JSON-friendly.""" + import math + + import numpy as np + import pandas as pd + + if hasattr(obj, "__dataclass_fields__"): + return {k: plain(v) for k, v in asdict(obj).items()} + if isinstance(obj, dict): + return {str(k): plain(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [plain(v) for v in obj] + if isinstance(obj, (np.integer,)): + return int(obj) + if isinstance(obj, (np.floating, float)): + f = float(obj) + return None if math.isnan(f) or math.isinf(f) else f + if isinstance(obj, (np.bool_,)): + return bool(obj) + if isinstance(obj, (pd.Timestamp,)): + return obj.isoformat() + if obj is pd.NaT: + return None + if isinstance(obj, (pd.Timedelta,)): + return str(obj) + return obj diff --git a/python/dxray/src/dxray/_profile.py b/python/dxray/src/dxray/_profile.py new file mode 100644 index 0000000..721171d --- /dev/null +++ b/python/dxray/src/dxray/_profile.py @@ -0,0 +1,69 @@ +"""One profile per column: its real type, missing values, stats, top values, and data for a small chart.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from ._infer import Kind, datetime_values, infer, is_missing_text, is_text, numeric_values +from ._model import Column + + +def _fmt_value(v): + if isinstance(v, (float, np.floating)): + return round(float(v), 4) + if isinstance(v, (np.integer,)): + return int(v) + return v + + +def profile_column(name: str, s: pd.Series) -> tuple[Column, Kind]: + k = infer(s, name) + raw_missing = int(s.isna().sum()) + text_missing = int(is_missing_text(s[s.notna()]).sum()) if is_text(s) else 0 + missing = raw_missing + text_missing + present = s[s.notna()] + if text_missing: + present = present[~is_missing_text(present)] + col = Column(name=name, kind=k.kind, stored_as=k.stored_as, note=k.note, count=len(present), missing=missing, + unique=int(present.astype(str).nunique()) if len(present) else 0) + + if k.kind == "numeric": + x = numeric_values(s, k).astype(float) + x = x[np.isfinite(x)] + if len(x): + q1, med, q3 = np.percentile(x, [25, 50, 75]) + col.stats = {"min": x.min(), "max": x.max(), "mean": x.mean(), "median": med, "std": x.std(ddof=0), + "q1": q1, "q3": q3, "zeros": int((x == 0).sum()), "negatives": int((x < 0).sum()), + "skew": float(x.skew()) if len(x) > 2 else 0.0, "sum": x.sum()} + col.stats = {key: _fmt_value(v) for key, v in col.stats.items()} + lo, hi = np.percentile(x, [1, 99]) if len(x) > 50 else (x.min(), x.max()) + clipped = x[(x >= lo) & (x <= hi)] + if len(clipped) and clipped.max() > clipped.min(): + counts, edges = np.histogram(clipped, bins=min(24, max(6, int(np.sqrt(len(clipped)))))) + col.chart = {"type": "hist", "counts": counts.tolist(), "edges": [round(float(e), 4) for e in edges]} + elif k.kind == "datetime": + d = datetime_values(s, k).dropna() + if len(d): + col.stats = {"min": d.min(), "max": d.max(), "span_days": int((d.max() - d.min()).days)} + by = d.dt.to_period("M" if col.stats["span_days"] > 90 else "D").value_counts().sort_index() + col.chart = {"type": "line", "labels": [str(p) for p in by.index], "values": by.astype(int).tolist()} + elif k.kind in ("categorical", "boolean", "constant"): + vc = present.astype(str).str.strip().value_counts() + col.top = [(v, int(c)) for v, c in vc.head(10).items()] + col.chart = {"type": "bar", "labels": [str(v) for v, _ in col.top], "values": [c for _, c in col.top]} + elif k.kind in ("text", "email", "url", "id"): + lengths = present.astype(str).str.len() + if len(lengths): + col.stats = {"avg_length": round(float(lengths.mean()), 1), "max_length": int(lengths.max())} + col.top = [(v, int(c)) for v, c in present.astype(str).value_counts().head(3).items()] + return col, k + + +def profile(df: pd.DataFrame) -> tuple[list[Column], dict[str, Kind]]: + cols, kinds = [], {} + for name in df.columns: + c, k = profile_column(str(name), df[name]) + cols.append(c) + kinds[str(name)] = k + return cols, kinds diff --git a/python/dxray/src/dxray/_quality.py b/python/dxray/src/dxray/_quality.py new file mode 100644 index 0000000..cc50a3e --- /dev/null +++ b/python/dxray/src/dxray/_quality.py @@ -0,0 +1,138 @@ +"""What's wrong with the data: each problem in one sentence, with examples and the pandas line that fixes it.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from ._infer import Kind, is_missing_text, is_text, numeric_values +from ._model import Column, Issue + +SEVERITY = {"high": 0, "medium": 1, "low": 2} + + +def _q(name: str) -> str: + return repr(name) + + +def _pct(n: int, total: int) -> str: + p = 100.0 * n / total if total else 0 + return f"{p:.0f}%" if p >= 1 else f"{p:.1f}%" if p >= 0.1 else "<0.1%" + + +def find_issues(df: pd.DataFrame, cols: list[Column], kinds: dict[str, Kind]) -> list[Issue]: + n = len(df) + out: list[Issue] = [] + if n == 0: + return [Issue("high", "The table is empty.", code="empty-table")] + + dupes = int(df.duplicated().sum()) if df.shape[1] else 0 + if dupes: + out.append(Issue("high" if dupes / n > 0.01 else "medium", f"{dupes:,} rows ({_pct(dupes, n)}) are exact duplicates of another row.", + count=dupes, fix="df = df.drop_duplicates()", auto=True, code="duplicate-rows")) + + for c in cols: + s, k = df[_orig(df, c.name)], kinds[c.name] + name = c.name + if k.kind == "empty": + out.append(Issue("medium", f"'{name}' has no values at all.", name, n, fix=f"df = df.drop(columns=[{_q(name)}])", auto=True, code="empty-column")) + continue + if k.kind == "constant": + out.append(Issue("low", f"'{name}' has the same value in every row ({c.top[0][0] if c.top else s.dropna().iloc[0]!r}): it tells you nothing.", + name, n, fix=f"df = df.drop(columns=[{_q(name)}])", code="constant-column")) + if c.missing: + share = c.missing / n + sev = "high" if share > 0.3 else "medium" if share > 0.05 else "low" + out.append(Issue(sev, f"'{name}' is missing {c.missing:,} values ({_pct(c.missing, n)}).", name, c.missing, + fix=(f"df[{_q(name)}] = df[{_q(name)}].fillna(df[{_q(name)}].median())" if k.kind == "numeric" + else f"df = df.dropna(subset=[{_q(name)}])"), code="missing")) + if is_text(s): + present = s.dropna() + sentinel = is_missing_text(present) + if sentinel.any(): + words = sorted(present[sentinel].astype(str).str.strip().unique().tolist())[:5] + out.append(Issue("medium", f"'{name}' uses text like {', '.join(repr(w) for w in words)} to mean missing ({int(sentinel.sum()):,} rows).", + name, int(sentinel.sum()), words, fix=f"df[{_q(name)}] = df[{_q(name)}].replace({words!r}, pd.NA)", auto=True, code="missing-as-text")) + if k.convertible == "numeric": + ex = present[~sentinel].astype(str).head(3).tolist() + out.append(Issue("high", f"'{name}' holds numbers stored as text (like {', '.join(repr(e) for e in ex)}), so you can't sum or average it.", + name, len(present), ex, fix=f"df[{_q(name)}] = pd.to_numeric(df[{_q(name)}].astype(str).str.replace(r'[,$€£₹¥%\\s]', '', regex=True), errors='coerce')", + auto=True, code="numbers-as-text")) + if k.convertible == "datetime": + ex = present[~sentinel].astype(str).head(2).tolist() + out.append(Issue("medium", f"'{name}' holds dates stored as text (like {', '.join(repr(e) for e in ex)}).", name, len(present), ex, + fix=f"df[{_q(name)}] = pd.to_datetime(df[{_q(name)}], errors='coerce')", auto=True, code="dates-as-text")) + text = present[~sentinel].astype(str) + padded = int((text != text.str.strip()).sum()) + if padded: + ex = text[text != text.str.strip()].head(3).tolist() + out.append(Issue("low", f"'{name}' has {padded:,} values with spaces at the start or end (like {ex[0]!r}).", name, padded, ex, + fix=f"df[{_q(name)}] = df[{_q(name)}].str.strip()", auto=True, code="whitespace")) + if k.kind in ("categorical", "text", "boolean") and len(text): + groups = text.str.strip().str.lower().str.replace(r"\s+", " ", regex=True) + variants = text.str.strip().groupby(groups).nunique() + messy = variants[variants > 1] + if len(messy): + first = messy.index[0] + spellings = sorted(text[groups == first].str.strip().unique().tolist())[:4] + rows = int(groups.isin(messy.index).sum()) + out.append(Issue("medium", f"'{name}' spells the same value different ways (like {', '.join(repr(v) for v in spellings)}): {len(messy)} value{'s' * (len(messy) != 1)} affected.", + name, rows, spellings, fix=f"df[{_q(name)}] = df[{_q(name)}].str.strip().str.title()", auto=True, code="inconsistent-categories")) + if k.kind == "text" and c.unique and not k.convertible: + kinds_present = present.map(lambda v: type(v).__name__).value_counts() + if len(kinds_present) > 1: + out.append(Issue("medium", f"'{name}' mixes value types ({', '.join(kinds_present.index[:3])}).", name, len(present), + fix=f"df[{_q(name)}] = df[{_q(name)}].astype(str)", code="mixed-types")) + if k.kind == "numeric": + x = numeric_values(s, k).dropna() + if len(x) >= 20: + # Money and counts are naturally lopsided: judge positive, skewed columns on a log scale. + log = x.min() >= 0 and x.skew() > 1 + t = np.log1p(x) if log else x + q1, q3 = np.percentile(t, [25, 75]) + iqr = q3 - q1 + if iqr > 0: + lo, hi = q1 - 3 * iqr, q3 + 3 * iqr + if log: + lo, hi, q1, q3 = max(0.0, float(np.expm1(lo))), float(np.expm1(hi)), float(np.expm1(q1)), float(np.expm1(q3)) + far = x[(x < lo) | (x > hi)] + if len(far): + ex = sorted(far.unique().tolist(), key=lambda v: -abs(v - np.median(x)))[:3] + out.append(Issue("medium" if len(far) / len(x) < 0.05 else "low", + f"'{name}' has {len(far):,} extreme value{'s' * (len(far) != 1)} far outside the usual range ({_num(q1)} to {_num(q3)}), like {', '.join(_num(e) for e in ex)}.", + name, len(far), ex, fix=f"df = df[df[{_q(name)}].between({_num(lo, raw=True)}, {_num(hi, raw=True)})]", code="outliers")) + for bad in (-999, -9999, 9999, 99999, -1): + hits = int((x == bad).sum()) + if hits >= 3 and hits / len(x) > 0.005 and (bad != -1 or (x >= 0).mean() > 0.95): + out.append(Issue("medium", f"'{name}' uses {bad} {hits:,} times: probably a stand-in for missing.", name, hits, [bad], + fix=f"df[{_q(name)}] = df[{_q(name)}].replace({bad}, np.nan)", code="sentinel-number")) + break + if k.kind == "id" or (c.unique and c.count and c.unique / c.count > 0.9 and "id" in name.lower()): + present = s.dropna() + d = int(present.duplicated().sum()) + if d: + out.append(Issue("high", f"'{name}' looks like an ID but {d:,} values repeat.", name, d, present[present.duplicated()].head(3).tolist(), + fix=f"df[df[{_q(name)}].duplicated(keep=False)]", code="duplicate-ids")) + if k.kind == "categorical" and c.unique > 50: + out.append(Issue("low", f"'{name}' has {c.unique} different values: too many to compare groups easily.", name, c.unique, code="high-cardinality")) + out.sort(key=lambda i: (SEVERITY[i.severity], -i.count)) + return out + + +def _orig(df: pd.DataFrame, name: str): + """The real column label for a stringified name.""" + for c in df.columns: + if str(c) == name: + return c + return name + + +def _num(v: float, raw: bool = False) -> str: + v = float(v) + if raw: + return repr(round(v, 4)) + if abs(v) >= 1e6: + return f"{v / 1e6:,.1f}M" + if abs(v) >= 1000: + return f"{v:,.0f}" + return f"{v:,.2f}".rstrip("0").rstrip(".") if v != int(v) else f"{int(v):,}" diff --git a/python/dxray/src/dxray/_report.py b/python/dxray/src/dxray/_report.py new file mode 100644 index 0000000..5543391 --- /dev/null +++ b/python/dxray/src/dxray/_report.py @@ -0,0 +1,234 @@ +"""The scan result: printable in a terminal, rich in Jupyter, and saveable as one self-contained HTML page.""" + +from __future__ import annotations + +import html +import json +import os +import sys +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from ._model import Column, Insight, Issue, plain + +ICON = {"high": "●", "medium": "●", "low": "○"} +AUTO = "dx.clean() fixes this" + + +@dataclass +class Report: + rows: int + columns: list[Column] + issues: list[Issue] + insights: list[Insight] + target: str | None = None + name: str = "dataset" + memory_mb: float = 0.0 + created: str = field(default_factory=lambda: datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")) + + # ------------------------------------------------------------------ quick facts + + @property + def health(self) -> int: + """0-100: how clean the data is. Each problem costs points by severity, scaled by how much of the data it touches.""" + cost = {"high": 14, "medium": 6, "low": 2} + penalty = 0.0 + for i in self.issues: + reach = min(1.0, i.count / self.rows) if self.rows and i.count else 0.3 + penalty += cost[i.severity] * (0.4 + 0.6 * reach) + return max(0, round(100 - penalty)) + + def column(self, name: str) -> Column: + return next(c for c in self.columns if c.name == name) + + def to_dict(self) -> dict[str, Any]: + return plain({"name": self.name, "rows": self.rows, "columns": self.columns, "issues": self.issues, "insights": self.insights, + "target": self.target, "health": self.health, "created": self.created}) + + def to_json(self, path: str | os.PathLike[str] | None = None, indent: int = 2) -> str: + text = json.dumps(self.to_dict(), indent=indent, ensure_ascii=False) + if path: + Path(path).write_text(text, encoding="utf-8") + return text + + # ------------------------------------------------------------------ text + + def summary(self) -> str: + kinds: dict[str, int] = {} + for c in self.columns: + kinds[c.kind] = kinds.get(c.kind, 0) + 1 + mix = ", ".join(f"{n} {k}" for k, n in sorted(kinds.items(), key=lambda kv: -kv[1])) + return f"{self.rows:,} rows × {len(self.columns)} columns ({mix}). Health {self.health}/100: {len(self.issues)} issue{'s' * (len(self.issues) != 1)}, {len(self.insights)} insight{'s' * (len(self.insights) != 1)}." + + def to_text(self, color: bool | None = None, max_issues: int = 10, max_insights: int = 10) -> str: + c = _colors(sys.stdout.isatty() if color is None else color) + lines = [f"{c['mint']}◆ dxray{c['reset']} {c['bold']}{self.name}{c['reset']} {self.summary()}", ""] + if self.insights: + lines.append(f"{c['bold']}What stands out{c['reset']}") + for i in self.insights[:max_insights]: + lines.append(f" {c['mint']}→{c['reset']} {i.title}") + lines.append("") + if self.issues: + lines.append(f"{c['bold']}Data problems{c['reset']}") + for i in self.issues[:max_issues]: + col = c['red'] if i.severity == 'high' else c['yellow'] if i.severity == 'medium' else c['dim'] + lines.append(f" {col}{ICON[i.severity]}{c['reset']} {i.title}" + (f" {c['dim']}fix: {i.fix}{c['reset']}" if i.fix else "")) + if len(self.issues) > max_issues: + lines.append(f" {c['dim']}…and {len(self.issues) - max_issues} more{c['reset']}") + lines.append("") + lines.append(f"{c['bold']}Columns{c['reset']}") + w = max((len(col.name) for col in self.columns), default=4) + for col in self.columns: + extra = _col_line(col) + miss = f"{col.missing_pct:.0f}% missing" if col.missing else "" + lines.append(f" {col.name.ljust(w)} {c['cyan']}{col.kind.ljust(11)}{c['reset']} {c['dim']}{miss.ljust(12)}{c['reset']} {extra}") + return "\n".join(lines) + + def __str__(self) -> str: + return self.to_text(color=False) + + def __repr__(self) -> str: + return f"" + + def show(self) -> None: + text = self.to_text() + try: + print(text) + except UnicodeEncodeError: # an old Windows console code page: plain symbols instead + print(text.translate(str.maketrans({"◆": "*", "→": "->", "●": "!", "○": "-", "…": "...", "×": "x"})).encode("ascii", "replace").decode()) + + def to_markdown(self) -> str: + out = [f"# {self.name}", "", self.summary(), ""] + if self.insights: + out += ["## What stands out", ""] + [f"- {i.title}" for i in self.insights] + [""] + if self.issues: + out += ["## Data problems", "", "| Severity | Problem | Fix |", "|---|---|---|"] + pipe = lambda t: t.replace("|", "\\|") # noqa: E731 + out += [f"| {i.severity} | {pipe(i.title)} | " + (f"`{pipe(i.fix)}`" if i.fix else "") + " |" for i in self.issues] + out.append("") + out += ["## Columns", "", "| Column | Type | Missing | Unique | Summary |", "|---|---|---|---|---|"] + out += [f"| {c.name} | {c.kind} | {c.missing_pct:.0f}% | {c.unique:,} | {_col_line(c)} |" for c in self.columns] + return "\n".join(out) + "\n" + + # ------------------------------------------------------------------ HTML + + def _repr_html_(self) -> str: + return _html_body(self, standalone=False) + + def to_html(self, path: str | os.PathLike[str] | None = None) -> str: + page = f"{html.escape(self.name)}: dxray report{_html_body(self, standalone=True)}" + if path: + Path(path).write_text(page, encoding="utf-8") + return page + + +def _col_line(c: Column) -> str: + s = c.stats + if c.kind == "numeric" and s: + from ._insights import nice + return f"{nice(s['min'])} to {nice(s['max'])}, median {nice(s['median'])}" + (f" ({c.note})" if c.note else "") + if c.kind == "datetime" and s: + return f"{str(s['min'])[:10]} to {str(s['max'])[:10]}" + (f" ({c.note})" if c.note else "") + if c.top and c.kind in ("categorical", "boolean", "constant"): + return ", ".join(f"{v} ({n:,})" for v, n in c.top[:3]) + (f" +{c.unique - 3} more" if c.unique > 3 else "") + if c.kind in ("text", "email", "url", "id") and s: + return f"{c.unique:,} unique, avg {s.get('avg_length', 0)} chars" + return "" + + +def _colors(on: bool) -> dict[str, str]: + if on and os.name == "nt": + os.system("") + codes = {"bold": "1", "dim": "2", "red": "31", "yellow": "33", "cyan": "36", "mint": "38;5;86", "reset": "0"} + return {k: (f"\033[{v}m" if on else "") for k, v in codes.items()} + + +# ---------------------------------------------------------------------- charts as inline SVG (no JavaScript, no CDN) + +def _svg_chart(ch: dict, w: int = 420, h: int = 150) -> str: + if not ch: + return "" + e = html.escape + t = ch.get("type") + pad = 26 + if t in ("bar",) and ch.get("values"): + vals, labels = ch["values"], ch["labels"] + top = max(max(vals), 0) or 1 + bw = (w - pad) / len(vals) + bars = "".join(f"{e(str(l))}: {v:,.4g}" + + (f"{e(str(l)[:10])}" if len(vals) <= 12 else "") + for i, (v, l) in enumerate(zip(vals, labels))) + return f"{bars}" + if t == "hist" and ch.get("counts"): + cs, edges = ch["counts"], ch["edges"] + top = max(cs) or 1 + bw = (w - pad) / len(cs) + bars = "".join(f"{edges[i]:,.4g} to {edges[i + 1]:,.4g}: {c:,}" for i, c in enumerate(cs)) + return f"{bars}{edges[0]:,.4g}{edges[-1]:,.4g}" + if t == "line" and len(ch.get("values", [])) >= 2: + vals, labels = ch["values"], ch["labels"] + lo, hi = min(vals), max(vals) + span = (hi - lo) or 1 + step = (w - pad - 8) / (len(vals) - 1) + pts = " ".join(f"{pad + i * step:.1f},{h - 22 - (v - lo) / span * (h - 36):.1f}" for i, v in enumerate(vals)) + dots = "".join(f"{e(str(l))}: {v:,.4g}" for i, (v, l) in enumerate(zip(vals, labels))) + return (f"{dots}" + f"{e(str(labels[0]))}{e(str(labels[-1]))}") + if t == "scatter" and ch.get("x"): + xs, ys = ch["x"], ch["y"] + x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys) + sx = lambda v: pad + (v - x0) / ((x1 - x0) or 1) * (w - pad - 8) # noqa: E731 + sy = lambda v: h - 20 - (v - y0) / ((y1 - y0) or 1) * (h - 30) # noqa: E731 + dots = "".join(f"" for a, b in zip(xs, ys)) + return (f"{dots}" + f"{e(ch.get('xlabel', ''))} →↑ {e(ch.get('ylabel', ''))}") + return "" + + +def _html_body(r: Report, standalone: bool) -> str: + e = html.escape + hc = "good" if r.health >= 80 else "ok" if r.health >= 55 else "bad" + ins = "".join(f"
{e(i.kind)}

{e(i.title)}

" + + (f"

{e(i.detail)}

" if i.detail else "") + _svg_chart(i.chart) + "
" for i in r.insights) + iss = "".join(f"{i.severity}{e(i.title)}" + + (f"
e.g. {e(', '.join(repr(x) for x in i.examples[:3]))}" if i.examples else "") + + "" + ("" + e(i.fix) + "" if i.fix else "") + (AUTO if i.auto else "") + "" for i in r.issues) + cols = "".join(f"
{e(c.name)}{e(c.kind)}
" + f"

{e(_col_line(c))}

{c.count:,} values · {c.unique:,} unique" + (f" · {c.missing_pct:.1f}% missing" if c.missing else "") + "

" + + _svg_chart(c.chart, 300, 90) + "
" for c in r.columns) + head = f"
◆ dxray

{e(r.name)}

{e(r.summary())}

{r.health}health
" + body = (f"
{head}" + + (f"

What stands out

{ins}
" if r.insights else "") + + (f"

Data problems

{iss}
" if r.issues else "

Data problems

None found. Nice and clean.

") + + f"

Columns

{cols}
" + + (f"
Made with dxray · {e(r.created)}
" if standalone else "") + + "
") + return body if standalone else f"{body}" + + +CSS = """ +.dxray{--bg:#0b0d14;--card:#121624;--line:#232a3c;--text:#e8edf2;--muted:#8d98a8;--mint:#68f4d1;--cyan:#4cdcf2;--violet:#b79bff;--red:#ff6b8a;--amber:#ffcf6b; +font:14px/1.55 Inter,"Segoe UI",system-ui,sans-serif;color:var(--text);background:var(--bg);padding:28px;border-radius:16px;max-width:1180px;margin:auto} +body{margin:0;background:#0b0d14} +.dxray h1{margin:4px 0 6px;font-size:28px;letter-spacing:-.5px}.dxray h2{margin:30px 0 12px;font-size:18px}.dxray h3{margin:6px 0;font-size:15px;line-height:1.45} +.dxray .top{display:flex;justify-content:space-between;gap:20px;align-items:center}.dxray .top p{margin:0;color:var(--muted)} +.dxray .brand{color:var(--mint);font:700 12px ui-monospace,Consolas,monospace;letter-spacing:1px} +.dxray .health{display:grid;place-items:center;min-width:92px;height:92px;border-radius:50%;border:3px solid var(--mint)}.dxray .health b{font-size:30px;line-height:1}.dxray .health span{font-size:11px;color:var(--muted);margin-top:-18px} +.dxray .health.ok{border-color:var(--amber)}.dxray .health.bad{border-color:var(--red)} +.dxray .insights{display:grid;grid-template-columns:repeat(auto-fill,minmax(330px,1fr));gap:12px} +.dxray .insight,.dxray .col{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 16px} +.dxray .insight p{margin:0 0 8px;color:var(--muted);font-size:13px} +.dxray .kind{display:inline-block;padding:1px 8px;border-radius:99px;background:#68f4d114;color:var(--mint);font:600 11px ui-monospace,Consolas,monospace} +.dxray table.issues{width:100%;border-collapse:collapse}.dxray .issues td{padding:10px;border-top:1px solid var(--line);vertical-align:top} +.dxray .issues small{color:var(--muted)}.dxray code{font:12px ui-monospace,Consolas,monospace;color:var(--cyan);word-break:break-all} +.dxray .sev{font:700 11px ui-monospace,Consolas,monospace;text-transform:uppercase}.dxray .high .sev{color:var(--red)}.dxray .medium .sev{color:var(--amber)}.dxray .low .sev{color:var(--muted)} +.dxray .auto{display:block;margin-top:4px;color:var(--mint);font-size:12px} +.dxray .cols{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:10px}.dxray .col header{display:flex;justify-content:space-between;gap:8px} +.dxray .col p{margin:6px 0 0;font-size:13px}.dxray .meta{color:var(--muted)}.dxray .miss{color:var(--amber)} +.dxray svg.chart{width:100%;height:auto;margin-top:8px}.dxray svg rect,.dxray svg circle{fill:var(--cyan)}.dxray svg.hist rect{fill:var(--violet)} +.dxray svg polyline{fill:none;stroke:var(--mint);stroke-width:2}.dxray svg text{fill:var(--muted);font:10px ui-monospace,Consolas,monospace} +.dxray footer{margin-top:28px;color:var(--muted);font-size:12px}.dxray a{color:var(--mint)} +@media(max-width:640px){.dxray{padding:16px}.dxray .top{flex-direction:column;align-items:flex-start}} +""" diff --git a/python/dxray/src/dxray/cli.py b/python/dxray/src/dxray/cli.py new file mode 100644 index 0000000..1a1f50a --- /dev/null +++ b/python/dxray/src/dxray/cli.py @@ -0,0 +1,68 @@ +"""The dxray command: dxray sales.csv [--target revenue] [--html report.html] [--json] [--clean out.csv] [--ask "..."]""" + +from __future__ import annotations + +import argparse +import sys + +from . import __version__ +from ._api import _frame, clean, for_llm, scan + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(prog="dxray", description="An X-ray for your data: what each column is, what's wrong, and what stands out.") + p.add_argument("file", help="a CSV, TSV, Excel, Parquet or JSON file") + p.add_argument("-t", "--target", help="the column you care about most: dxray shows what drives it") + p.add_argument("--html", metavar="PATH", help="also write a shareable HTML report") + p.add_argument("--json", action="store_true", help="print the report as JSON") + p.add_argument("--markdown", action="store_true", help="print the report as Markdown") + p.add_argument("--llm", action="store_true", help="print the dataset described for an AI model") + p.add_argument("--clean", metavar="PATH", help="write a cleaned copy (CSV or Parquet) and list the changes") + p.add_argument("--ask", metavar="QUESTION", help='ask Claude about the data (needs pip install "dxray[ai]" and ANTHROPIC_API_KEY)') + p.add_argument("--version", action="version", version=f"dxray {__version__}") + a = p.parse_args(argv) + if sys.stdout.encoding and sys.stdout.encoding.lower() not in ("utf-8", "utf8"): + try: + sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined] + except (AttributeError, ValueError): + pass + try: + df, name = _frame(a.file) + except FileNotFoundError: + print(f"dxray: no such file: {a.file}", file=sys.stderr) + return 2 + except ValueError as e: + print(f"dxray: {e}", file=sys.stderr) + return 2 + try: + report = scan(df, a.target, name=name) + except KeyError as e: + print(f"dxray: {e.args[0]}", file=sys.stderr) + return 2 + if a.json: + print(report.to_json()) + elif a.markdown: + print(report.to_markdown()) + elif a.llm: + print(for_llm(df, target=a.target, report=report)) + else: + report.show() + if a.html: + report.to_html(a.html) + print(f"\nReport written to {a.html}", file=sys.stderr) + if a.clean: + cleaned, log = clean(df) + (cleaned.to_parquet if a.clean.lower().endswith(".parquet") else lambda path: cleaned.to_csv(path, index=False))(a.clean) + print(f"\n{log}\nCleaned data written to {a.clean}", file=sys.stderr) + if a.ask: + from ._ask import AskError, ask + try: + print("\n" + str(ask(df, a.ask, target=a.target))) + except AskError as e: + print(f"dxray: {e}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/python/dxray/src/dxray/py.typed b/python/dxray/src/dxray/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/python/dxray/tests/conftest.py b/python/dxray/tests/conftest.py new file mode 100644 index 0000000..a38c975 --- /dev/null +++ b/python/dxray/tests/conftest.py @@ -0,0 +1,20 @@ +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "examples")) +from make_orders import make # noqa: E402 + + +@pytest.fixture(scope="session") +def orders_raw(): + """A year of shop orders with planted problems and patterns, as it comes out of a CSV (strings, not dates).""" + df = make() + df["order_date"] = df["order_date"].dt.strftime("%Y-%m-%d") + return df + + +@pytest.fixture +def orders(orders_raw): + return orders_raw.copy() diff --git a/python/dxray/tests/test_clean_llm_ask.py b/python/dxray/tests/test_clean_llm_ask.py new file mode 100644 index 0000000..4f3b467 --- /dev/null +++ b/python/dxray/tests/test_clean_llm_ask.py @@ -0,0 +1,136 @@ +"""dx.clean(), dx.for_llm(), dx.ask() (with a fake Claude client) and the dxray command.""" + +import json +import subprocess +import sys +from types import SimpleNamespace + +import pandas as pd +import pytest + +import dxray as dx +from dxray.cli import main + + +# ------------------------------------------------------------------ clean + +def test_clean_fixes_the_safe_problems(orders): + out, log = dx.clean(orders) + assert len(out) == len(orders) - 40 + assert pd.api.types.is_numeric_dtype(out["price"]) and out["price"].notna().sum() > 3800 + assert pd.api.types.is_datetime64_any_dtype(out["order_date"]) + assert set(out["region"].dropna().unique()) == {"North", "South", "East", "West"} + text = str(log) + assert "Dropped 40 duplicate rows" in text and "'price'" in text and "merged different spellings" in text + assert "trimmed spaces from 62" not in text, "missing values are not 'trimmed'" + + +def test_clean_never_drops_outliers_or_fills_gaps(orders): + out, _ = dx.clean(orders) + assert (out["quantity"] == 9999).sum() == 8 + assert out["ad_spend"].isna().sum() > 0 + + +def test_clean_leaves_the_original_alone(orders): + before = orders.copy() + dx.clean(orders) + pd.testing.assert_frame_equal(orders, before) + + +def test_clean_on_clean_data_changes_nothing(): + df = pd.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]}) + out, log = dx.clean(df) + pd.testing.assert_frame_equal(out, df) + assert "Nothing needed fixing" in str(log) + + +def test_clean_drops_empty_columns(): + out, log = dx.clean(pd.DataFrame({"a": [1, 2], "gone": [None, None], "na": ["N/A", "-"]})) + assert list(out.columns) == ["a"] and "empty column" in str(log) + + +# ------------------------------------------------------------------ for_llm + +def test_for_llm_is_compact_and_complete(orders): + text = dx.for_llm(orders, target="revenue") + assert text.startswith("# Dataset:") + for part in ("## Columns", "price | numeric (numbers stored as text)", "sample rows", "## Data problems", "## Findings"): + assert part in text + assert len(text) < 12000 + assert len(dx.for_llm(orders, max_chars=2000)) <= 2000 + + +# ------------------------------------------------------------------ ask (fake client: no network, no cost) + +class FakeStream: + def __init__(self, message): + self.message = message + def __enter__(self): + return self + def __exit__(self, *exc): + return False + def get_final_message(self): + return self.message + + +class FakeClient: + def __init__(self, text="Revenue grew 122% over the year.", stop="end_turn"): + self.calls = [] + msg = SimpleNamespace(content=[SimpleNamespace(type="thinking", thinking=""), SimpleNamespace(type="text", text=text)], + stop_reason=stop, model="claude-opus-5-5", + usage=SimpleNamespace(input_tokens=1200, output_tokens=40, cache_read_input_tokens=1100)) + beta_messages = SimpleNamespace(stream=lambda **kw: (self.calls.append(kw), FakeStream(msg))[1]) + self.beta = SimpleNamespace(messages=beta_messages) + + +def test_ask_sends_the_description_and_returns_the_answer(orders): + client = FakeClient() + answer = dx.ask(orders, "How did revenue change?", target="revenue", client=client) + assert str(answer) == "Revenue grew 122% over the year." and answer.cached_tokens == 1100 + call = client.calls[0] + assert call["model"] == "claude-opus-5-5" + assert call["messages"] == [{"role": "user", "content": "How did revenue change?"}] + system = call["system"][0] + assert system["cache_control"] == {"type": "ephemeral"} and "## Columns" in system["text"] and "revenue" in system["text"] + assert call["fallbacks"] == "default" and "server-side-fallback-2026-07-01" in call["betas"] + assert call["output_config"] == {"effort": "medium"} + + +def test_ask_refusal_and_bad_question(orders): + with pytest.raises(dx.AskError, match="declined"): + dx.ask(orders, "something", client=FakeClient(stop="refusal")) + with pytest.raises(ValueError): + dx.ask(orders, " ", client=FakeClient()) + + +def test_ask_without_a_key_explains(orders, monkeypatch): + for v in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_PROFILE"): + monkeypatch.delenv(v, raising=False) + monkeypatch.setenv("ANTHROPIC_CONFIG_DIR", "/nonexistent-dxray-test") + monkeypatch.setenv("HOME", "/nonexistent-dxray-test") + monkeypatch.setenv("USERPROFILE", "/nonexistent-dxray-test") + with pytest.raises(dx.AskError): + dx.ask(pd.DataFrame({"a": [1, 2, 3]}), "anything?") + + +# ------------------------------------------------------------------ the dxray command + +def test_cli(orders, tmp_path, capsys): + p = tmp_path / "orders.csv" + orders.to_csv(p, index=False) + assert main([str(p), "--target", "revenue", "--html", str(tmp_path / "r.html"), "--clean", str(tmp_path / "clean.csv")]) == 0 + out, err = capsys.readouterr() + assert "What stands out" in out and "Report written" in err and "duplicate rows" in err + assert (tmp_path / "r.html").exists() and len(pd.read_csv(tmp_path / "clean.csv")) == len(orders) - 40 + assert main([str(p), "--json"]) == 0 + assert json.loads(capsys.readouterr().out)["rows"] == len(orders) + assert main([str(p), "--llm"]) == 0 and capsys.readouterr().out.startswith("# Dataset:") + assert main([str(tmp_path / "missing.csv")]) == 2 + assert main([str(p), "--target", "nope"]) == 2 + + +def test_module_entry_point(orders, tmp_path): + p = tmp_path / "o.csv" + orders.head(200).to_csv(p, index=False) + r = subprocess.run([sys.executable, "-m", "dxray", str(p), "--markdown"], capture_output=True, text=True, encoding="utf-8") + assert r.returncode == 0 and r.stdout.startswith("# o.csv") diff --git a/python/dxray/tests/test_infer.py b/python/dxray/tests/test_infer.py new file mode 100644 index 0000000..3e8378a --- /dev/null +++ b/python/dxray/tests/test_infer.py @@ -0,0 +1,45 @@ +import numpy as np +import pandas as pd +import pytest + +from dxray import infer +from dxray._infer import parse_number_text + + +@pytest.mark.parametrize("values, kind, note", [ + ([1.5, 2.0, 3.25, 4.0, 10.0], "numeric", ""), + (["$1,200.50", "$45", "$3.99", "$12,000", "$7"], "numeric", "numbers stored as text"), + (["12%", "45%", "3%", "99%", "50%"], "numeric", "numbers stored as text"), + (["2026-01-03", "2026-02-14", "2025-12-31", "2026-03-01", "2026-04-20"], "datetime", "dates stored as text"), + (["yes", "no", "yes", "yes", "no"], "boolean", "yes/no stored as text"), + ([True, False, True, True, False], "boolean", ""), + ([0, 1, 1, 0, 1, 0], "boolean", ""), + (["a@x.com", "b@y.org", "c@z.io", "d@w.net", "e@v.co"], "email", ""), + (["https://a.com", "https://b.com/x", "http://c.org", "https://d.io", "https://e.net"], "url", ""), + (["red", "blue", "red", "green", "blue", "red", "red", "blue"], "categorical", ""), + (["same", "same", "same"], "constant", ""), + ([None, None, None], "empty", ""), + (["N/A", "-", "null", None], "empty", ""), +]) +def test_kinds(values, kind, note): + k = infer(pd.Series(values, name="col")) + assert k.kind == kind + assert k.note == note + + +def test_ids_by_name_and_uniqueness(): + assert infer(pd.Series(range(100), name="user_id")).kind == "id" + assert infer(pd.Series(range(100), name="score")).kind == "numeric" + assert infer(pd.Series([f"ORD-{i:05d}" for i in range(500)], name="ref")).kind == "id" + + +def test_free_text(): + words = [f"Customer said thing number {i} about the product" for i in range(300)] + assert infer(pd.Series(words, name="comment")).kind == "text" + + +def test_parse_number_text(): + s = pd.Series(["$1,200.50", "(45)", "12%", "€3", "abc", None]) + out = parse_number_text(s) + assert out.iloc[0] == 1200.5 and out.iloc[1] == -45 and out.iloc[2] == 12 and out.iloc[3] == 3 + assert np.isnan(out.iloc[4]) and np.isnan(out.iloc[5]) diff --git a/python/dxray/tests/test_scan.py b/python/dxray/tests/test_scan.py new file mode 100644 index 0000000..e2cc4db --- /dev/null +++ b/python/dxray/tests/test_scan.py @@ -0,0 +1,148 @@ +"""dx.scan() on a dataset with known problems and patterns: it must find every one, and not invent others.""" + +import json + +import numpy as np +import pandas as pd + +import dxray as dx + + +def codes(report, column=None): + return {i.code for i in report.issues if column is None or i.column == column} + + +def titles(report, kind=None): + return [i.title for i in report.insights if kind is None or i.kind == kind] + + +def test_finds_every_planted_problem(orders): + r = dx.scan(orders) + assert "numbers-as-text" in codes(r, "price") + assert "missing-as-text" in codes(r, "price") + assert "inconsistent-categories" in codes(r, "region") + assert "whitespace" in codes(r, "region") + assert "duplicate-rows" in codes(r) + assert "duplicate-ids" in codes(r, "order_id") + assert "dates-as-text" in codes(r, "order_date") + assert "dates-as-text" in codes(r, "signup_date") + assert "outliers" in codes(r, "quantity") + assert "constant-column" in codes(r, "channel") + assert "missing" in codes(r, "ad_spend") + dup = next(i for i in r.issues if i.code == "duplicate-rows") + assert dup.count == 40 + + +def test_no_false_alarms_on_naturally_lopsided_money(orders): + r = dx.scan(orders) + assert "outliers" not in codes(r, "revenue"), "big orders are normal for revenue, not errors" + assert "outliers" not in codes(r, "price") + + +def test_finds_the_planted_patterns(orders): + r = dx.scan(orders, target="revenue") + t = " ".join(titles(r)) + assert "What drives 'revenue'" in t and "'ad_spend'" in t + assert any("'tier'" in x and "Premium" in x for x in titles(r)) + assert any("rose" in x and "'revenue'" in x for x in titles(r, "trend")), "revenue grows through the year" + assert any("dropped" in x and "2026-03" in x for x in titles(r, "change")), "the March slump" + assert any("top 20% of 'customer'" in x for x in titles(r, "concentration")), "the 80/20 customers" + + +def test_churn_is_driven_by_support_tickets(orders): + r = dx.scan(orders, target="churned") + drivers = [i for i in r.insights if i.kind == "driver"] + assert drivers and "'support_tickets'" in drivers[0].title + + +def test_trends_use_the_order_date_not_signups(orders): + r = dx.scan(orders) + for i in r.insights: + if i.kind in ("trend", "change"): + assert i.columns[0] == "order_date" + + +def test_typos_do_not_fake_trends_or_8020(orders): + r = dx.scan(orders) + assert not any("'quantity'" in x for x in titles(r, "concentration")) + assert not any("%" in x and int(x.split("%")[0].split()[-1].replace(",", "")) > 1000 for x in titles(r, "change")) + + +def test_insights_are_ranked_and_capped(orders): + r = dx.scan(orders, target="revenue", insights=5) + assert len(r.insights) == 5 + scores = [i.score for i in r.insights] + assert scores == sorted(scores, reverse=True) + + +def test_columns_are_profiled(orders): + r = dx.scan(orders) + price = r.column("price") + assert price.kind == "numeric" and price.note == "numbers stored as text" + assert price.missing == 62 # 60 planted, and 2 more copied by the duplicate rows + assert 10 < price.stats["median"] < 200 + assert r.column("tier").top[0][0] in ("Basic", "Plus", "Premium") + assert r.column("order_date").chart["type"] == "line" + + +def test_health_score(orders): + messy = dx.scan(orders).health + clean_df, _ = dx.clean(orders) + tidy = dx.scan(clean_df).health + assert 0 <= messy < 70 < tidy <= 100 + + +def test_outputs(orders, tmp_path): + r = dx.scan(orders, target="revenue", name="orders") + text = str(r) + assert "orders" in text and "What stands out" in text and "Data problems" in text + page = r.to_html(tmp_path / "r.html") + assert page.startswith("") and "" in r._repr_html_() and "