Download source/src/evm_bert/kaggle_data.py from willynilly-fr/evm-positions-scratch-20ep: direct link, hf CLI and curl.
- Browser
- Download file 28.4 kB
-
https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/src/evm_bert/kaggle_data.py
- Command line
-
hf download hf://willynilly-fr/evm-positions-scratch-20ep/source/src/evm_bert/kaggle_data.py
-
curl -L -o kaggle_data.py https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/src/evm_bert/kaggle_data.py
28.4 kB
| """Exact Kaggle account labels linked to independently verified signed transactions. | |
| FLAG belongs to an account. Linking its outgoing transactions creates a weakly | |
| supervised account benchmark, not ground truth transaction fraud annotations. | |
| """ | |
| from __future__ import annotations | |
| from collections import Counter | |
| from concurrent.futures import ThreadPoolExecutor | |
| import csv | |
| from datetime import datetime, timezone | |
| import hashlib | |
| import io | |
| import json | |
| from pathlib import Path | |
| import random | |
| import re | |
| import sys | |
| import time | |
| from typing import Any | |
| import zipfile | |
| from datasets import Dataset, DatasetDict, load_from_disk | |
| import httpx | |
| import pyarrow.parquet as pq | |
| from omegaconf import DictConfig, OmegaConf | |
| from evm_bert.data import ( | |
| DataError, RpcClient, _checksum, _enable_fast_recovery, _integer, _write_jsonl, | |
| load_rows, reconstruct_raw, validate_transaction, | |
| ) | |
| SOURCE_REF = "vagifa/ethereum-frauddetection-dataset" | |
| SOURCE_URL = f"https://www.kaggle.com/datasets/{SOURCE_REF}" | |
| DOWNLOAD_URL = f"https://www.kaggle.com/api/v1/datasets/download/{SOURCE_REF}" | |
| METADATA_URL = "https://www.kaggle.com/api/v1/datasets/list?search=ethereum-frauddetection-dataset" | |
| EXPLORER_URL = "https://eth.blockscout.com" | |
| SOURCE_ZIP_SHA256 = "095c140499eb6c08545306b9f72363d6202d05ab3ac3ec804daf8ff9f484ad46" | |
| SOURCE_CSV_SHA256 = "874e125be2ac6220a92c7dbacf6c6f1766c60e3966473406d6700090831f7d9a" | |
| LABEL_SCOPE = "account_flag_proxy" | |
| def _settings(config: DictConfig | dict[str, Any]) -> dict[str, Any]: | |
| raw = OmegaConf.to_container(config, resolve=True) if isinstance(config, DictConfig) else config | |
| return dict(raw.get("kaggle", raw)) | |
| def _save_json(path: Path, value: Any) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_suffix(path.suffix + ".tmp") | |
| temporary.write_text(json.dumps(value, sort_keys=True, indent=2) + "\n") | |
| temporary.replace(path) | |
| def download_source(source_dir: str | Path) -> dict[str, Any]: | |
| """Fetch the exact official source, pinned by version-one content checksums.""" | |
| output = Path(source_dir) | |
| output.mkdir(parents=True, exist_ok=True) | |
| archive = output / "source.zip" | |
| csv_path = output / "transaction_dataset.csv" | |
| if not archive.exists(): | |
| with httpx.Client(timeout=90, follow_redirects=True) as client: | |
| response = client.get(DOWNLOAD_URL) | |
| response.raise_for_status() | |
| content = response.content | |
| if hashlib.sha256(content).hexdigest() != SOURCE_ZIP_SHA256: | |
| raise DataError("official Kaggle archive differs from pinned version 1") | |
| archive.write_bytes(content) | |
| if _checksum(archive) != SOURCE_ZIP_SHA256: | |
| raise DataError("Kaggle source ZIP checksum mismatch") | |
| with zipfile.ZipFile(io.BytesIO(archive.read_bytes())) as bundle: | |
| if bundle.namelist() != ["transaction_dataset.csv"]: | |
| raise DataError("unexpected Kaggle archive members") | |
| content = bundle.read("transaction_dataset.csv") | |
| if hashlib.sha256(content).hexdigest() != SOURCE_CSV_SHA256: | |
| raise DataError("Kaggle source CSV checksum mismatch") | |
| if csv_path.exists() and csv_path.read_bytes() != content: | |
| raise DataError("existing Kaggle CSV differs from original archive") | |
| csv_path.write_bytes(content) | |
| metadata_path = output / "metadata.json" | |
| if not metadata_path.exists(): | |
| response = httpx.get(METADATA_URL, timeout=30, follow_redirects=True) | |
| response.raise_for_status() | |
| _save_json(metadata_path, response.json()) | |
| metadata_body = json.loads(metadata_path.read_text()) | |
| metadata = next((item for item in metadata_body if item.get("ref") == SOURCE_REF), None) | |
| if metadata is None: | |
| raise DataError("Kaggle metadata does not identify requested source") | |
| return {"ref": SOURCE_REF, "url": SOURCE_URL, "download_url": DOWNLOAD_URL, | |
| "version": 1, "csv_sha256": SOURCE_CSV_SHA256, "zip_sha256": SOURCE_ZIP_SHA256, | |
| "csv_path": str(csv_path), "metadata_sha256": _checksum(metadata_path), | |
| "license": metadata["licenseName"], | |
| "license_url": "https://opendatacommons.org/licenses/odbl/1-0/", | |
| "contents_license_url": "https://opendatacommons.org/licenses/dbcl/1-0/", | |
| "kaggle_last_updated": metadata["lastUpdated"], | |
| "downloaded_at": datetime.now(timezone.utc).isoformat()} | |
| def cutoff_metadata(source_dir: str | Path, before_block: int, published_at: str) -> dict[str, Any]: | |
| """Preserve an indexed block header to timestamp the historical cursor.""" | |
| path = Path(source_dir) / "cutoff_block.json" | |
| url = f"{EXPLORER_URL}/api/v2/blocks/{before_block}" | |
| if not path.exists(): | |
| response = httpx.get(url, timeout=30) | |
| response.raise_for_status() | |
| _save_json(path, response.json()) | |
| block = json.loads(path.read_text()) | |
| if int(block["height"]) != before_block: | |
| raise DataError("cached cutoff header has the wrong block height") | |
| if datetime.fromisoformat(block["timestamp"]) >= datetime.fromisoformat(published_at): | |
| raise DataError("historical transaction cutoff is not before Kaggle publication") | |
| return {"before_block_exclusive": before_block, "block_hash": block["hash"].lower(), | |
| "timestamp": block["timestamp"], "header_source": url, | |
| "header_sha256": _checksum(path), | |
| "rationale": "historical activity before Kaggle January 2021 publication; exact label observation dates unavailable"} | |
| def read_source(csv_path: str | Path) -> tuple[list[dict[str, str]], dict[str, int]]: | |
| """Preserve every source row; reject ambiguous duplicate-account labels.""" | |
| with Path(csv_path).open(newline="") as stream: | |
| rows = list(csv.DictReader(stream)) | |
| labels: dict[str, int] = {} | |
| for row in rows: | |
| account = row["Address"].strip().lower() | |
| if row["FLAG"] not in ("0", "1"): | |
| raise DataError("invalid source FLAG") | |
| if not re.fullmatch(r"0x[0-9a-f]{40}", account): | |
| continue # Original row is preserved in full table, excluded from address linking. | |
| label = int(row["FLAG"]) | |
| if account in labels and labels[account] != label: | |
| raise DataError("conflicting FLAG labels for duplicate source account") | |
| labels[account] = label | |
| return rows, labels | |
| def split_accounts(labels: dict[str, int], seed: int) -> dict[str, str]: | |
| """Stratified 70/15/15 account split before any transaction acquisition.""" | |
| result: dict[str, str] = {} | |
| rng = random.Random(seed) | |
| for label in (0, 1): | |
| addresses = sorted(account for account, target in labels.items() if target == label) | |
| if len(addresses) < 7: | |
| raise DataError("both labels need at least seven distinct accounts") | |
| rng.shuffle(addresses) | |
| train_end = int(len(addresses) * .7) | |
| validation_end = train_end + int(len(addresses) * .15) | |
| for index, account in enumerate(addresses): | |
| result[account] = ("train" if index < train_end else | |
| "validation" if index < validation_end else "test") | |
| return result | |
| def _request_history(account: str, before_block: int, cache: Path) -> dict[str, Any]: | |
| path = cache / "history" / f"{account}.json" | |
| if path.exists(): | |
| body = json.loads(path.read_text()) | |
| if body.get("requested_before_block") != before_block: | |
| raise DataError("history cache cutoff differs from requested cutoff") | |
| return body | |
| url = f"{EXPLORER_URL}/api/v2/addresses/{account}/transactions" | |
| params = {"filter": "from", "block_number": before_block, "index": 0} | |
| for attempt in range(4): | |
| try: | |
| response = httpx.get(url, params=params, timeout=35) | |
| response.raise_for_status() | |
| body = response.json() | |
| if not isinstance(body.get("items"), list): | |
| raise DataError("unexpected Blockscout history response") | |
| body = {"url": url, "params": params, "requested_before_block": before_block, | |
| "fetched_at": datetime.now(timezone.utc).isoformat(), **body} | |
| _save_json(path, body) | |
| return body | |
| except (httpx.HTTPError, ValueError): | |
| if attempt == 3: | |
| raise | |
| time.sleep(.5 * 2**attempt) | |
| raise AssertionError("unreachable") | |
| def _acquire_account(account: str, label: int, split: str, source_row_id: int, | |
| settings: dict[str, Any], cache: Path) -> dict[str, Any]: | |
| """Only transactions actually signed by the labeled account are admissible.""" | |
| before_block = int(settings.get("before_block", 11580000)) | |
| count = int(settings.get("transactions_per_account", 2)) | |
| history = _request_history(account, before_block, cache) | |
| endpoints = list(settings.get("rpc_endpoints", ["https://ethereum-rpc.publicnode.com", | |
| "https://eth.llamarpc.com"])) | |
| rpc = RpcClient(endpoints, 1, float(settings.get("timeout_seconds", 30)), 2) | |
| selected: list[dict[str, Any]] = [] | |
| skipped: list[dict[str, str]] = [] | |
| try: | |
| for item in history["items"]: | |
| tx_hash = item["hash"].lower() | |
| if item["from"]["hash"].lower() != account: | |
| raise DataError("explorer returned a different outgoing signer") | |
| if int(item["block_number"]) >= before_block: | |
| raise DataError("explorer historical cursor admitted a transaction beyond cutoff") | |
| snapshot = cache / "rpc" / f"{tx_hash}.json" | |
| if snapshot.exists(): | |
| source = json.loads(snapshot.read_text()) | |
| else: | |
| tx = rpc.call("eth_getTransactionByHash", [tx_hash]) | |
| source = {"endpoint": rpc.last_endpoint, "transaction": tx, | |
| "fetched_at": datetime.now(timezone.utc).isoformat()} | |
| _save_json(snapshot, source) | |
| tx = source["transaction"] | |
| try: | |
| raw = reconstruct_raw(tx) | |
| details = validate_transaction(tx, raw, 1) | |
| if details["sender"] != account or details["tx_hash"] != tx_hash: | |
| raise DataError("RPC transaction does not belong to labeled account") | |
| if _integer(tx["blockNumber"]) != int(item["block_number"]): | |
| raise DataError("explorer/RPC block number mismatch") | |
| selected.append({**details, "raw_hex": "0x" + raw.hex(), "label": label, | |
| "account": account, "split": split, "kaggle_row_id": source_row_id, | |
| "label_scope": LABEL_SCOPE, "chain": "ethereum", | |
| "block_number": _integer(tx["blockNumber"]), | |
| "block_hash": tx["blockHash"].lower(), | |
| "transaction_index": _integer(tx["transactionIndex"]), | |
| "timestamp": item["timestamp"], | |
| "source_method": "blockscout_outgoing_index+public_rpc_signed_rlp"}) | |
| if len(selected) == count: | |
| break | |
| except DataError as exc: | |
| skipped.append({"tx_hash": tx_hash, "reason": str(exc)}) | |
| finally: | |
| rpc.close() | |
| return {"account": account, "label": label, "split": split, "transactions": selected, | |
| "rejected_transactions": skipped, "history_rows": len(history["items"]), | |
| "reason": None if selected else "no eligible signed historical outgoing transaction in first history page"} | |
| def _export(output: Path, rows: list[dict[str, Any]], filename: str) -> None: | |
| output.mkdir(parents=True, exist_ok=True) | |
| dataset = DatasetDict({name: Dataset.from_list([row for row in rows if row["split"] == name]) | |
| for name in ("train", "validation", "test")}) | |
| dataset.save_to_disk(str(output / "dataset")) | |
| _write_jsonl(output / filename, rows) | |
| (output / "parquet").mkdir(exist_ok=True) | |
| for name, partition in dataset.items(): | |
| partition.to_parquet(str(output / "parquet" / f"{name}.parquet")) | |
| def _overlap(rows: list[dict[str, Any]], pretraining_dir: str) -> dict[str, Any]: | |
| path = Path(pretraining_dir) | |
| if not path.exists(): | |
| raise DataError("pretraining corpus required for benchmark leakage audit") | |
| manifest = json.loads((path / "manifest.json").read_text()) | |
| expected_digest = manifest.get("sha256", {}).get("transactions.jsonl") | |
| if not expected_digest or _checksum(path / "transactions.jsonl") != expected_digest: | |
| raise DataError("pretraining corpus JSONL does not match its manifest checksum") | |
| original = load_rows(path) | |
| if len(original) != manifest["rows"]: | |
| raise DataError("pretraining corpus row count differs from its manifest") | |
| hashes = {row["tx_hash"].lower() for row in original} | |
| senders = {row["sender"].lower() for row in original} | |
| seen_hashes = sorted({row["tx_hash"] for row in rows} & hashes) | |
| if seen_hashes: | |
| raise DataError("benchmark transaction overlaps pretraining corpus") | |
| return {"corpus_path": str(path), "corpus_rows": len(original), | |
| "corpus_manifest_sha256": _checksum(path / "manifest.json"), | |
| "exact_transaction_hash_overlap": len(seen_hashes), | |
| "accounts_seen_as_pretraining_senders": sorted({row["account"] for row in rows} & senders), | |
| "policy": "zero exact transaction overlap; account identity overlap reported"} | |
| def prepare_kaggle(config: DictConfig | dict[str, Any]) -> dict[str, Any]: | |
| """Create full account table and a balanced account-label raw-byte benchmark.""" | |
| settings = _settings(config) | |
| output = Path(settings.get("output_dir", "data/kaggle/transactions")) | |
| if (output / "audit.json").exists(): | |
| return validate_kaggle(config) | |
| source = download_source(settings.get("source_dir", "data/kaggle/source")) | |
| cutoff = cutoff_metadata(settings.get("source_dir", "data/kaggle/source"), | |
| int(settings.get("before_block", 11580000)), | |
| source["kaggle_last_updated"]) | |
| original, labels = read_source(source["csv_path"]) | |
| mapping = split_accounts(labels, int(settings.get("seed", 42))) | |
| row_ids = {row["Address"].strip().lower(): index for index, row in reversed(list(enumerate(original)))} | |
| target = int(settings.get("accounts_per_class", 250)) | |
| if target < 10: | |
| raise DataError("at least ten accounts per class required") | |
| quotas = {"train": int(target * .7), "validation": int(target * .15)} | |
| quotas["test"] = target - sum(quotas.values()) | |
| cache = output / "acquisition_cache" | |
| selected: list[dict[str, Any]] = [] | |
| attempts: list[dict[str, Any]] = [] | |
| _enable_fast_recovery() | |
| with ThreadPoolExecutor(max_workers=int(settings.get("workers", 4))) as pool: | |
| for label in (0, 1): | |
| for split, quota in quotas.items(): | |
| candidates = sorted(account for account, value in labels.items() | |
| if value == label and mapping[account] == split) | |
| random.Random(int(settings.get("seed", 42)) + label).shuffle(candidates) | |
| successes = 0 | |
| # Small batches permit bounded failover while keeping candidate order deterministic. | |
| for offset in range(0, len(candidates), 4): | |
| batch = candidates[offset:offset + min(4, quota - successes)] | |
| futures = [pool.submit(_acquire_account, account, label, split, row_ids[account], | |
| settings, cache) for account in batch] | |
| for account, future in zip(batch, futures): | |
| try: | |
| result = future.result() | |
| except (httpx.HTTPError, RuntimeError, ValueError, KeyError) as exc: | |
| result = {"account": account, "label": label, "split": split, | |
| "transactions": [], "reason": f"{type(exc).__name__}: {exc}"} | |
| attempt = {key: value for key, value in result.items() if key != "transactions"} | |
| attempt["selected_transactions"] = len(result["transactions"]) | |
| attempts.append(attempt) | |
| if result["transactions"]: | |
| selected.extend(result["transactions"]) | |
| successes += 1 | |
| print(f"Kaggle label={label} {split}: {successes}/{quota} accounts; " | |
| f"{len(selected)} signed transactions", file=sys.stderr, flush=True) | |
| if successes == quota: | |
| break | |
| if successes != quota: | |
| raise DataError(f"insufficient eligible source accounts for label {label} {split}") | |
| selected.sort(key=lambda row: (row["split"], row["account"], row["block_number"], row["transaction_index"])) | |
| overlap = _overlap(selected, str(settings.get("pretraining_dir", "data/transactions"))) | |
| accounts_output = Path(settings.get("accounts_output_dir", "data/kaggle/accounts")) | |
| account_rows = [{"row_id": index, "account": row["Address"].strip().lower(), | |
| "label": int(row["FLAG"]), "split": mapping.get(row["Address"].strip().lower(), "train"), | |
| "account_address_valid": row["Address"].strip().lower() in labels, | |
| "features_json": json.dumps(row, sort_keys=True), "label_scope": "account_FLAG"} | |
| for index, row in enumerate(original)] | |
| _export(accounts_output, account_rows, "accounts.jsonl") | |
| _export(output, selected, "transactions.jsonl") | |
| account_counts = {name: dict(Counter(str(labels[a]) for a in set(row["account"] for row in selected | |
| if row["split"] == name))) | |
| for name in ("train", "validation", "test")} | |
| audit = {"format_version": 1, "created_at": datetime.now(timezone.utc).isoformat(), | |
| "source": source, "source_csv_sha256": SOURCE_CSV_SHA256, | |
| "source_rows": len(original), "source_unique_accounts": len(labels), | |
| "source_unique_original_identifiers": len({row["Address"].strip().lower() for row in original}), | |
| "source_unique_valid_accounts": len(labels), | |
| "source_duplicate_rows": len(original) - len({row["Address"].strip().lower() for row in original}), | |
| "source_invalid_address_rows": [{"row_id": index, "address": row["Address"]} | |
| for index, row in enumerate(original) if row["Address"].strip().lower() not in labels], | |
| "source_class_counts_rows": dict(Counter(row["FLAG"] for row in original)), | |
| "rows": len(selected), "accounts": len({row["account"] for row in selected}), | |
| "splits": dict(Counter(row["split"] for row in selected)), | |
| "account_class_counts": account_counts, "config": settings, | |
| "cutoff": cutoff, | |
| "hashes_verified": len(selected), "signatures_verified": len(selected), | |
| "label_scope": LABEL_SCOPE, "split_policy": "stratified 70/15/15 unique accounts before acquisition; duplicate CSV accounts grouped", | |
| "account_labels": {row["account"]: row["label"] for row in selected}, | |
| "account_splits": {row["account"]: row["split"] for row in selected}, | |
| "pretraining_overlap": overlap, | |
| "sampling_attempts": attempts, | |
| "limitations": ["Kaggle FLAG labels accounts, not individual transactions; this is a weakly supervised account classification benchmark", | |
| "only outgoing signed Ethereum transactions; no incoming counterparties inherit labels", | |
| "balanced convenience subset conditional on public index availability, not the complete Kaggle benchmark", | |
| "at most two most recent eligible transactions before cutoff per account by default; only first history page searched", | |
| "label observation dates and provenance are not supplied by source; pre-publication cutoff does not establish temporal causality", | |
| "source statistics and addresses are excluded as explicit classifier features; raw signed envelopes retain counterparties and signatures", | |
| "public RPC signature/hash verification does not constitute independent consensus proof"]} | |
| audit["sha256"] = {str(path.relative_to(output)): _checksum(path) for path in sorted(output.rglob("*")) | |
| if path.is_file() and path.name != "audit.json"} | |
| _save_json(output / "audit.json", audit) | |
| _save_json(accounts_output / "manifest.json", {"source": source, "rows": len(account_rows), | |
| "unique_accounts": len(labels), "unique_valid_accounts": len(labels), | |
| "unique_original_identifiers": len({row["Address"].strip().lower() for row in original}), | |
| "split_policy": audit["split_policy"], | |
| "sha256": {str(path.relative_to(accounts_output)): _checksum(path) | |
| for path in sorted(accounts_output.rglob("*")) if path.is_file() and path.name != "manifest.json"}}) | |
| return validate_kaggle(config) | |
| def validate_kaggle(config: DictConfig | dict[str, Any]) -> dict[str, Any]: | |
| """Audit source labels, canonical envelopes, exports, disjointness and overlap.""" | |
| settings = _settings(config) | |
| output = Path(settings.get("output_dir", "data/kaggle/transactions")) | |
| audit = json.loads((output / "audit.json").read_text()) | |
| for relative, digest in audit["sha256"].items(): | |
| path = output / relative | |
| if not path.is_relative_to(output) or not path.is_file() or _checksum(path) != digest: | |
| raise DataError(f"Kaggle file checksum mismatch: {relative}") | |
| csv_path = Path(audit["source"]["csv_path"]) | |
| source_zip = csv_path.parent / "source.zip" | |
| if _checksum(source_zip) != SOURCE_ZIP_SHA256: | |
| raise DataError("Kaggle original source ZIP checksum mismatch") | |
| if _checksum(csv_path) != SOURCE_CSV_SHA256: | |
| raise DataError("Kaggle original source CSV checksum mismatch") | |
| if _checksum(csv_path.parent / "metadata.json") != audit["source"].get("metadata_sha256"): | |
| raise DataError("Kaggle original metadata checksum mismatch") | |
| expected_cutoff = cutoff_metadata(csv_path.parent, int(settings.get("before_block", 11580000)), | |
| audit["source"]["kaggle_last_updated"]) | |
| if expected_cutoff != audit["cutoff"]: | |
| raise DataError("Kaggle historical cutoff header binding changed") | |
| original, labels = read_source(csv_path) | |
| expected_splits = split_accounts(labels, int(settings.get("seed", 42))) | |
| rows = load_rows(output) | |
| seen: set[str] = set() | |
| groups: dict[str, str] = {} | |
| _enable_fast_recovery() | |
| for row in rows: | |
| if row["tx_hash"] in seen: | |
| raise DataError("duplicate linked transaction") | |
| seen.add(row["tx_hash"]) | |
| account = row["account"] | |
| if labels[account] != row["label"] or expected_splits[account] != row["split"]: | |
| raise DataError("Kaggle source label/split binding mismatch") | |
| if account in groups and groups[account] != row["split"]: | |
| raise DataError("account leaks between benchmark splits") | |
| groups[account] = row["split"] | |
| if original[row["kaggle_row_id"]]["Address"].strip().lower() != account: | |
| raise DataError("source row does not identify linked account") | |
| source = json.loads((output / "acquisition_cache" / "rpc" / f"{row['tx_hash']}.json").read_text()) | |
| tx = source["transaction"] | |
| details = validate_transaction(tx, bytes.fromhex(row["raw_hex"][2:]), 1) | |
| if (row["block_number"] != _integer(tx["blockNumber"]) | |
| or row["block_hash"] != tx["blockHash"].lower() | |
| or row["transaction_index"] != _integer(tx["transactionIndex"])): | |
| raise DataError("linked transaction block metadata differs from RPC snapshot") | |
| if row["label_scope"] != LABEL_SCOPE or row["chain_id"] != 1: | |
| raise DataError("linked transaction label scope or chain changed") | |
| history = json.loads((output / "acquisition_cache" / "history" / f"{account}.json").read_text()) | |
| indexed = next((item for item in history["items"] if item["hash"].lower() == row["tx_hash"]), None) | |
| if (indexed is None or indexed["from"]["hash"].lower() != account | |
| or int(indexed["block_number"]) != row["block_number"] | |
| or indexed["timestamp"] != row["timestamp"]): | |
| raise DataError("linked transaction differs from historical outgoing index") | |
| if any(row[key] != value for key, value in details.items()) or row["sender"] != account: | |
| raise DataError("linked transaction differs from independently verified signed envelope") | |
| if row["block_number"] >= audit["cutoff"]["before_block_exclusive"]: | |
| raise DataError("linked transaction is newer than historical cutoff") | |
| dataset = load_from_disk(str(output / "dataset")) | |
| for split in ("train", "validation", "test"): | |
| expected = [row for row in rows if row["split"] == split] | |
| if [dict(row) for row in dataset[split]] != expected: | |
| raise DataError("Kaggle HF export differs from canonical linked transactions") | |
| if pq.read_table(output / "parquet" / f"{split}.parquet").to_pylist() != expected: | |
| raise DataError("Kaggle Parquet export differs from canonical linked transactions") | |
| accounts_output = Path(settings.get("accounts_output_dir", "data/kaggle/accounts")) | |
| account_manifest = json.loads((accounts_output / "manifest.json").read_text()) | |
| for relative, digest in account_manifest["sha256"].items(): | |
| path = accounts_output / relative | |
| if not path.is_relative_to(accounts_output) or not path.is_file() or _checksum(path) != digest: | |
| raise DataError(f"Kaggle full account table checksum mismatch: {relative}") | |
| exported = load_rows(accounts_output / "accounts.jsonl") | |
| expected_accounts = [{"row_id": index, "account": row["Address"].strip().lower(), | |
| "label": int(row["FLAG"]), | |
| "split": expected_splits.get(row["Address"].strip().lower(), "train"), | |
| "account_address_valid": row["Address"].strip().lower() in labels, | |
| "features_json": json.dumps(row, sort_keys=True), | |
| "label_scope": "account_FLAG"} | |
| for index, row in enumerate(original)] | |
| if exported != expected_accounts: | |
| raise DataError("full account table differs from all original Kaggle rows") | |
| account_dataset = load_from_disk(str(accounts_output / "dataset")) | |
| for split in ("train", "validation", "test"): | |
| expected = [row for row in expected_accounts if row["split"] == split] | |
| if ([dict(row) for row in account_dataset[split]] != expected | |
| or pq.read_table(accounts_output / "parquet" / f"{split}.parquet").to_pylist() != expected): | |
| raise DataError("full account table exports differ from canonical source rows") | |
| overlap = _overlap(rows, str(settings.get("pretraining_dir", "data/transactions"))) | |
| if overlap != audit["pretraining_overlap"]: | |
| raise DataError("Kaggle/pretraining overlap audit changed") | |
| if len(rows) != audit["rows"] or len(groups) != audit["accounts"]: | |
| raise DataError("Kaggle manifest count mismatch") | |
| return {"valid": True, "rows": len(rows), "accounts": len(groups), | |
| "source_rows": len(original), "source_unique_accounts": len(labels), | |
| "source_unique_original_identifiers": len({row["Address"].strip().lower() for row in original}), | |
| "source_unique_valid_accounts": len(labels), | |
| "hashes_verified": len(rows), "signatures_verified": len(rows), | |
| "account_class_counts": audit["account_class_counts"], "splits": audit["splits"], | |
| "pretraining_overlap": overlap, "output_dir": str(output), | |
| "accounts_output_dir": str(settings.get("accounts_output_dir", "data/kaggle/accounts")), | |
| "audit": str(output / "audit.json")} | |