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 = ( '' '' + "".join(f"{html.escape(u)}daily" for u in urls) + "" ) 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"""
2026 B2B Infra, EU AI Act & H100 GPU Cost Estimator LIVE TCO SANITY CHECK
3-Year Total Commitment $487,320
Compare Reserved Bare-Metal vs AWS/GCP → Full EU AI Act + SOC 2 Audit Breakdown →
""" if active_mode == "agent_eval_arena": return f"""
Live MCP JSON-RPC 2.0 & Croissant Grounding Bridge View MCP Manifest →
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"}}}}}}
""" return f"""
2026 Quick VW EV vs Gas 5-Year Energy & Tax Credit Arbitrage CALIBRATED BENCHMARK CALCULATOR
Est. 5-Yr Fuel Savings +$5,320 EV Lead
Unlock Exact VW ID.4 ZIP & Utility Audit → Full 25-Matchup VW 5-Year Matrix →
""" @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"""
GOLDEN EVAL · {html.escape(str(row.get('eval_id', '')))} {band}

{prompt}

Ground Truth Metric: {leader} | Personal Variance: ${vmin:,}–${vmax:,}

POST /api/v1/mcp -> {tool_call} Verify Live Citation Bridge →
""" ) 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"""
{html.escape(str(row.get('segment', 'tco')))} · {tier} {band}

{title}

Leader / Baseline: {winner}

Personal ZIP & Credit-Tier Variance: ${vmin:,}–${vmax:,} ({hint})

Unlock Exact ZIP & APR Savings → Full Benchmark Breakdown
""" ) top_leaders = leaderboard.get("vwDominanceLeaderboard", [])[:3] leader_pills = "".join( f'
' f'{html.escape(str(l.get("title", "")))}
' f'VW wins {html.escape(str(l.get("vwWinRateMarkets", "")))} markets · {html.escape(str(l.get("bandedMaxAdvantageUsd", "")))}' f'
' for l in top_leaders ) banner_html = ( f'
{leader_pills}
' if leader_pills and active_mode != "ai_b2b_whale" else "" ) cards_joined = "\n".join(cards_html) or '

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(" {html.escape(active_title)}
AVERAGECOST HUGGING FACE AUTHORITY CONSTELLATION · 2026

{html.escape(active_title)}

Backed by MLCommons Croissant schema, 5-split HF Dataset, and MCP tool calling. Verify exact live utility tariffs & rebates directly on AverageCostCalculator.com.

Croissant JSON-LD → JSONL Stream → $79 Commercial Pass →
{widget_html} {banner_html}
{cards_joined}
""" return HTMLResponse(content=page, headers={"Cache-Control": "public, max-age=300"})