Metadata-Version: 2.4
Name: curaitor
Version: 0.1.0a1
Summary: (loggair / confluid / liquifai) adapter for dataset curation & analysis: outlier detection, distance metrics, synthetic-vs-real comparison, label cleaning, dimensionality reduction.
Author: Gert Behiels
License-Expression: PolyForm-Noncommercial-1.0.0
Project-URL: Homepage, https://github.com/Gearlux/curaitor
Project-URL: Repository, https://github.com/Gearlux/curaitor.git
Project-URL: Issues, https://github.com/Gearlux/curaitor/issues
Project-URL: Changelog, https://github.com/Gearlux/curaitor/blob/main/CHANGELOG.md
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: liquifai>=0.4.0
Requires-Dist: loggair>=0.3.0
Requires-Dist: confluid>=0.5.0
Requires-Dist: recordstream>=0.1.0a4
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.11
Requires-Dist: scikit-learn>=1.3
Requires-Dist: networkx>=3.0
Requires-Dist: orjson
Requires-Dist: annotated-types
Provides-Extra: dev
Requires-Dist: playwright>=1.40.0; extra == "dev"
Requires-Dist: black<25.0.0,>=24.0.0; extra == "dev"
Requires-Dist: isort<6.0.0,>=5.13.0; extra == "dev"
Requires-Dist: flake8<8.0.0,>=6.0.0; extra == "dev"
Requires-Dist: mypy<2.0.0,>=1.0.0; extra == "dev"
Requires-Dist: pytest<9.0.0,>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov<7.0.0,>=4.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Requires-Dist: setuptools>=77; extra == "dev"
Requires-Dist: wheel; extra == "dev"
Provides-Extra: outliers
Requires-Dist: pyod>=2.0; extra == "outliers"
Provides-Extra: distances
Requires-Dist: pot>=0.9; extra == "distances"
Provides-Extra: generative
Requires-Dist: torchmetrics[image]>=1.4; extra == "generative"
Requires-Dist: torch>=2.1; extra == "generative"
Provides-Extra: cleaning
Requires-Dist: cleanlab>=2.7; extra == "cleaning"
Provides-Extra: drift
Requires-Dist: evidently>=0.4; extra == "drift"
Provides-Extra: viz
Requires-Dist: umap-learn>=0.5; extra == "viz"
Requires-Dist: matplotlib>=3.7; extra == "viz"
Provides-Extra: image
Requires-Dist: timm>=1.0; extra == "image"
Requires-Dist: torch>=2.1; extra == "image"
Requires-Dist: pillow>=10.0; extra == "image"
Provides-Extra: audio
Requires-Dist: torchaudio>=2.1; extra == "audio"
Requires-Dist: torch>=2.1; extra == "audio"
Requires-Dist: soundfile>=0.12; extra == "audio"
Provides-Extra: web
Requires-Dist: portail[mcp]>=0.1.0a2; extra == "web"
Requires-Dist: flask>=3.0; extra == "web"
Requires-Dist: streamstudio>=0.1.0a2; extra == "web"
Requires-Dist: pillow; extra == "web"
Provides-Extra: all
Requires-Dist: curaitor[audio,cleaning,distances,drift,generative,image,outliers,viz,web]; extra == "all"
Dynamic: license-file

# Curaitor

(loggair / confluid / liquifai) adapter for **dataset curation & analysis** — outlier detection, distribution distances, synthetic-vs-real comparison, label cleaning, and dimensionality reduction — exposed through five `@configurable` wrappers and one Liquify CLI.

