sqllocks-shape-integrations 0.9.1__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.
- shape_integrations/__init__.py +16 -0
- shape_integrations/anonymeter_eval.py +223 -0
- shape_integrations/duckdb_source.py +144 -0
- shape_integrations/evaluate.py +182 -0
- shape_integrations/evaluation.py +83 -0
- shape_integrations/extras.py +38 -0
- shape_integrations/ibis.py +39 -0
- shape_integrations/lineage.py +254 -0
- shape_integrations/manifest_view.py +106 -0
- shape_integrations/mlflow_log.py +227 -0
- shape_integrations/openlineage_events.py +63 -0
- shape_integrations/presidio_detector.py +194 -0
- shape_integrations/schemas/shape-run-facet.json +31 -0
- shape_integrations/sdmetrics_eval.py +109 -0
- shape_integrations/testing.py +89 -0
- sqllocks_shape_integrations-0.9.1.dist-info/METADATA +47 -0
- sqllocks_shape_integrations-0.9.1.dist-info/RECORD +21 -0
- sqllocks_shape_integrations-0.9.1.dist-info/WHEEL +5 -0
- sqllocks_shape_integrations-0.9.1.dist-info/entry_points.txt +10 -0
- sqllocks_shape_integrations-0.9.1.dist-info/licenses/LICENSE +21 -0
- sqllocks_shape_integrations-0.9.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Shape plugin: thin, optional adapters for tools teams already use.
|
|
2
|
+
|
|
3
|
+
* ``shape.commands``: ``lineage`` (OpenLineage), ``mlflow`` (MLflow) and ``evaluate``
|
|
4
|
+
(SDMetrics, Anonymeter).
|
|
5
|
+
* ``shape.detectors``: ``presidio``.
|
|
6
|
+
* ``shape.sources``: ``duckdb``; :func:`shape_integrations.ibis.connect` for notebooks.
|
|
7
|
+
|
|
8
|
+
Importing this package imports none of the third-party libraries; each adapter loads its own
|
|
9
|
+
when it runs, and exits 2 with the pip command when the extra is missing.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from .extras import EXTRAS, MissingExtraError
|
|
13
|
+
|
|
14
|
+
SHAPE_API = "1.0"
|
|
15
|
+
|
|
16
|
+
__all__ = ["EXTRAS", "SHAPE_API", "MissingExtraError"]
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Anonymeter privacy-risk report (imports Anonymeter: needs the ``anonymeter`` extra).
|
|
2
|
+
|
|
3
|
+
Per table: singling out (multivariate queries of up to three columns, fixed seed),
|
|
4
|
+
linkability (the columns split in two halves in table order, ten neighbours at most) and
|
|
5
|
+
inference (each column in turn as the secret, the others as what the attacker knows).
|
|
6
|
+
``n_attacks`` is 500, or fewer when the real or control table has fewer rows.
|
|
7
|
+
|
|
8
|
+
The singling-out *attack* queries are seeded, so its attack rate repeats. Anonymeter does not
|
|
9
|
+
seed its baseline (random-guess) rates or the linkability and inference sampling, so those
|
|
10
|
+
can differ a little between runs.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import warnings
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import pyarrow as pa # type: ignore[import-untyped]
|
|
20
|
+
|
|
21
|
+
from .evaluate import EvaluateInputError
|
|
22
|
+
from .extras import require
|
|
23
|
+
|
|
24
|
+
SHAPE_API = "1.0"
|
|
25
|
+
|
|
26
|
+
N_ATTACKS = 500
|
|
27
|
+
MIN_ROWS = 2
|
|
28
|
+
SEED = 20261003
|
|
29
|
+
ATTEMPTS_PER_ATTACK = 100
|
|
30
|
+
MAX_NEIGHBORS = 10
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _supported(t: pa.DataType) -> bool:
|
|
34
|
+
return not (
|
|
35
|
+
pa.types.is_list(t)
|
|
36
|
+
or pa.types.is_large_list(t)
|
|
37
|
+
or pa.types.is_struct(t)
|
|
38
|
+
or pa.types.is_map(t)
|
|
39
|
+
or pa.types.is_binary(t)
|
|
40
|
+
or pa.types.is_large_binary(t)
|
|
41
|
+
or pa.types.is_fixed_size_binary(t)
|
|
42
|
+
or pa.types.is_null(t)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _rate(r: Any) -> dict[str, float]:
|
|
47
|
+
return {"value": float(r.value), "error": float(r.error)}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _outcome(res: Any, n_attacks: int, notes: list[str]) -> dict[str, Any]:
|
|
51
|
+
risk = res.risk()
|
|
52
|
+
out: dict[str, Any] = {
|
|
53
|
+
"n_attacks": n_attacks,
|
|
54
|
+
"n_success": int(res.n_success),
|
|
55
|
+
"n_baseline": int(res.n_baseline),
|
|
56
|
+
"attack_rate": _rate(res.attack_rate),
|
|
57
|
+
"baseline_rate": _rate(res.baseline_rate),
|
|
58
|
+
"risk": {"value": float(risk.value), "ci": [float(risk.ci[0]), float(risk.ci[1])]},
|
|
59
|
+
}
|
|
60
|
+
if res.control_rate is not None:
|
|
61
|
+
out["n_control"] = int(res.n_control)
|
|
62
|
+
out["control_rate"] = _rate(res.control_rate)
|
|
63
|
+
if notes:
|
|
64
|
+
out["notes"] = notes
|
|
65
|
+
return out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _Notes(logging.Handler):
|
|
69
|
+
def __init__(self) -> None:
|
|
70
|
+
super().__init__(level=logging.WARNING)
|
|
71
|
+
self.messages: list[str] = []
|
|
72
|
+
|
|
73
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
74
|
+
self.messages.append(record.getMessage())
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _collect(run: Any) -> tuple[Any, list[str]]:
|
|
78
|
+
"""Call ``run()`` and return its result with Anonymeter's own warnings as notes."""
|
|
79
|
+
handler = _Notes()
|
|
80
|
+
logger = logging.getLogger("anonymeter")
|
|
81
|
+
logger.addHandler(handler)
|
|
82
|
+
try:
|
|
83
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
84
|
+
warnings.simplefilter("always")
|
|
85
|
+
result = run()
|
|
86
|
+
finally:
|
|
87
|
+
logger.removeHandler(handler)
|
|
88
|
+
notes = [str(w.message) for w in caught if "anonymeter" in str(w.filename)] + handler.messages
|
|
89
|
+
return result, sorted(set(notes))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _table_results(real: Any, synth: Any, control: Any, attacks: list[str]) -> dict[str, Any]:
|
|
93
|
+
from anonymeter.evaluators import (
|
|
94
|
+
InferenceEvaluator,
|
|
95
|
+
LinkabilityEvaluator,
|
|
96
|
+
SinglingOutEvaluator,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
n = min(N_ATTACKS, len(real), len(control))
|
|
100
|
+
cols = list(real.columns)
|
|
101
|
+
out: dict[str, Any] = {"rows": {"real": len(real), "synthetic": len(synth)}}
|
|
102
|
+
if "singling-out" in attacks:
|
|
103
|
+
|
|
104
|
+
def singling() -> Any:
|
|
105
|
+
e = SinglingOutEvaluator(
|
|
106
|
+
ori=real,
|
|
107
|
+
syn=synth,
|
|
108
|
+
control=control,
|
|
109
|
+
n_attacks=n,
|
|
110
|
+
n_cols=min(3, len(cols)),
|
|
111
|
+
seed=SEED,
|
|
112
|
+
max_attempts=ATTEMPTS_PER_ATTACK * n,
|
|
113
|
+
)
|
|
114
|
+
e.evaluate(mode="multivariate")
|
|
115
|
+
return e.results()
|
|
116
|
+
|
|
117
|
+
res, notes = _collect(singling)
|
|
118
|
+
out["singling_out"] = _outcome(res, n, notes)
|
|
119
|
+
if "linkability" in attacks:
|
|
120
|
+
if len(cols) < 2:
|
|
121
|
+
out["linkability"] = {"skipped": "needs at least 2 columns"}
|
|
122
|
+
else:
|
|
123
|
+
half = len(cols) // 2
|
|
124
|
+
|
|
125
|
+
def linkability() -> Any:
|
|
126
|
+
e = LinkabilityEvaluator(
|
|
127
|
+
ori=real,
|
|
128
|
+
syn=synth,
|
|
129
|
+
control=control,
|
|
130
|
+
n_attacks=n,
|
|
131
|
+
aux_cols=(cols[:half], cols[half:]),
|
|
132
|
+
n_neighbors=min(MAX_NEIGHBORS, len(synth)),
|
|
133
|
+
)
|
|
134
|
+
e.evaluate(n_jobs=1)
|
|
135
|
+
return e.results()
|
|
136
|
+
|
|
137
|
+
res, notes = _collect(linkability)
|
|
138
|
+
out["linkability"] = _outcome(res, n, notes)
|
|
139
|
+
if "inference" in attacks:
|
|
140
|
+
if len(cols) < 2:
|
|
141
|
+
out["inference"] = {"skipped": "needs at least 2 columns"}
|
|
142
|
+
else:
|
|
143
|
+
per_secret = {}
|
|
144
|
+
for secret in cols:
|
|
145
|
+
|
|
146
|
+
def inference(secret: str = secret) -> Any:
|
|
147
|
+
e = InferenceEvaluator(
|
|
148
|
+
ori=real,
|
|
149
|
+
syn=synth,
|
|
150
|
+
control=control,
|
|
151
|
+
aux_cols=[c for c in cols if c != secret],
|
|
152
|
+
secret=secret,
|
|
153
|
+
regression=real[secret].dtype.kind == "f",
|
|
154
|
+
n_attacks=n,
|
|
155
|
+
)
|
|
156
|
+
e.evaluate(n_jobs=1)
|
|
157
|
+
return e.results()
|
|
158
|
+
|
|
159
|
+
res, notes = _collect(inference)
|
|
160
|
+
per_secret[secret] = _outcome(res, n, notes)
|
|
161
|
+
out["inference"] = {"secrets": per_secret}
|
|
162
|
+
return out
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def run(
|
|
166
|
+
real: dict[str, pa.Table],
|
|
167
|
+
synth: dict[str, pa.Table],
|
|
168
|
+
control: dict[str, pa.Table],
|
|
169
|
+
attacks: list[str],
|
|
170
|
+
) -> tuple[str, dict[str, Any]]:
|
|
171
|
+
mod = require("anonymeter", "anonymeter", name="Anonymeter")
|
|
172
|
+
from importlib import metadata
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
tool_version = metadata.version("anonymeter")
|
|
176
|
+
except metadata.PackageNotFoundError:
|
|
177
|
+
tool_version = str(getattr(mod, "__version__", "unknown"))
|
|
178
|
+
tables: dict[str, Any] = {}
|
|
179
|
+
skipped: dict[str, list[str]] = {}
|
|
180
|
+
for name in sorted(real):
|
|
181
|
+
keep = [f.name for f in real[name].schema if _supported(f.type)]
|
|
182
|
+
dropped = [c for c in real[name].column_names if c not in keep]
|
|
183
|
+
if dropped:
|
|
184
|
+
skipped[name] = dropped
|
|
185
|
+
if not keep:
|
|
186
|
+
raise EvaluateInputError(f"table {name!r} has no column Anonymeter can evaluate")
|
|
187
|
+
frames = [t[name].select(keep).to_pandas() for t in (real, synth, control)]
|
|
188
|
+
if min(len(frames[0]), len(frames[2])) < MIN_ROWS or len(frames[1]) < 1:
|
|
189
|
+
raise EvaluateInputError(
|
|
190
|
+
f"table {name!r}: Anonymeter needs at least {MIN_ROWS} real and control rows "
|
|
191
|
+
"and one synthetic row"
|
|
192
|
+
)
|
|
193
|
+
try:
|
|
194
|
+
tables[name] = _table_results(frames[0], frames[1], frames[2], attacks)
|
|
195
|
+
except (ValueError, KeyError, TypeError) as exc:
|
|
196
|
+
raise EvaluateInputError(
|
|
197
|
+
f"Anonymeter could not evaluate table {name!r}: {exc}"
|
|
198
|
+
) from None
|
|
199
|
+
return tool_version, {
|
|
200
|
+
"attacks": list(attacks),
|
|
201
|
+
"tables": tables,
|
|
202
|
+
"skipped_columns": skipped,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def summary(results: dict[str, Any]) -> list[str]:
|
|
207
|
+
lines = ["Anonymeter privacy risk (0 is best, 1 is worst)"]
|
|
208
|
+
for table, res in results["tables"].items():
|
|
209
|
+
lines.append(f" {table}")
|
|
210
|
+
for key in ("singling_out", "linkability"):
|
|
211
|
+
if key in res:
|
|
212
|
+
lines.append(f" {key}: {_risk(res[key])}")
|
|
213
|
+
if "inference" in res:
|
|
214
|
+
for secret, r in res["inference"].get("secrets", {}).items():
|
|
215
|
+
lines.append(f" inference of {secret}: {_risk(r)}")
|
|
216
|
+
return lines
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _risk(res: dict[str, Any]) -> str:
|
|
220
|
+
if "skipped" in res:
|
|
221
|
+
return f"skipped ({res['skipped']})"
|
|
222
|
+
lo, hi = res["risk"]["ci"]
|
|
223
|
+
return f"{res['risk']['value']:.3f} (95% CI {lo:.3f} to {hi:.3f})"
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""The ``duckdb`` source (``shape.sources``): ``duckdb://FILE.duckdb?table=T``.
|
|
2
|
+
|
|
3
|
+
Everything between ``duckdb://`` and ``?`` is the file path (``duckdb:///tmp/x.duckdb`` is
|
|
4
|
+
absolute, ``duckdb://data/x.duckdb`` is relative to the working directory). ``table`` is ``T`` or
|
|
5
|
+
``SCHEMA.T``. The only query option is ``table``; any other option, in particular anything that
|
|
6
|
+
could ask for a writable connection, is refused rather than ignored.
|
|
7
|
+
|
|
8
|
+
The connection is always read-only (``read_only=True``), a missing file is an error and is
|
|
9
|
+
never created, and rows come out as Arrow batches (``batch_size`` rows at most, 65,536 by
|
|
10
|
+
default). Table names are quoted as identifiers, never spliced into SQL as text.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import urllib.parse
|
|
16
|
+
from collections.abc import Iterator
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import pyarrow as pa # type: ignore[import-untyped]
|
|
22
|
+
|
|
23
|
+
from .extras import require
|
|
24
|
+
|
|
25
|
+
SHAPE_API = "1.0"
|
|
26
|
+
|
|
27
|
+
SCHEME = "duckdb"
|
|
28
|
+
DEFAULT_BATCH_ROWS = 65536
|
|
29
|
+
_PREFIX = f"{SCHEME}://"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class DuckDbUri:
|
|
34
|
+
path: str
|
|
35
|
+
table: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _is_duckdb(uri: str) -> bool:
|
|
39
|
+
return isinstance(uri, str) and uri.lower().startswith(_PREFIX)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def parse(uri: str) -> DuckDbUri:
|
|
43
|
+
if not _is_duckdb(uri):
|
|
44
|
+
raise ValueError(f"not a duckdb:// URI: {uri!r}")
|
|
45
|
+
rest = uri[len(_PREFIX) :]
|
|
46
|
+
location, _, query = rest.partition("?")
|
|
47
|
+
path = urllib.parse.unquote(location)
|
|
48
|
+
if not path:
|
|
49
|
+
raise ValueError("duckdb:// URI has no file: duckdb://FILE.duckdb?table=T")
|
|
50
|
+
if path.startswith(":memory:") or path == ":memory:":
|
|
51
|
+
raise ValueError("an in-memory DuckDB cannot be opened read-only: name a .duckdb file")
|
|
52
|
+
params = urllib.parse.parse_qs(query, keep_blank_values=True)
|
|
53
|
+
for key in params:
|
|
54
|
+
if key != "table":
|
|
55
|
+
raise ValueError(f"unknown option {key!r} in duckdb:// URI (only 'table' is allowed)")
|
|
56
|
+
tables = params.get("table", [])
|
|
57
|
+
if not tables or not tables[0]:
|
|
58
|
+
raise ValueError("duckdb:// URI needs a table: duckdb://FILE.duckdb?table=T")
|
|
59
|
+
if len(tables) > 1:
|
|
60
|
+
raise ValueError("'table' may be given once in a duckdb:// URI")
|
|
61
|
+
table = tables[0]
|
|
62
|
+
parts = table.split(".")
|
|
63
|
+
if len(parts) > 2 or not all(parts):
|
|
64
|
+
raise ValueError(f"table {table!r} must be 'table' or 'schema.table'")
|
|
65
|
+
return DuckDbUri(path, table)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def quote_table(table: str) -> str:
|
|
69
|
+
"""``T`` or ``S.T`` as quoted SQL identifiers."""
|
|
70
|
+
return ".".join('"' + part.replace('"', '""') + '"' for part in table.split("."))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _connect(target: DuckDbUri) -> Any:
|
|
74
|
+
if not Path(target.path).is_file():
|
|
75
|
+
raise FileNotFoundError(f"DuckDB file not found: {target.path}")
|
|
76
|
+
duckdb = require("duckdb", "ibis", name="DuckDB")
|
|
77
|
+
return duckdb.connect(target.path, read_only=True)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _check_table(con: Any, target: DuckDbUri) -> None:
|
|
81
|
+
parts = target.table.split(".")
|
|
82
|
+
schema, name = (parts[0], parts[1]) if len(parts) == 2 else (None, parts[0])
|
|
83
|
+
rows = con.execute(
|
|
84
|
+
"SELECT table_schema, table_name FROM information_schema.tables "
|
|
85
|
+
"WHERE table_name = ? AND (? IS NULL OR table_schema = ?)",
|
|
86
|
+
[name, schema, schema],
|
|
87
|
+
).fetchall()
|
|
88
|
+
if rows:
|
|
89
|
+
return
|
|
90
|
+
names = [
|
|
91
|
+
f"{s}.{n}" if s != "main" else n
|
|
92
|
+
for s, n in con.execute(
|
|
93
|
+
"SELECT table_schema, table_name FROM information_schema.tables "
|
|
94
|
+
"WHERE table_schema NOT IN ('information_schema', 'pg_catalog') "
|
|
95
|
+
"ORDER BY 1, 2 LIMIT 20"
|
|
96
|
+
).fetchall()
|
|
97
|
+
]
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"no table {target.table!r} in {target.path}"
|
|
100
|
+
+ (f" (tables: {', '.join(names)})" if names else " (it has no tables)")
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _reader(result: Any, batch_size: int) -> Any:
|
|
105
|
+
"""A record-batch reader of a DuckDB result (``to_arrow_reader`` replaced the older name)."""
|
|
106
|
+
method = getattr(result, "to_arrow_reader", None) or result.fetch_record_batch
|
|
107
|
+
return method(batch_size)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class DuckDbSource:
|
|
111
|
+
"""A table of a DuckDB file, read-only, as Arrow batches."""
|
|
112
|
+
|
|
113
|
+
name = "duckdb"
|
|
114
|
+
schemes = (SCHEME,)
|
|
115
|
+
|
|
116
|
+
def can_open(self, uri: str) -> bool:
|
|
117
|
+
return _is_duckdb(uri)
|
|
118
|
+
|
|
119
|
+
def schema(self, uri: str, **options: Any) -> pa.Schema:
|
|
120
|
+
target = parse(uri)
|
|
121
|
+
con = _connect(target)
|
|
122
|
+
try:
|
|
123
|
+
_check_table(con, target)
|
|
124
|
+
reader = con.execute(f"SELECT * FROM {quote_table(target.table)} LIMIT 0")
|
|
125
|
+
schema: pa.Schema = _reader(reader, 1).schema
|
|
126
|
+
return schema
|
|
127
|
+
finally:
|
|
128
|
+
con.close()
|
|
129
|
+
|
|
130
|
+
def read(self, uri: str, **options: Any) -> Iterator[pa.RecordBatch]:
|
|
131
|
+
batch_size = options.get("batch_size", DEFAULT_BATCH_ROWS)
|
|
132
|
+
if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 1:
|
|
133
|
+
raise ValueError(f"batch_size must be a positive integer, got {batch_size!r}")
|
|
134
|
+
target = parse(uri)
|
|
135
|
+
return self._batches(target, batch_size)
|
|
136
|
+
|
|
137
|
+
def _batches(self, target: DuckDbUri, batch_size: int) -> Iterator[pa.RecordBatch]:
|
|
138
|
+
con = _connect(target)
|
|
139
|
+
try:
|
|
140
|
+
_check_table(con, target)
|
|
141
|
+
reader = con.execute(f"SELECT * FROM {quote_table(target.table)}")
|
|
142
|
+
yield from _reader(reader, batch_size)
|
|
143
|
+
finally:
|
|
144
|
+
con.close()
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""``shape evaluate sdmetrics|anonymeter``: informational reports about synthetic data.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
shape evaluate sdmetrics REAL_DIR SYNTH_DIR [--tables a,b] [-o REPORT.json] [--json]
|
|
6
|
+
shape evaluate anonymeter REAL_DIR SYNTH_DIR --control CONTROL_DIR
|
|
7
|
+
[--attacks singling-out,linkability,inference]
|
|
8
|
+
[-o REPORT.json] [--json]
|
|
9
|
+
|
|
10
|
+
Tables are read from the directories as ``shape verify`` reads them (Parquet, CSV and JSONL,
|
|
11
|
+
one table per file, named by the file stem). The report is a ``shape-evaluation`` document.
|
|
12
|
+
Both commands are informational: they exit 0 when the evaluation ran and 2 on bad input (a
|
|
13
|
+
missing directory or table, columns that differ, too few rows, a missing extra). They are not
|
|
14
|
+
gates; no Shape gate or threshold reads them.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import pyarrow as pa # type: ignore[import-untyped]
|
|
24
|
+
|
|
25
|
+
from . import evaluation
|
|
26
|
+
from .extras import MissingExtraError
|
|
27
|
+
|
|
28
|
+
SHAPE_API = "1.0"
|
|
29
|
+
|
|
30
|
+
EXIT_OK = 0
|
|
31
|
+
EXIT_INPUT = 2
|
|
32
|
+
|
|
33
|
+
ATTACKS = ("singling-out", "linkability", "inference")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class EvaluateInputError(ValueError):
|
|
37
|
+
"""The directories, tables or options given to ``shape evaluate`` cannot be evaluated."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load_dir(label: str, path: str) -> dict[str, pa.Table]:
|
|
41
|
+
"""The tables of directory ``path`` (``label`` names it in messages)."""
|
|
42
|
+
from shape.quality.verify import load_tables
|
|
43
|
+
|
|
44
|
+
p = Path(path)
|
|
45
|
+
if not p.is_dir():
|
|
46
|
+
raise EvaluateInputError(f"{label} directory not found: {p}")
|
|
47
|
+
try:
|
|
48
|
+
tables = load_tables(p)
|
|
49
|
+
except (OSError, ValueError, pa.ArrowException) as exc:
|
|
50
|
+
raise EvaluateInputError(f"{label} {p}: {exc}") from None
|
|
51
|
+
if not tables:
|
|
52
|
+
raise EvaluateInputError(f"{label} directory has no Parquet, CSV or JSONL tables: {p}")
|
|
53
|
+
return tables
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def split_names(text: str | None, what: str) -> list[str] | None:
|
|
57
|
+
if text is None:
|
|
58
|
+
return None
|
|
59
|
+
names = [n.strip() for n in text.split(",")]
|
|
60
|
+
if not all(names):
|
|
61
|
+
raise EvaluateInputError(f"{what} must be a comma-separated list without empty names")
|
|
62
|
+
return names
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def select_tables(
|
|
66
|
+
real: dict[str, pa.Table], others: dict[str, dict[str, pa.Table]], wanted: list[str] | None
|
|
67
|
+
) -> list[str]:
|
|
68
|
+
"""The tables to evaluate: ``wanted``, or every table of ``real``. Each must exist in every
|
|
69
|
+
directory of ``others`` with the same column names."""
|
|
70
|
+
names = wanted if wanted is not None else sorted(real)
|
|
71
|
+
if len(set(names)) != len(names):
|
|
72
|
+
raise EvaluateInputError("--tables names a table twice")
|
|
73
|
+
for name in names:
|
|
74
|
+
if name not in real:
|
|
75
|
+
raise EvaluateInputError(
|
|
76
|
+
f"table {name!r} is not in the real directory (has: {', '.join(sorted(real))})"
|
|
77
|
+
)
|
|
78
|
+
for label, tables in others.items():
|
|
79
|
+
if name not in tables:
|
|
80
|
+
raise EvaluateInputError(f"table {name!r} is not in the {label} directory")
|
|
81
|
+
if tables[name].column_names != real[name].column_names and set(
|
|
82
|
+
tables[name].column_names
|
|
83
|
+
) != set(real[name].column_names):
|
|
84
|
+
raise EvaluateInputError(
|
|
85
|
+
f"table {name!r}: the {label} columns differ from the real columns"
|
|
86
|
+
)
|
|
87
|
+
return list(names)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _emit(args: Any, report: dict[str, Any], summary: list[str]) -> None:
|
|
91
|
+
text = evaluation.to_json(report)
|
|
92
|
+
if args.output:
|
|
93
|
+
out = Path(args.output)
|
|
94
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
out.write_text(text, encoding="utf-8")
|
|
96
|
+
if args.json:
|
|
97
|
+
sys.stdout.write(text)
|
|
98
|
+
elif not args.output:
|
|
99
|
+
print("\n".join(summary))
|
|
100
|
+
else:
|
|
101
|
+
print(f"wrote {args.output}")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _fail(message: str) -> int:
|
|
105
|
+
print(f"shape: error: {message}", file=sys.stderr)
|
|
106
|
+
return EXIT_INPUT
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _common(p: Any) -> None:
|
|
110
|
+
p.add_argument("real", metavar="REAL_DIR", help="directory of the real tables")
|
|
111
|
+
p.add_argument("synth", metavar="SYNTH_DIR", help="directory of the synthetic tables")
|
|
112
|
+
p.add_argument("-o", "--output", metavar="REPORT.json", help="write the report here")
|
|
113
|
+
p.add_argument("--json", action="store_true", help="print the report as JSON")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class EvaluateCommand:
|
|
117
|
+
name = "evaluate"
|
|
118
|
+
help = "Evaluate synthetic data with SDMetrics or Anonymeter (informational reports)"
|
|
119
|
+
|
|
120
|
+
def configure(self, parser: Any) -> None:
|
|
121
|
+
sub = parser.add_subparsers(dest="tool", required=True)
|
|
122
|
+
sd = sub.add_parser("sdmetrics", help="SDMetrics quality report", allow_abbrev=False)
|
|
123
|
+
_common(sd)
|
|
124
|
+
sd.add_argument("--tables", metavar="a,b", help="tables to evaluate (default: all)")
|
|
125
|
+
an = sub.add_parser("anonymeter", help="Anonymeter privacy-risk report", allow_abbrev=False)
|
|
126
|
+
_common(an)
|
|
127
|
+
an.add_argument(
|
|
128
|
+
"--control", required=True, metavar="CONTROL_DIR", help="real rows held out of training"
|
|
129
|
+
)
|
|
130
|
+
an.add_argument(
|
|
131
|
+
"--attacks",
|
|
132
|
+
metavar="a,b",
|
|
133
|
+
help=f"attacks to run, from {', '.join(ATTACKS)} (default: all)",
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
def run(self, args: Any) -> int:
|
|
137
|
+
try:
|
|
138
|
+
if args.tool == "sdmetrics":
|
|
139
|
+
return self._sdmetrics(args)
|
|
140
|
+
return self._anonymeter(args)
|
|
141
|
+
except MissingExtraError as exc:
|
|
142
|
+
return _fail(str(exc))
|
|
143
|
+
except (EvaluateInputError, evaluation.EvaluationReportError) as exc:
|
|
144
|
+
return _fail(str(exc))
|
|
145
|
+
|
|
146
|
+
def _sdmetrics(self, args: Any) -> int:
|
|
147
|
+
real = load_dir("real", args.real)
|
|
148
|
+
synth = load_dir("synthetic", args.synth)
|
|
149
|
+
tables = select_tables(real, {"synthetic": synth}, split_names(args.tables, "--tables"))
|
|
150
|
+
from . import sdmetrics_eval
|
|
151
|
+
|
|
152
|
+
version, results = sdmetrics_eval.run(
|
|
153
|
+
{t: real[t] for t in tables}, {t: synth[t] for t in tables}
|
|
154
|
+
)
|
|
155
|
+
report = evaluation.make_report("sdmetrics", version, results)
|
|
156
|
+
_emit(args, report, sdmetrics_eval.summary(report["results"]))
|
|
157
|
+
return EXIT_OK
|
|
158
|
+
|
|
159
|
+
def _anonymeter(self, args: Any) -> int:
|
|
160
|
+
attacks = split_names(args.attacks, "--attacks") or list(ATTACKS)
|
|
161
|
+
unknown = [a for a in attacks if a not in ATTACKS]
|
|
162
|
+
if unknown:
|
|
163
|
+
raise EvaluateInputError(
|
|
164
|
+
f"unknown attack {unknown[0]!r}; choose from {', '.join(ATTACKS)}"
|
|
165
|
+
)
|
|
166
|
+
if len(set(attacks)) != len(attacks):
|
|
167
|
+
raise EvaluateInputError("--attacks names an attack twice")
|
|
168
|
+
real = load_dir("real", args.real)
|
|
169
|
+
synth = load_dir("synthetic", args.synth)
|
|
170
|
+
control = load_dir("control", args.control)
|
|
171
|
+
tables = select_tables(real, {"synthetic": synth, "control": control}, None)
|
|
172
|
+
from . import anonymeter_eval
|
|
173
|
+
|
|
174
|
+
version, results = anonymeter_eval.run(
|
|
175
|
+
{t: real[t] for t in tables},
|
|
176
|
+
{t: synth[t] for t in tables},
|
|
177
|
+
{t: control[t] for t in tables},
|
|
178
|
+
attacks,
|
|
179
|
+
)
|
|
180
|
+
report = evaluation.make_report("anonymeter", version, results)
|
|
181
|
+
_emit(args, report, anonymeter_eval.summary(report["results"]))
|
|
182
|
+
return EXIT_OK
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""The ``shape-evaluation`` report: what ``shape evaluate`` writes (format, version 1).
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
{"format": "shape-evaluation", "version": 1, "tool": "sdmetrics" | "anonymeter",
|
|
6
|
+
"tool_version": "...", "results": {...}}
|
|
7
|
+
|
|
8
|
+
``results`` is the tool's own outcome, in the shape documented in docs/plugins/integrations.md.
|
|
9
|
+
A reader of version 1 refuses a report of a higher version and a report of another format.
|
|
10
|
+
The report holds scores, counts and column names, never row values.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
EVALUATION_FORMAT = "shape-evaluation"
|
|
21
|
+
EVALUATION_VERSION = 1
|
|
22
|
+
TOOLS = ("sdmetrics", "anonymeter")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class EvaluationReportError(ValueError):
|
|
26
|
+
"""A file is not an evaluation report this version can read."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class EvaluationVersionError(EvaluationReportError):
|
|
30
|
+
"""The report was written by a newer Shape."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def clean(value: Any) -> Any:
|
|
34
|
+
"""``value`` as JSON-safe data: NaN and infinity become ``None``, containers are copied."""
|
|
35
|
+
if isinstance(value, float):
|
|
36
|
+
return value if math.isfinite(value) else None
|
|
37
|
+
if isinstance(value, dict):
|
|
38
|
+
return {str(k): clean(v) for k, v in value.items()}
|
|
39
|
+
if isinstance(value, (list, tuple)):
|
|
40
|
+
return [clean(v) for v in value]
|
|
41
|
+
if hasattr(value, "item") and callable(value.item): # a NumPy scalar
|
|
42
|
+
return clean(value.item())
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def make_report(tool: str, tool_version: str, results: dict[str, Any]) -> dict[str, Any]:
|
|
47
|
+
if tool not in TOOLS:
|
|
48
|
+
raise EvaluationReportError(f"unknown tool {tool!r}; known: {', '.join(TOOLS)}")
|
|
49
|
+
return {
|
|
50
|
+
"format": EVALUATION_FORMAT,
|
|
51
|
+
"version": EVALUATION_VERSION,
|
|
52
|
+
"tool": tool,
|
|
53
|
+
"tool_version": tool_version,
|
|
54
|
+
"results": clean(results),
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def to_json(report: dict[str, Any]) -> str:
|
|
59
|
+
return json.dumps(report, indent=2, sort_keys=True, allow_nan=False) + "\n"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_report(path: str | Path) -> dict[str, Any]:
|
|
63
|
+
"""Read and check a report; raises :class:`EvaluationReportError`."""
|
|
64
|
+
p = Path(path)
|
|
65
|
+
try:
|
|
66
|
+
raw = json.loads(p.read_text(encoding="utf-8"))
|
|
67
|
+
except (OSError, ValueError) as exc:
|
|
68
|
+
raise EvaluationReportError(f"{p}: cannot read as JSON: {exc}") from None
|
|
69
|
+
if not isinstance(raw, dict) or raw.get("format") != EVALUATION_FORMAT:
|
|
70
|
+
raise EvaluationReportError(f"{p} is not a {EVALUATION_FORMAT} report")
|
|
71
|
+
version = raw.get("version")
|
|
72
|
+
if isinstance(version, bool) or not isinstance(version, int):
|
|
73
|
+
raise EvaluationReportError(f"{p}: 'version' must be an integer, got {version!r}")
|
|
74
|
+
if version > EVALUATION_VERSION:
|
|
75
|
+
raise EvaluationVersionError(
|
|
76
|
+
f"{p} is {EVALUATION_FORMAT} version {version}, written by a newer Shape; this Shape "
|
|
77
|
+
f"reads versions up to {EVALUATION_VERSION}. Upgrade Shape to read it"
|
|
78
|
+
)
|
|
79
|
+
if raw.get("tool") not in TOOLS:
|
|
80
|
+
raise EvaluationReportError(f"{p}: unknown tool {raw.get('tool')!r}")
|
|
81
|
+
if not isinstance(raw.get("tool_version"), str) or not isinstance(raw.get("results"), dict):
|
|
82
|
+
raise EvaluationReportError(f"{p}: 'tool_version' and 'results' are required")
|
|
83
|
+
return raw
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The optional libraries behind each adapter, and the error when one is missing.
|
|
2
|
+
|
|
3
|
+
Importing :mod:`shape_integrations` imports none of them. An adapter calls :func:`require` when
|
|
4
|
+
it first needs its library; a command turns :class:`MissingExtraError` into exit code 2.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib
|
|
10
|
+
from types import ModuleType
|
|
11
|
+
|
|
12
|
+
EXTRAS = ("openlineage", "mlflow", "presidio", "sdmetrics", "anonymeter", "ibis")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MissingExtraError(ImportError):
|
|
16
|
+
"""An adapter's third-party library is not installed."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, name: str, extra: str) -> None:
|
|
19
|
+
self.name = name
|
|
20
|
+
self.extra = extra
|
|
21
|
+
super().__init__(
|
|
22
|
+
f"{name} needs the '{extra}' extra: pip install 'sqllocks-shape-integrations[{extra}]'"
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def require(module: str, extra: str, *, name: str | None = None) -> ModuleType:
|
|
27
|
+
"""Import ``module`` or raise :class:`MissingExtraError` naming ``extra``.
|
|
28
|
+
|
|
29
|
+
A library that is installed but fails inside its own import (a broken dependency) is not
|
|
30
|
+
reported as missing: that error passes through unchanged.
|
|
31
|
+
"""
|
|
32
|
+
try:
|
|
33
|
+
return importlib.import_module(module)
|
|
34
|
+
except ModuleNotFoundError as exc:
|
|
35
|
+
top = module.split(".")[0]
|
|
36
|
+
if exc.name is not None and exc.name.split(".")[0] != top:
|
|
37
|
+
raise
|
|
38
|
+
raise MissingExtraError(name or top, extra) from None
|