Metadata-Version: 2.4
Name: freshdata-cleaner
Version: 3.0.1
Summary: Dry-run cleaning plans for pandas and Polars DataFrames and LazyFrames.
Author: FreshCode-Org
License: MIT
Project-URL: Homepage, https://github.com/FreshCode-Org/freshdata
Project-URL: Repository, https://github.com/FreshCode-Org/freshdata
Project-URL: Issues, https://github.com/FreshCode-Org/freshdata/issues
Keywords: data-cleaning,pandas,polars,duckdb,data-quality,imputation,machine-learning
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy<2.4.0,>=1.24.0
Requires-Dist: pandas>=2.0.0
Provides-Extra: migrate
Requires-Dist: libcst>=1.4.0; extra == "migrate"
Provides-Extra: polars
Requires-Dist: polars>=1.0.0; extra == "polars"
Requires-Dist: pyarrow>=15.0.0; extra == "polars"
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.25; extra == "docs"
Requires-Dist: pymdown-extensions>=10.0; extra == "docs"
Provides-Extra: test
Requires-Dist: pytest>=8.0.0; extra == "test"
Requires-Dist: pytest-cov>=5.0.0; extra == "test"
Provides-Extra: dev
Requires-Dist: polars>=1.0.0; extra == "dev"
Requires-Dist: duckdb>=1.0.0; extra == "dev"
Requires-Dist: pyarrow>=15.0.0; extra == "dev"
Requires-Dist: scikit-learn>=1.4.0; extra == "dev"
Requires-Dist: psutil>=5.9.0; extra == "dev"
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: hypothesis>=6.100.0; extra == "dev"
Requires-Dist: build>=1.2.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Requires-Dist: ruff>=0.5.0; extra == "dev"
Requires-Dist: mypy>=1.10.0; extra == "dev"
Dynamic: license-file

# freshdata

**Dry-run data repair plans for Polars and pandas—compiled into native expressions without silent mutations.**

