Spaces:
Runtime error
Runtime error
Deploy Space: update src
Browse files2 unmodified lines345678274 unmodified lines2832842852862872882892902912 unmodified lines2942952962972982993003013023038 unmodified lines312313314315316317318297 unmodified lines6166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546551 unmodified line6576586596606616626636646656666676686696706716726736742 unmodified linesimport jsonimport osimport refrom pathlib import Pathimport numpy as np274 unmodified linesdef dataset_short_name(dataset: str) -> str:if dataset in DATASET_SHORT_NAMES:return DATASET_SHORT_NAMES[dataset]label = dataset.replace("_", " ")for prefix in ("open meteo ", "noaa coops ", "noaa ndbc ", "nws ", "usgs ", "wikimedia "):if label.lower().startswith(prefix):label = label[len(prefix) :]2 unmodified linesdef lookup_dataset_domain(dataset: str, root_dir: str = "results") -> str:# Primary: dataset_properties.csvprops_path = Path(root_dir) / "dataset_properties.csv"if props_path.exists():props = pd.read_csv(props_path)match = props[props["dataset"].str.lower() == dataset.lower()]if not match.empty and "domain" in match.columns:return str(match.iloc[0]["domain"])8 unmodified linescontinue# dataset column in all_results is "dataset_id/freq/term", strip suffixdf["_ds_key"] = df["dataset"].astype(str).str.split("/").str[0]match = df[df["_ds_key"].str.lower() == dataset.lower()]if not match.empty:return str(match.iloc[0]["domain"])except Exception:297 unmodified lines}def make_domain_pie_chart(root_dir: str = "results") -> object | None:"""Build a plotly Pie chart showing dataset count per domain.Uses dataset_properties.csv for domain info, with display_domain mapping.Returns None if plotly is unavailable or no data."""go = _get_plotly()if go is None:return Noneprops_path = Path(root_dir) / "dataset_properties.csv"if not props_path.exists():return Nonetry:df = pd.read_csv(props_path)except Exception:return Noneif df.empty or "domain" not in df.columns:return Nonedf["display_domain"] = df["domain"].map(lambda d: display_domain(d))# Build per-domain dataset list for hover textdomain_datasets: dict[str, list[str]] = {}for _, row in df.iterrows():dd = row["display_domain"]ds_name = dataset_short_name(str(row.get("dataset", "")))domain_datasets.setdefault(dd, []).append(ds_name)labels = list(domain_datasets.keys())values = [len(v) for v in domain_datasets.values()]hover = [", ".join(ds_list) for ds_list in domain_datasets.values()]colors = [DOMAIN_COLORS.get(label, "#94a3b8") for label in labels]fig = go.Figure(data=[go.Pie(1 unmodified linevalues=values,hovertext=hover,hoverinfo="label+percent+text",textinfo="label+value",marker=dict(colors=colors),hole=0.35,)])fig.update_layout(title=dict(text="Dataset coverage by domain", font=dict(size=14)),margin=dict(l=20, r=20, t=50, b=20),height=320,paper_bgcolor="rgba(0,0,0,0)",plot_bgcolor="rgba(0,0,0,0)",font=dict(color="black"),legend=dict(orientation="h", yanchor="bottom", y=-0.15, xanchor="center", x=0.5),showlegend=True,)return fig2 unmodified lines3456789274 unmodified lines2842852862872882892902912922932 unmodified lines2962972982993003013023033043053068 unmodified lines315316317318319320321297 unmodified lines6196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427431 unmodified line7457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648652 unmodified linesimport jsonimport osimport refrom datetime import datetime, timedelta, timezonefrom pathlib import Pathimport numpy as np274 unmodified linesdef dataset_short_name(dataset: str) -> str:base = dataset.split("/")[0].strip()if base in DATASET_SHORT_NAMES:return DATASET_SHORT_NAMES[base]label = base.replace("_", " ")for prefix in ("open meteo ", "noaa coops ", "noaa ndbc ", "nws ", "usgs ", "wikimedia "):if label.lower().startswith(prefix):label = label[len(prefix) :]2 unmodified linesdef lookup_dataset_domain(dataset: str, root_dir: str = "results") -> str:# Primary: dataset_properties.csvbase = dataset.split("/")[0].strip()props_path = Path(root_dir) / "dataset_properties.csv"if props_path.exists():props = pd.read_csv(props_path)match = props[props["dataset"].str.lower() == base.lower()]if not match.empty and "domain" in match.columns:return str(match.iloc[0]["domain"])8 unmodified linescontinue# dataset column in all_results is "dataset_id/freq/term", strip suffixdf["_ds_key"] = df["dataset"].astype(str).str.split("/").str[0]match = df[df["_ds_key"].str.lower() == base.lower()]if not match.empty:return str(match.iloc[0]["domain"])except Exception:297 unmodified lines}def _today_start_utc8() -> datetime:"""Return midnight today in UTC+8 as an aware datetime."""utc8 = timezone(timedelta(hours=8))return datetime.now(utc8).replace(hour=0, minute=0, second=0, microsecond=0)def get_dataset_last_eval_time(ds_base: str, root_dir: str = "results") -> datetime | None:latest_dt: datetime | None = None# Scan model directoriesfor model_dir in Path(root_dir).iterdir():if not model_dir.is_dir():continueforecasts_dir = model_dir / "forecasts"if not forecasts_dir.is_dir():continue# Find files matching the base namefor fp in forecasts_dir.glob(f"{ds_base}*.json"):try:# To be super fast, regex search for evaluated_atcontent = fp.read_text()match = re.search(r'"evaluated_at"\s*:\s*"([^"]+)"', content)if match:eval_at = match.group(1)dt = datetime.fromisoformat(eval_at.replace("Z", "+00:00"))if latest_dt is None or dt > latest_dt:latest_dt = dtexcept Exception:continuereturn latest_dtdef make_domain_pie_chart(root_dir: str = "results") -> object | None:"""Build a plotly Pie chart showing evaluated timestamp count per domain today.Reads eval_history.jsonl to count total evaluated timestamps since UTC+8 00:00 today,grouped by domain."""go = _get_plotly()if go is None:return None# Domain mapping from dataset_properties.csvprops_path = Path(root_dir) / "dataset_properties.csv"if not props_path.exists():return Nonetry:props = pd.read_csv(props_path)except Exception:return Nonedomain_map: dict[str, str] = {}for _, row in props.iterrows():domain_map[str(row["dataset"]).lower()] = display_domain(str(row["domain"]))today_start = _today_start_utc8()utc8 = today_start.tzinfo# Read eval_history.jsonlhistory_path = Path(root_dir) / "eval_history.jsonl"timestamp_counts: dict[str, int] = {} # domain → total timestampsdomain_datasets: dict[str, set[str]] = {} # domain → set of dataset short namesif history_path.exists():try:with open(history_path) as f:for line in f:if not line.strip():continueentry = json.loads(line)eval_at = entry.get("evaluated_at", "")if eval_at:eval_dt = datetime.fromisoformat(eval_at.replace("Z", "+00:00"))if eval_dt.astimezone(utc8) >= today_start:ds_base = entry.get("dataset", "")pred_len = entry.get("prediction_length", 0)domain = domain_map.get(ds_base.lower(), "Other")timestamp_counts[domain] = timestamp_counts.get(domain, 0) + pred_lendomain_datasets.setdefault(domain, set()).add(dataset_short_name(ds_base))except Exception:pass# Fallback to current snapshots count if history is empty or failsif not timestamp_counts:seen_datasets: set[str] = set()for model_dir in sorted(Path(root_dir).iterdir()):forecasts_dir = model_dir / "forecasts"if not forecasts_dir.is_dir():continuefor fp in forecasts_dir.glob("*.json"):try:snap = json.loads(fp.read_text())except Exception:continueeval_at = snap.get("evaluated_at", "")if eval_at:try:eval_dt = datetime.fromisoformat(eval_at.replace("Z", "+00:00"))if eval_dt.astimezone(utc8) < today_start:continueexcept Exception:continueds_full = snap.get("dataset", "")ds_base = ds_full.split("/")[0]if ds_base in seen_datasets:continueseen_datasets.add(ds_base)domain = domain_map.get(ds_base.lower(), "Other")n_ts = len(snap.get("context", [])) + len(snap.get("actuals", []))timestamp_counts[domain] = timestamp_counts.get(domain, 0) + n_tsdomain_datasets.setdefault(domain, set()).add(dataset_short_name(ds_base))if not timestamp_counts:return Nonelabels = list(timestamp_counts.keys())values = list(timestamp_counts.values())hover = [", ".join(sorted(domain_datasets.get(d, []))) for d in labels]colors = [DOMAIN_COLORS.get(label, "#94a3b8") for label in labels]fig = go.Figure(data=[go.Pie(1 unmodified linevalues=values,hovertext=hover,hoverinfo="label+percent+text",textinfo="label+value+percent",textposition="inside",textfont=dict(size=14, color="white"),insidetextorientation="radial",marker=dict(colors=colors),hole=0.25,)])fig.update_layout(title=dict(text="Evaluated timestamps by domain (today, UTC+8)",font=dict(size=16, weight="bold"),),margin=dict(l=20, r=20, t=60, b=20),height=500,paper_bgcolor="rgba(0,0,0,0)",plot_bgcolor="rgba(0,0,0,0)",font=dict(color="black"),showlegend=True,legend=dict(orientation="h",yanchor="bottom",y=-0.1,xanchor="center",x=0.5))return fig# ---------------------------------------------------------------------------# Per-domain status helpers# ---------------------------------------------------------------------------def load_eval_intervals(root_dir: str = "results") -> dict[str, int]:"""Load per-dataset eval intervals from dataset_eval_intervals.json."""path = Path(root_dir) / "dataset_eval_intervals.json"if not path.exists():return {}try:return {str(k): int(v) for k, v in json.loads(path.read_text()).items()}except Exception:return {}def _format_interval(seconds: int) -> str:if seconds >= 86400:d = seconds // 86400return f"{d}d"if seconds >= 3600:h = seconds // 3600return f"{h}h"if seconds >= 60:m = seconds // 60return f"{m}min"return f"{seconds}s"def build_domain_status_md(domain: str,datasets: list[str],root_dir: str = "results",) -> str:"""Build a compact markdown status line for a domain tab.Shows data source, last eval time, last evaluated time for this domain,and per-dataset refresh intervals."""utc8 = timezone(timedelta(hours=8))# 1. Last eval time from online_status.jsonstatus_path = Path(root_dir) / "online_status.json"last_eval = "n/a"data_source = "TS-Bench"if status_path.exists():try:status = json.loads(status_path.read_text())finished = status.get("finished_at", "")if finished:dt = datetime.fromisoformat(finished.replace("Z", "+00:00"))last_eval = dt.astimezone(utc8).strftime("%Y-%m-%d %H:%M:%S") + " (UTC+8)"data_source = status.get("data_source", "TS-Bench")except Exception:pass# 2. Last evaluated time for this domain (max of all datasets in the domain)domain_latest_dt: datetime | None = Nonefor ds in datasets:ds_base = ds.split("/")[0].strip()eval_dt = get_dataset_last_eval_time(ds_base, root_dir)if eval_dt:if domain_latest_dt is None or eval_dt > domain_latest_dt:domain_latest_dt = eval_dtlast_evaluated = "n/a"if domain_latest_dt:last_evaluated = domain_latest_dt.astimezone(utc8).strftime("%Y-%m-%d %H:%M:%S") + " (UTC+8)"# 3. Auto-refresh per-datasetintervals = load_eval_intervals(root_dir)ds_parts: list[str] = []for ds in datasets:short = dataset_short_name(ds)ds_base = ds.split("/")[0].strip()interval = intervals.get(ds_base)if interval:ds_parts.append(f"{short} every {_format_interval(interval)}")else:ds_parts.append(short)parts = [f"**Data**: {data_source}",f"**Last eval**: {last_eval}",f"**Last evaluated**: {last_evaluated}",]if ds_parts:parts.append("**Refresh**: " + " · ".join(ds_parts))return " | ".join(parts)
src/utils.py+219-28