dataforge-07 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dataforge/__init__.py +204 -0
- dataforge/__main__.py +5 -0
- dataforge/agent/__init__.py +16 -0
- dataforge/agent/providers.py +259 -0
- dataforge/agent/scratchpad.py +183 -0
- dataforge/agent/tool_actions.py +343 -0
- dataforge/bench/__init__.py +31 -0
- dataforge/bench/core.py +426 -0
- dataforge/bench/groq_client.py +386 -0
- dataforge/bench/methods.py +443 -0
- dataforge/bench/report.py +309 -0
- dataforge/bench/runner.py +247 -0
- dataforge/causal/__init__.py +21 -0
- dataforge/causal/dag.py +174 -0
- dataforge/causal/pc.py +232 -0
- dataforge/causal/root_cause.py +193 -0
- dataforge/cli/__init__.py +50 -0
- dataforge/cli/audit.py +70 -0
- dataforge/cli/bench.py +154 -0
- dataforge/cli/common.py +267 -0
- dataforge/cli/constraints.py +407 -0
- dataforge/cli/profile.py +147 -0
- dataforge/cli/release.py +166 -0
- dataforge/cli/repair.py +407 -0
- dataforge/cli/revert.py +139 -0
- dataforge/cli/watch.py +144 -0
- dataforge/datasets/__init__.py +25 -0
- dataforge/datasets/embedded/hospital/clean.csv +11 -0
- dataforge/datasets/embedded/hospital/dirty.csv +11 -0
- dataforge/datasets/real_world.py +290 -0
- dataforge/datasets/registry.py +103 -0
- dataforge/detectors/__init__.py +80 -0
- dataforge/detectors/base.py +145 -0
- dataforge/detectors/decimal_shift.py +166 -0
- dataforge/detectors/fd_violation.py +157 -0
- dataforge/detectors/type_mismatch.py +173 -0
- dataforge/engine/__init__.py +39 -0
- dataforge/engine/repair.py +905 -0
- dataforge/env/__init__.py +22 -0
- dataforge/env/environment.py +883 -0
- dataforge/env/observation.py +61 -0
- dataforge/env/openenv_core.py +161 -0
- dataforge/env/reward.py +128 -0
- dataforge/env/server.py +176 -0
- dataforge/evaluation_contract.py +76 -0
- dataforge/fixtures/hospital_10rows.csv +11 -0
- dataforge/fixtures/hospital_schema.yaml +17 -0
- dataforge/http/__init__.py +1 -0
- dataforge/http/problem.py +103 -0
- dataforge/integrations/__init__.py +1 -0
- dataforge/integrations/dbt.py +164 -0
- dataforge/observability.py +76 -0
- dataforge/py.typed +1 -0
- dataforge/release/__init__.py +1 -0
- dataforge/release/doctor.py +367 -0
- dataforge/release/full_vision.py +702 -0
- dataforge/release/gate.py +861 -0
- dataforge/release/playground_check.py +411 -0
- dataforge/repair_contract.py +468 -0
- dataforge/repairers/__init__.py +88 -0
- dataforge/repairers/base.py +77 -0
- dataforge/repairers/decimal_shift.py +43 -0
- dataforge/repairers/fd_violation.py +225 -0
- dataforge/repairers/type_mismatch.py +73 -0
- dataforge/safety/__init__.py +5 -0
- dataforge/safety/adversarial/attack_01_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_02_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_03_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_04_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_05_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_06_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_07_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_08_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_09_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_10_phone_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_11_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_12_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_13_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_14_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_15_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_16_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_17_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_18_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_19_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_20_ssn_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_21_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_22_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_23_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_24_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_25_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_26_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_27_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_28_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_29_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_30_email_pii.yaml +8 -0
- dataforge/safety/adversarial/attack_31_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_32_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_33_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_34_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_35_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_36_row_delete.yaml +11 -0
- dataforge/safety/adversarial/attack_37_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_38_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_39_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_40_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_41_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_42_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_43_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_44_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_45_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_46_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_47_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_48_row_delete.yaml +7 -0
- dataforge/safety/adversarial/attack_49_row_delete.yaml +8 -0
- dataforge/safety/adversarial/attack_50_row_delete.yaml +7 -0
- dataforge/safety/constitution.py +307 -0
- dataforge/safety/constitutions/default.yaml +40 -0
- dataforge/safety/filter.py +134 -0
- dataforge/schema_inference.py +620 -0
- dataforge/stores/__init__.py +46 -0
- dataforge/stores/base.py +73 -0
- dataforge/stores/cloud.py +78 -0
- dataforge/stores/csv.py +94 -0
- dataforge/stores/duckdb.py +313 -0
- dataforge/stores/patch_plan.py +178 -0
- dataforge/stores/registry.py +82 -0
- dataforge/stores/repair.py +121 -0
- dataforge/stores/revert.py +22 -0
- dataforge/stores/sql.py +27 -0
- dataforge/table.py +228 -0
- dataforge/transactions/__init__.py +34 -0
- dataforge/transactions/files.py +96 -0
- dataforge/transactions/log.py +613 -0
- dataforge/transactions/revert.py +102 -0
- dataforge/transactions/txn.py +104 -0
- dataforge/ui/__init__.py +1 -0
- dataforge/ui/profile_view.py +136 -0
- dataforge/ui/repair_diff.py +91 -0
- dataforge/verifier/__init__.py +55 -0
- dataforge/verifier/constraint_ir.py +155 -0
- dataforge/verifier/explain.py +47 -0
- dataforge/verifier/gate.py +5 -0
- dataforge/verifier/schema.py +111 -0
- dataforge/verifier/smt.py +433 -0
- dataforge_07-0.1.0.dist-info/METADATA +436 -0
- dataforge_07-0.1.0.dist-info/RECORD +150 -0
- dataforge_07-0.1.0.dist-info/WHEEL +5 -0
- dataforge_07-0.1.0.dist-info/entry_points.txt +3 -0
- dataforge_07-0.1.0.dist-info/licenses/LICENSE +176 -0
- dataforge_07-0.1.0.dist-info/top_level.txt +1 -0
dataforge/cli/revert.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""CLI subcommand: ``dataforge revert <txn_id>``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Annotated
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.panel import Panel
|
|
12
|
+
|
|
13
|
+
from dataforge.transactions.log import sha256_file, verify_transaction_log
|
|
14
|
+
from dataforge.transactions.revert import TransactionRevertError, revert_transaction
|
|
15
|
+
|
|
16
|
+
_console = Console(stderr=True)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def revert(
|
|
20
|
+
txn_id: Annotated[
|
|
21
|
+
str,
|
|
22
|
+
typer.Argument(help="Transaction identifier to revert."),
|
|
23
|
+
],
|
|
24
|
+
search_root: Annotated[
|
|
25
|
+
Path | None,
|
|
26
|
+
typer.Option(
|
|
27
|
+
"--search-root",
|
|
28
|
+
help="Root directory used to locate the transaction log.",
|
|
29
|
+
exists=True,
|
|
30
|
+
file_okay=False,
|
|
31
|
+
dir_okay=True,
|
|
32
|
+
readable=True,
|
|
33
|
+
),
|
|
34
|
+
] = None,
|
|
35
|
+
json_output: Annotated[
|
|
36
|
+
bool,
|
|
37
|
+
typer.Option("--json", help="Print the revert receipt as JSON."),
|
|
38
|
+
] = False,
|
|
39
|
+
) -> None:
|
|
40
|
+
"""Revert a previously applied DataForge repair transaction."""
|
|
41
|
+
try:
|
|
42
|
+
transaction = revert_transaction(txn_id, search_root=search_root)
|
|
43
|
+
except TransactionRevertError as exc:
|
|
44
|
+
if json_output:
|
|
45
|
+
typer.echo(
|
|
46
|
+
json.dumps(
|
|
47
|
+
{
|
|
48
|
+
"schema_version": "repair_revert_receipt_v1",
|
|
49
|
+
"ok": False,
|
|
50
|
+
"txn_id": txn_id,
|
|
51
|
+
"error": str(exc),
|
|
52
|
+
},
|
|
53
|
+
indent=2,
|
|
54
|
+
sort_keys=True,
|
|
55
|
+
)
|
|
56
|
+
)
|
|
57
|
+
raise typer.Exit(code=1) from exc
|
|
58
|
+
_console.print(Panel(f"[bold red]{exc}[/bold red]", title="Revert Error", style="red"))
|
|
59
|
+
raise typer.Exit(code=1) from exc
|
|
60
|
+
except Exception as exc:
|
|
61
|
+
if json_output:
|
|
62
|
+
typer.echo(
|
|
63
|
+
json.dumps(
|
|
64
|
+
{
|
|
65
|
+
"schema_version": "repair_revert_receipt_v1",
|
|
66
|
+
"ok": False,
|
|
67
|
+
"txn_id": txn_id,
|
|
68
|
+
"error": str(exc),
|
|
69
|
+
},
|
|
70
|
+
indent=2,
|
|
71
|
+
sort_keys=True,
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
raise typer.Exit(code=2) from exc
|
|
75
|
+
_console.print(Panel(f"[bold red]{exc}[/bold red]", title="Revert Error", style="red"))
|
|
76
|
+
raise typer.Exit(code=2) from exc
|
|
77
|
+
|
|
78
|
+
audit_report = verify_transaction_log(txn_id, search_root=search_root)
|
|
79
|
+
if json_output:
|
|
80
|
+
if transaction.source_kind == "table_store":
|
|
81
|
+
typer.echo(
|
|
82
|
+
json.dumps(
|
|
83
|
+
{
|
|
84
|
+
"schema_version": "repair_revert_receipt_v1",
|
|
85
|
+
"ok": True,
|
|
86
|
+
"txn_id": transaction.txn_id,
|
|
87
|
+
"source_kind": transaction.source_kind,
|
|
88
|
+
"backend": transaction.backend,
|
|
89
|
+
"source_path": transaction.source_path,
|
|
90
|
+
"expected_source_sha256": transaction.source_sha256,
|
|
91
|
+
"restored_source_sha256": None,
|
|
92
|
+
"reverted_at": transaction.reverted_at.isoformat()
|
|
93
|
+
if transaction.reverted_at is not None
|
|
94
|
+
else None,
|
|
95
|
+
"audit_verdict": audit_report.verdict.value,
|
|
96
|
+
"revert_event_sha256": audit_report.head_sha256,
|
|
97
|
+
},
|
|
98
|
+
indent=2,
|
|
99
|
+
sort_keys=True,
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
raise typer.Exit(code=0)
|
|
103
|
+
source_path = Path(transaction.source_path)
|
|
104
|
+
typer.echo(
|
|
105
|
+
json.dumps(
|
|
106
|
+
{
|
|
107
|
+
"schema_version": "repair_revert_receipt_v1",
|
|
108
|
+
"ok": True,
|
|
109
|
+
"txn_id": transaction.txn_id,
|
|
110
|
+
"source_path": transaction.source_path,
|
|
111
|
+
"expected_source_sha256": transaction.source_sha256,
|
|
112
|
+
"restored_source_sha256": sha256_file(source_path),
|
|
113
|
+
"reverted_at": transaction.reverted_at.isoformat()
|
|
114
|
+
if transaction.reverted_at is not None
|
|
115
|
+
else None,
|
|
116
|
+
"audit_verdict": audit_report.verdict.value,
|
|
117
|
+
"revert_event_sha256": audit_report.head_sha256,
|
|
118
|
+
},
|
|
119
|
+
indent=2,
|
|
120
|
+
sort_keys=True,
|
|
121
|
+
)
|
|
122
|
+
)
|
|
123
|
+
raise typer.Exit(code=0)
|
|
124
|
+
|
|
125
|
+
title = (
|
|
126
|
+
"Table Store Revert Complete"
|
|
127
|
+
if transaction.source_kind == "table_store"
|
|
128
|
+
else "Revert Complete"
|
|
129
|
+
)
|
|
130
|
+
Console().print(
|
|
131
|
+
Panel(
|
|
132
|
+
(
|
|
133
|
+
f"[green]Source restored successfully.[/green]\n"
|
|
134
|
+
f"Transaction: [bold]{transaction.txn_id}[/bold]"
|
|
135
|
+
),
|
|
136
|
+
title=title,
|
|
137
|
+
style="green",
|
|
138
|
+
)
|
|
139
|
+
)
|
dataforge/cli/watch.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""CLI subcommand: ``dataforge watch``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated, Literal
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.panel import Panel
|
|
13
|
+
|
|
14
|
+
from dataforge.cli.common import load_schema, read_csv, resolve_cli_path
|
|
15
|
+
from dataforge.detectors import run_all_detectors
|
|
16
|
+
from dataforge.detectors.base import Schema
|
|
17
|
+
from dataforge.ui.profile_view import render_profile_table
|
|
18
|
+
from dataforge.ui.repair_diff import render_repair_diff
|
|
19
|
+
|
|
20
|
+
_console = Console(stderr=True)
|
|
21
|
+
|
|
22
|
+
WatchAction = Literal["profile", "repair"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _load_optional_schema(schema_path: Path | None) -> Schema | None:
|
|
26
|
+
if schema_path is None:
|
|
27
|
+
return None
|
|
28
|
+
resolved_schema = resolve_cli_path(schema_path)
|
|
29
|
+
if not resolved_schema.exists():
|
|
30
|
+
raise typer.BadParameter(f"Schema file '{schema_path}' does not exist.")
|
|
31
|
+
return load_schema(resolved_schema)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _profile_once(path: Path, schema: Schema | None, json_output: bool) -> None:
|
|
35
|
+
df = read_csv(path)
|
|
36
|
+
issues = run_all_detectors(df, schema)
|
|
37
|
+
if json_output:
|
|
38
|
+
typer.echo(
|
|
39
|
+
json.dumps(
|
|
40
|
+
{
|
|
41
|
+
"event": "profile",
|
|
42
|
+
"path": str(path),
|
|
43
|
+
"issues_count": len(issues),
|
|
44
|
+
"issues": [issue.model_dump(mode="json") for issue in issues],
|
|
45
|
+
},
|
|
46
|
+
indent=2,
|
|
47
|
+
sort_keys=True,
|
|
48
|
+
)
|
|
49
|
+
)
|
|
50
|
+
return
|
|
51
|
+
render_profile_table(issues, Console(), file_path=str(path))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _repair_once(path: Path, schema: Schema | None, apply: bool, json_output: bool) -> None:
|
|
55
|
+
from dataforge.engine.repair import RepairPipelineRequest, run_repair_pipeline
|
|
56
|
+
|
|
57
|
+
result = run_repair_pipeline(
|
|
58
|
+
RepairPipelineRequest(
|
|
59
|
+
source_path=path,
|
|
60
|
+
mode="apply" if apply else "dry_run",
|
|
61
|
+
schema=schema,
|
|
62
|
+
interactive=False,
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
if json_output:
|
|
66
|
+
payload = result.model_dump(mode="json")
|
|
67
|
+
payload["event"] = "repair"
|
|
68
|
+
typer.echo(json.dumps(payload, indent=2, sort_keys=True))
|
|
69
|
+
return
|
|
70
|
+
render_repair_diff(result.fixes, Console(), file_path=str(path))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _run_once(
|
|
74
|
+
path: Path, schema: Schema | None, action: WatchAction, apply: bool, json: bool
|
|
75
|
+
) -> None:
|
|
76
|
+
if action == "repair":
|
|
77
|
+
_repair_once(path, schema, apply, json)
|
|
78
|
+
else:
|
|
79
|
+
_profile_once(path, schema, json)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def watch(
|
|
83
|
+
path: Annotated[
|
|
84
|
+
Path,
|
|
85
|
+
typer.Argument(help="CSV or dbt artifact path to watch."),
|
|
86
|
+
],
|
|
87
|
+
schema: Annotated[
|
|
88
|
+
Path | None,
|
|
89
|
+
typer.Option("--schema", help="Path to a YAML schema file with column types and FDs."),
|
|
90
|
+
] = None,
|
|
91
|
+
action: Annotated[
|
|
92
|
+
WatchAction,
|
|
93
|
+
typer.Option("--action", help="Action to run when the file changes: profile or repair."),
|
|
94
|
+
] = "profile",
|
|
95
|
+
apply: Annotated[
|
|
96
|
+
bool,
|
|
97
|
+
typer.Option("--apply", help="Apply repairs on change. Defaults to dry-run repair."),
|
|
98
|
+
] = False,
|
|
99
|
+
interval: Annotated[
|
|
100
|
+
float,
|
|
101
|
+
typer.Option("--interval", min=0.1, help="Polling interval in seconds."),
|
|
102
|
+
] = 2.0,
|
|
103
|
+
once: Annotated[
|
|
104
|
+
bool,
|
|
105
|
+
typer.Option("--once", help="Run once and exit, useful for CI acceptance."),
|
|
106
|
+
] = False,
|
|
107
|
+
json_output: Annotated[
|
|
108
|
+
bool,
|
|
109
|
+
typer.Option("--json", help="Print watch events as JSON."),
|
|
110
|
+
] = False,
|
|
111
|
+
) -> None:
|
|
112
|
+
"""Poll a path and rerun profile or repair when it changes."""
|
|
113
|
+
resolved_path = resolve_cli_path(path)
|
|
114
|
+
if not resolved_path.exists():
|
|
115
|
+
_console.print(f"[bold red]Watch path not found:[/bold red] {path}")
|
|
116
|
+
raise typer.Exit(code=2)
|
|
117
|
+
parsed_schema = _load_optional_schema(schema)
|
|
118
|
+
|
|
119
|
+
if apply and action != "repair":
|
|
120
|
+
_console.print(
|
|
121
|
+
Panel(
|
|
122
|
+
"--apply is only valid with --action repair.",
|
|
123
|
+
title="Watch Error",
|
|
124
|
+
style="red",
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
raise typer.Exit(code=2)
|
|
128
|
+
|
|
129
|
+
_run_once(resolved_path, parsed_schema, action, apply, json_output)
|
|
130
|
+
if once:
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
last_mtime = resolved_path.stat().st_mtime_ns
|
|
134
|
+
while True:
|
|
135
|
+
time.sleep(interval)
|
|
136
|
+
try:
|
|
137
|
+
current_mtime = resolved_path.stat().st_mtime_ns
|
|
138
|
+
except FileNotFoundError:
|
|
139
|
+
_console.print(f"[bold red]Watch path disappeared:[/bold red] {resolved_path}")
|
|
140
|
+
raise typer.Exit(code=2) from None
|
|
141
|
+
if current_mtime == last_mtime:
|
|
142
|
+
continue
|
|
143
|
+
last_mtime = current_mtime
|
|
144
|
+
_run_once(resolved_path, parsed_schema, action, apply, json_output)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Dataset loading helpers for DataForge."""
|
|
2
|
+
|
|
3
|
+
from dataforge.datasets.real_world import (
|
|
4
|
+
DatasetDownloadError,
|
|
5
|
+
GroundTruthCell,
|
|
6
|
+
RealWorldDataset,
|
|
7
|
+
load_real_world_dataset,
|
|
8
|
+
)
|
|
9
|
+
from dataforge.datasets.registry import (
|
|
10
|
+
DATASET_REGISTRY,
|
|
11
|
+
DatasetMetadata,
|
|
12
|
+
HeaderMismatch,
|
|
13
|
+
get_dataset_metadata,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DATASET_REGISTRY",
|
|
18
|
+
"DatasetDownloadError",
|
|
19
|
+
"DatasetMetadata",
|
|
20
|
+
"GroundTruthCell",
|
|
21
|
+
"HeaderMismatch",
|
|
22
|
+
"RealWorldDataset",
|
|
23
|
+
"get_dataset_metadata",
|
|
24
|
+
"load_real_world_dataset",
|
|
25
|
+
]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
id,age,admission_date,name
|
|
2
|
+
1,30,2020-01-01,Alice
|
|
3
|
+
2,45,2020-01-02,Bob
|
|
4
|
+
3,30,2020-01-03,Carol
|
|
5
|
+
4,29,2020-01-04,Dave
|
|
6
|
+
5,35,2020-01-05,Eve
|
|
7
|
+
6,51,2020-01-06,Frank
|
|
8
|
+
7,40,2020-01-07,Grace
|
|
9
|
+
8,35,2020-01-08,Heidi
|
|
10
|
+
9,28,2020-01-09,Ivan
|
|
11
|
+
10,60,2020-01-10,Judy
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
id,age,admission_date,name
|
|
2
|
+
1,30,2020-01-01,Alice
|
|
3
|
+
2,45,2020-01-02,Bob
|
|
4
|
+
3,N/A,2020-01-03,Carol
|
|
5
|
+
4,29,2020-01-04,Dave
|
|
6
|
+
5,null,2020-01-05,Eve
|
|
7
|
+
6,51,2020-01-06,Frank
|
|
8
|
+
7,40,2020-01-07,Grace
|
|
9
|
+
8,35,2020-01-08,Heidi
|
|
10
|
+
9,28,2020-01-09,Ivan
|
|
11
|
+
10,60,2020-01-10,Judy
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""Download, cache, and align real-world benchmark datasets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
import pandas as pd
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
from dataforge.datasets.registry import DatasetMetadata, HeaderMismatch, get_dataset_metadata
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DatasetDownloadError(RuntimeError):
|
|
19
|
+
"""Raised when a real-world dataset cannot be downloaded or loaded from cache."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_LOGGER = logging.getLogger("dataforge.datasets.real_world")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class GroundTruthCell(BaseModel):
|
|
26
|
+
"""Single cell-level dirty-to-clean correction used for benchmark scoring."""
|
|
27
|
+
|
|
28
|
+
row: int = Field(ge=0)
|
|
29
|
+
column: str = Field(min_length=1)
|
|
30
|
+
dirty_value: str
|
|
31
|
+
clean_value: str
|
|
32
|
+
|
|
33
|
+
model_config = {"frozen": True}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, kw_only=True)
|
|
37
|
+
class RealWorldDataset:
|
|
38
|
+
"""Loaded real-world dataset with aligned dirty/clean DataFrames."""
|
|
39
|
+
|
|
40
|
+
metadata: DatasetMetadata
|
|
41
|
+
dirty_df: pd.DataFrame
|
|
42
|
+
clean_df: pd.DataFrame
|
|
43
|
+
canonical_columns: tuple[str, ...]
|
|
44
|
+
ground_truth: tuple[GroundTruthCell, ...]
|
|
45
|
+
dirty_sha256: str
|
|
46
|
+
clean_sha256: str
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _resolve_cache_root(cache_root: Path | None) -> Path:
|
|
50
|
+
"""Resolve the root benchmark cache directory."""
|
|
51
|
+
if cache_root is not None:
|
|
52
|
+
return cache_root
|
|
53
|
+
return Path.home() / ".dataforge" / "cache"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _dataset_cache_dir(dataset_name: str, *, cache_root: Path | None) -> Path:
|
|
57
|
+
"""Return the cache directory for one dataset."""
|
|
58
|
+
return _resolve_cache_root(cache_root) / "real_world" / dataset_name
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _read_cached_csv(path: Path) -> pd.DataFrame:
|
|
62
|
+
"""Read a cached CSV using string-preserving defaults."""
|
|
63
|
+
return pd.read_csv(path, dtype=str, keep_default_na=False, na_filter=False)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _sha256_file(path: Path) -> str:
|
|
67
|
+
"""Return the SHA-256 digest for a cached artifact."""
|
|
68
|
+
digest = hashlib.sha256()
|
|
69
|
+
with path.open("rb") as handle:
|
|
70
|
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
71
|
+
digest.update(chunk)
|
|
72
|
+
return digest.hexdigest()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _download_bytes(url: str) -> bytes:
|
|
76
|
+
"""Download raw CSV bytes from an upstream source URL."""
|
|
77
|
+
try:
|
|
78
|
+
timeout = float(os.environ.get("DATAFORGE_DOWNLOAD_TIMEOUT_S", "5"))
|
|
79
|
+
except ValueError:
|
|
80
|
+
timeout = 5.0
|
|
81
|
+
with httpx.Client(timeout=timeout, follow_redirects=True) as client:
|
|
82
|
+
response = client.get(url)
|
|
83
|
+
response.raise_for_status()
|
|
84
|
+
return response.content
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _download_to_cache(metadata: DatasetMetadata, dataset_dir: Path) -> None:
|
|
88
|
+
"""Download dirty/clean CSV files into the dataset cache directory."""
|
|
89
|
+
dataset_dir.mkdir(parents=True, exist_ok=True)
|
|
90
|
+
dirty_url, clean_url = metadata.source_urls
|
|
91
|
+
_LOGGER.info("dataset_download_start name=%s dir=%s", metadata.name, dataset_dir)
|
|
92
|
+
(dataset_dir / "dirty.csv").write_bytes(_download_bytes(dirty_url))
|
|
93
|
+
(dataset_dir / "clean.csv").write_bytes(_download_bytes(clean_url))
|
|
94
|
+
_LOGGER.info("dataset_download_complete name=%s dir=%s", metadata.name, dataset_dir)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _validate_cached_hashes(
|
|
98
|
+
*,
|
|
99
|
+
metadata: DatasetMetadata,
|
|
100
|
+
dirty_path: Path,
|
|
101
|
+
clean_path: Path,
|
|
102
|
+
) -> tuple[str, str]:
|
|
103
|
+
"""Verify cached bytes match the pinned upstream source metadata."""
|
|
104
|
+
dirty_sha256 = _sha256_file(dirty_path)
|
|
105
|
+
clean_sha256 = _sha256_file(clean_path)
|
|
106
|
+
mismatches: list[str] = []
|
|
107
|
+
if dirty_sha256 != metadata.dirty_sha256:
|
|
108
|
+
mismatches.append(
|
|
109
|
+
f"dirty.csv sha256 mismatch: expected {metadata.dirty_sha256}, got {dirty_sha256}"
|
|
110
|
+
)
|
|
111
|
+
if clean_sha256 != metadata.clean_sha256:
|
|
112
|
+
mismatches.append(
|
|
113
|
+
f"clean.csv sha256 mismatch: expected {metadata.clean_sha256}, got {clean_sha256}"
|
|
114
|
+
)
|
|
115
|
+
if mismatches:
|
|
116
|
+
raise DatasetDownloadError(
|
|
117
|
+
f"Cached dataset '{metadata.name}' does not match pinned Raha source "
|
|
118
|
+
f"{metadata.source_revision}: "
|
|
119
|
+
+ "; ".join(mismatches)
|
|
120
|
+
+ f". Remove '{dirty_path.parent}' or rerun with a clean --cache-root."
|
|
121
|
+
)
|
|
122
|
+
return dirty_sha256, clean_sha256
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _load_embedded_dataset(name: str) -> tuple[pd.DataFrame, pd.DataFrame, str, str] | None:
|
|
126
|
+
root = Path(__file__).parent / "embedded" / name
|
|
127
|
+
dirty_path = root / "dirty.csv"
|
|
128
|
+
clean_path = root / "clean.csv"
|
|
129
|
+
if not dirty_path.exists() or not clean_path.exists():
|
|
130
|
+
return None
|
|
131
|
+
return (
|
|
132
|
+
_read_cached_csv(dirty_path),
|
|
133
|
+
_read_cached_csv(clean_path),
|
|
134
|
+
_sha256_file(dirty_path),
|
|
135
|
+
_sha256_file(clean_path),
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _manual_download_message(metadata: DatasetMetadata, dataset_dir: Path, cause: Exception) -> str:
|
|
140
|
+
"""Build a user-facing manual download error message."""
|
|
141
|
+
dirty_url, clean_url = metadata.source_urls
|
|
142
|
+
return (
|
|
143
|
+
f"Could not download dataset '{metadata.name}' and no cached copy was found.\n\n"
|
|
144
|
+
f"Cause: {cause}\n"
|
|
145
|
+
f"Cache target: {dataset_dir}\n"
|
|
146
|
+
f"Dirty URL: {dirty_url}\n"
|
|
147
|
+
f"Clean URL: {clean_url}\n\n"
|
|
148
|
+
"How to download manually:\n"
|
|
149
|
+
f"1. Download both CSV files from the URLs above into '{dataset_dir}'.\n"
|
|
150
|
+
"2. Save them exactly as 'dirty.csv' and 'clean.csv', then rerun the benchmark."
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _header_mismatches(
|
|
155
|
+
dirty_columns: list[str], clean_columns: list[str]
|
|
156
|
+
) -> tuple[HeaderMismatch, ...]:
|
|
157
|
+
"""Collect header-name mismatches across aligned dirty/clean columns."""
|
|
158
|
+
mismatches: list[HeaderMismatch] = []
|
|
159
|
+
for dirty_name, clean_name in zip(dirty_columns, clean_columns, strict=True):
|
|
160
|
+
if dirty_name != clean_name:
|
|
161
|
+
mismatches.append(HeaderMismatch(dirty_name=dirty_name, clean_name=clean_name))
|
|
162
|
+
return tuple(mismatches)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _compute_ground_truth(
|
|
166
|
+
dirty_df: pd.DataFrame,
|
|
167
|
+
clean_df: pd.DataFrame,
|
|
168
|
+
) -> tuple[GroundTruthCell, ...]:
|
|
169
|
+
"""Compute cell-level dirty-to-clean diffs across aligned DataFrames."""
|
|
170
|
+
ground_truth: list[GroundTruthCell] = []
|
|
171
|
+
for row_index, (dirty_row, clean_row) in enumerate(
|
|
172
|
+
zip(
|
|
173
|
+
dirty_df.itertuples(index=False, name=None),
|
|
174
|
+
clean_df.itertuples(index=False, name=None),
|
|
175
|
+
strict=True,
|
|
176
|
+
)
|
|
177
|
+
):
|
|
178
|
+
for column, dirty_value, clean_value in zip(
|
|
179
|
+
clean_df.columns,
|
|
180
|
+
dirty_row,
|
|
181
|
+
clean_row,
|
|
182
|
+
strict=True,
|
|
183
|
+
):
|
|
184
|
+
dirty_text = str(dirty_value)
|
|
185
|
+
clean_text = str(clean_value)
|
|
186
|
+
if dirty_text != clean_text:
|
|
187
|
+
ground_truth.append(
|
|
188
|
+
GroundTruthCell(
|
|
189
|
+
row=row_index,
|
|
190
|
+
column=str(column),
|
|
191
|
+
dirty_value=dirty_text,
|
|
192
|
+
clean_value=clean_text,
|
|
193
|
+
)
|
|
194
|
+
)
|
|
195
|
+
return tuple(ground_truth)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def load_real_world_dataset(
|
|
199
|
+
name: str,
|
|
200
|
+
*,
|
|
201
|
+
cache_root: Path | None = None,
|
|
202
|
+
verify_hashes: bool = True,
|
|
203
|
+
allow_embedded_fallback: bool = False,
|
|
204
|
+
) -> RealWorldDataset:
|
|
205
|
+
"""Load a real-world benchmark dataset from cache or upstream.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
name: Canonical dataset name.
|
|
209
|
+
cache_root: Optional cache root override, mainly for tests.
|
|
210
|
+
verify_hashes: Verify cached/downloaded bytes against pinned upstream hashes.
|
|
211
|
+
allow_embedded_fallback: Allow tiny bundled fixture data when the canonical
|
|
212
|
+
upstream dataset cannot be downloaded. This is intended for local tests only.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
The aligned dirty/clean dataset bundle.
|
|
216
|
+
|
|
217
|
+
Raises:
|
|
218
|
+
DatasetDownloadError: If the dataset is not cached and download fails.
|
|
219
|
+
ValueError: If dirty/clean files disagree on row or column count.
|
|
220
|
+
"""
|
|
221
|
+
metadata = get_dataset_metadata(name)
|
|
222
|
+
dataset_dir = _dataset_cache_dir(name, cache_root=cache_root)
|
|
223
|
+
dirty_path = dataset_dir / "dirty.csv"
|
|
224
|
+
clean_path = dataset_dir / "clean.csv"
|
|
225
|
+
|
|
226
|
+
dirty_df: pd.DataFrame | None = None
|
|
227
|
+
clean_df: pd.DataFrame | None = None
|
|
228
|
+
dirty_sha256: str | None = None
|
|
229
|
+
clean_sha256: str | None = None
|
|
230
|
+
|
|
231
|
+
if not dirty_path.exists() or not clean_path.exists():
|
|
232
|
+
_LOGGER.info("dataset_cache_miss name=%s dir=%s", name, dataset_dir)
|
|
233
|
+
try:
|
|
234
|
+
_download_to_cache(metadata, dataset_dir)
|
|
235
|
+
except Exception as exc: # pragma: no cover - exercised through tests via monkeypatch
|
|
236
|
+
fallback = _load_embedded_dataset(name) if allow_embedded_fallback else None
|
|
237
|
+
if fallback is None:
|
|
238
|
+
raise DatasetDownloadError(
|
|
239
|
+
_manual_download_message(metadata, dataset_dir, exc)
|
|
240
|
+
) from exc
|
|
241
|
+
dirty_df, clean_df, dirty_sha256, clean_sha256 = fallback
|
|
242
|
+
else:
|
|
243
|
+
_LOGGER.info("dataset_cache_hit name=%s dir=%s", name, dataset_dir)
|
|
244
|
+
|
|
245
|
+
if dirty_df is None or clean_df is None:
|
|
246
|
+
if verify_hashes:
|
|
247
|
+
dirty_sha256, clean_sha256 = _validate_cached_hashes(
|
|
248
|
+
metadata=metadata,
|
|
249
|
+
dirty_path=dirty_path,
|
|
250
|
+
clean_path=clean_path,
|
|
251
|
+
)
|
|
252
|
+
else:
|
|
253
|
+
dirty_sha256 = _sha256_file(dirty_path)
|
|
254
|
+
clean_sha256 = _sha256_file(clean_path)
|
|
255
|
+
dirty_df = _read_cached_csv(dirty_path)
|
|
256
|
+
clean_df = _read_cached_csv(clean_path)
|
|
257
|
+
elif dirty_sha256 is None or clean_sha256 is None:
|
|
258
|
+
raise DatasetDownloadError(f"Dataset '{name}' loaded without artifact hashes.")
|
|
259
|
+
|
|
260
|
+
if len(dirty_df.index) != len(clean_df.index):
|
|
261
|
+
raise ValueError(f"Dataset '{name}' dirty/clean row counts do not match.")
|
|
262
|
+
if len(dirty_df.columns) != len(clean_df.columns):
|
|
263
|
+
raise ValueError(f"Dataset '{name}' dirty/clean column counts do not match.")
|
|
264
|
+
|
|
265
|
+
clean_columns = [str(column) for column in clean_df.columns]
|
|
266
|
+
mismatches = _header_mismatches(
|
|
267
|
+
[str(column) for column in dirty_df.columns],
|
|
268
|
+
clean_columns,
|
|
269
|
+
)
|
|
270
|
+
dirty_df.columns = clean_columns
|
|
271
|
+
clean_df.columns = clean_columns
|
|
272
|
+
|
|
273
|
+
loaded_metadata = metadata.model_copy(
|
|
274
|
+
update={
|
|
275
|
+
"n_rows": len(clean_df.index),
|
|
276
|
+
"n_columns": len(clean_columns),
|
|
277
|
+
"header_mismatches": mismatches,
|
|
278
|
+
}
|
|
279
|
+
)
|
|
280
|
+
if dirty_sha256 is None or clean_sha256 is None:
|
|
281
|
+
raise DatasetDownloadError(f"Dataset '{name}' loaded without artifact hashes.")
|
|
282
|
+
return RealWorldDataset(
|
|
283
|
+
metadata=loaded_metadata,
|
|
284
|
+
dirty_df=dirty_df,
|
|
285
|
+
clean_df=clean_df,
|
|
286
|
+
canonical_columns=tuple(clean_columns),
|
|
287
|
+
ground_truth=_compute_ground_truth(dirty_df, clean_df),
|
|
288
|
+
dirty_sha256=dirty_sha256,
|
|
289
|
+
clean_sha256=clean_sha256,
|
|
290
|
+
)
|