Spaces:
Running on Zero
Running on Zero
Download lab/export_csv.py from Segizu/timestral-backtest-lab: direct link, hf CLI and curl.
- Browser
- Download file 2.07 kB
-
https://huggingface.co/spaces/Segizu/timestral-backtest-lab/resolve/main/lab/export_csv.py
- Command line
-
hf download hf://spaces/Segizu/timestral-backtest-lab/lab/export_csv.py
-
curl -L -o export_csv.py https://huggingface.co/spaces/Segizu/timestral-backtest-lab/resolve/main/lab/export_csv.py
2.07 kB
| """Downloadable CSV writers with formula injection escaping.""" | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import Any, Mapping | |
| import numpy as np | |
| import pandas as pd | |
| def escape_csv_cell(value: Any) -> str: | |
| """Neutralize spreadsheet formula injection for untrusted string cells.""" | |
| if value is None: | |
| return "" | |
| if isinstance(value, (int, float, np.integer, np.floating)): | |
| if isinstance(value, (float, np.floating)) and not np.isfinite(value): | |
| return "" | |
| return str(value) | |
| text = str(value) | |
| if text and text[0] in {"=", "+", "-", "@", "\t", "\r"}: | |
| return "'" + text | |
| return text | |
| def _safe_frame(columns: dict[str, Any]) -> pd.DataFrame: | |
| data = {k: [escape_csv_cell(v) for v in vals] for k, vals in columns.items()} | |
| return pd.DataFrame(data) | |
| def write_forecast_csv( | |
| path: Path | str, | |
| *, | |
| times: list[Any], | |
| median: np.ndarray, | |
| q_low: np.ndarray, | |
| q_high: np.ndarray, | |
| low_level: float, | |
| high_level: float, | |
| ) -> Path: | |
| path = Path(path) | |
| median = np.asarray(median, dtype=np.float64) | |
| q_low = np.asarray(q_low, dtype=np.float64) | |
| q_high = np.asarray(q_high, dtype=np.float64) | |
| frame = _safe_frame( | |
| { | |
| "time": list(times), | |
| "median": median.tolist(), | |
| f"q{low_level:g}": q_low.tolist(), | |
| f"q{high_level:g}": q_high.tolist(), | |
| } | |
| ) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| frame.to_csv(path, index=False) | |
| return path | |
| def write_metrics_csv(path: Path | str, rows: Mapping[str, Mapping[str, Any]]) -> Path: | |
| path = Path(path) | |
| models: list[str] = [] | |
| maes: list[Any] = [] | |
| mases: list[Any] = [] | |
| for name, metrics in rows.items(): | |
| models.append(name) | |
| maes.append(metrics.get("mae", "")) | |
| mases.append(metrics.get("mase", "")) | |
| frame = _safe_frame({"model": models, "mae": maes, "mase": mases}) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| frame.to_csv(path, index=False) | |
| return path | |