[![PyPI version](https://img.shields.io/pypi/v/freshdata-cleaner.svg)](https://pypi.org/project/freshdata-cleaner/)
[![Python versions](https://img.shields.io/pypi/pyversions/freshdata-cleaner.svg)](https://pypi.org/project/freshdata-cleaner/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/FreshCode-Org/freshdata/blob/main/LICENSE)
[![CI](https://github.com/FreshCode-Org/freshdata/actions/workflows/ci-verification-gates.yml/badge.svg?branch=main)](https://github.com/FreshCode-Org/freshdata/actions/workflows/ci-verification-gates.yml)

Most automated data-cleaning libraries fail in production for three reasons:
1. **Silent corruption:** One-call black boxes impute missing target labels or clip primary keys without warning.
2. **Broken lazy execution:** Wrappers claim Polars support but silently convert `LazyFrame` inputs to pandas or call `.unique(maintain_order=True)`, blowing up memory on multi-gigabyte scans.
3. **Zero diffability:** You cannot review or version-control what a heuristic cleaner is about to do before it mutates your data.

`freshdata` separates **planning** from **execution**:
* **`fd.suggest_plan(lf)`** runs a single streaming aggregation pass over a Polars `LazyFrame` (or pandas `DataFrame`), protects ID and target columns automatically, and outputs an inspectable, diffable `CleanPlan` containing precomputed scalar thresholds.
* **`fd.apply_plan(lf, plan)`** compiles those approved actions into pure, fused Polars expressions (`pl.Expr`)—requiring **zero Python UDFs**. A `LazyFrame` in stays a `LazyFrame` out, and a Polars-made plan needs **zero `.collect()` calls**. (A pandas-made plan with `parse_currency` runs one query over that column, see [Known differences](#known-differences-between-pandas-and-polars).)

---

## Install

```bash
pip install "freshdata-cleaner[polars]"
```

For pandas only, `pip install freshdata-cleaner` is enough.

To install the AST codemod tool for upgrading legacy `2.x` scripts:

```bash
pip install "freshdata-cleaner[migrate]"
```

---

## 30-Second Quickstart

```python
import polars as pl
import freshdata as fd

# 1. Start from a LazyFrame. In production this is a scan, for example
#    lf = pl.scan_parquet("s3://bucket/raw_customer_events.parquet")
lf = pl.LazyFrame({
    "Customer ID": [1, 2, 3, 4, 5, 5],
    "Signup Age": [34, None, 29, 120, 41, 41],
    "Segment": [" retail", "b2b ", "retail", None, "b2b", "b2b"],
    "Invoice Total": [12.5, 9.0, 11.0, 10.5, 14.0, 14.0],
    "churned": [0, 1, 0, 0, 1, 1],
})

# 2. Define explicit column protections and rules
config = fd.CleanConfig(
    id_columns=("customer_id",),
    target_column="churned",
    default_impute="auto",      # median for numeric columns
    default_outliers="preserve",
    drop_duplicates=True,       # streaming-safe unique(maintain_order=False)
    rules={
        "signup_age": fd.ColumnRule(impute="median", outliers="clip"),
    },
)

# 3. Generate a dry-run repair plan (IQR bounds come from one 1-row summary query)
plan = fd.suggest_plan(lf, config=config)

for action in plan.actions:
    print(f"[{action.stage}] {action.column}: {action.action} {action.parameters}")
# Output:
# [column_names] Customer ID: normalize_name {'to': 'customer_id'}
# [column_names] Signup Age: normalize_name {'to': 'signup_age'}
# [missing] signup_age: impute_median {}
# [column_names] Segment: normalize_name {'to': 'segment'}
# [strings] segment: strip_strings {}
# [column_names] Invoice Total: normalize_name {'to': 'invoice_total'}
# [outliers] signup_age: clip_iqr {'lower': 27.875, 'upper': 48.875}
# [duplicates] *: drop_duplicates {}
# customer_id (id) and churned (target) get no imputation, stripping, or clipping.

# 4. Compile the approved plan onto the LazyFrame (zero materialization)
cleaned_lf, report = fd.apply_plan(lf, plan, return_report=True)

assert isinstance(cleaned_lf, pl.LazyFrame)
assert "PYTHON_UDF" not in cleaned_lf.explain()

# 5. Materialize only when your downstream pipeline is ready
df = cleaned_lf.collect(engine="streaming")
```

To check that the LazyFrame stays lazy on 5 million rows, run
[`examples/lazy_check.py`](https://github.com/FreshCode-Org/freshdata/blob/main/examples/lazy_check.py).
It times `suggest_plan`, `apply_plan` and `collect`, and prints the query plan.

---

## Diffing Repair Plans Before Execution

Never guess how a configuration change alters your dataset. Compare two `CleanPlan` artifacts directly in code or CI:

```python
import dataclasses

clipped = fd.suggest_plan(lf, dataclasses.replace(config, default_outliers="clip"))
diff = plan.diff(clipped)

for action in diff["added"]:
    print(f"+ [{action.stage}] {action.column}: {action.action} {action.parameters}")
for action in diff["removed"]:
    print(f"- [{action.stage}] {action.column}: {action.action}")
for change in diff["modified"]:
    print(f"~ [{change['stage']}] {change['column']}: {change['before']['parameters']} -> {change['after']['parameters']}")
# + [outliers] invoice_total: clip_iqr {'lower': 6.125, 'upper': 18.125}
```

---

## The Complete API (12 Exports)

`freshdata` v3.0 exposes exactly 12 public symbols. There are no hidden submodules, natural-language rule compilers, or domain-specific bloat.

| Export | Type | Purpose |
| :--- | :--- | :--- |
| `fd.profile` | Function | Read-only column null, cardinality, and quantile summary |
| `fd.suggest_plan` | Function | Single-pass streaming planner returning a dry-run `CleanPlan` |
| `fd.apply_plan` | Function | Compiles a `CleanPlan` into native expressions without materializing |
| `fd.clean` | Function | Shorthand for `apply_plan(df, suggest_plan(df, config))` |
| `fd.Cleaner` | Class | Reusable stateful wrapper around `CleanConfig` for batch pipelines |
| `fd.CleanConfig` | Dataclass | Frozen pipeline specification with strict backend enforcement |
| `fd.ColumnRule` | Dataclass | Explicit per-column role, imputation, and outlier override |
| `fd.CleanPlan` | Dataclass | Serializable, diffable tuple of planned `ActionRecord` items |
| `fd.ActionRecord` | Dataclass | Single column operation with baked scalar parameters and rationale |
| `fd.CleanReport` | Dataclass | Post-application audit record of renamed/dropped columns and actions |
| `fd.ProfileReport` | Dataclass | Dataset-level read-only diagnostic container |
| `fd.ColumnProfile` | Dataclass | Per-column statistical summary emitted by `fd.profile()` |

---

## Where `freshdata` Fits

`freshdata` is a **planning and repair engine**, not a schema validation gate or orchestration framework. Use it alongside focused tools in your stack:

| Tool | Primary Job | Mutates Data? | Lazy Polars Native? |
| :--- | :--- | :--- | :--- |
| **Pandera / Great Expectations** | Assert schema contracts and fail bad batches | No | Partial |
| **pyjanitor** | Imperative method-chaining helpers | Yes (manual) | No (pandas-first) |
| **freshdata** | Propose, diff, and compile automated repair plans | Yes (via `CleanPlan`) | Yes (`pl.Expr`) |

---

## Guaranteeing Zero-Fallback Execution

By default, `CleanConfig(strict_backend=True)` refuses to run any operation that cannot be expressed natively on your input frame:
* **No silent `.to_pandas()` conversions:** Passing a `pl.LazyFrame` or `pl.DataFrame` executes 100% inside Polars.
* **No Python row loops:** String normalization, null imputation, and IQR clipping compile down to `.str.strip_chars()`, `.fill_null()`, and `.clip()`.
* **Streaming-compatible deduplication:** When `drop_duplicates=True`, `freshdata` emits `.unique(maintain_order=False)` so Polars streaming pipelines never stall holding row order in RAM.

---

## Known differences between pandas and Polars

The two backends give different results in these cases. `tests/test_known_differences.py` checks each row.

| Case | pandas | Polars |
| :--- | :--- | :--- |
| Currency strings such as `"$1,200"` | Plans `parse_currency` and gives `1200.0` | Keeps the string |
| Blank strings (`""`, `"  "`) | `strip_strings` turns them into nulls | `strip_strings` keeps `""` |
| Fill values and IQR fences | Computed after earlier steps such as `drop_nulls` and `drop_duplicates` | Computed on the input frame |
| Row order after `drop_duplicates` | Keeps the first row of each group, in order | No fixed order (`unique(maintain_order=False)`) |
| Replaying a plan on new data | Uses the fill value stored in the plan | Computes the fill value again on the new data |
| `CleanReport` for a LazyFrame | Not applicable | `original_rows` and `cleaned_rows` are `0`, because freshdata does not run a query to count rows |
| A pandas-made plan with `parse_currency`, applied to a LazyFrame | Not applicable | `apply_plan` runs one query (`collect()`) to check that each value is a currency string. If one is not, it skips the column. A Polars-made plan has no `parse_currency` step, so it stays fully lazy |

If you need the same result on both backends, use the same backend for planning and applying, and check the plan before you apply it.

---

## Upgrading from v2.x

If you are upgrading from `freshdata` 2.x (`freshdata-cleaner`), run the included `libcst` codemod to rewrite legacy wrappers (`clean_csv`, `fill_missing`, `compare_plans`, etc.) into the v3.0 core API:

```bash
# Preview unified diff without modifying files
freshdata-migrate src/ tests/ --check --diff

# Apply deterministic AST rewrites in-place
freshdata-migrate src/ tests/
```

---

## Get help

- **Questions:** ask in [GitHub Discussions Q&A](https://github.com/FreshCode-Org/freshdata/discussions/categories/q-a).
- **Bugs:** [open an issue](https://github.com/FreshCode-Org/freshdata/issues/new/choose) with a minimal Polars or pandas snippet and the `plan.to_dict()` output you got.
- **Security reports:** use a [private advisory](https://github.com/FreshCode-Org/freshdata/security/advisories/new), not a public issue.

## Contributing & Issues

Bug reports, benchmark reproductions, and pull requests are welcome.
1. Open an issue with a minimal reproducible Polars or pandas snippet.
2. Run the test suite locally via `pytest -q`.
3. Ensure any changes to `_core/backends.py` pass the lazy materialization poison test (`tests/test_backend_honesty.py`).

## License

MIT License. See [LICENSE](https://github.com/FreshCode-Org/freshdata/blob/main/LICENSE) for details.