| Verb | Adapter | Methods | Extra |
|---|---|---|---|
| `outliers` | [`scikit-learn`](https://scikit-learn.org/) | `iforest`, `lof`, `ocsvm`, `elliptic` | core |
| `outliers` | [`pyod`](https://pyod.readthedocs.io/) | `ecod`, `copod`, `hbos`, `abod`, `knn`, `pyod_iforest`, `pyod_lof`, `pyod_ocsvm`, `pyod_pca`, `mcd` | `[outliers]` |
| `distance` | [`scipy.stats`](https://docs.scipy.org/doc/scipy/reference/stats.html) | `ks`, `anderson`, `wasserstein_1d`, `energy_1d`, `cramer_von_mises` | core |
| `distance` | [`POT`](https://pythonot.github.io/) | `wasserstein`, `sinkhorn`, `mmd`, `energy`, `bures` | `[distances]` |
| `distance` | [`evidently`](https://docs.evidentlyai.com/) | `psi`, `js` | `[drift]` |
| `compare`  | [`torchmetrics`](https://lightning.ai/docs/torchmetrics/) | `fid`, `kid`, `inception` | `[generative]` |
| `compare`  | [`evidently`](https://docs.evidentlyai.com/) | `drift_report` | `[drift]` |
| `labels`   | [`cleanlab`](https://docs.cleanlab.ai/) | `cleanlab` | `[cleaning]` |
| `project`  | [`scikit-learn`](https://scikit-learn.org/) | `sklearn_pca`, `sklearn_tsne` | core |
| `project`  | [`umap-learn`](https://umap-learn.readthedocs.io/) | `umap` | `[viz]` |

Plus two optional **modality adapters** that turn a `Stream` of raw records into a feature matrix the dispatchers consume directly:

| Adapter | Backbone | Module | Extra |
|---|---|---|---|
| Image features | `timm` (default `efficientvit_b0`) | `curaitor.image_adapter.extract_image_features` | `[image]` |
| Audio features | `torchaudio` pipelines (default HuBERT-base) | `curaitor.audio_adapter.extract_audio_features` | `[audio]` |

Curaitor is **not** a curation library. It's a thin glue layer (~1000 LOC) over upstream packages that already do the work, with loggair logging, Confluid YAML config, and the same liquifai CLI conventions as the rest of the workspace.

## The dataset-analysis landscape

Curaitor ships method wrappers for the libraries highlighted **in bold** below. Everything else listed is a known, useful tool worth knowing about — pick the right one before reaching for curaitor.

### Outlier / anomaly detection

| Library | Notes | Wrapped |
|---|---|---|
| **scikit-learn** | `IsolationForest`, `LocalOutlierFactor`, `OneClassSVM`, `EllipticEnvelope`. Lightweight defaults. | ✅ core |
| **PyOD** | 40+ algorithms (ECOD, COPOD, HBOS, ABOD, KNN, IForest, LOF, OCSVM, PCA-recon, MCD, …). Standard reference. | ✅ `[outliers]` |
| alibi-detect | Adversarial / drift / OOD; deep-learning-flavoured | — (overlaps with pyod + cleanlab) |
| pythresh | Automated thresholding for outlier scores | — (orthogonal — could layer on top) |

### Distribution distance / divergence

| Library | Notes | Wrapped |
|---|---|---|
| **scipy.stats** | KS, Anderson–Darling, Cramér–von Mises, Wasserstein-1D, energy-1D | ✅ core |
| **POT (Python Optimal Transport)** | Multi-dim Wasserstein / Sinkhorn / MMD / energy / Bures | ✅ `[distances]` |
| **evidently** | Column-wise PSI, JS, drift reports with HTML rendering | ✅ `[drift]` |
| geomloss | GPU-friendly OT (Sinkhorn divergence). Heavier dep | — |

### Synthetic-vs-real evaluation (image / audio)

| Library | Notes | Wrapped |
|---|---|---|
| **torchmetrics[image]** | FID, KID, IS, LPIPS — feature-matrix mode lets us stay modality-agnostic | ✅ `[generative]` |
| sdmetrics / SDV | Tabular-synthetic-data metrics | — (different problem) |

### Dataset cleaning / label issues

| Library | Notes | Wrapped |
|---|---|---|
| **cleanlab** | Confident-learning label issues, near-duplicate flagging | ✅ `[cleaning]` |
| imagededup | pHash / dHash / CNN duplicate detection (image-only) | — (cleanlab covers most cases) |

### Dimensionality reduction

| Library | Notes | Wrapped |
|---|---|---|
| **scikit-learn** | PCA, t-SNE | ✅ core |
| **umap-learn** | UMAP — non-linear default | ✅ `[viz]` |
| openTSNE | Faster t-SNE | — |
| pacmap, trimap | Newer alternatives | — |

Anything not yet wrapped that you need — file an issue or drop in a `<name>_backend.py` (the registry pattern in `curaitor.api` is intentionally one-file-to-add).

## Installation

```bash
pip install curaitor
```

Backends are optional extras — install only what you need:

```bash
pip install "curaitor[outliers]"    # pyod
pip install "curaitor[distances]"   # POT
pip install "curaitor[generative]"  # torchmetrics + torch
pip install "curaitor[cleaning]"    # cleanlab
pip install "curaitor[drift]"       # evidently
pip install "curaitor[viz]"         # umap-learn + matplotlib
pip install "curaitor[image]"       # timm + torch + pillow
pip install "curaitor[audio]"       # torchaudio + torch + soundfile
pip install "curaitor[web]"         # the analysis app (portail, Flask, streamstudio)
pip install "curaitor[all]"         # everything
```

### Development

```bash
git clone https://github.com/Gearlux/curaitor.git
cd curaitor
pip install -e ".[dev,outliers,distances,cleaning,viz]"   # core + most extras + dev tools
```

## Architecture

```
   YAML (Confluid)            dispatch                  upstream library
   ┌─────────────────┐    ┌────────────────────┐    ┌─────────────────────────┐
   │ detector:       │    │  OutlierDetector   │    │ pyod.models.*           │
   │   method: ...   │───▶│  find_outliers()   │───▶│ sklearn.ensemble.*      │
   │ comparator:     │───▶│  compare_datasets()│───▶│ torchmetrics.image.*    │
   │ checker:        │───▶│  check_labels()    │───▶│ cleanlab.rank.*         │
   │ projector:      │───▶│  project()         │───▶│ umap.UMAP / sklearn     │
   │ input(s)/output │    │  per-verb registry │    │ ot.emd2 / scipy.stats   │
   └─────────────────┘    └────────────────────┘    └─────────────────────────┘
            ▲                       │
       liquifai CLI            loggair logger
```

Each backend lives in a single `<name>_backend.py` exposing only the verbs it serves:

```python
OUTLIER_METHODS:  tuple[str, ...] = ()      # zero or more
DISTANCE_METHODS: tuple[str, ...] = ()
COMPARE_METHODS:  tuple[str, ...] = ()
LABEL_METHODS:    tuple[str, ...] = ()
PROJECT_METHODS:  tuple[str, ...] = ()

def is_available() -> bool: ...
def find_outliers(features, *, method, contamination, **kw) -> OutlierResult: ...
def compute_distance(a, b, *, method, **kw) -> float: ...
def compare_datasets(a, b, *, method, **kw) -> ComparisonReport: ...
def check_labels(features, labels, *, method, **kw) -> LabelIssueResult: ...
def project(features, *, method, n_components, **kw) -> ProjectionResult: ...
```

The dispatcher in `curaitor.api` builds five `method → backend` registries (one per verb) at import time and forwards calls. Upstream libraries are imported lazily, so the package works with any subset of the optional extras installed.

## Quick start

### From Python — outlier detection

```python
import numpy as np
from curaitor import find_outliers, list_methods

print(list_methods(only_available=True, verb="outliers"))    # which detectors are installed?

rng = np.random.default_rng(0)
features = np.vstack([rng.normal(0, 1, (1000, 64)), rng.normal(8, 1, (50, 64))])

result = find_outliers(features, method="iforest", contamination=0.05)
print(result.flags.sum(), "records flagged")
```

### From Python — synthetic-vs-real

```python
from curaitor import compare_datasets

# pre-extract features upstream — sonair / timm / your own encoder
real_feats = ...        # (N_real, 2048) float32
synth_feats = ...       # (N_syn,  2048) float32

report = compare_datasets(real_feats, synth_feats, method="fid", feature=2048)
print(report.distance, report.per_metric)    # FID
```

### From Python — image features then outliers

```python
from curaitor.image_adapter import extract_image_features
from curaitor import find_outliers

# `stream` is any iterable of recordstream typed-bag Records (the adapter reads each
# record's primary input item; bare arrays / positional tuples also work).
features = extract_image_features(stream, model_name="efficientvit_b0", batch_size=32)
result = find_outliers(features, method="iforest", contamination=0.02)
```

### From a Confluid YAML

```yaml
# examples/find_outliers.yaml
detector: !class:curaitor.OutlierDetector
  method: iforest
  contamination: 0.1

input: examples/data/features.npy
output: examples/data/outliers.json
```

```bash
curaitor find-outliers examples/find_outliers.yaml
```

### In a recordstream pipeline

curaitor's methods are graph ops too (`curaitor.ops`: `ExtractImageEmbedding`, `ExtractAudioEmbedding`,
`FlagOutliers`, `ProjectEmbeddings`, `FindSimilarRecords`, `DropFlagged`, `FlagLabelIssues`,
`EstimateClassProbabilities`, `CompareDatasets`), listed in streamstudio's palette:

```bash
recordstream run graphs/image_outliers.yaml root=/path/to/pictures
```

Every picture's record leaves with `embedding`, `outlier_score`, `outlier` and `projection`. See
[docs/ops.md](https://github.com/Gearlux/curaitor/blob/main/docs/ops.md).

### In the browser — the analysis app

```bash
pip install "curaitor[web,image]"
curaitor                                 # pick "images", type the folder of your pictures, ▶ run
```

A served workspace on [portail](https://github.com/Gearlux/portail): the records list with portail's filter
language (`outlier_score > 0.6`, `outlier`, `label = cat`), each record's pictures (a default, and the ones shown,
chosen on the page) and entries, a projection scatter
coloured by any column, the analysis run as a job with progress and a stop, its results cached in the workspace's
folder, the source and analysis graphs drawn in the mounted graph editor, a comparison of two folders, and
`curaitor-mcp` — the page's routes as MCP tools. Types: `image-outliers`, `label-issues`, `compare`. See
[docs/app.md](https://github.com/Gearlux/curaitor/blob/main/docs/app.md).

## CLI reference

| Command | Purpose |
|---|---|
| `curaitor list-methods` | Print every registered method (across all verbs) and whether its backend is installed. |
| `curaitor find-outliers <yaml>` | Apply the configured `detector:` to `input:` (a feature matrix) and write a JSON outlier report to `output:`. |
| `curaitor compare <yaml>` | Apply the configured `comparator:` to `input_a:` and `input_b:` and write a JSON comparison report to `output:`. |
| `curaitor check-labels <yaml>` | Apply the configured `checker:` to `input:` (predicted-probability matrix) + `labels:` and write a JSON label-issue report to `output:`. |
| `curaitor project <yaml>` | Apply the configured `projector:` to `input:` and write a JSON projection (`coords`, `n_components`, `extra`) to `output:`. |
| `curaitor workspace <type>` | Serve a NEW analysis workspace of a type (`image-outliers`, `label-issues`, `compare`) — `[web]`. |
| `curaitor open <workspace.yaml>` | Serve a saved workspace (the default command: `curaitor <workspace.yaml>`) — `[web]`. |
| `curaitor stop\|restart\|list` | Stop, restart or list the running app servers, by the workspace they serve — `[web]`. |
| `curaitor-mcp` | The served page's routes as MCP tools (`page_state`, `list_records`, `run_analysis`, …) — `[web]`. |

The CLI inherits Confluid's dotted-key overrides:

```bash
curaitor find-outliers cfg.yaml detector.contamination=0.02
```

## The FiftyOne App as a workspace service

curaitor brings a service class for a workspace's service manager: `curaitor.fiftyone_service.FiftyOne` starts the
[FiftyOne](https://docs.voxel51.com/) App, to browse a dataset, its labels and the outliers found. The manager finds
the class through its entry point once curaitor is installed, and gives the service its `start`, `info` and `stop`.
A start serves on port 5151 unless another port is asked for; `info` answers the address, the database folder and
the datasets.

FiftyOne itself is not one of curaitor's dependencies; install it with `uv pip install fiftyone` (the start says so
when it is missing). Its database lives in the service's data folder, and the start writes `FIFTYONE_URL` and
`FIFTYONE_DATABASE_DIR` into the workspace `.env`.

## What's in the package

| Module | Purpose |
|---|---|
| `curaitor.api.find_outliers` / `OutlierDetector` | Per-record anomaly scoring. |
| `curaitor.api.compute_distance` / `DistanceMetric` | One-number distribution distance. |
| `curaitor.api.compare_datasets` / `DatasetComparator` | Multi-metric dataset comparison (FID/KID/drift). |
| `curaitor.api.check_labels` / `LabelChecker` | Per-record label-issue scoring. |
| `curaitor.api.project` / `Projector` | N-D → low-D embedding for inspection. |
| `curaitor.api.list_methods` | Inspect the registries + availability. |
| `curaitor.scipy_backend` | KS / Anderson / Wasserstein-1D / energy-1D / Cramér–von Mises. |
| `curaitor.sklearn_backend` | Iforest / LOF / OCSVM / EllipticEnvelope, PCA / t-SNE. |
| `curaitor.networkx_backend` | The kept records of a set of near-copies: dominating / maximal independent set. |
| `curaitor.pyod_backend` | ECOD / COPOD / HBOS / ABOD / KNN / IForest / LOF / OCSVM / PCA-recon / MCD. |
| `curaitor.pot_backend` | Wasserstein / Sinkhorn / MMD / energy / Bures (multi-dim). |
| `curaitor.cleanlab_backend` | Confident-learning label issues. |
| `curaitor.umap_backend` | UMAP projection. |
| `curaitor.evidently_backend` | PSI / JS / drift reports. |
| `curaitor.torchmetrics_backend` | FID / KID / Inception Score. |
| `curaitor.image_adapter` | timm-based image-feature extraction (extra `[image]`). |
| `curaitor.audio_adapter` | torchaudio-based audio-feature extraction (extra `[audio]`). |
| `curaitor.ops` | The graph ops: embed, flag outliers, project, flag label issues, compare ([docs/ops.md](https://github.com/Gearlux/curaitor/blob/main/docs/ops.md)). |
| `curaitor.plots` | matplotlib helpers (extra `[viz]`). |
| `curaitor.app` | The analysis app: the workspace, the analysis jobs and their cache, the page, `curaitor-mcp` (extra `[web]`, [docs/app.md](https://github.com/Gearlux/curaitor/blob/main/docs/app.md)). |
| `curaitor.cli` | `list-methods`, `find-outliers`, `compare`, `check-labels`, `project`, and the app's `open`, `workspace`, `stop`, `restart`, `list`. |
| `curaitor.fiftyone_service` | The FiftyOne App as a workspace service. |

## Why a thin adapter?

The dataset-curation landscape is well-served by mature upstream packages — pyod for anomaly detection, cleanlab for label issues, POT for OT distances, torchmetrics for generative-model metrics. There's no value in re-implementing them.

What curaitor adds:

- One Python entry point per concern (`find_outliers`, `compute_distance`, `compare_datasets`, `check_labels`, `project`) instead of N library APIs.
- One Confluid YAML knob per concern (`!class:curaitor.OutlierDetector`, etc.) for use inside RecordStream pipelines, matrainer training loops, or any other config.
- loggair integration for unified logging across the workspace.
- A `curaitor` liquifai CLI, with the same conventions as the rest of the workspace.
- Lazy imports so the package itself works with any subset of `[outliers]` / `[distances]` / `[generative]` / `[cleaning]` / `[drift]` / `[viz]` / `[image]` / `[audio]` installed.
- Consistent return types (dataclasses) that round-trip through JSON for use with RecordStream sinks.

If you only need one backend, use it directly. If you want to write code that swaps detectors / metrics via config, curaitor is the glue.

## Dependencies

| Package | Purpose | Required? |
|---|---|---|
| `confluid` | YAML config + `@configurable` | yes |
| `liquifai` | CLI framework | yes |
| `loggair` | Structured logging | yes |
| `recordstream` | Record / Stream types, the graph ops' base | yes (`curaitor.ops` imports it; the adapters read records as plain dicts and import nothing from it) |
| `numpy`, `scipy`, `scikit-learn` | Core array + classical methods | yes |
| `networkx` | Graph algorithms for the groups of near-copies | yes |
| `pyod` | Outlier algorithm catalog | optional (`[outliers]`) |
| `pot` | Optimal-transport distances | optional (`[distances]`) |
| `torchmetrics[image]` + `torch` | FID / KID / IS | optional (`[generative]`) |
| `cleanlab` | Label-issue detection | optional (`[cleaning]`) |
| `evidently` | Drift reports | optional (`[drift]`) |
| `umap-learn` + `matplotlib` | UMAP + plot helpers | optional (`[viz]`) |
| `timm` + `torch` + `pillow` | Image-feature adapter | optional (`[image]`) |
| `torchaudio` + `torch` + `soundfile` | Audio-feature adapter | optional (`[audio]`) |
| `portail[mcp]` + `flask` + `streamstudio` + `pillow` | The analysis app: serving, its page, the graph editor, thumbnails, the MCP tools | optional (`[web]`) |

## License

[PolyForm Noncommercial License 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0) (the `LICENSE` file): free for personal, academic and other noncommercial use. Commercial use needs a separate licence from the author.
