khipu-weave 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- khipu_weave-0.1.0/.env.example +31 -0
- khipu_weave-0.1.0/DataSets/README.md +35 -0
- khipu_weave-0.1.0/LICENSE +21 -0
- khipu_weave-0.1.0/MANIFEST.in +12 -0
- khipu_weave-0.1.0/PKG-INFO +73 -0
- khipu_weave-0.1.0/README.md +47 -0
- khipu_weave-0.1.0/benchmarks/README.md +37 -0
- khipu_weave-0.1.0/benchmarks/__init__.py +1 -0
- khipu_weave-0.1.0/benchmarks/benchmark_cleaning.py +317 -0
- khipu_weave-0.1.0/benchmarks/books_prediction.py +464 -0
- khipu_weave-0.1.0/benchmarks/cleaning_benchmark.json +697 -0
- khipu_weave-0.1.0/benchmarks/notebooks/01_books_full_benchmark.ipynb +1302 -0
- khipu_weave-0.1.0/benchmarks/notebooks/03_books_genre_prediction.ipynb +279 -0
- khipu_weave-0.1.0/benchmarks/notebooks/04_tabular_prediction.ipynb +465 -0
- khipu_weave-0.1.0/benchmarks/notebooks/04_tabular_prediction_iris_results.md +77 -0
- khipu_weave-0.1.0/benchmarks/notebooks/04_tabular_prediction_results.md +78 -0
- khipu_weave-0.1.0/benchmarks/prepare_books_benchmark.py +229 -0
- khipu_weave-0.1.0/docs/README.md +120 -0
- khipu_weave-0.1.0/docs/augmentation/README.md +159 -0
- khipu_weave-0.1.0/docs/backends/README.md +55 -0
- khipu_weave-0.1.0/docs/cleaning/README.md +60 -0
- khipu_weave-0.1.0/docs/pipeline/README.md +75 -0
- khipu_weave-0.1.0/docs/quality/README.md +63 -0
- khipu_weave-0.1.0/docs/reference/README.md +315 -0
- khipu_weave-0.1.0/docs/testing/README.md +75 -0
- khipu_weave-0.1.0/examples/README.md +27 -0
- khipu_weave-0.1.0/examples/automatic_cleaning.py +38 -0
- khipu_weave-0.1.0/examples/clean_csv.py +60 -0
- khipu_weave-0.1.0/examples/feature_adder_demo.py +43 -0
- khipu_weave-0.1.0/examples/laptop_schema.json +21 -0
- khipu_weave-0.1.0/examples/live_smoke_test.py +123 -0
- khipu_weave-0.1.0/examples/quality_config.json +16 -0
- khipu_weave-0.1.0/examples/run_cleaning.py +6 -0
- khipu_weave-0.1.0/examples/run_full_scenario.py +56 -0
- khipu_weave-0.1.0/examples/scenarios/README.md +26 -0
- khipu_weave-0.1.0/examples/scenarios/__init__.py +1 -0
- khipu_weave-0.1.0/examples/scenarios/fixtures.json +1927 -0
- khipu_weave-0.1.0/examples/scenarios/report.py +120 -0
- khipu_weave-0.1.0/examples/scenarios/runner.py +528 -0
- khipu_weave-0.1.0/examples/scenarios/scoring.py +134 -0
- khipu_weave-0.1.0/import_datasets/README.md +22 -0
- khipu_weave-0.1.0/import_datasets/import_autompg_dataset.py +22 -0
- khipu_weave-0.1.0/import_datasets/import_laptop_price_dataset.py +23 -0
- khipu_weave-0.1.0/import_datasets/import_top_book_sellers_dataset.py +25 -0
- khipu_weave-0.1.0/notebooks/00_quickstart.ipynb +3741 -0
- khipu_weave-0.1.0/notebooks/02_clean_any_csv.ipynb +765 -0
- khipu_weave-0.1.0/notebooks/README.md +10 -0
- khipu_weave-0.1.0/pyproject.toml +46 -0
- khipu_weave-0.1.0/setup.cfg +4 -0
- khipu_weave-0.1.0/src/khipu_weave/README.md +23 -0
- khipu_weave-0.1.0/src/khipu_weave/__init__.py +45 -0
- khipu_weave-0.1.0/src/khipu_weave/_data.py +49 -0
- khipu_weave-0.1.0/src/khipu_weave/_evidence.py +57 -0
- khipu_weave-0.1.0/src/khipu_weave/_pipeline.py +85 -0
- khipu_weave-0.1.0/src/khipu_weave/_prompts.py +231 -0
- khipu_weave-0.1.0/src/khipu_weave/_protocols.py +188 -0
- khipu_weave-0.1.0/src/khipu_weave/_schema.py +94 -0
- khipu_weave-0.1.0/src/khipu_weave/augmentation.py +757 -0
- khipu_weave-0.1.0/src/khipu_weave/backend.py +350 -0
- khipu_weave-0.1.0/src/khipu_weave/cleaning.py +952 -0
- khipu_weave-0.1.0/src/khipu_weave/cleaning_pipeline.py +452 -0
- khipu_weave-0.1.0/src/khipu_weave/discovery.py +287 -0
- khipu_weave-0.1.0/src/khipu_weave/duplicates.py +281 -0
- khipu_weave-0.1.0/src/khipu_weave/evaluation.py +294 -0
- khipu_weave-0.1.0/src/khipu_weave/execution.py +62 -0
- khipu_weave-0.1.0/src/khipu_weave/experiment_backends.py +102 -0
- khipu_weave-0.1.0/src/khipu_weave/feature_adder.py +330 -0
- khipu_weave-0.1.0/src/khipu_weave/prediction.py +144 -0
- khipu_weave-0.1.0/src/khipu_weave/prediction_cache.py +362 -0
- khipu_weave-0.1.0/src/khipu_weave/prediction_experiments.py +342 -0
- khipu_weave-0.1.0/src/khipu_weave/quality.py +495 -0
- khipu_weave-0.1.0/src/khipu_weave/quality_pipeline.py +276 -0
- khipu_weave-0.1.0/src/khipu_weave/rate_limit.py +46 -0
- khipu_weave-0.1.0/src/khipu_weave/reporting.py +175 -0
- khipu_weave-0.1.0/src/khipu_weave/verification.py +537 -0
- khipu_weave-0.1.0/src/khipu_weave.egg-info/PKG-INFO +73 -0
- khipu_weave-0.1.0/src/khipu_weave.egg-info/SOURCES.txt +110 -0
- khipu_weave-0.1.0/src/khipu_weave.egg-info/dependency_links.txt +1 -0
- khipu_weave-0.1.0/src/khipu_weave.egg-info/entry_points.txt +2 -0
- khipu_weave-0.1.0/src/khipu_weave.egg-info/requires.txt +18 -0
- khipu_weave-0.1.0/src/khipu_weave.egg-info/top_level.txt +1 -0
- khipu_weave-0.1.0/tests/README.md +35 -0
- khipu_weave-0.1.0/tests/test_augmentation.py +372 -0
- khipu_weave-0.1.0/tests/test_backend.py +106 -0
- khipu_weave-0.1.0/tests/test_batch_recovery.py +127 -0
- khipu_weave-0.1.0/tests/test_books_benchmark.py +167 -0
- khipu_weave-0.1.0/tests/test_books_prediction.py +360 -0
- khipu_weave-0.1.0/tests/test_cleaning.py +324 -0
- khipu_weave-0.1.0/tests/test_dataset_imports.py +34 -0
- khipu_weave-0.1.0/tests/test_discovery.py +204 -0
- khipu_weave-0.1.0/tests/test_duplicates.py +90 -0
- khipu_weave-0.1.0/tests/test_evaluation.py +431 -0
- khipu_weave-0.1.0/tests/test_experiment_backends.py +143 -0
- khipu_weave-0.1.0/tests/test_fallback.py +124 -0
- khipu_weave-0.1.0/tests/test_feature_adder.py +264 -0
- khipu_weave-0.1.0/tests/test_full_scenario.py +115 -0
- khipu_weave-0.1.0/tests/test_hardening.py +277 -0
- khipu_weave-0.1.0/tests/test_hybrid_cleaning.py +265 -0
- khipu_weave-0.1.0/tests/test_issue_references.py +60 -0
- khipu_weave-0.1.0/tests/test_notebook_workflows.py +289 -0
- khipu_weave-0.1.0/tests/test_numeric_formats.py +162 -0
- khipu_weave-0.1.0/tests/test_pipeline.py +308 -0
- khipu_weave-0.1.0/tests/test_prediction.py +152 -0
- khipu_weave-0.1.0/tests/test_prediction_cache.py +286 -0
- khipu_weave-0.1.0/tests/test_prediction_experiments.py +430 -0
- khipu_weave-0.1.0/tests/test_prediction_notebook.py +193 -0
- khipu_weave-0.1.0/tests/test_provider_backends.py +407 -0
- khipu_weave-0.1.0/tests/test_quality.py +151 -0
- khipu_weave-0.1.0/tests/test_quality_discovery.py +66 -0
- khipu_weave-0.1.0/tests/test_quality_pipeline.py +173 -0
- khipu_weave-0.1.0/tests/test_rate_limit.py +85 -0
- khipu_weave-0.1.0/tests/test_verification.py +478 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Copy to .env only if you do not already have a working .env.
|
|
2
|
+
# Keep real keys in .env, never in this template or Git.
|
|
3
|
+
# See docs/backends/README.md for provider-specific examples.
|
|
4
|
+
|
|
5
|
+
# Supervised experiments use the first configured provider in this order.
|
|
6
|
+
# Hosted providers each need a model and key. Ollama needs a model.
|
|
7
|
+
OPENAI_MODEL=
|
|
8
|
+
OPENAI_API_KEY=
|
|
9
|
+
GEMINI_MODEL=
|
|
10
|
+
GEMINI_API_KEY=
|
|
11
|
+
ANTHROPIC_MODEL=
|
|
12
|
+
ANTHROPIC_API_KEY=
|
|
13
|
+
OLLAMA_MODEL=
|
|
14
|
+
# OLLAMA_BASE_URL=http://localhost:11434
|
|
15
|
+
# OLLAMA_API_KEY=
|
|
16
|
+
|
|
17
|
+
# Starting example: a local OpenAI-compatible server you have already started.
|
|
18
|
+
# Replace the format, URL and model for your chosen connection.
|
|
19
|
+
# Supervised experiments also use these settings if none of the above are configured.
|
|
20
|
+
LLM_API_FORMAT=openai
|
|
21
|
+
LLM_BASE_URL=http://localhost:8000/v1
|
|
22
|
+
LLM_MODEL=your-served-model-id
|
|
23
|
+
LLM_API_KEY=
|
|
24
|
+
|
|
25
|
+
# Optional backup on the same endpoint/format/key. Blank disables it.
|
|
26
|
+
LLM_FALLBACK_MODEL=
|
|
27
|
+
|
|
28
|
+
# HTTP request limit for this process; includes retries and fallback.
|
|
29
|
+
LLM_REQUESTS_PER_MINUTE=15
|
|
30
|
+
|
|
31
|
+
# Advanced settings are optional; see docs/reference/README.md#backend-settings.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Example datasets
|
|
2
|
+
|
|
3
|
+
[Project overview](../docs/README.md) · [Download scripts](../import_datasets/README.md)
|
|
4
|
+
|
|
5
|
+
This directory contains source datasets and prepared benchmarks.
|
|
6
|
+
|
|
7
|
+
| File | What its rows describe |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| `amazon_bestselling_books.csv` | Books, ratings, reviews and prices |
|
|
10
|
+
| `laptop_price.csv` | Laptops, specifications and prices |
|
|
11
|
+
| `AmesHousing.csv` | Houses and sale prices |
|
|
12
|
+
| `auto_mpg.csv` | Vehicles and fuel consumption |
|
|
13
|
+
|
|
14
|
+
The books classification task uses `Genre` as its target and `Price` as an input
|
|
15
|
+
feature. The cleaning pipeline excludes `Genre` from model prompts and edits.
|
|
16
|
+
|
|
17
|
+
## Benchmarks
|
|
18
|
+
|
|
19
|
+
Prepared samples with deliberate errors and separate known answers. Each folder
|
|
20
|
+
has its own description. The main files have different jobs:
|
|
21
|
+
|
|
22
|
+
- `input.csv`: dirty data to give the cleaner.
|
|
23
|
+
- `labels.json`: expected answers used locally for scoring.
|
|
24
|
+
- `reference.csv`: original sampled values, before deliberate errors.
|
|
25
|
+
- `protocol.json` / metadata files, where present: how the sample was prepared.
|
|
26
|
+
|
|
27
|
+
The Ames, books holdout, and laptop protocols record SHA-256 hashes of the
|
|
28
|
+
benchmark files and the implementation at the time of each experiment. The
|
|
29
|
+
benchmark files still match those hashes. Some implementation files have changed
|
|
30
|
+
since then, so any live scores from those runs apply to the recorded versions.
|
|
31
|
+
Protocol source paths preserve the names used when each run was captured; they
|
|
32
|
+
may differ from the current package layout.
|
|
33
|
+
|
|
34
|
+
Reference answers and labels are used locally for scoring. New runs are stored
|
|
35
|
+
under the Git-ignored `.cache/` directory. Package builds exclude the raw datasets.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hazar (@hazarcs), Sameer (@sameersiddiqui22), and Nicolas (@Nicotico2000)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
include .env.example
|
|
2
|
+
include DataSets/README.md
|
|
3
|
+
recursive-include examples *.py *.json *.md
|
|
4
|
+
recursive-include docs README.md
|
|
5
|
+
recursive-include tests *.py *.md
|
|
6
|
+
recursive-include import_datasets *.py *.md
|
|
7
|
+
recursive-include notebooks *.md *.ipynb
|
|
8
|
+
recursive-include benchmarks *.py *.md *.ipynb *.json
|
|
9
|
+
prune notebooks/.ipynb_checkpoints
|
|
10
|
+
global-exclude *-checkpoint.ipynb
|
|
11
|
+
prune docs/superpowers
|
|
12
|
+
prune .superpowers
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: khipu-weave
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Configurable LLM-assisted cleaning of tabular data
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/hazarcs/khipu-weave
|
|
7
|
+
Project-URL: Documentation, https://github.com/hazarcs/khipu-weave/tree/main/docs
|
|
8
|
+
Project-URL: Issues, https://github.com/hazarcs/khipu-weave/issues
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: pandas<4,>=1.5
|
|
13
|
+
Requires-Dist: scikit-learn<2,>=1.1
|
|
14
|
+
Requires-Dist: python-dotenv<2,>=1
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
17
|
+
Requires-Dist: ruff; extra == "dev"
|
|
18
|
+
Requires-Dist: build; extra == "dev"
|
|
19
|
+
Provides-Extra: notebooks
|
|
20
|
+
Requires-Dist: ipykernel>=6; extra == "notebooks"
|
|
21
|
+
Requires-Dist: nbformat>=5; extra == "notebooks"
|
|
22
|
+
Provides-Extra: sampling
|
|
23
|
+
Requires-Dist: imbalanced-learn<1,>=0.12.4; extra == "sampling"
|
|
24
|
+
Requires-Dist: scikit-learn<1.6; python_version < "3.10" and extra == "sampling"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# khipu-weave
|
|
28
|
+
|
|
29
|
+
A Python package for cleaning tabular data with LLM-assisted rule discovery and
|
|
30
|
+
local validation. It standardizes categories and formats, flags possible errors,
|
|
31
|
+
and repairs values when the source row contains supporting evidence. The cleaning
|
|
32
|
+
pipeline preserves rows and records its findings in an audit report.
|
|
33
|
+
|
|
34
|
+
The package also supports synthetic training examples and LLM-inferred features.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install khipu-weave
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Offline example
|
|
43
|
+
|
|
44
|
+
From the repository root after [installation](docs/pipeline/README.md#installation):
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
.venv/bin/python examples/run_full_scenario.py \
|
|
48
|
+
--output-dir .cache/offline-check
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The HTML report at `.cache/offline-check/report.html` contains inputs, expected
|
|
52
|
+
outputs, and observed results. Offline mode skips model-dependent cases. Each run
|
|
53
|
+
requires a new output directory.
|
|
54
|
+
|
|
55
|
+
## Quickstart
|
|
56
|
+
|
|
57
|
+
Open the [quickstart notebook](notebooks/00_quickstart.ipynb) to clean a CSV,
|
|
58
|
+
add an LLM-derived feature, and fit classifiers with and without synthetic
|
|
59
|
+
training rows using the same prepared data.
|
|
60
|
+
The [benchmark notebooks](benchmarks/README.md) contain research runs and saved
|
|
61
|
+
results.
|
|
62
|
+
|
|
63
|
+
## Documentation
|
|
64
|
+
|
|
65
|
+
- [Project overview](docs/README.md)
|
|
66
|
+
- [CSV pipeline](docs/pipeline/README.md)
|
|
67
|
+
- [Cleaning methods](docs/cleaning/README.md)
|
|
68
|
+
- [Data quality checks](docs/quality/README.md)
|
|
69
|
+
- [Model backends](docs/backends/README.md)
|
|
70
|
+
- [Tests and benchmarks](docs/testing/README.md)
|
|
71
|
+
- [User notebooks](notebooks/README.md)
|
|
72
|
+
- [Benchmarks and experiments](benchmarks/README.md)
|
|
73
|
+
- [Configuration reference](docs/reference/README.md)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# khipu-weave
|
|
2
|
+
|
|
3
|
+
A Python package for cleaning tabular data with LLM-assisted rule discovery and
|
|
4
|
+
local validation. It standardizes categories and formats, flags possible errors,
|
|
5
|
+
and repairs values when the source row contains supporting evidence. The cleaning
|
|
6
|
+
pipeline preserves rows and records its findings in an audit report.
|
|
7
|
+
|
|
8
|
+
The package also supports synthetic training examples and LLM-inferred features.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install khipu-weave
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Offline example
|
|
17
|
+
|
|
18
|
+
From the repository root after [installation](docs/pipeline/README.md#installation):
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
.venv/bin/python examples/run_full_scenario.py \
|
|
22
|
+
--output-dir .cache/offline-check
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The HTML report at `.cache/offline-check/report.html` contains inputs, expected
|
|
26
|
+
outputs, and observed results. Offline mode skips model-dependent cases. Each run
|
|
27
|
+
requires a new output directory.
|
|
28
|
+
|
|
29
|
+
## Quickstart
|
|
30
|
+
|
|
31
|
+
Open the [quickstart notebook](notebooks/00_quickstart.ipynb) to clean a CSV,
|
|
32
|
+
add an LLM-derived feature, and fit classifiers with and without synthetic
|
|
33
|
+
training rows using the same prepared data.
|
|
34
|
+
The [benchmark notebooks](benchmarks/README.md) contain research runs and saved
|
|
35
|
+
results.
|
|
36
|
+
|
|
37
|
+
## Documentation
|
|
38
|
+
|
|
39
|
+
- [Project overview](docs/README.md)
|
|
40
|
+
- [CSV pipeline](docs/pipeline/README.md)
|
|
41
|
+
- [Cleaning methods](docs/cleaning/README.md)
|
|
42
|
+
- [Data quality checks](docs/quality/README.md)
|
|
43
|
+
- [Model backends](docs/backends/README.md)
|
|
44
|
+
- [Tests and benchmarks](docs/testing/README.md)
|
|
45
|
+
- [User notebooks](notebooks/README.md)
|
|
46
|
+
- [Benchmarks and experiments](benchmarks/README.md)
|
|
47
|
+
- [Configuration reference](docs/reference/README.md)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Benchmarks and experiments
|
|
2
|
+
|
|
3
|
+
These notebooks and helpers document research runs. For the short, reusable
|
|
4
|
+
scikit-learn example, start with the [quickstart](../notebooks/00_quickstart.ipynb).
|
|
5
|
+
|
|
6
|
+
## Notebooks
|
|
7
|
+
|
|
8
|
+
- [Books cleaning benchmark](notebooks/01_books_full_benchmark.ipynb) compares
|
|
9
|
+
cleaning against known answers.
|
|
10
|
+
- [Book genre prediction](notebooks/03_books_genre_prediction.ipynb) compares
|
|
11
|
+
experiments on a shared train/test split.
|
|
12
|
+
- [Tabular prediction experiments](notebooks/04_tabular_prediction.ipynb)
|
|
13
|
+
compares configurable cleaning, feature and augmentation stages. Historical
|
|
14
|
+
outputs are saved alongside the notebook.
|
|
15
|
+
|
|
16
|
+
The longer [CSV cleaning walkthrough](../notebooks/02_clean_any_csv.ipynb) is
|
|
17
|
+
kept with the user-facing notebooks.
|
|
18
|
+
|
|
19
|
+
## Scripts
|
|
20
|
+
|
|
21
|
+
- `benchmark_cleaning.py` runs the older nine-fixture cleaning benchmark.
|
|
22
|
+
- `prepare_books_benchmark.py` prepares a controlled books sample without
|
|
23
|
+
model requests.
|
|
24
|
+
- `books_prediction.py` contains the cached book genre experiment helper.
|
|
25
|
+
|
|
26
|
+
## Running the notebooks
|
|
27
|
+
|
|
28
|
+
From the repository root, install the optional notebook and sampling tools:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
python -m pip install -e ".[notebooks,sampling]"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Model-backed cells require provider settings in `.env`. The book prediction
|
|
35
|
+
helper in this folder is experimental and is not part of the installed package.
|
|
36
|
+
Prepared benchmark inputs and their local scoring labels are described in the
|
|
37
|
+
[dataset README](../DataSets/README.md#benchmarks).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Research and benchmark code kept outside the installable package."""
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""Score a small synthetic benchmark, offline by default.
|
|
2
|
+
|
|
3
|
+
Offline invocation is a no-op baseline and fixture/evaluator check, never model
|
|
4
|
+
validation. ``--live`` explicitly loads environment configuration and makes
|
|
5
|
+
bounded provider calls with no automatic retries. Labels stay local to scoring.
|
|
6
|
+
|
|
7
|
+
Examples (from the repository root):
|
|
8
|
+
.venv/bin/python benchmarks/benchmark_cleaning.py --max-cases 9
|
|
9
|
+
.venv/bin/python benchmarks/benchmark_cleaning.py --live --max-cases 4
|
|
10
|
+
.venv/bin/python benchmarks/benchmark_cleaning.py --live --domain books \
|
|
11
|
+
--operations formats --repeats 2 --output
|
|
12
|
+
|
|
13
|
+
The optional bare --output writes .cache/cleaning-benchmark.json. Existing files
|
|
14
|
+
are never overwritten; select a new path for another run. No credentials or full
|
|
15
|
+
prompts are written to results. Saved reports include scored outputs and bounded
|
|
16
|
+
findings for audit. This is illustrative validation on 36 handcrafted
|
|
17
|
+
cells, not a measured result on actual book/laptop datasets.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import json
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
from collections import defaultdict
|
|
27
|
+
from dataclasses import replace
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Optional, Sequence
|
|
30
|
+
|
|
31
|
+
import pandas as pd
|
|
32
|
+
|
|
33
|
+
# Permit direct execution from an uninstalled source checkout.
|
|
34
|
+
if __package__ in (None, ""):
|
|
35
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
|
36
|
+
|
|
37
|
+
from khipu_weave.evaluation import aggregate_evaluations, evaluate_cleaning
|
|
38
|
+
|
|
39
|
+
FIXTURES = Path(__file__).with_name("cleaning_benchmark.json")
|
|
40
|
+
OPERATIONS = ("categories", "formats", "detect", "repair")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def case_frames(case: dict) -> tuple:
|
|
44
|
+
"""Build frames without inferring float dtypes for missing integer labels."""
|
|
45
|
+
source = pd.DataFrame(case["source"], index=case.get("index"), dtype=object)
|
|
46
|
+
expected = pd.DataFrame(case["expected"], index=case.get("index"), dtype=object)
|
|
47
|
+
errors = {tuple(cell) for cell in case["errors"]}
|
|
48
|
+
abstain = {tuple(cell) for cell in case.get("abstain_cells", [])}
|
|
49
|
+
return source, expected, errors, abstain
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_fixtures(path: Path = FIXTURES) -> list:
|
|
53
|
+
"""Validate explicit ground truth without importing a provider or loading .env."""
|
|
54
|
+
document = json.loads(Path(path).read_text())
|
|
55
|
+
if document.get("format_version") != 1 or not isinstance(document.get("cases"), list):
|
|
56
|
+
raise ValueError("Expected benchmark format_version 1 and a cases array")
|
|
57
|
+
cases, identifiers = document["cases"], set()
|
|
58
|
+
for case in cases:
|
|
59
|
+
if case["id"] in identifiers or case["operation"] not in OPERATIONS:
|
|
60
|
+
raise ValueError("Fixture IDs must be unique and operations supported")
|
|
61
|
+
identifiers.add(case["id"])
|
|
62
|
+
source, expected, errors, abstain = case_frames(case)
|
|
63
|
+
evaluate_cleaning(
|
|
64
|
+
source,
|
|
65
|
+
expected,
|
|
66
|
+
source.copy(),
|
|
67
|
+
pd.DataFrame(),
|
|
68
|
+
errors=errors,
|
|
69
|
+
abstain_cells=abstain,
|
|
70
|
+
columns=list(case["schema"]),
|
|
71
|
+
schema=case["schema"],
|
|
72
|
+
)
|
|
73
|
+
if any(column not in source for column in case.get("exclude_columns", [])):
|
|
74
|
+
raise ValueError("Excluded fixture columns must exist")
|
|
75
|
+
if set(case.get("exclude_columns", [])) & set(case["schema"]):
|
|
76
|
+
raise ValueError("Excluded columns cannot be editable")
|
|
77
|
+
return cases
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _CountedBackend:
|
|
81
|
+
def __init__(self, backend):
|
|
82
|
+
self.backend = backend
|
|
83
|
+
self.requests = 0
|
|
84
|
+
|
|
85
|
+
def complete(self, *, system: str, payload: dict) -> dict:
|
|
86
|
+
self.requests += 1
|
|
87
|
+
return self.backend.complete(system=system, payload=payload)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _positive(value: str) -> int:
|
|
91
|
+
result = int(value)
|
|
92
|
+
if result < 1:
|
|
93
|
+
raise argparse.ArgumentTypeError("Must be a positive integer")
|
|
94
|
+
return result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _signature(actual: pd.DataFrame, report: pd.DataFrame, columns: list) -> tuple:
|
|
98
|
+
# Internal repeat comparison only; cell contents are never included in results.
|
|
99
|
+
fields = [c for c in ("row_position", "column", "status", "proposed") if c in report]
|
|
100
|
+
report_records = report[fields].to_dict("records") if fields else []
|
|
101
|
+
return (
|
|
102
|
+
actual[columns].to_json(orient="split", date_format="iso"),
|
|
103
|
+
json.dumps(report_records, sort_keys=True, default=str),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _group(runs: list, field: str) -> dict:
|
|
108
|
+
grouped = defaultdict(list)
|
|
109
|
+
for run in runs:
|
|
110
|
+
if "evaluation" in run:
|
|
111
|
+
grouped[run[field]].append(run["evaluation"])
|
|
112
|
+
return {name: aggregate_evaluations(results) for name, results in grouped.items()}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
116
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
117
|
+
parser.add_argument(
|
|
118
|
+
"--live", action="store_true", help="Explicitly enable paid/network inference"
|
|
119
|
+
)
|
|
120
|
+
parser.add_argument("--fixtures", type=Path, default=FIXTURES)
|
|
121
|
+
parser.add_argument("--domain", nargs="+", help="Restrict to fixture domains")
|
|
122
|
+
parser.add_argument("--operations", nargs="+", help="Operations, separated by spaces or commas")
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
"--max-cases",
|
|
125
|
+
type=_positive,
|
|
126
|
+
default=4,
|
|
127
|
+
help="Maximum fixtures per repeat (default 4; all methods represented)",
|
|
128
|
+
)
|
|
129
|
+
parser.add_argument("--repeats", type=_positive, default=1)
|
|
130
|
+
parser.add_argument("--timeout", type=_positive, default=45, help="Seconds per live request")
|
|
131
|
+
parser.add_argument("--max-tokens", type=_positive, default=4096)
|
|
132
|
+
parser.add_argument(
|
|
133
|
+
"--delay-seconds",
|
|
134
|
+
type=float,
|
|
135
|
+
default=0,
|
|
136
|
+
help="Live-only delay between fixtures, from 0 to 60 seconds",
|
|
137
|
+
)
|
|
138
|
+
parser.add_argument(
|
|
139
|
+
"--output",
|
|
140
|
+
type=Path,
|
|
141
|
+
nargs="?",
|
|
142
|
+
const=Path(".cache/cleaning-benchmark.json"),
|
|
143
|
+
help="Optionally write JSON, refusing to overwrite an existing file",
|
|
144
|
+
)
|
|
145
|
+
args = parser.parse_args(argv)
|
|
146
|
+
if not 0 <= args.delay_seconds <= 60:
|
|
147
|
+
parser.error("--delay-seconds must be between 0 and 60")
|
|
148
|
+
if args.output and args.output.exists():
|
|
149
|
+
parser.error("Output already exists; choose a new output path")
|
|
150
|
+
try:
|
|
151
|
+
cases = load_fixtures(args.fixtures)
|
|
152
|
+
except (ValueError, KeyError, TypeError, OSError) as exc:
|
|
153
|
+
parser.error(f"Invalid fixtures ({type(exc).__name__})")
|
|
154
|
+
domains = {case["domain"] for case in cases}
|
|
155
|
+
if args.domain and set(args.domain) - domains:
|
|
156
|
+
parser.error("Unknown domain")
|
|
157
|
+
operations = {op for item in (args.operations or OPERATIONS) for op in item.split(",")}
|
|
158
|
+
if operations - set(OPERATIONS):
|
|
159
|
+
parser.error("Unknown operation")
|
|
160
|
+
cases = [
|
|
161
|
+
case
|
|
162
|
+
for case in cases
|
|
163
|
+
if case["operation"] in operations and (not args.domain or case["domain"] in args.domain)
|
|
164
|
+
][: args.max_cases]
|
|
165
|
+
if not cases:
|
|
166
|
+
parser.error("No fixtures match the requested filters")
|
|
167
|
+
|
|
168
|
+
backend = None
|
|
169
|
+
if args.live:
|
|
170
|
+
from khipu_weave import ChatBackend
|
|
171
|
+
|
|
172
|
+
# Environment/.env access is confined to this explicitly enabled branch.
|
|
173
|
+
backend = replace(
|
|
174
|
+
ChatBackend.from_env(), timeout=args.timeout, max_retries=0, max_tokens=args.max_tokens
|
|
175
|
+
)
|
|
176
|
+
runs, signatures, stopped_reason = [], defaultdict(list), None
|
|
177
|
+
for repeat in range(1, args.repeats + 1):
|
|
178
|
+
for case in cases:
|
|
179
|
+
if args.live and runs and args.delay_seconds:
|
|
180
|
+
time.sleep(args.delay_seconds)
|
|
181
|
+
source, expected, errors, abstain = case_frames(case)
|
|
182
|
+
columns = list(case["schema"])
|
|
183
|
+
record = {
|
|
184
|
+
"case": case["id"],
|
|
185
|
+
"domain": case["domain"],
|
|
186
|
+
"operation": case["operation"],
|
|
187
|
+
"repeat": repeat,
|
|
188
|
+
"requests": 0,
|
|
189
|
+
}
|
|
190
|
+
counted = _CountedBackend(backend) if args.live else None
|
|
191
|
+
try:
|
|
192
|
+
if args.live:
|
|
193
|
+
from khipu_weave import LLMDataCleaner
|
|
194
|
+
|
|
195
|
+
cleaner = LLMDataCleaner(
|
|
196
|
+
backend=counted,
|
|
197
|
+
schema=case["schema"],
|
|
198
|
+
operations=(case["operation"],),
|
|
199
|
+
constraints=case.get("constraints"),
|
|
200
|
+
exclude_columns=case.get("exclude_columns"),
|
|
201
|
+
batch_size=len(source),
|
|
202
|
+
cache=False,
|
|
203
|
+
)
|
|
204
|
+
# Only input records/config enter inference; expected/errors never do.
|
|
205
|
+
actual = cleaner.fit_transform(source)
|
|
206
|
+
report = cleaner.report_
|
|
207
|
+
else:
|
|
208
|
+
actual, report = source.copy(deep=True), pd.DataFrame()
|
|
209
|
+
record["evaluation"] = evaluate_cleaning(
|
|
210
|
+
source,
|
|
211
|
+
expected,
|
|
212
|
+
actual,
|
|
213
|
+
report,
|
|
214
|
+
errors=errors,
|
|
215
|
+
abstain_cells=abstain,
|
|
216
|
+
columns=columns,
|
|
217
|
+
schema=case["schema"],
|
|
218
|
+
)
|
|
219
|
+
signatures[case["id"]].append(_signature(actual, report, columns))
|
|
220
|
+
if args.output:
|
|
221
|
+
record["scored_columns"] = columns
|
|
222
|
+
record["cleaned_records"] = json.loads(
|
|
223
|
+
actual[columns].to_json(orient="records", date_format="iso")
|
|
224
|
+
)
|
|
225
|
+
# Audit only selected cells, with no raw prompts, contextual
|
|
226
|
+
# records, excluded targets, evidence text or credentials.
|
|
227
|
+
fields = [
|
|
228
|
+
field
|
|
229
|
+
for field in ("row_position", "column", "status", "proposed", "reason")
|
|
230
|
+
if field in report
|
|
231
|
+
]
|
|
232
|
+
selected = (
|
|
233
|
+
report.loc[report["column"].isin(columns), fields]
|
|
234
|
+
if "column" in report
|
|
235
|
+
else pd.DataFrame()
|
|
236
|
+
)
|
|
237
|
+
findings = json.loads(selected.head(200).to_json(orient="records"))
|
|
238
|
+
for finding in findings:
|
|
239
|
+
if isinstance(finding.get("reason"), str):
|
|
240
|
+
finding["reason"] = finding["reason"][:240]
|
|
241
|
+
record["findings"] = findings
|
|
242
|
+
record["omitted_findings"] = max(0, len(selected) - len(findings))
|
|
243
|
+
except (ValueError, TypeError, RuntimeError) as exc:
|
|
244
|
+
# Provider exception messages are intentionally not logged: configuration
|
|
245
|
+
# and arbitrary third-party exceptions may include sensitive content.
|
|
246
|
+
record["error_type"] = type(exc).__name__
|
|
247
|
+
if "HTTP 429" in str(exc):
|
|
248
|
+
stopped_reason = "provider_rate_limit"
|
|
249
|
+
finally:
|
|
250
|
+
record["requests"] = counted.requests if counted else 0
|
|
251
|
+
runs.append(record)
|
|
252
|
+
if stopped_reason:
|
|
253
|
+
break
|
|
254
|
+
if stopped_reason:
|
|
255
|
+
break
|
|
256
|
+
scored = [run["evaluation"] for run in runs if "evaluation" in run]
|
|
257
|
+
by_pair = defaultdict(list)
|
|
258
|
+
for run in runs:
|
|
259
|
+
if "evaluation" in run:
|
|
260
|
+
by_pair[f"{run['domain']}/{run['operation']}"].append(run["evaluation"])
|
|
261
|
+
result = {
|
|
262
|
+
"mode": "live_model_validation" if args.live else "offline_no_op_baseline",
|
|
263
|
+
"model_validation": bool(args.live),
|
|
264
|
+
"backend": (
|
|
265
|
+
{
|
|
266
|
+
"model": backend.model,
|
|
267
|
+
"timeout_seconds": backend.timeout,
|
|
268
|
+
"max_retries": backend.max_retries,
|
|
269
|
+
"max_tokens": backend.max_tokens,
|
|
270
|
+
"temperature": backend.temperature,
|
|
271
|
+
"json_mode": backend.json_mode,
|
|
272
|
+
}
|
|
273
|
+
if backend is not None
|
|
274
|
+
else None
|
|
275
|
+
),
|
|
276
|
+
"provenance": "Handcrafted synthetic illustrative fixtures; not verified actual datasets.",
|
|
277
|
+
"scope": "Each fixture runs one operation; only editable schema cells enter denominators.",
|
|
278
|
+
"planned_runs": len(cases) * args.repeats,
|
|
279
|
+
"attempted_runs": len(runs),
|
|
280
|
+
"successful_runs": len(scored),
|
|
281
|
+
"failed_runs": len(runs) - len(scored),
|
|
282
|
+
"requests": sum(run["requests"] for run in runs),
|
|
283
|
+
"stopped_reason": stopped_reason,
|
|
284
|
+
"runs": runs,
|
|
285
|
+
"aggregate": aggregate_evaluations(scored),
|
|
286
|
+
"by_domain": _group(runs, "domain"),
|
|
287
|
+
"by_operation": _group(runs, "operation"),
|
|
288
|
+
"by_domain_operation": {
|
|
289
|
+
key: aggregate_evaluations(values) for key, values in by_pair.items()
|
|
290
|
+
},
|
|
291
|
+
"consistency": [
|
|
292
|
+
{
|
|
293
|
+
"case": case["id"],
|
|
294
|
+
"completed_repeats": len(signatures[case["id"]]),
|
|
295
|
+
"identical_outputs_and_findings": (
|
|
296
|
+
len(set(signatures[case["id"]])) == 1
|
|
297
|
+
if len(signatures[case["id"]]) > 1
|
|
298
|
+
else None
|
|
299
|
+
),
|
|
300
|
+
}
|
|
301
|
+
for case in cases
|
|
302
|
+
],
|
|
303
|
+
}
|
|
304
|
+
output = json.dumps(result, indent=2, allow_nan=False) + "\n"
|
|
305
|
+
if args.output:
|
|
306
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
307
|
+
try:
|
|
308
|
+
with args.output.open("x") as destination:
|
|
309
|
+
destination.write(output)
|
|
310
|
+
except FileExistsError:
|
|
311
|
+
parser.error("Output already exists; choose a new output path")
|
|
312
|
+
print(output, end="")
|
|
313
|
+
return 1 if result["failed_runs"] else 0
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
if __name__ == "__main__":
|
|
317
|
+
raise SystemExit(main())
|