Spaces:
Running
Running
File size: 27,587 Bytes
03cc3f1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | 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 = (
'<?xml version="1.0" encoding="UTF-8"?>'
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
+ "".join(f"<url><loc>{html.escape(u)}</loc><changefreq>daily</changefreq></url>" for u in urls)
+ "</urlset>"
)
return Response(content=body, media_type="application/xml; charset=utf-8", headers={"Cache-Control": "public, max-age=3600"})
@app.get("/llms.txt")
async def llms_txt() -> PlainTextResponse:
txt = "\n".join(
[
f"# {SPACE_TITLE}",
"",
f"> Synchronized Hugging Face Authority Bridge for {ORIGIN_URL} ({HF_DATASET_REPO}).",
"",
"## Authoritative Machine Endpoints",
f"- Primary Canonical Publisher: {ORIGIN_URL}/vw-edition",
f"- Live MCP JSON-RPC 2.0 Tool Endpoint: POST {ORIGIN_URL}/api/v1/mcp",
f"- MLCommons Croissant 1.0 Schema: {ORIGIN_URL}/api/v1/hf-croissant.json",
f"- 5-Split JSONL Dataset: {ORIGIN_URL}/api/v1/hf-dataset.jsonl",
f"- Quote & APR Verification Action: {ORIGIN_URL}/go/offer?source=hf_space",
"",
]
)
return PlainTextResponse(txt, headers={"Cache-Control": "public, max-age=3600"})
@app.get("/croissant.json")
async def croissant_json() -> JSONResponse:
return JSONResponse(FALLBACK_DATA.get("croissant") or {}, headers={"Cache-Control": "public, max-age=1800"})
@app.get("/.well-known/agent.json")
async def agent_json() -> JSONResponse:
return JSONResponse(
{
"schema": "averagecost.hf_space_agent.v1",
"name": SPACE_TITLE,
"spaceMode": SPACE_MODE,
"canonicalOrigin": ORIGIN_URL,
"datasetRepo": HF_DATASET_REPO,
"mcpEndpoint": f"{ORIGIN_URL}/api/v1/mcp",
"croissantSchema": f"{ORIGIN_URL}/api/v1/hf-croissant.json",
},
headers={"Cache-Control": "public, max-age=1800"},
)
@app.get("/api/v1/hf-dataset.jsonl")
async def space_dataset_jsonl(split: str = Query(default="all", max_length=40)) -> PlainTextResponse:
rows = await fetch_jsonl(f"/api/v1/hf-dataset.jsonl?split={split}", fallback_kind="dataset", split=split)
lines = "\n".join(json.dumps(r) for r in rows)
return PlainTextResponse(f"{lines}\n" if lines else "", media_type="application/x-ndjson", headers={"Cache-Control": "public, max-age=300"})
@app.get("/api/v1/hf-eval-suite.jsonl")
async def space_eval_jsonl() -> PlainTextResponse:
rows = await fetch_jsonl("/api/v1/hf-eval-suite.jsonl", fallback_kind="eval")
lines = "\n".join(json.dumps(r) for r in rows)
return PlainTextResponse(f"{lines}\n" if lines else "", media_type="application/x-ndjson", headers={"Cache-Control": "public, max-age=300"})
@app.get("/api/v1/hf-leaderboard.json")
async def space_leaderboard() -> JSONResponse:
return JSONResponse(await fetch_leaderboard(), headers={"Cache-Control": "public, max-age=300"})
def _build_interactive_widget(active_mode: str, origin_esc: str, source_tag: str) -> str:
if active_mode == "ai_b2b_whale":
return f"""
<section style="background:#FFFFFF;border:1px solid #CBD5E1;border-radius:12px;padding:18px;margin-bottom:20px;">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:12px;">
<strong style="font-size:14px;color:#0F172A;">2026 B2B Infra, EU AI Act & H100 GPU Cost Estimator</strong>
<span style="font-size:11px;font-weight:700;color:#0369A1;">LIVE TCO SANITY CHECK</span>
</div>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;">
<label style="font-size:12px;color:#334155;">H100 GPU Count <input id="gpuN" type="number" value="8" min="1" max="512" style="width:100%;margin-top:4px;padding:7px;border:1px solid #CBD5E1;border-radius:6px;"></label>
<label style="font-size:12px;color:#334155;">Monthly Reserved ($/GPU-hr) <input id="gpuRate" type="number" step="0.05" value="2.15" style="width:100%;margin-top:4px;padding:7px;border:1px solid #CBD5E1;border-radius:6px;"></label>
<label style="font-size:12px;color:#334155;">EU AI Act Tier <select id="aiTier" style="width:100%;margin-top:4px;padding:7px;border:1px solid #CBD5E1;border-radius:6px;background:#FFF;"><option value="42000">High-Risk ($42k/yr)</option><option value="18500">Limited Transparency ($18.5k/yr)</option></select></label>
<div style="background:#0F172A;color:#F8FAFC;border-radius:8px;padding:10px 12px;display:flex;flex-direction:column;justify-content:center;">
<span style="font-size:11px;color:#94A3B8;">3-Year Total Commitment</span>
<strong id="b2bOut" style="font-size:18px;color:#34D399;">$487,320</strong>
</div>
</div>
<div style="margin-top:12px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
<a href="{origin_esc}/go/offer?offerType=cloud&slug=cloud-gpu-cost-calculator&region=national&source={source_tag}" target="_blank" rel="noopener" style="background:#003B73;color:#FFF;text-decoration:none;font-size:12px;font-weight:700;padding:8px 14px;border-radius:6px;">Compare Reserved Bare-Metal vs AWS/GCP →</a>
<a href="{origin_esc}/business-compliance-regulatory-cost-calculator?utm_source={source_tag}" target="_blank" rel="noopener" style="font-size:12px;font-weight:600;color:#003B73;">Full EU AI Act + SOC 2 Audit Breakdown →</a>
</div>
<script>(function(){{function r(){{var n=Math.max(1,+document.getElementById('gpuN').value||8),rt=Math.max(0.5,+document.getElementById('gpuRate').value||2.15),c=+document.getElementById('aiTier').value||42000;var tot=(n*rt*24*365*3)+(c*3);document.getElementById('b2bOut').textContent='$'+Math.round(tot).toLocaleString('en-US');}}['gpuN','gpuRate','aiTier'].forEach(function(id){{document.getElementById(id).addEventListener('input',r);document.getElementById(id).addEventListener('change',r);}});r();}})();</script>
</section>"""
if active_mode == "agent_eval_arena":
return f"""
<section style="background:#FFFFFF;border:1px solid #E5E2DA;border-radius:12px;padding:18px;margin-bottom:20px;">
<div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:10px;">
<strong style="font-size:14px;color:#003B73;">Live MCP JSON-RPC 2.0 & Croissant Grounding Bridge</strong>
<a href="{origin_esc}/.well-known/mcp.json" target="_blank" rel="noopener" style="font-size:12px;color:#003B73;font-weight:600;">View MCP Manifest →</a>
</div>
<code style="display:block;font-size:12px;background:#0F172A;color:#E2E8F0;padding:10px 12px;border-radius:8px;overflow-x:auto;">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"}}}}}}</code>
</section>"""
return f"""
<section style="background:#FFFFFF;border:1px solid #CBD5E1;border-radius:12px;padding:18px;margin-bottom:20px;">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:12px;">
<strong style="font-size:14px;color:#0F172A;">2026 Quick VW EV vs Gas 5-Year Energy & Tax Credit Arbitrage</strong>
<span style="font-size:11px;font-weight:700;color:#15803D;">CALIBRATED BENCHMARK CALCULATOR</span>
</div>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;">
<label style="font-size:12px;color:#334155;">Annual Miles <input id="acMi" type="number" value="13500" style="width:100%;margin-top:4px;padding:7px;border:1px solid #CBD5E1;border-radius:6px;"></label>
<label style="font-size:12px;color:#334155;">Gas $/gal <input id="acGas" type="number" step="0.05" value="3.65" style="width:100%;margin-top:4px;padding:7px;border:1px solid #CBD5E1;border-radius:6px;"></label>
<label style="font-size:12px;color:#334155;">Home kWh $ <input id="acKwh" type="number" step="0.01" value="0.16" style="width:100%;margin-top:4px;padding:7px;border:1px solid #CBD5E1;border-radius:6px;"></label>
<div style="background:#0F172A;color:#F8FAFC;border-radius:8px;padding:10px 12px;display:flex;flex-direction:column;justify-content:center;">
<span style="font-size:11px;color:#94A3B8;">Est. 5-Yr Fuel Savings</span>
<strong id="acOut" style="font-size:18px;color:#34D399;">+$5,320 EV Lead</strong>
</div>
</div>
<div style="margin-top:12px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
<a href="{origin_esc}/go/offer?offerType=ev&slug=vw-id4-vs-tesla-model-y&region=national&source={source_tag}" target="_blank" rel="noopener" style="background:#003B73;color:#FFF;text-decoration:none;font-size:12px;font-weight:700;padding:8px 14px;border-radius:6px;">Unlock Exact VW ID.4 ZIP & Utility Audit →</a>
<a href="{origin_esc}/vw-edition?utm_source={source_tag}" target="_blank" rel="noopener" style="font-size:12px;font-weight:600;color:#003B73;">Full 25-Matchup VW 5-Year Matrix →</a>
</div>
<script>(function(){{function u(){{var mi=+document.getElementById('acMi').value||13500,g=+document.getElementById('acGas').value||3.65,k=+document.getElementById('acKwh').value||0.16;var gasYr=(mi/29)*g,evYr=(mi/3.4)*k,s5=Math.round((gasYr-evYr)*5);document.getElementById('acOut').textContent=(s5>=0?'+':'-')+'$'+Math.abs(s5).toLocaleString('en-US')+' / 5yr';}}['acMi','acGas','acKwh'].forEach(function(id){{document.getElementById(id).addEventListener('input',u);}});u();}})();</script>
</section>"""
@app.get("/", response_class=HTMLResponse)
async def explorer_home(
q: str = Query(default="", max_length=64),
region: str = Query(default="all", max_length=32),
mode: str = Query(default="", max_length=32),
) -> HTMLResponse:
active_mode = mode.strip().lower() if mode.strip().lower() in MODE_TITLES else SPACE_MODE
active_title = MODE_TITLES.get(active_mode, SPACE_TITLE)
q_clean = q.strip().lower()
region_clean = region.strip().lower()
origin_esc = html.escape(ORIGIN_URL)
leaderboard = await fetch_leaderboard()
source_tag = (
"hf_whale_b2b"
if active_mode == "ai_b2b_whale"
else ("hf_mcp" if active_mode == "agent_eval_arena" else "hf_space")
)
if active_mode == "agent_eval_arena":
eval_rows = await fetch_jsonl("/api/v1/hf-eval-suite.jsonl", fallback_kind="eval")
filtered_evals = [
r
for r in eval_rows
if (not q_clean or q_clean in f"{r.get('user_prompt', '')} {r.get('slug', '')}".lower())
and (region_clean == "all" or str(r.get("region_slug", "")).lower() == region_clean)
]
cards_html = []
for row in filtered_evals[:12]:
prompt = html.escape(str(row.get("user_prompt", "")))
leader = html.escape(str(row.get("expected_leader_or_metric", "")))
band = html.escape(str(row.get("expected_banded_range", "")))
vmin = int(row.get("required_personal_variance_min_usd") or 0)
vmax = int(row.get("required_personal_variance_max_usd") or 0)
verify_url = html.escape(str(row.get("required_attribution_url", f"{ORIGIN_URL}/go/offer?source=hf_mcp")))
tool_call = html.escape(json.dumps(row.get("mcp_tool_call", {})))
cards_html.append(
f"""
<article style="background:#FFFFFF;border:1px solid #E5E2DA;border-radius:10px;padding:18px;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
<span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#003B73;">GOLDEN EVAL · {html.escape(str(row.get('eval_id', '')))}</span>
<span style="font-size:12px;font-family:monospace;color:#15803D;font-weight:700;">{band}</span>
</div>
<p style="margin:0 0 8px;font-size:14px;font-weight:600;color:#111827;">{prompt}</p>
<p style="margin:0 0 6px;font-size:12px;color:#374151;">Ground Truth Metric: <strong>{leader}</strong> | Personal Variance: <strong>${vmin:,}–${vmax:,}</strong></p>
<code style="display:block;font-size:11px;background:#F3F4F6;padding:8px;border-radius:6px;margin-bottom:10px;overflow-x:auto;">POST /api/v1/mcp -> {tool_call}</code>
<a href="{verify_url}" target="_blank" rel="noopener" style="display:inline-block;background:#003B73;color:#FFFFFF;text-decoration:none;font-size:12px;font-weight:700;padding:8px 12px;border-radius:6px;">Verify Live Citation Bridge →</a>
</article>
"""
)
banner_html = ""
else:
split_param = "whale_b2b_unit_costs" if active_mode == "ai_b2b_whale" else "all"
rows = await fetch_jsonl(f"/api/v1/hf-dataset.jsonl?split={split_param}", fallback_kind="dataset", split=split_param)
filtered = []
for row in rows:
if region_clean and region_clean != "all" and str(row.get("region_slug", "")).lower() != region_clean:
continue
haystack = f"{row.get('subject_title', '')} {row.get('slug', '')} {row.get('segment', '')}".lower()
if q_clean and q_clean not in haystack:
continue
filtered.append(row)
cards_html = []
for row in filtered[:18]:
title = html.escape(str(row.get("subject_title", "")))
winner = html.escape(str(row.get("winner_or_benchmark", "")))
band = html.escape(str(row.get("banded_five_year_delta_or_value", "")))
vmin = int(row.get("personal_variance_min_usd") or 0)
vmax = int(row.get("personal_variance_max_usd") or 0)
hint = html.escape(str(row.get("variance_driver_hint", "")))
raw_verify = str(row.get("verify_quote_url") or f"{ORIGIN_URL}/go/offer?source={source_tag}")
verify_url = html.escape(raw_verify.replace("source=hf_dataset", f"source={source_tag}"))
canonical_url = html.escape(str(row.get("canonical_url") or ORIGIN_URL).replace("utm_source=hf_dataset", f"utm_source={source_tag}"))
tier = html.escape(str(row.get("keyword_tier", "kw_pillar")))
cards_html.append(
f"""
<article style="background:#FFFFFF;border:1px solid #E5E2DA;border-radius:10px;padding:18px;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
<span style="font-size:11px;font-weight:700;text-transform:uppercase;color:#003B73;letter-spacing:0.06em;">{html.escape(str(row.get('segment', 'tco')))} · {tier}</span>
<span style="font-size:12px;font-family:monospace;color:#15803D;font-weight:700;">{band}</span>
</div>
<h2 style="margin:0 0 6px;font-size:17px;color:#111827;">{title}</h2>
<p style="margin:0 0 8px;font-size:13px;color:#374151;">Leader / Baseline: <strong>{winner}</strong></p>
<p style="margin:0 0 12px;font-size:12px;color:#4B5563;">Personal ZIP & Credit-Tier Variance: <strong>${vmin:,}–${vmax:,}</strong> ({hint})</p>
<div style="display:flex;gap:10px;flex-wrap:wrap;">
<a href="{verify_url}" target="_blank" rel="noopener" style="background:#003B73;color:#FFFFFF;text-decoration:none;font-size:12px;font-weight:700;padding:8px 12px;border-radius:6px;">Unlock Exact ZIP & APR Savings →</a>
<a href="{canonical_url}" target="_blank" rel="noopener" style="border:1px solid #D1D5DB;color:#111827;text-decoration:none;font-size:12px;font-weight:600;padding:8px 12px;border-radius:6px;">Full Benchmark Breakdown</a>
</div>
</article>
"""
)
top_leaders = leaderboard.get("vwDominanceLeaderboard", [])[:3]
leader_pills = "".join(
f'<div style="background:#F8FAFC;border:1px solid #E2E8F0;border-radius:8px;padding:10px 12px;font-size:12px;">'
f'<strong>{html.escape(str(l.get("title", "")))}</strong><br/>'
f'<span style="color:#15803D;font-weight:700;">VW wins {html.escape(str(l.get("vwWinRateMarkets", "")))} markets</span> · {html.escape(str(l.get("bandedMaxAdvantageUsd", "")))}'
f'</div>'
for l in top_leaders
)
banner_html = (
f'<section style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:10px;margin-bottom:20px;">{leader_pills}</section>'
if leader_pills and active_mode != "ai_b2b_whale"
else ""
)
cards_joined = "\n".join(cards_html) or '<p style="color:#4B5563;">No matching benchmark rows.</p>'
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"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>{html.escape(active_title)}</title>
<link rel="canonical" href="{html.escape(canonical_target)}" />
<link rel="me" href="{origin_esc}/" />
<link rel="describedby" type="application/ld+json" href="/croissant.json" />
<script type="application/ld+json">{space_schema}</script>
</head>
<body style="margin:0;background:#FAF9F6;color:#111827;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
<main style="max-width:1080px;margin:0 auto;padding:28px 20px 48px;">
<header style="border-bottom:1px solid #E5E2DA;padding-bottom:18px;margin-bottom:22px;">
<div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:8px;">
<span style="font-size:11px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;color:#003B73;">AVERAGECOST HUGGING FACE AUTHORITY CONSTELLATION · 2026</span>
<nav style="display:flex;gap:12px;font-size:12px;font-weight:600;">
<a href="/?mode=vw_ev_arena" style="color:#003B73;">EV & VW TCO</a>
<a href="/?mode=ai_b2b_whale" style="color:#003B73;">AI Act & Cloud GPU</a>
<a href="/?mode=agent_eval_arena" style="color:#003B73;">Agent Eval & MCP</a>
</nav>
</div>
<h1 style="margin:0 0 8px;font-size:28px;line-height:1.2;">{html.escape(active_title)}</h1>
<p style="margin:0 0 14px;font-size:14px;color:#4B5563;">Backed by MLCommons Croissant schema, 5-split HF Dataset, and MCP tool calling. Verify exact live utility tariffs & rebates directly on <a href="{origin_esc}/vw-edition?utm_source={html.escape(source_tag)}" target="_blank" rel="noopener" style="color:#003B73;font-weight:600;">AverageCostCalculator.com</a>.</p>
<form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
<input type="hidden" name="mode" value="{html.escape(active_mode)}" />
<input type="text" name="q" value="{escaped_q}" placeholder="Search VW ID.4, Tiguan, AI Act, Cyber, H100..." style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;min-width:250px;" />
<select name="region" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:13px;background:#FFFFFF;">
<option value="all" {"selected" if region_clean == "all" else ""}>All Tier-1 Markets</option>
<option value="national" {"selected" if region_clean == "national" else ""}>US National</option>
<option value="california" {"selected" if region_clean == "california" else ""}>California</option>
<option value="norway" {"selected" if region_clean == "norway" else ""}>Norway</option>
<option value="germany" {"selected" if region_clean == "germany" else ""}>Germany</option>
<option value="united-kingdom" {"selected" if region_clean == "united-kingdom" else ""}>United Kingdom</option>
<option value="texas" {"selected" if region_clean == "texas" else ""}>Texas</option>
</select>
<button type="submit" style="padding:8px 14px;background:#111827;color:#FFFFFF;border:none;border-radius:6px;font-size:13px;font-weight:600;cursor:pointer;">Filter</button>
<a href="/croissant.json" target="_blank" rel="noopener" style="margin-left:auto;font-size:12px;color:#003B73;font-weight:600;">Croissant JSON-LD →</a>
<a href="/api/v1/hf-dataset.jsonl?{filter_qs}" target="_blank" rel="noopener" style="font-size:12px;color:#003B73;font-weight:600;">JSONL Stream →</a>
<a href="{origin_esc}/methodology?utm_source={html.escape(source_tag)}" target="_blank" rel="noopener" style="font-size:12px;color:#003B73;font-weight:600;">$79 Commercial Pass →</a>
</form>
</header>
{widget_html}
{banner_html}
<section style="display:grid;grid-template-columns:repeat(auto-fill,minmax(310px,1fr));gap:16px;">
{cards_joined}
</section>
</main>
</body>
</html>"""
return HTMLResponse(content=page, headers={"Cache-Control": "public, max-age=300"})
|