Datasets:
Download generator/engine.py from misatadata/retail-star-answer-key: direct link, hf CLI and curl.
- Browser
- Download file 5.32 kB
-
https://huggingface.co/datasets/misatadata/retail-star-answer-key/resolve/main/generator/engine.py
- Command line
-
hf download hf://datasets/misatadata/retail-star-answer-key/generator/engine.py
-
curl -L -o engine.py https://huggingface.co/datasets/misatadata/retail-star-answer-key/resolve/main/generator/engine.py
5.32 kB
| """Run the Blueprint through the Misata Studio engine and keep what the engine says about its own output.""" | |
| from __future__ import annotations | |
| import json | |
| import time | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import pandas as pd | |
| from . import blueprint as B | |
| class EngineRun: | |
| tables: dict[str, pd.DataFrame] | |
| design: dict[str, Any] | |
| report: dict[str, Any] | |
| clickhouse_ddl: str = "" | |
| DELIVERED = ("stores", "products", "customers", "orders", "order_lines", "returns") | |
| def engine_clickhouse_ddl(bp: Any, tables: dict[str, pd.DataFrame]) -> str: | |
| """The DDL the engine's own ClickHouse export writes for these tables, kept to compare with clickhouse/ddl.sql.""" | |
| import tempfile | |
| from misata_engine.export import ParquetSource, sql_ddl | |
| with tempfile.TemporaryDirectory() as tmp: | |
| for name in DELIVERED: | |
| (Path(tmp) / name).mkdir() | |
| tables[name][[c for c in tables[name].columns if not c.startswith("_")]].to_parquet(Path(tmp) / name / "part-0.parquet") | |
| return sql_ddl(bp, ParquetSource(tmp), "clickhouse") | |
| def _plain(x: Any) -> Any: | |
| """A certificate or finding as JSON: numpy numbers, timestamps and sets made ordinary.""" | |
| return json.loads(json.dumps(x, default=lambda o: o.item() if hasattr(o, "item") else str(o))) | |
| def engine_commit() -> str: | |
| """The Misata Studio commit the engine came from (git, or MISATA_ENGINE_COMMIT for a copy of the tree), whether its | |
| files had changes, and a digest of its source files, which names the engine exactly either way.""" | |
| import hashlib | |
| import os | |
| import subprocess | |
| import misata_engine | |
| here = Path(misata_engine.__file__).resolve().parent | |
| digest = hashlib.sha256() | |
| for f in sorted(here.rglob("*.py")): | |
| digest.update(f.relative_to(here).as_posix().encode() + b"\0" + f.read_bytes()) | |
| files = f"source digest {digest.hexdigest()[:16]}" | |
| try: | |
| sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=here, capture_output=True, text=True, check=True).stdout.strip() | |
| dirty = subprocess.run(["git", "status", "--porcelain", "--", "."], cwd=here, capture_output=True, text=True, check=True).stdout.strip() | |
| return f"{sha}{' with uncommitted engine changes' if dirty else ''}, {files}" | |
| except (OSError, subprocess.CalledProcessError): | |
| return f"{os.environ.get('MISATA_ENGINE_COMMIT', 'commit unknown')}, {files}" | |
| def run(seed: int, scale: float = 1.0) -> EngineRun: | |
| import misata_engine as me | |
| from misata_engine.blueprint.guide import lint, parse | |
| from misata_engine.oracle import scorecard | |
| design = B.build(scale=scale, seed=seed) | |
| bp, problems = parse(design) | |
| if bp is None: | |
| raise SystemExit("the Blueprint does not parse:\n " + "\n ".join(problems)) | |
| started = time.time() | |
| res = me.run("", blueprint=bp, seed=seed) | |
| seconds = round(time.time() - started, 1) | |
| cert = res.certificate or {} | |
| if not res.passed or not cert.get("passed", True): | |
| said = [f.message for f in res.verdict.findings[:20]] + [w["text"] for w in cert.get("withdrawn_claims") or []] | |
| raise SystemExit("the engine did not pass the build:\n " + "\n ".join(said)) | |
| tables = dict(res.tables) | |
| card = scorecard.score({k: v for k, v in tables.items() if k in ("customers", "products", "orders", "order_lines", "returns")}) | |
| report = { | |
| "engine": "misata_engine (Misata Studio)", | |
| "engine_commit": engine_commit(), | |
| "seed": seed, | |
| "scale": scale, | |
| "seconds": seconds, | |
| "passed": bool(res.passed and cert.get("passed", True)), | |
| "lint": [str(w) for w in lint(bp)], | |
| "planned": list(bp.levers.get("_planned") or []), | |
| "notes": [str(n) for n in res.notes], | |
| "findings": [{"severity": str(f.severity), "message": f.message} for f in res.verdict.findings], | |
| "certificate": _plain(res.certificate), | |
| "realism_scorecard": scorecard.render(card), | |
| "rows": {k: len(v) for k, v in tables.items()}, | |
| } | |
| return EngineRun(tables=tables, design=design, report=report, clickhouse_ddl=engine_clickhouse_ddl(bp, tables)) | |
| def score_delivered(parquet_dir: Path) -> str: | |
| """The engine's realism scorecard read on the delivered files, after every step that follows the engine; decimals are | |
| read as numbers.""" | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from misata_engine.oracle import scorecard | |
| tables = {} | |
| for name in ("dim_product", "dim_customer", "dim_store", "orders", "order_lines", "returns"): | |
| t = pq.read_table(parquet_dir / f"{name}.parquet") | |
| cast = pa.schema([pa.field(f.name, pa.float64()) if pa.types.is_decimal(f.type) else f for f in t.schema]) | |
| tables[name] = t.cast(cast).to_pandas() | |
| return scorecard.render(scorecard.score(tables)) | |
| def save_report(er: EngineRun, out: Path) -> None: | |
| out.mkdir(parents=True, exist_ok=True) | |
| (out / "blueprint.json").write_text(json.dumps(er.design, indent=1, ensure_ascii=False)) | |
| (out / "engine_report.json").write_text(json.dumps(er.report, indent=1, ensure_ascii=False)) | |
| (out / "realism_scorecard.txt").write_text(er.report["realism_scorecard"]) | |
| (out / "engine_clickhouse_ddl.sql").write_text(er.clickhouse_ddl) | |