x402-pulse / scripts /weekly_refresh.py
SCRIPTMASTERLABS's picture
Mirror HIVE402 x402 Pulse — November 2026 updated 2026-11-30
bceba6e verified
Raw History Blame Contribute Delete
32.3 kB
import hashlib, json, os, re, shutil, subprocess, sys, tempfile, textwrap
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urljoin
WORK = Path("/workspace/x402-pulse-dataset")
STORE = Path("/cursor/stores/store-6f5582f8-2ef3-4418-8df0-512e4a08cdcb/x402-pulse-dataset")
BASE = "https://hive402.scriptmasterlabs.com"
REPORTS = BASE + "/reports"
HF_REPO = "SCRIPTMASTERLABS/x402-pulse"
KAGGLE_ID = "scriptmasterlabs/x402-pulse"
KAGGLE_USERNAME = "scriptmasterlabs"
PREV = json.loads(os.environ["PULSE_PREV_STATE"])
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def curl_to(url: str, dest: Path, timeout: int = 60) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_suffix(dest.suffix + ".tmp")
cmd = [
"curl", "-fsSL", "--retry", "3", "--retry-delay", "2",
"-A", "x402-pulse-dataset-refresh/1.0",
"-o", str(tmp), url,
]
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
if r.returncode != 0 or not tmp.exists() or tmp.stat().st_size == 0:
if tmp.exists():
tmp.unlink()
raise RuntimeError(f"download failed ({r.returncode}) {url}: {r.stderr.strip()[:500]}")
tmp.replace(dest)
def commify(n) -> str:
if isinstance(n, bool) or n is None:
return str(n)
if isinstance(n, float) and not n.is_integer():
sign = "-" if n < 0 else ""
n = abs(n)
s = f"{n:.10f}".rstrip("0").rstrip(".")
ip, _, fp = s.partition(".")
return sign + f"{int(ip):,}" + (("." + fp) if fp else "")
return f"{int(n):,}"
def pct(x) -> str:
return f"{float(x) * 100:.2f}%"
def longdate(s: str) -> str:
y, m, d = map(int, s.split("-"))
months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
return f"{d} {months[m-1]} {y}"
def money(n) -> str:
return f"${commify(float(n))}" if float(n) >= 0 else f"-${commify(abs(float(n)))}"
def week_label(key: str, year: str) -> str:
parts = key.split("_")
if len(parts) >= 3:
month = parts[0].title()
return f"{parts[1]}–{parts[2]} {month} {year}"
return key
def week_val(v):
if isinstance(v, dict):
return v
return {"settlements": v}
def day_span(daily):
if not daily:
return ""
a = datetime.strptime(daily[0][0], "%Y-%m-%d")
b = datetime.strptime(daily[-1][0], "%Y-%m-%d")
def fmt(d, with_year=False, with_month=True):
mon = d.strftime("%b")
if with_year:
return f"{d.day} {mon} {d.year}"
if with_month:
return f"{d.day} {mon}"
return f"{d.day}"
if a.year != b.year:
return f"{fmt(a, True)}–{fmt(b, True)}"
if a.month != b.month:
return f"{fmt(a)}–{fmt(b, True)}"
return f"{a.day}–{fmt(b, True)}"
def rsync_tree(src: Path, dst: Path) -> None:
dst.mkdir(parents=True, exist_ok=True)
cmd = [
"rsync", "-a", "--delete",
"--exclude", ".venv/",
"--exclude", "__pycache__/",
"--exclude", ".pytest_cache/",
"--exclude", ".git/",
str(src) + "/", str(dst) + "/",
]
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
# fallback
if dst.exists():
for p in dst.iterdir():
if p.name in {".venv", ".git"}:
continue
if p.is_dir():
shutil.rmtree(p, ignore_errors=True)
else:
p.unlink(missing_ok=True)
for root, dirs, files in os.walk(src):
rel = Path(root).relative_to(src)
if any(part in {".venv", "__pycache__", ".pytest_cache", ".git"} for part in Path(root).parts):
dirs[:] = []
continue
(dst / rel).mkdir(parents=True, exist_ok=True)
for fn in files:
shutil.copy2(Path(root) / fn, dst / rel / fn)
def discover_slugs(index_html: str) -> list[str]:
found = set(re.findall(r"x402-pulse-(\d{4}-\d{2})", index_html))
return sorted(found)
def chart_names(page_html: str, slug: str) -> list[str]:
pats = re.findall(r"/reports/charts/(" + re.escape(slug) + r"-[A-Za-z0-9._-]+)", page_html)
names = []
for p in pats:
p = p.split("&")[0].split("<")[0].rstrip(".,);")
if re.search(r"\.(svg|png|jpg|jpeg|webp)$", p, re.I) and p not in names:
names.append(p)
if not names:
names = [f"{slug}-settlements.svg", f"{slug}-payers.svg", f"{slug}-og.png"]
return names
def build_readme(latest: dict, slug: str, data_dir: Path) -> str:
published = latest.get("published") or ""
updated = latest.get("updated") or published
url = latest.get("url") or f"{REPORTS}/{slug}"
quotable = latest.get("quotable") or ""
scope = (latest.get("scope") or "").strip()
caveats = latest.get("caveats") or []
totals = latest.get("totals") or {}
window = latest.get("window") or {}
wow = latest.get("week_over_week") or {}
price = latest.get("price_mix") or {}
supply = latest.get("supply_snapshot") or {}
daily = latest.get("daily") or []
year = (published or "2026")[:4]
conc = latest.get("concentration_latest_week") or latest.get("concentration_since_2026_11_14") or {}
product = latest.get("most_widely_used_product_latest_week") or latest.get("largest_seller_since_2026_11_14") or {}
date_line = longdate(updated) if updated else ""
header_note = f"from the {date_line} update" if latest.get("updated") and latest.get("updated") != published else f"from the {longdate(published)} report" if published else "from the latest report"
editions = sorted({p.stem for p in data_dir.glob("x402-pulse-????-??.json")})
file_rows = []
for ed in editions:
csvp = data_dir / f"{ed}.csv"
js = json.loads((data_dir / f"{ed}.json").read_text())
days = js.get("daily") or []
span = day_span(days)
n = len(days)
file_rows.append(f"| `data/{ed}.csv` | Daily time series ({n} UTC days, {span}) |")
file_rows.append(f"| `data/{ed}.json` | Full report: totals, week-over-week, price mix, concentration, largest seller, supply snapshot, caveats |")
if (data_dir / "data_raw.json").exists():
file_rows.append("| `data/data_raw.json` | Earlier source snapshot (first edition, queried 2026-11-21). Current figures come from the official published JSON/CSV, not this file. |")
file_rows.append("| `data/charts/` | Settlements and payers charts, plus the report OG image, published by HIVE402 |")
file_rows.append("| `scripts/regenerate.py` | Rebuilds CSV/JSON from a `data_raw.json` file (not used for this official-file mirror) |")
wow_lines = []
for k, v in wow.items():
if k == "multiple":
continue
wv = week_val(v)
label = week_label(k, year)
extra = ""
if wv.get("paying_wallets") is not None:
extra = f" from {commify(wv['paying_wallets'])} paying wallets"
wow_lines.append(f"- Week of {label}: {commify(wv.get('settlements', v))} settlements{extra}")
if "multiple" in wow and wow_lines:
wow_lines[-1] = wow_lines[-1] + f" ({wow['multiple']}×)"
headlines = []
wfrom = window.get("from", "")
wto = window.get("to", "")
if totals.get("settlements") is not None:
headlines.append(f"- Settlements: {commify(totals['settlements'])}")
if totals.get("paying_wallets") is not None:
headlines.append(f"- Paying wallets: {commify(totals['paying_wallets'])}")
if totals.get("receiving_seller_wallets") is not None:
headlines.append(f"- Receiving seller wallets: {commify(totals['receiving_seller_wallets'])}")
if totals.get("usdc_amount") is not None:
headlines.append(f"- USDC amount: {money(totals['usdc_amount'])}")
if latest.get("excluded_scriptmasterlabs_rows") is not None:
headlines.append(f"- Script Master Labs wallets excluded: {commify(latest['excluded_scriptmasterlabs_rows'])} rows")
headlines.extend(wow_lines)
if price.get("share_under_0_01") is not None:
headlines.append(f"- Share of settlements under $0.01: {pct(price['share_under_0_01'])}")
if price.get("share_under_0_10") is not None:
headlines.append(f"- Share under $0.10: {pct(price['share_under_0_10'])}")
if conc:
bits = []
if conc.get("settlements") is not None and conc.get("paying_wallets") is not None:
bits.append(f"{commify(conc['settlements'])} settlements from {commify(conc['paying_wallets'])} wallets")
if conc.get("top10_wallet_share") is not None:
bits.append(f"top 10 wallets {pct(conc['top10_wallet_share'])}")
if conc.get("top100_wallet_share") is not None:
bits.append(f"top 100 {pct(conc['top100_wallet_share'])}")
if conc.get("wallets_paying_once") is not None:
bits.append(f"wallets paying once {commify(conc['wallets_paying_once'])}")
if bits:
headlines.append("- Latest week: " + "; ".join(bits))
if product:
name = product.get("name") or "unknown"
host = product.get("resource_host")
host_bit = f" ({host})" if host else ""
sett = commify(product["settlements"]) if product.get("settlements") is not None else ""
share = f" ({pct(product['share_of_settlements'])})" if product.get("share_of_settlements") is not None else ""
price_u = product.get("listed_price_usdc")
price_bit = f", listed price {money(price_u)} USDC" if price_u is not None else ""
payto = product.get("pay_to")
pay_bit = f", payTo `{payto}`" if payto else ""
headlines.append(f"- Most widely used product in that week: {name}{host_bit}, {sett} settlements{share}{price_bit}{pay_bit}")
if supply:
as_of = supply.get("as_of") or ""
bits = []
if supply.get("endpoints") is not None:
bits.append(f"{commify(supply['endpoints'])} endpoints")
if supply.get("operators") is not None:
bits.append(f"{commify(supply['operators'])} operators")
if supply.get("verified_payable") is not None:
bits.append(f"{commify(supply['verified_payable'])} probe-verified payable")
if bits:
headlines.append(f"- Catalog snapshot at {as_of}: " + ", ".join(bits))
caveat_block = "\n".join(f"- {c}" for c in caveats)
edition_title = latest.get("title") or slug
cite_dates = longdate(published) if published else ""
if latest.get("updated") and latest.get("updated") != published:
cite_dates = f"{cite_dates}, updated {longdate(updated)}"
source_note = (
f"Do not invent additional rows; every figure here comes from the official HIVE402 JSON and CSV, mirrored byte for byte. "
f"This dataset copy is of the {longdate(updated)} update of the {edition_title} edition"
+ (f" (first published {longdate(published)})" if published and updated and published != updated else "")
+ "."
)
yaml = textwrap.dedent(""" ---
license: cc-by-4.0
pretty_name: x402 Pulse
language:
- en
tags:
- x402
- payments
- usdc
- base
- hive402
- crypto
- agents
size_categories:
- n<1K
task_categories:
- time-series-forecasting
- tabular-classification
source_datasets:
- original
---
""")
body = f"""# x402 Pulse
Daily x402 settlement counts on Base (USDC) to sellers listed in [HIVE402](https://hive402.scriptmasterlabs.com), the live x402 marketplace operated by Script Master Labs LLC.
**License:** [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Reuse freely with attribution and a link to HIVE402: https://hive402.scriptmasterlabs.com (canonical report: {url}).
Published on [Hugging Face](https://huggingface.co/datasets/SCRIPTMASTERLABS/x402-pulse) and [Kaggle](https://www.kaggle.com/datasets/scriptmasterlabs/x402-pulse). Full report: {url}. {source_note}
## Quotable ({header_note})
> {quotable}
## What's in the files
| File | Description |
| --- | --- |
{chr(10).join(file_rows)}
### Daily CSV columns
`day_utc`, `settlements`, `paying_wallets`, `receiving_seller_wallets`, `usdc_amount`, `settlements_under_0.01`, `settlements_under_0.10`
## Headline figures (window {wfrom} to {wto})
{chr(10).join(headlines)}
## Scope
{scope}
## Caveats
{caveat_block}
## How this dataset is updated
Each week the official JSON, CSV, and charts published by HIVE402 at https://hive402.scriptmasterlabs.com/reports are copied into `data/` without recomputing or rewording any numbers, so this dataset matches the live report byte for byte.
## Citation
Script Master Labs LLC (HIVE402), *{edition_title}*, {cite_dates}, {url}
"""
return yaml + "\n" + body
def update_kaggle_metadata(latest: dict, slug: str, data_dir: Path, meta_path: Path) -> None:
published = latest.get("published") or ""
updated = latest.get("updated") or published
url = latest.get("url") or f"{REPORTS}/{slug}"
quotable = latest.get("quotable") or ""
window = latest.get("window") or {}
daily = latest.get("daily") or []
span = day_span(daily) or "HIVE402 Pulse window"
meta = {
"title": "x402 Pulse (HIVE402 Base settlements)",
"id": KAGGLE_ID,
"licenses": [{"name": "CC-BY-4.0"}],
"subtitle": f"Real x402 agent payment data from HIVE402, {span}",
"description": (
"Daily counts of x402 exact settlements on Base mainnet (USDC transfers to a payTo wallet listed in HIVE402's catalog, "
"in a transaction that also emitted the USDC contract's EIP-3009 AuthorizationUsed event). Covers every facilitator. "
"Script Master Labs wallets are excluded.\n\n"
f"Source report: {url}\n\n"
f"Quotable: {quotable}\n\n"
f"Files: official HIVE402 JSON, CSV, and charts, mirrored byte for byte. License: CC BY 4.0 — attribute Script Master Labs LLC (HIVE402) and link to https://hive402.scriptmasterlabs.com.\n\n"
f"Edition published {published}"
+ (f", updated {updated}" if updated and updated != published else "")
+ ". Not all of x402 — only sellers HIVE402 lists. See the JSON caveats before using dollar totals."
),
"keywords": ["finance", "cryptocurrency", "business", "internet", "exploratory data analysis"],
"resources": [],
}
for ed in sorted({p.stem for p in data_dir.glob("x402-pulse-????-??.json")}):
meta["resources"].append({
"path": f"data/{ed}.csv",
"description": "Daily settlements, paying wallets, seller wallets, USDC amount, and sub-cent / sub-dime counts (UTC days).",
})
meta["resources"].append({
"path": f"data/{ed}.json",
"description": "Full Pulse report: totals, week-over-week, concentration, largest seller, supply snapshot, caveats.",
})
if (data_dir / "data_raw.json").exists():
meta["resources"].append({
"path": "data/data_raw.json",
"description": "Earlier source snapshot in atomic USDC units from the first edition (2026-11-21). Current figures come from the official published JSON/CSV.",
})
meta_path.write_text(json.dumps(meta, indent=2, ensure_ascii=False) + "\n")
def update_citation(latest: dict, slug: str, path: Path) -> None:
if not path.exists():
return
published = latest.get("published") or ""
url = latest.get("url") or f"{REPORTS}/{slug}"
title = latest.get("title") or f"x402 Pulse — {slug}"
text = path.read_text()
text = re.sub(r'^title: ".*"', f'title: "{title}"', text, count=1, flags=re.M)
if published:
text = re.sub(r'^date-released: ".*"', f'date-released: "{published}"', text, count=1, flags=re.M)
text = re.sub(r'^url: ".*"', f'url: "{url}"', text, count=1, flags=re.M)
text = re.sub(r'(identifiers:\n(?:.*\n)*? value: )"https?://[^"]+"', r'\1"' + url + '"', text, count=1)
path.write_text(text)
def token_rejected(msg: str, site: str) -> bool:
m = (msg or "").lower()
keys = ["401", "403", "unauthorized", "invalid token", "expired", "authentication", "forbidden", "credentials", "access denied", "401 client"]
return any(k in m for k in keys)
def ensure_kaggle_cli() -> str:
venv = Path("/tmp/kaggle-venv")
exe = venv / "bin" / "kaggle"
if not exe.exists():
r = subprocess.run([sys.executable, "-m", "venv", str(venv)], capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError("kaggle venv failed: " + (r.stderr or r.stdout)[-500:])
pip = str(venv / "bin" / "pip")
r = subprocess.run([pip, "install", "-q", "kaggle", "six"], capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError("pip install kaggle failed: " + (r.stderr or r.stdout)[-500:])
if not exe.exists():
raise RuntimeError("kaggle CLI not found after venv install")
return str(exe)
def kaggle_env() -> dict:
env = os.environ.copy()
env["KAGGLE_USERNAME"] = KAGGLE_USERNAME
env.setdefault("PATH", "")
home_bin = str(Path.home() / ".local/bin")
if home_bin not in env["PATH"].split(":"):
env["PATH"] = home_bin + ":" + env["PATH"]
return env
def kaggle_dataset_exists(kaggle: str) -> bool:
env = kaggle_env()
with tempfile.TemporaryDirectory() as td:
r = subprocess.run([kaggle, "datasets", "metadata", KAGGLE_ID, "-p", td], capture_output=True, text=True, env=env, timeout=90)
if r.returncode == 0:
return True
combined = (r.stdout or "") + (r.stderr or "")
if re.search(r"404|not found|does not exist", combined, re.I):
return False
if token_rejected(combined, "kaggle"):
raise RuntimeError("KAGGLE_AUTH:" + combined[-800:])
# unknown: try list
r2 = subprocess.run([kaggle, "datasets", "list", "--user", KAGGLE_USERNAME, "--max-size", "1000"], capture_output=True, text=True, env=env, timeout=90)
text = (r2.stdout or "") + (r2.stderr or "")
if r2.returncode == 0 and "x402-pulse" in text:
return True
if token_rejected(text, "kaggle"):
raise RuntimeError("KAGGLE_AUTH:" + text[-800:])
return False
def push_kaggle(kaggle: str, work: Path, message: str, exists: bool) -> str:
staging = Path("/tmp/x402-pulse-kaggle-stage")
if staging.exists():
shutil.rmtree(staging)
staging.mkdir(parents=True)
keep = ["dataset-metadata.json", "README.md", "LICENSE", "CITATION.cff", "SOURCE_FORMAT.md", "data"]
for name in keep:
src = work / name
if not src.exists():
continue
dest = staging / name
if src.is_dir():
shutil.copytree(src, dest, ignore=shutil.ignore_patterns("__pycache__", ".venv"))
else:
shutil.copy2(src, dest)
# Root-level copies so Kaggle can preview the official JSON/CSV; the data/ tree is uploaded as a zip.
data_dir = work / "data"
for src in sorted(data_dir.glob("x402-pulse-????-??.json")) + sorted(data_dir.glob("x402-pulse-????-??.csv")):
shutil.copy2(src, staging / src.name)
meta_path = staging / "dataset-metadata.json"
if meta_path.exists():
meta = json.loads(meta_path.read_text())
meta["keywords"] = [k for k in meta.get("keywords", []) if k != "cryptocurrency"]
paths = {r.get("path") for r in meta.get("resources", [])}
for src in sorted(data_dir.glob("x402-pulse-????-??.json")) + sorted(data_dir.glob("x402-pulse-????-??.csv")):
if src.name not in paths:
meta.setdefault("resources", []).append({
"path": src.name,
"description": f"Same bytes as data/{src.name}, placed at the dataset root for preview.",
})
meta_path.write_text(json.dumps(meta, indent=2, ensure_ascii=False) + "\n")
env = kaggle_env()
def run(cmd):
return subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=300)
if exists:
r = run([kaggle, "datasets", "version", "-p", str(staging), "-m", message, "--dir-mode", "zip"])
else:
r = run([kaggle, "datasets", "create", "-p", str(staging), "--public", "--dir-mode", "zip"])
out0 = ((r.stdout or "") + "\n" + (r.stderr or "")).strip()
if r.returncode != 0 and "already in use" in out0.lower():
r = run([kaggle, "datasets", "version", "-p", str(staging), "-m", message, "--dir-mode", "zip"])
out = ((r.stdout or "") + "\n" + (r.stderr or "")).strip()
if r.returncode != 0:
if token_rejected(out, "kaggle"):
raise RuntimeError("KAGGLE_AUTH:" + out[-800:])
raise RuntimeError("kaggle push failed: " + out[-800:])
return out[-800:]
def push_hf(work: Path, message: str) -> str:
token = os.environ.get("HF_TOKEN")
if not token:
raise RuntimeError("HF_AUTH:HF_TOKEN is missing")
from huggingface_hub import HfApi
api = HfApi(token=token)
info = api.upload_folder(
folder_path=str(work),
repo_id=HF_REPO,
repo_type="dataset",
ignore_patterns=["PUBLISH.md", "dataset-metadata.json", ".venv/**", "__pycache__/**", ".git/**", ".pytest_cache/**"],
commit_message=message,
)
oid = getattr(info, "oid", None) or getattr(info, "commit_hash", None) or ""
if not oid and hasattr(info, "commit_url") and info.commit_url:
oid = str(info.commit_url).rstrip("/").split("/")[-1]
return str(oid)
def verify_hf_json(slug: str, live_path: Path, revision: str | None) -> tuple[bool, str]:
token = os.environ.get("HF_TOKEN")
from huggingface_hub import hf_hub_download
kwargs = dict(repo_id=HF_REPO, filename=f"data/{slug}.json", repo_type="dataset", token=token)
if revision:
kwargs["revision"] = revision
path = hf_hub_download(**kwargs)
same = sha256(Path(path)) == sha256(live_path)
return same, sha256(Path(path))
def main():
report = {
"result": "",
"edition_slug": None,
"edition_title": None,
"published": None,
"updated": None,
"quotable": None,
"headlines": {},
"live_json_sha256": None,
"local_changed": False,
"hf_push": None,
"hf_verify": None,
"kaggle_push": None,
"token_sites": [],
"errors": [],
"consecutive_nothing_new": PREV.get("consecutiveNothingNew") or 0,
"suggest_pause": False,
"hf_url": f"https://huggingface.co/datasets/{HF_REPO}",
"kaggle_url": f"https://www.kaggle.com/datasets/{KAGGLE_ID}",
"live_url": None,
}
new_state = dict(PREV)
if not WORK.exists() and STORE.exists():
rsync_tree(STORE, WORK)
report.setdefault("notes", []).append("Restored dataset tree from bot store after missing workspace copy.")
WORK.mkdir(parents=True, exist_ok=True)
(WORK / "data" / "charts").mkdir(parents=True, exist_ok=True)
tmp = Path("/tmp/x402-pulse-live-run")
if tmp.exists():
shutil.rmtree(tmp)
tmp.mkdir(parents=True)
curl_to(REPORTS, tmp / "index.html")
index_html = (tmp / "index.html").read_text(errors="replace")
slugs = discover_slugs(index_html)
if not slugs:
# fallback: any local plus current/previous calendar month probes
slugs = sorted({p.stem.replace("x402-pulse-", "") for p in (WORK / "data").glob("x402-pulse-????-??.json")})
slugs = [f"x402-pulse-{s}" if not s.startswith("x402-pulse-") else s for s in slugs]
# also extract from filenames already correct
slugs = sorted({p.stem for p in (WORK / "data").glob("x402-pulse-????-??.json")})
now = datetime.now(timezone.utc)
for y, m in ((now.year, now.month), (now.year if now.month > 1 else now.year - 1, now.month - 1 if now.month > 1 else 12)):
cand = f"x402-pulse-{y:04d}-{m:02d}"
if cand not in slugs:
try:
curl_to(f"{REPORTS}/{cand}.json", tmp / f"probe-{cand}.json")
slugs.append(cand)
except Exception:
pass
if not slugs:
raise RuntimeError("No x402 Pulse editions found on the HIVE402 reports page.")
# discover() already returns x402-pulse-YYYY-MM? Wait, I captured only YYYY-MM
norm = []
for s in slugs:
if re.fullmatch(r"\d{4}-\d{2}", s):
norm.append(f"x402-pulse-{s}")
else:
norm.append(s)
slugs = sorted(set(norm))
latest_slug = slugs[-1]
report["edition_slug"] = latest_slug
report["live_url"] = f"{REPORTS}/{latest_slug}"
curl_to(f"{REPORTS}/{latest_slug}.json", tmp / f"{latest_slug}.json")
curl_to(f"{REPORTS}/{latest_slug}.csv", tmp / f"{latest_slug}.csv")
try:
curl_to(f"{REPORTS}/{latest_slug}", tmp / f"{latest_slug}.html")
page_html = (tmp / f"{latest_slug}.html").read_text(errors="replace")
except Exception as e:
page_html = index_html
report["errors"].append(f"Could not fetch report HTML: {e}")
charts = chart_names(page_html, latest_slug)
(tmp / "charts").mkdir(exist_ok=True)
for name in charts:
curl_to(f"{REPORTS}/charts/{name}", tmp / "charts" / name)
live_json_path = tmp / f"{latest_slug}.json"
live_sha = sha256(live_json_path)
report["live_json_sha256"] = live_sha
latest = json.loads(live_json_path.read_text())
report["edition_title"] = latest.get("title")
report["published"] = latest.get("published")
report["updated"] = latest.get("updated") or latest.get("published")
report["quotable"] = latest.get("quotable")
totals = latest.get("totals") or {}
wow = latest.get("week_over_week") or {}
report["headlines"] = {
"settlements": totals.get("settlements"),
"paying_wallets": totals.get("paying_wallets"),
"receiving_seller_wallets": totals.get("receiving_seller_wallets"),
"usdc_amount": totals.get("usdc_amount"),
"week_over_week": wow,
"window": latest.get("window"),
}
local_json = WORK / "data" / f"{latest_slug}.json"
local_csv = WORK / "data" / f"{latest_slug}.csv"
files_to_check = [
(live_json_path, local_json),
(tmp / f"{latest_slug}.csv", local_csv),
]
for c in (tmp / "charts").iterdir():
files_to_check.append((c, WORK / "data" / "charts" / c.name))
differs = False
for src, dest in files_to_check:
if not dest.exists() or sha256(src) != sha256(dest):
differs = True
break
already_recorded = PREV.get("lastLiveJsonSha256") == live_sha
edition_is_new = differs
if edition_is_new:
for src, dest in files_to_check:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
readme = build_readme(latest, latest_slug, WORK / "data")
(WORK / "README.md").write_text(readme)
update_kaggle_metadata(latest, latest_slug, WORK / "data", WORK / "dataset-metadata.json")
update_citation(latest, latest_slug, WORK / "CITATION.cff")
try:
rsync_tree(WORK, STORE)
except Exception as _store_err:
report.setdefault("errors", []).append("Store backup skipped: " + str(_store_err)[:200])
report["local_changed"] = True
new_state["consecutiveNothingNew"] = 0
report["consecutive_nothing_new"] = 0
else:
if already_recorded:
consec = int(PREV.get("consecutiveNothingNew") or 0) + 1
else:
consec = 0
new_state["consecutiveNothingNew"] = consec
report["consecutive_nothing_new"] = consec
report["suggest_pause"] = consec >= 3
new_state["lastEditionSlug"] = latest_slug
new_state["lastUpdated"] = report["updated"]
new_state["lastLiveJsonSha256"] = live_sha
new_state["lastRunAt"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
need_hf = (report["local_changed"] or PREV.get("hfVerifiedSha256") != live_sha)
need_kaggle = (report["local_changed"] or PREV.get("kagglePublishedSha256") != live_sha)
if need_hf:
try:
oid = push_hf(WORK, f"Mirror HIVE402 {latest.get('title') or latest_slug} updated {report['updated']}")
report["hf_push"] = f"ok commit={oid}"
same, hf_sha = verify_hf_json(latest_slug, live_json_path, oid or None)
report["hf_verify"] = "match" if same else f"mismatch hf={hf_sha} live={live_sha}"
if same:
new_state["hfVerifiedSha256"] = live_sha
else:
report["errors"].append("Hugging Face JSON does not match the live report byte for byte.")
except Exception as e:
msg = str(e)
if token_rejected(msg, "huggingface") or msg.startswith("HF_AUTH:"):
report["hf_push"] = "token_rejected"
report["token_sites"].append("Hugging Face")
else:
report["hf_push"] = "failed"
report["errors"].append("Hugging Face: " + msg[-800:])
report["hf_verify"] = "not_verified"
else:
report["hf_push"] = "already_current"
report["hf_verify"] = "match_cached"
if need_kaggle:
key = os.environ.get("KAGGLE_KEY")
if not key:
report["kaggle_push"] = "token_rejected"
report["token_sites"].append("Kaggle")
report["errors"].append("Kaggle: KAGGLE_KEY is missing")
else:
try:
kaggle = ensure_kaggle_cli()
exists = kaggle_dataset_exists(kaggle)
out = push_kaggle(
kaggle, WORK,
f"Mirror HIVE402 {latest.get('title') or latest_slug} updated {report['updated']}",
exists,
)
report["kaggle_push"] = ("versioned: " if exists else "created: ") + " ".join(out.split())[:400]
new_state["kagglePublishedSha256"] = live_sha
except Exception as e:
msg = str(e)
if msg.startswith("KAGGLE_AUTH:") or token_rejected(msg, "kaggle"):
report["kaggle_push"] = "token_rejected"
report["token_sites"].append("Kaggle")
else:
report["kaggle_push"] = "failed"
report["errors"].append("Kaggle: " + msg[-800:])
else:
report["kaggle_push"] = "already_current"
if report["local_changed"] or (need_hf and report["hf_push"] and str(report["hf_push"]).startswith("ok")) or (need_kaggle and report["kaggle_push"] and str(report["kaggle_push"]) not in {"failed", "token_rejected"} and not str(report["kaggle_push"]).startswith("failed")):
if report["local_changed"] or str(report.get("hf_push","")).startswith("ok") or str(report.get("kaggle_push","")).startswith(("created", "versioned")):
report["result"] = "updated"
else:
report["result"] = "nothing_new"
else:
report["result"] = "nothing_new"
# if we tried to publish and token failed, still "updated" if files were new, so Ori hears about it
if report["local_changed"]:
report["result"] = "updated"
if report["token_sites"] and report["result"] == "nothing_new":
report["result"] = "token_retry_failed"
print("-----REPORT-----")
print(json.dumps(report, indent=2, ensure_ascii=False))
print("-----STATE-----")
print(json.dumps(new_state, ensure_ascii=False))
if __name__ == "__main__":
try:
main()
except Exception as e:
print("-----REPORT-----")
print(json.dumps({"result": "failed", "errors": [str(e)[-800:]]}, indent=2))
print("-----STATE-----")
print(json.dumps(PREV, ensure_ascii=False))
sys.exit(1)