"use client"; import { useEffect, useMemo, useState } from "react"; import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis, } from "recharts"; import { TrendingUp, Target, Thermometer, Hash, BarChart3, Crosshair } from "lucide-react"; type MetricPayload = { hit_rate: number; mae: number; total_days: number; brier_score?: number; }; type TrainingCity = { city_id: string; name: string; deb?: MetricPayload; mu?: MetricPayload; }; const STAT_CARD_CLASSES: Record = { blue: "bg-blue-50 border-blue-200", emerald: "bg-emerald-50 border-emerald-200", amber: "bg-amber-50 border-amber-200", purple: "bg-purple-50 border-purple-200", }; const STAT_ICON_CLASSES: Record = { blue: "text-blue-600", emerald: "text-emerald-600", amber: "text-amber-600", purple: "text-purple-600", }; function barColor(hr: number) { if (hr >= 65) return "#059669"; if (hr >= 45) return "#d97706"; return "#dc2626"; } const TRAINING_CACHE_KEY = "polyweather_training_accuracy_v1"; const TRAINING_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours function readTrainingCache(): TrainingCity[] | null { try { const raw = localStorage.getItem(TRAINING_CACHE_KEY); if (!raw) return null; const cached = JSON.parse(raw); if (cached.ts && Date.now() - cached.ts < TRAINING_CACHE_TTL_MS && Array.isArray(cached.data)) { return cached.data; } } catch { /* ignore */ } return null; } function writeTrainingCache(data: TrainingCity[]) { try { localStorage.setItem(TRAINING_CACHE_KEY, JSON.stringify({ ts: Date.now(), data })); } catch { /* ignore */ } } export function TrainingDashboard({ isEn }: { isEn: boolean }) { const [data, setData] = useState(() => readTrainingCache()); useEffect(() => { let cancelled = false; fetch("/api/ops/training/accuracy", { cache: "no-store", headers: { Accept: "application/json" } }) .then(async (res) => { if (!res.ok) return null; return res.json() as Promise<{ accuracy: TrainingCity[] }>; }) .then((payload) => { if (cancelled || !payload?.accuracy) return; const filtered = payload.accuracy.filter((c) => (c.deb || c.mu) && ((c.deb?.total_days ?? 0) + (c.mu?.total_days ?? 0)) >= 5); setData(filtered); writeTrainingCache(filtered); }) .catch(() => {}); return () => { cancelled = true; }; }, []); const debSorted = useMemo(() => (data || []).filter((c) => c.deb).sort((a, b) => (b.deb?.hit_rate ?? 0) - (a.deb?.hit_rate ?? 0)), [data]); const muSorted = useMemo(() => (data || []).filter((c) => c.mu).sort((a, b) => (b.mu?.hit_rate ?? 0) - (a.mu?.hit_rate ?? 0)), [data]); const debStats = useMemo(() => { if (!debSorted.length) return null; const avgHit = debSorted.reduce((s, c) => s + (c.deb?.hit_rate ?? 0), 0) / debSorted.length; const avgMae = debSorted.reduce((s, c) => s + (c.deb?.mae ?? 0), 0) / debSorted.length; const avgDays = Math.round(debSorted.reduce((s, c) => s + (c.deb?.total_days ?? 0), 0) / Math.max(debSorted.length, 1)); return { avgHit, avgMae, avgDays, cities: debSorted.length }; }, [debSorted]); const muStats = useMemo(() => { if (!muSorted.length) return null; const avgHit = muSorted.reduce((s, c) => s + (c.mu?.hit_rate ?? 0), 0) / muSorted.length; const avgMae = muSorted.reduce((s, c) => s + (c.mu?.mae ?? 0), 0) / muSorted.length; const avgBrier = muSorted.reduce((s, c) => s + (c.mu?.brier_score ?? 0), 0) / muSorted.length; const avgDays = Math.round(muSorted.reduce((s, c) => s + (c.mu?.total_days ?? 0), 0) / Math.max(muSorted.length, 1)); return { avgHit, avgMae, avgBrier, avgDays, cities: muSorted.length }; }, [muSorted]); const debHitChart = useMemo( () => debSorted.slice(0, 18).map((c) => ({ name: c.name, value: Number((c.deb?.hit_rate ?? 0).toFixed(1)) })), [debSorted], ); const debMaeChart = useMemo( () => [...debSorted].sort((a, b) => (a.deb?.mae ?? 99) - (b.deb?.mae ?? 99)).slice(0, 18).map((c) => ({ name: c.name, value: Number((c.deb?.mae ?? 0).toFixed(2)) })), [debSorted], ); const muHitChart = useMemo( () => muSorted.slice(0, 18).map((c) => ({ name: c.name, value: Number((c.mu?.hit_rate ?? 0).toFixed(1)) })), [muSorted], ); const muBrierChart = useMemo( () => [...muSorted].sort((a, b) => (a.mu?.brier_score ?? 99) - (b.mu?.brier_score ?? 99)).slice(0, 18).map((c) => ({ name: c.name, value: Number((c.mu?.brier_score ?? 0).toFixed(3)) })), [muSorted], ); return (

{isEn ? "Model Training Accuracy" : "模型训练准确率"}

{isEn ? "DEB temperature forecast vs. Probability Mu calibration — per-city backtesting metrics." : "DEB 气温预报 与 概率 μ 校准 — 各城市回测指标。"}

{/* ── DEB Section ── */} {debStats && ( <>

{isEn ? "DEB Temperature Forecast" : "DEB 气温预报"}

{[ { icon: Hash, label: isEn ? "Cities" : "城市数", value: debStats.cities, tone: "blue" }, { icon: Target, label: isEn ? "Avg Hit" : "平均命中", value: `${debStats.avgHit.toFixed(1)}%`, tone: "emerald" }, { icon: Thermometer, label: isEn ? "Avg Error" : "平均误差", value: `${debStats.avgMae.toFixed(1)}°`, tone: "amber" }, { icon: TrendingUp, label: isEn ? "Avg Days/City" : "每城平均天数", value: debStats.avgDays.toLocaleString(), tone: "purple" }, ].map(({ icon: Icon, label, value, tone }) => (
{label}
{String(value)}
))}
`${v}%`} /> [`${Number(v)}%`, isEn ? "Hit Rate" : "命中率"]} /> `${v}°`} /> [`${Number(v)}°`, isEn ? "Error" : "误差"]} />
)} {/* ── Mu Section ── */} {muStats && ( <>

{isEn ? "Probability Mu Calibration" : "概率 μ 校准"}

{[ { icon: Hash, label: isEn ? "Cities" : "城市数", value: muStats.cities, tone: "blue" }, { icon: Target, label: isEn ? "Avg Hit" : "平均命中", value: `${muStats.avgHit.toFixed(1)}%`, tone: "emerald" }, { icon: Thermometer, label: isEn ? "Avg Error" : "平均误差", value: `${muStats.avgMae.toFixed(2)}°`, tone: "amber" }, { icon: Crosshair, label: isEn ? "Avg Brier" : "平均 Brier", value: muStats.avgBrier.toFixed(4), tone: "purple" }, ].map(({ icon: Icon, label, value, tone }) => (
{label}
{String(value)}
))}
`${v}%`} /> [`${Number(v)}%`, isEn ? "Hit Rate" : "命中率"]} /> `${Number(v).toFixed(2)}`} /> [`${Number(v).toFixed(4)}`, "Brier"]} />
)} {/* ── Combined Table ── */}
{debSorted.length || muSorted.length ? ( (() => { const cities = new Map(); for (const c of debSorted) cities.set(c.city_id, { deb: c.deb, mu: c.mu, name: c.name }); for (const c of muSorted) { const existing = cities.get(c.city_id); if (existing) existing.mu = c.mu; else cities.set(c.city_id, { deb: c.deb, mu: c.mu, name: c.name }); } const merged = [...cities.entries()] .sort((a, b) => { const aMax = Math.max(a[1].deb?.hit_rate ?? 0, a[1].mu?.hit_rate ?? 0); const bMax = Math.max(b[1].deb?.hit_rate ?? 0, b[1].mu?.hit_rate ?? 0); return bMax - aMax; }) .slice(0, 30); return merged.map(([cityId, { deb, mu, name }], i) => { const debHit = deb?.hit_rate ?? 0; const muHit = mu?.hit_rate ?? 0; const brier = mu?.brier_score; return ( ); }); })() ) : ( )}
# {isEn ? "City" : "城市"} {isEn ? "DEB Hit" : "DEB 命中"} {isEn ? "DEB Error" : "DEB 误差"} {isEn ? "μ Hit" : "μ 命中"} Brier {isEn ? "Days" : "天数"}
{i + 1} {name} {deb ? `${debHit.toFixed(0)}%` : "--"} {deb ? `${deb.mae.toFixed(1)}°` : "--"} {mu ? `${muHit.toFixed(0)}%` : "--"} {brier != null ? brier.toFixed(4) : "--"} {(deb?.total_days ?? 0) + (mu?.total_days ?? 0)}
{data === null ? (isEn ? "Loading..." : "加载中...") : (isEn ? "No training data" : "暂无训练数据")}

{isEn ? "DEB = temperature forecast accuracy. μ = probability calibration. Brier = lower is better. Updated daily." : "DEB = 气温预报准确率。μ = 概率校准。Brier = 越低越好。每日更新。"}

); } function ChartCard({ title, children }: { title: string; children: React.ReactNode }) { return (

{title}

{children}
); }