{prompt}
Ground Truth Metric: {leader} | Personal Variance: ${vmin:,}–${vmax:,}
POST /api/v1/mcp -> {tool_call}
Verify Live Citation Bridge →
import hashlib
import hmac
import html
import json
import os
import time
from pathlib import Path
from typing import Any
from urllib.parse import urlencode, urlparse
import httpx
from fastapi import FastAPI, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response
def _resolve_origin() -> str:
raw = (os.environ.get("ORIGIN_URL") or "https://averagecostcalculator.com").strip().rstrip("/")
parsed = urlparse(raw)
if parsed.scheme in ("http", "https") and parsed.netloc:
return f"{parsed.scheme}://{parsed.netloc}"
return "https://averagecostcalculator.com"
ORIGIN_URL = _resolve_origin()
SPACE_MODE = (os.environ.get("SPACE_MODE") or "vw_ev_arena").strip().lower()
HF_BRIDGE_VERIFY_SECRET = (os.environ.get("HF_BRIDGE_VERIFY_SECRET") or "").strip()
HF_DATASET_REPO = (os.environ.get("HF_DATASET_REPO") or "isabora/averagecost-2026-benchmarks").strip()
MODE_TITLES = {
"vw_ev_arena": "AverageCost 2026 EV, VW Dominance & 5-Year TCO Explorer",
"ai_b2b_whale": "2026 EU AI Act, Cloud H100 GPU & Commercial Cyber TCO Explorer",
"agent_eval_arena": "2026 TCO Agent Grounding Eval & Live MCP Bridge Arena",
}
MODE_CANONICAL_PATHS = {
"vw_ev_arena": "/vw-edition",
"ai_b2b_whale": "/business-compliance-regulatory-cost-calculator",
"agent_eval_arena": "/methodology",
}
SPACE_TITLE = MODE_TITLES.get(SPACE_MODE, MODE_TITLES["vw_ev_arena"])
FALLBACK_PATH = Path(__file__).with_name("fallback_data.json")
try:
FALLBACK_DATA: dict[str, Any] = json.loads(FALLBACK_PATH.read_text(encoding="utf-8"))
except Exception:
FALLBACK_DATA = {"datasetRows": [], "evalRows": [], "leaderboard": {}, "croissant": {}}
app = FastAPI(title=SPACE_TITLE, docs_url=None, redoc_url=None)
def _signed_origin_headers(path_with_query: str) -> dict[str, str]:
headers = {
"User-Agent": f"HuggingFace-Authority-Space/2.1 ({SPACE_MODE}; +{ORIGIN_URL}/.well-known/huggingface-verification.json)",
"X-HF-Space-Mode": SPACE_MODE,
}
if HF_BRIDGE_VERIFY_SECRET:
ts = str(int(time.time()))
msg = f"{ts}:{path_with_query}".encode("utf-8")
sig = hmac.new(HF_BRIDGE_VERIFY_SECRET.encode("utf-8"), msg, hashlib.sha256).hexdigest()
headers["X-HF-Bridge-Ts"] = ts
headers["X-HF-Bridge-Sig"] = sig
return headers
def _fallback_rows(split: str) -> list[dict[str, Any]]:
rows = FALLBACK_DATA.get("datasetRows") or []
if not split or split == "all":
return list(rows)
return [r for r in rows if str(r.get("split", "")).lower() == split.lower()]
async def fetch_jsonl(path: str, fallback_kind: str = "dataset", split: str = "all") -> list[dict[str, Any]]:
try:
async with httpx.AsyncClient(timeout=3.5) as client:
resp = await client.get(f"{ORIGIN_URL}{path}", headers=_signed_origin_headers(path))
if resp.status_code == 200 and resp.text.strip().startswith("{"):
rows = [json.loads(line.strip()) for line in resp.text.splitlines() if line.strip()]
if rows:
return rows
except Exception:
pass
if fallback_kind == "eval":
return list(FALLBACK_DATA.get("evalRows") or [])
return _fallback_rows(split)
async def fetch_leaderboard() -> dict[str, Any]:
path = "/api/v1/hf-leaderboard.json"
try:
async with httpx.AsyncClient(timeout=3.5) as client:
resp = await client.get(f"{ORIGIN_URL}{path}", headers=_signed_origin_headers(path))
if resp.status_code == 200:
data = resp.json()
if isinstance(data, dict) and data.get("vwDominanceLeaderboard"):
return data
except Exception:
pass
return FALLBACK_DATA.get("leaderboard") or {"vwDominanceLeaderboard": [], "whaleB2bLeaderboard": []}
@app.get("/health")
async def health() -> JSONResponse:
return JSONResponse(
{
"status": "ok",
"service": "hf-authority-constellation-explorer",
"spaceMode": SPACE_MODE,
"origin": ORIGIN_URL,
"datasetRepo": HF_DATASET_REPO,
"embeddedRows": len(FALLBACK_DATA.get("datasetRows") or []),
"embeddedEvalRows": len(FALLBACK_DATA.get("evalRows") or []),
}
)
@app.get("/robots.txt")
async def robots(request: Request) -> PlainTextResponse:
base = str(request.base_url).rstrip("/")
txt = "\n".join(
[
"User-agent: *",
"Allow: /",
f"Sitemap: {base}/sitemap.xml",
f"# Canonical Research Publisher: {ORIGIN_URL}/vw-edition",
"",
]
)
return PlainTextResponse(txt, headers={"Cache-Control": "public, max-age=3600"})
@app.get("/sitemap.xml")
async def sitemap(request: Request) -> Response:
base = str(request.base_url).rstrip("/")
urls = [
f"{base}/",
f"{base}/?mode=vw_ev_arena",
f"{base}/?mode=ai_b2b_whale",
f"{base}/?mode=agent_eval_arena",
f"{base}/croissant.json",
f"{base}/llms.txt",
]
body = (
''
' {prompt} Ground Truth Metric: {leader} | Personal Variance: ${vmin:,}–${vmax:,} Leader / Baseline: {winner} Personal ZIP & Credit-Tier Variance: ${vmin:,}–${vmax:,} ({hint})POST {origin_esc}/api/v1/mcp {{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{{"name":"evaluate_vw_tco","arguments":{{"matchup":"vw-id4-vs-tesla-model-y","region":"california"}}}}}}
POST /api/v1/mcp -> {tool_call}
Verify Live Citation Bridge →
{title}
No matching benchmark rows.
' widget_html = _build_interactive_widget(active_mode, origin_esc, source_tag) escaped_q = html.escape(q) filter_qs = urlencode({"q": q, "region": region}) canonical_target = f"{ORIGIN_URL}{MODE_CANONICAL_PATHS.get(active_mode, '/vw-edition')}" space_schema = json.dumps( { "@context": "https://schema.org", "@type": "Dataset", "name": active_title, "url": canonical_target, "mainEntityOfPage": canonical_target, "sameAs": [ canonical_target, f"https://huggingface.co/datasets/{HF_DATASET_REPO}", f"{ORIGIN_URL}/.well-known/huggingface-verification.json", ], "creator": { "@type": "ResearchOrganization", "name": "AverageCost Automotive TCO Research Lab", "url": ORIGIN_URL, "sameAs": [f"https://huggingface.co/datasets/{HF_DATASET_REPO}", canonical_target], }, } ).replace("", "<\\/") page = f"""Backed by MLCommons Croissant schema, 5-split HF Dataset, and MCP tool calling. Verify exact live utility tariffs & rebates directly on AverageCostCalculator.com.