-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathascends_server.py
More file actions
1906 lines (1697 loc) · 70.4 KB
/
ascends_server.py
File metadata and controls
1906 lines (1697 loc) · 70.4 KB
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import logging
from pathlib import Path
from joblib import dump
from datetime import datetime
import shutil
import json
import re
from typing import Optional, Dict, Any, List
from fastapi import Request, Form, UploadFile, File
from fastapi import Query
import io
from joblib import load
from urllib.parse import quote
from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse
import pandas as pd
import numpy as np
from math import sqrt
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
r2_score,
mean_absolute_error,
mean_squared_error,
accuracy_score,
precision_score,
recall_score,
f1_score,
roc_auc_score,
ConfusionMatrixDisplay,
)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor, HistGradientBoostingRegressor
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
import matplotlib
matplotlib.use("Agg") # headless
import matplotlib.pyplot as plt
import time
try:
import xgboost as xgb # type: ignore
except Exception:
xgb = None # xgb optional; we'll fallback if absent
from uuid import uuid4
import dcor
from sklearn.feature_selection import mutual_info_regression, mutual_info_classif
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from ascends.core.explain import (
explain_model as core_explain,
save_importance_plot,
save_default_shap_plot,
)
logger = logging.getLogger("ascends.gui")
app = FastAPI(title="ASCENDS GUI", version="0.1.0")
BASE_DIR = Path(__file__).parent
TEMPLATES_DIR = BASE_DIR / "templates"
STATIC_DIR = BASE_DIR / "static"
WORKSPACE_DIR = BASE_DIR / "workspace"
UPLOADS_DIR = WORKSPACE_DIR / "uploads"
PREVIEW_NROWS = 5
def _ws_dir(ws_id: str) -> Path:
"""Workspace directory for a given session id."""
return WORKSPACE_DIR / ws_id
TEMPLATES_DIR.mkdir(exist_ok=True)
STATIC_DIR.mkdir(exist_ok=True)
UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
def _safe_csv_filename(original: str) -> str:
stem = Path(original).stem[:50] or "upload"
return f"{stem}-{uuid4().hex[:8]}.csv"
MAX_UPLOAD_BYTES = 50 * 1024 * 1024 # 50 MB
async def _save_csv(file: UploadFile) -> Path:
name = _safe_csv_filename(file.filename or "data.csv")
dest = UPLOADS_DIR / name
content = await file.read()
if len(content) > MAX_UPLOAD_BYTES:
raise ValueError(f"File too large ({len(content) // (1024 * 1024)} MB). Maximum allowed is 50 MB.")
dest.write_bytes(content)
return dest
def _manifest_path(ws_id: str) -> Path:
return _ws_dir(ws_id) / "manifest.json"
def _corr_dirs(ws_id: str) -> tuple[Path, Path]:
"""Return (data_dir, img_dir) for correlation artifacts."""
data_dir = _ws_dir(ws_id) / "corr"
img_dir = STATIC_DIR / "workspace" / ws_id / "corr"
data_dir.mkdir(parents=True, exist_ok=True)
img_dir.mkdir(parents=True, exist_ok=True)
return data_dir, img_dir
def _compute_correlations(
df: pd.DataFrame, target: str, inputs: List[str], metrics: List[str], task: str
) -> Dict[str, pd.DataFrame]:
y = df[target].values
X = df[inputs]
out: Dict[str, pd.DataFrame] = {}
# Pearson
if "pearson" in metrics:
vals = []
for c in inputs:
x = df[c].values
if np.std(x) == 0 or np.std(y) == 0:
vals.append((c, 0.0))
else:
r = np.corrcoef(x, y)[0, 1]
vals.append((c, float(r)))
pearson_df = pd.DataFrame(vals, columns=["feature", "score"]).sort_values(
by="score", key=lambda s: np.abs(s), ascending=False
)
out["pearson"] = pearson_df
# Spearman (Pearson on ranks; no SciPy dependency)
if "spearman" in metrics:
vals = []
y_rank = pd.Series(y).rank(method="average").values
for c in inputs:
x_rank = df[c].rank(method="average").values
if np.std(x_rank) == 0 or np.std(y_rank) == 0:
vals.append((c, 0.0))
else:
r = np.corrcoef(x_rank, y_rank)[0, 1]
vals.append((c, float(r)))
spearman_df = pd.DataFrame(vals, columns=["feature", "score"]).sort_values(
by="score", key=lambda s: np.abs(s), ascending=False
)
out["spearman"] = spearman_df
# Mutual information
if "mi" in metrics:
if task == "c":
# Classification target: expect integer labels
y_disc = pd.Series(y).astype("category").cat.codes.values
mi_vals = mutual_info_classif(X.values, y_disc, random_state=0)
else:
mi_vals = mutual_info_regression(X.values, y, random_state=0)
mi_df = pd.DataFrame({"feature": inputs, "score": mi_vals}).sort_values(
by="score", ascending=False
)
out["mi"] = mi_df
# Distance correlation
if "dcor" in metrics:
vals = []
y_f = np.asarray(y, dtype=np.float64)
# Optional speed cap for very large datasets
n = len(y_f)
if n > 5000:
rng = np.random.RandomState(0)
idx = rng.choice(n, 5000, replace=False)
y_f = y_f[idx]
X_sub = X.iloc[idx, :]
else:
X_sub = X
for c in inputs:
x = np.asarray(X_sub[c].values, dtype=np.float64)
try:
s = float(dcor.distance_correlation(x, y_f))
except Exception:
s = 0.0
vals.append((c, s))
dcor_df = pd.DataFrame(vals, columns=["feature", "score"]).sort_values(
by="score", ascending=False
)
out["dcor"] = dcor_df
return out
def _plot_metric_bars(
scores: pd.DataFrame,
metric: str,
target: str,
n_used: int,
out_png: Path,
top_k: Optional[int] = None,
) -> None:
# Sort & limit to Top-K
dfp = scores.copy()
if metric in {"pearson", "spearman"}:
dfp = dfp.sort_values(by="score", key=lambda s: np.abs(s), ascending=False)
else:
dfp = dfp.sort_values(by="score", ascending=False)
if top_k and top_k > 0:
dfp = dfp.head(top_k)
# Figure size (golden ratio), tuned a bit for readability
fig_w = 8.0
fig_h = fig_w / 1.618 # golden ratio
fig, ax = plt.subplots(figsize=(fig_w, fig_h), dpi=300)
# Vertical bars: features on X axis
x = np.arange(len(dfp))
ax.bar(x, dfp["score"])
ax.set_xticks(x)
ax.set_xticklabels(list(dfp["feature"]), rotation=55, ha="right")
ax.set_xlabel("Feature")
ax.set_ylabel("Score")
ax.set_title(f"{metric.title()} vs. {target} (N={n_used})")
# Grid and baseline for signed metrics
ax.grid(axis="y", linestyle=":", alpha=0.4)
if metric in {"pearson", "spearman"}:
ax.axhline(0.0, linewidth=0.8, alpha=0.6, color="black")
# Tight layout with extra bottom room for labels
fig.tight_layout()
fig.subplots_adjust(bottom=0.28)
out_png.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(out_png, bbox_inches="tight")
plt.close(fig)
def _prepare_corr_dataframe(csv_path: str, target: str, inputs: List[str]) -> tuple[pd.DataFrame, Dict[str, Any]]:
raw = pd.read_csv(csv_path)
cols = list(inputs) + [target]
# Keep only requested columns that actually exist
existing = [c for c in cols if c in raw.columns]
df = raw.loc[:, existing].copy()
# Coerce to numeric for all used columns
for c in existing:
df[c] = pd.to_numeric(df[c], errors="coerce")
rows_before = len(df)
# Drop any rows with NaNs in used columns
df = df.dropna(axis=0, how="any")
rows_after = len(df)
# Ensure floating dtype for all used columns (dcor prefers float arrays)
df = df.astype("float64")
dropped = rows_before - rows_after
# Skip constant input columns
skipped: List[str] = []
good_inputs: List[str] = []
for c in inputs:
if c in df.columns:
if df[c].nunique(dropna=True) <= 1:
skipped.append(c)
else:
good_inputs.append(c)
# Final column order: good inputs + target (if present)
keep_cols = [c for c in good_inputs if c in df.columns] + ([target] if target in df.columns else [])
df = df.loc[:, keep_cols]
info: Dict[str, Any] = {
"rows_in": rows_before,
"rows_used": rows_after,
"rows_dropped": dropped,
"skipped_inputs": skipped,
"used_inputs": good_inputs,
}
return df, info
def _save_manifest(ws_id: str, data: Dict[str, Any]) -> None:
"""Save the manifest for a given workspace ID."""
d = _ws_dir(ws_id)
d.mkdir(parents=True, exist_ok=True)
_manifest_path(ws_id).write_text(json.dumps(data, indent=2), encoding="utf-8")
def _load_manifest(ws_id: str) -> Dict[str, Any]:
"""Load the manifest for a given workspace ID."""
p = _manifest_path(ws_id)
if p.exists():
return json.loads(p.read_text(encoding="utf-8"))
return {}
@app.get("/favicon.svg")
async def _favicon_svg():
# Serve the SVG to requests for /favicon.svg
return FileResponse(STATIC_DIR / "favicon.svg", media_type="image/svg+xml")
@app.get("/apple-touch-icon.png")
@app.get("/apple-touch-icon-precomposed.png")
async def _apple_touch_icon():
# iOS prefers PNG, but serving SVG avoids 404 and is acceptable as a placeholder.
return FileResponse(STATIC_DIR / "favicon.svg", media_type="image/svg+xml")
@app.get("/health")
def health() -> Dict[str, Any]:
return {"status": "ok", "port": 7777}
@app.get("/", response_class=HTMLResponse)
async def home(request: Request) -> HTMLResponse:
return templates.TemplateResponse("home.html", {"request": request})
@app.get("/ui-lab", response_class=HTMLResponse)
async def ui_lab(request: Request) -> HTMLResponse:
"""TS + utility-first UI proof page."""
return templates.TemplateResponse("ui_lab.html", {"request": request})
# Helper to preserve order & uniqueness
def _unique_preserve(seq: List[str]) -> List[str]:
seen = set()
out: List[str] = []
for x in seq:
if x not in seen:
seen.add(x)
out.append(x)
return out
# Replace /train GET with context that loads manifest using ws_id or cookie
# Replace the /train GET to load manifest by ws_id (from query or cookie)
# Replace the /train GET with a version that logs what it sees
@app.get("/train", response_class=HTMLResponse)
async def train_page(request: Request, ws_id: Optional[str] = None) -> HTMLResponse:
ws = ws_id or request.query_params.get("ws_id")
ctx: Dict[str, Any] = {"request": request, "ws_id": ws}
if ws:
mf = _load_manifest(ws) or {}
shap_view = str(mf.get("shap_view", "ascends")).lower()
if shap_view not in {"ascends", "default"}:
shap_view = "ascends"
ctx.update({
"csv_path": mf.get("csv_path"),
"all_columns": mf.get("columns", []),
"selected": mf.get("selected", []),
"inputs": mf.get("inputs", []),
"target": mf.get("target"),
"shap_view": shap_view,
})
# DESIGN DECISION:
# Keep ASCENDS custom plot as the default UI because users found it more readable.
# If "default" plot is requested but unavailable, fallback to ASCENDS plot.
shap_png = STATIC_DIR / "workspace" / ws / "train" / f"shap_importance_{shap_view}.png"
legacy_png = STATIC_DIR / "workspace" / ws / "train" / "shap_importance.png"
fallback_png = STATIC_DIR / "workspace" / ws / "train" / "shap_importance_ascends.png"
shap_csv = _ws_dir(ws) / "train" / "shap_importance.csv"
if shap_png.exists():
ctx["shap_img_url"] = f"/static/workspace/{ws}/train/{shap_png.name}?ts={int(time.time())}"
elif shap_view == "default" and fallback_png.exists():
ctx["shap_img_url"] = f"/static/workspace/{ws}/train/{fallback_png.name}?ts={int(time.time())}"
elif legacy_png.exists():
ctx["shap_img_url"] = f"/static/workspace/{ws}/train/{legacy_png.name}?ts={int(time.time())}"
if shap_csv.exists():
try:
df_shap = pd.read_csv(shap_csv).head(10)
ctx["shap_rows"] = df_shap.values.tolist()
except Exception:
pass
# Always include saved runs for the bottom-right pane
ctx["saved_runs"] = _list_saved_runs()
return templates.TemplateResponse("train.html", ctx)
@app.post("/train/shap", response_class=HTMLResponse)
async def train_shap(
request: Request,
ws_id: str = Form(...),
max_samples: int = Form(300),
shap_view: str = Form("ascends"),
) -> HTMLResponse:
"""Compute SHAP/permutation importance for the latest trained model in this workspace."""
mf = _load_manifest(ws_id) or {}
ctx: Dict[str, Any] = {
"request": request,
"ws_id": ws_id,
"csv_path": mf.get("csv_path"),
"all_columns": mf.get("columns", []),
"selected": mf.get("selected", []),
"inputs": mf.get("inputs", []),
"target": mf.get("target"),
"saved_runs": _list_saved_runs(),
}
shap_view = str(shap_view or "ascends").lower()
if shap_view not in {"ascends", "default"}:
shap_view = "ascends"
ctx["shap_view"] = shap_view
rec = LAST_TRAIN.get(ws_id)
if not rec:
ctx["train_error"] = "No trained model found in this workspace. Train first, then run SHAP."
return templates.TemplateResponse("train.html", ctx)
# Keep showing existing train outputs if present
ctx["metrics_train"] = rec.get("metrics_train")
ctx["metrics_test"] = rec.get("metrics_test")
ctx["parity_img_url"] = rec.get("parity_img_url")
csv_path = rec.get("csv_path")
inputs = rec.get("inputs", [])
target = rec.get("target")
task = rec.get("params", {}).get("task", "r")
est = rec.get("estimator")
if not csv_path or not est or not inputs or not target:
ctx["train_error"] = "Insufficient training context for SHAP. Re-train and try again."
return templates.TemplateResponse("train.html", ctx)
try:
df = pd.read_csv(csv_path)
required = [c for c in inputs if c in df.columns] + ([target] if target in df.columns else [])
if target not in required:
raise ValueError("Target column missing in source CSV.")
df2 = df[required].dropna(axis=0, how="any")
X = df2[inputs]
y = df2[target]
task_name = "classification" if str(task).lower() == "c" else "regression"
expl = core_explain(
model=est,
X=X,
y=y,
task=task_name,
max_samples=max(50, int(max_samples)),
random_state=42,
)
except Exception as e:
ctx["train_error"] = f"SHAP failed: {e}"
return templates.TemplateResponse("train.html", ctx)
# Save artifacts
data_dir = _ws_dir(ws_id) / "train"
data_dir.mkdir(parents=True, exist_ok=True)
img_dir = _train_img_dir(ws_id)
csv_out = data_dir / "shap_importance.csv"
report_out = data_dir / "shap_report.json"
png_ascends = img_dir / "shap_importance_ascends.png"
png_default = img_dir / "shap_importance_default.png"
imp_df = expl["importance_df"]
imp_df.to_csv(csv_out, index=False)
save_importance_plot(
imp_df,
png_ascends,
method=str(expl.get("method", "shap")),
top_n=20,
)
default_ready = False
if str(expl.get("method", "")).lower() == "shap":
try:
save_default_shap_plot(
model=est,
X=X,
out_png=png_default,
max_samples=max(50, int(max_samples)),
random_state=42,
max_display=20,
)
default_ready = True
except Exception as e:
warn = str(expl.get("warning") or "").strip()
extra = f"Default SHAP view failed ({e}); using ASCENDS view."
expl["warning"] = f"{warn} {extra}".strip() if warn else extra
report_out.write_text(
json.dumps(
{
"method": expl.get("method"),
"warning": expl.get("warning"),
"n_samples": expl.get("n_samples"),
"csv_path": str(csv_out),
"png_ascends_path": str(png_ascends),
"png_default_path": str(png_default) if default_ready else None,
},
indent=2,
),
encoding="utf-8",
)
selected_png = png_default if (shap_view == "default" and default_ready) else png_ascends
ctx["shap_img_url"] = f"/static/workspace/{ws_id}/train/{selected_png.name}?ts={int(time.time())}"
ctx["shap_rows"] = imp_df.head(10).values.tolist()
if expl.get("warning"):
ctx["shap_warning"] = expl["warning"]
# Persist UI preference for next Train page load.
mf["shap_view"] = shap_view
_save_manifest(ws_id, mf)
return templates.TemplateResponse("train.html", ctx)
@app.post("/train/shap/view", response_class=HTMLResponse)
async def train_shap_view(
request: Request,
ws_id: str = Form(...),
shap_view: str = Form("ascends"),
) -> HTMLResponse:
"""Switch displayed SHAP image without recomputing model explanation."""
mf = _load_manifest(ws_id) or {}
shap_view = str(shap_view or "ascends").lower()
if shap_view not in {"ascends", "default"}:
shap_view = "ascends"
mf["shap_view"] = shap_view
_save_manifest(ws_id, mf)
ctx: Dict[str, Any] = {
"request": request,
"ws_id": ws_id,
"csv_path": mf.get("csv_path"),
"all_columns": mf.get("columns", []),
"selected": mf.get("selected", []),
"inputs": mf.get("inputs", []),
"target": mf.get("target"),
"saved_runs": _list_saved_runs(),
"shap_view": shap_view,
}
rec = LAST_TRAIN.get(ws_id)
if rec:
ctx["metrics_train"] = rec.get("metrics_train")
ctx["metrics_test"] = rec.get("metrics_test")
ctx["parity_img_url"] = rec.get("parity_img_url")
img_dir = _train_img_dir(ws_id)
selected_png = img_dir / f"shap_importance_{shap_view}.png"
fallback_png = img_dir / "shap_importance_ascends.png"
legacy_png = img_dir / "shap_importance.png"
if selected_png.exists():
ctx["shap_img_url"] = f"/static/workspace/{ws_id}/train/{selected_png.name}?ts={int(time.time())}"
elif fallback_png.exists():
ctx["shap_img_url"] = f"/static/workspace/{ws_id}/train/{fallback_png.name}?ts={int(time.time())}"
if shap_view == "default":
ctx["shap_warning"] = "Default SHAP view is not available for this run. Showing ASCENDS view."
elif legacy_png.exists():
ctx["shap_img_url"] = f"/static/workspace/{ws_id}/train/{legacy_png.name}?ts={int(time.time())}"
shap_csv = _ws_dir(ws_id) / "train" / "shap_importance.csv"
if shap_csv.exists():
try:
df_shap = pd.read_csv(shap_csv).head(10)
ctx["shap_rows"] = df_shap.values.tolist()
except Exception:
pass
return templates.TemplateResponse("train.html", ctx)
@app.post("/train/select", response_class=HTMLResponse)
async def train_select(
request: Request,
ws_id: str = Form(...),
action: str = Form(...),
columns: Optional[List[str]] = Form(None),
rm_inputs: Optional[List[str]] = Form(None),
target_choice: Optional[str] = Form(None),
) -> HTMLResponse:
"""Handle Train tab selection state (columns/inputs/target)."""
mf = _load_manifest(ws_id)
if not mf:
return templates.TemplateResponse(
"train.html",
{
"request": request,
"ws_id": ws_id,
"train_error": "Invalid session. Please upload/select data from Correlation tab first.",
"saved_runs": _list_saved_runs(),
},
)
all_columns: List[str] = list(mf.get("columns", []))
selected = set(mf.get("selected", []))
inputs = set(mf.get("inputs", []))
target = mf.get("target")
chosen_cols = columns or []
to_remove = rm_inputs or []
if action == "select_all":
selected = set(all_columns)
elif action == "select_none":
selected = set()
elif action == "to_inputs":
selected = set(chosen_cols)
for c in chosen_cols:
if c in all_columns:
inputs.add(c)
if target in inputs:
inputs.discard(target)
elif action == "remove_inputs":
for c in to_remove:
inputs.discard(c)
elif action == "set_target":
selected = set(chosen_cols)
if target_choice and target_choice in all_columns:
target = target_choice
if target in inputs:
inputs.discard(target)
ordered_inputs = sorted(inputs, key=lambda c: all_columns.index(c)) if all_columns else list(inputs)
ordered_selected = sorted(selected, key=lambda c: all_columns.index(c)) if all_columns else list(selected)
mf["inputs"] = ordered_inputs
mf["target"] = target
mf["selected"] = ordered_selected
_save_manifest(ws_id, mf)
ctx: Dict[str, Any] = {
"request": request,
"ws_id": ws_id,
"csv_path": mf.get("csv_path"),
"all_columns": all_columns,
"inputs": ordered_inputs,
"target": target,
"selected": ordered_selected,
"saved_runs": _list_saved_runs(),
}
return templates.TemplateResponse("train.html", ctx)
# Save the current trained model and artifacts into runs/<name>/
@app.post("/train/save", response_class=HTMLResponse)
async def train_save(
request: Request,
ws_id: str = Form(...),
save_name: Optional[str] = Form(None),
) -> HTMLResponse:
ctx: Dict[str, Any] = {"request": request, "ws_id": ws_id}
# Load manifest to re-populate panes
mf = _load_manifest(ws_id) or {}
ctx.update({
"csv_path": mf.get("csv_path"),
"all_columns": mf.get("columns", []),
"selected": mf.get("selected", []),
"inputs": mf.get("inputs", []),
"target": mf.get("target"),
})
rec = LAST_TRAIN.get(ws_id)
if not rec:
ctx["train_error"] = "No trained model available to save. Please Train first."
ctx["saved_runs"] = _list_saved_runs()
return templates.TemplateResponse("train.html", ctx)
# Determine run name
base = save_name or (rec["params"].get("model", "model") + "_" + datetime.now().strftime("%Y%m%d_%H%M%S"))
run_name = _unique_run_name(base) # also creates the directory atomically
out_dir = RUNS_DIR / run_name
# Save model
try:
dump(rec["estimator"], out_dir / "model.joblib")
except Exception as e:
ctx["train_error"] = f"Failed to save model: {e}"
shutil.rmtree(out_dir, ignore_errors=True)
ctx["saved_runs"] = _list_saved_runs()
return templates.TemplateResponse("train.html", ctx)
# Save metrics.csv (supports both regression and classification metric keys)
try:
import pandas as _pd
train_metrics = dict(rec.get("metrics_train", {}))
test_metrics = dict(rec.get("metrics_test", {}))
dfm = _pd.DataFrame(
[
{"split": "Train", **train_metrics},
{"split": "Test", **test_metrics},
]
)
dfm.to_csv(out_dir / "metrics.csv", index=False)
except Exception as e:
ctx["train_error"] = f"Failed to write metrics.csv: {e}"
shutil.rmtree(out_dir, ignore_errors=True)
ctx["saved_runs"] = _list_saved_runs()
return templates.TemplateResponse("train.html", ctx)
# Save manifest.json for the run
manifest = {
"name": run_name,
"created_at": rec["timestamp"],
"task": rec["params"].get("task", "r"),
"model": rec["params"].get("model"),
"seed": rec["params"].get("seed"),
"test_size": rec["params"].get("test_size"),
"tune": rec["params"].get("tune"),
"inputs": rec.get("inputs", []),
"target": rec.get("target"),
"csv_path": rec.get("csv_path"),
"ws_id": ws_id,
}
try:
(out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
except Exception as e:
ctx["train_error"] = f"Failed to write manifest.json: {e}"
shutil.rmtree(out_dir, ignore_errors=True)
ctx["saved_runs"] = _list_saved_runs()
return templates.TemplateResponse("train.html", ctx)
# Copy train visualization (parity/confusion) if present
try:
ws_train_dir = STATIC_DIR / "workspace" / ws_id / "train"
parity_img = ws_train_dir / "parity.png"
confusion_img = ws_train_dir / "confusion.png"
shap_img = ws_train_dir / "shap_importance_ascends.png"
if parity_img.exists():
shutil.copyfile(parity_img, out_dir / "parity.png")
if confusion_img.exists():
shutil.copyfile(confusion_img, out_dir / "confusion.png")
if shap_img.exists():
shutil.copyfile(shap_img, out_dir / "shap_importance.png")
except Exception:
pass
# Generate report.html
try:
_generate_report(run_name, out_dir, rec, ws_id)
except Exception as e:
logger.warning("Report generation failed for %s: %s", run_name, e)
ctx["save_ok"] = f"Saved run: {run_name}"
ctx["saved_runs"] = _list_saved_runs()
return templates.TemplateResponse("train.html", ctx)
@app.get("/train/report", response_class=HTMLResponse)
async def train_report_preview(request: Request, ws_id: str = Query(...)) -> HTMLResponse:
"""Render a live report from LAST_TRAIN without requiring Save."""
rec = LAST_TRAIN.get(ws_id)
if not rec:
return HTMLResponse(content="No trained model found. Please train a model first.", status_code=404)
return HTMLResponse(content=_render_report_html("(unsaved)", rec, ws_id))
def _render_report_html(run_name: str, rec: Dict[str, Any], ws_id: str, out_dir: Optional[Path] = None) -> str:
"""Render report.html from a LAST_TRAIN record and return HTML string.
When out_dir is provided (saved run), plot src paths are relative to the
run directory so the report works when opened directly from the filesystem.
"""
from ascends.core.interpret import interpret_run
task = rec["params"].get("task", "r")
task_label = "Classification" if task == "c" else "Regression"
train_metrics = dict(rec.get("metrics_train") or {})
test_metrics = dict(rec.get("metrics_test") or {})
inputs = rec.get("inputs", [])
target = rec.get("target", "")
n_train = rec.get("n_train") or 0
n_test = rec.get("n_test") or 0
metric_keys = list(dict.fromkeys(list(train_metrics.keys()) + list(test_metrics.keys())))
# Load SHAP importance if available
importance_rows = []
importance_df = None
shap_csv = _ws_dir(ws_id) / "train" / "shap_importance.csv"
if shap_csv.exists():
try:
importance_df = pd.read_csv(shap_csv)
importance_rows = importance_df.head(15).values.tolist()
except Exception:
pass
# Load target values for MAE context
target_values = None
if task in ("r", "regression"):
try:
csv_path = rec.get("csv_path")
if csv_path:
df_tmp = pd.read_csv(csv_path, usecols=[target])
target_values = df_tmp[target].dropna().tolist()
except Exception:
pass
raw_insights = interpret_run(
task=task,
train_metrics=train_metrics,
test_metrics=test_metrics,
n_train=n_train,
n_test=n_test,
target_values=target_values,
importance_df=importance_df,
)
def _level(text: str) -> str:
low = text.lower()
if any(w in low for w in ("overfitting", "imbalance", "leakage", "worse", "low", "poor", "large error", "small training", "heavily relies")):
return "warn"
if any(w in low for w in ("very good", "excellent", "consistent", "low error", "good")):
return "good"
return ""
insights = [{"text": t, "level": _level(t)} for t in raw_insights]
# Plot paths: relative for saved reports, absolute URLs for live preview
plot_files = []
if out_dir is not None:
for fname, label in [("parity.png", "Parity Plot"), ("confusion.png", "Confusion Matrix"), ("shap_importance.png", "Feature Importance")]:
if (out_dir / fname).exists():
plot_files.append({"src": fname, "label": label})
else:
ws_train_dir = STATIC_DIR / "workspace" / ws_id / "train"
for fname, label, url_name in [
("parity.png", "Parity Plot", "parity.png"),
("confusion.png", "Confusion Matrix", "confusion.png"),
("shap_importance_ascends.png", "Feature Importance", "shap_importance_ascends.png"),
]:
if (ws_train_dir / fname).exists():
plot_files.append({"src": f"/static/workspace/{ws_id}/train/{url_name}", "label": label})
return templates.get_template("report.html").render(
run_name=run_name,
task_label=task_label,
model=rec["params"].get("model", ""),
target=target,
created_at=rec.get("timestamp", ""),
train_metrics=train_metrics,
test_metrics=test_metrics,
metric_keys=metric_keys,
n_train=n_train,
n_test=n_test,
insights=insights,
plot_files=plot_files,
importance_rows=importance_rows,
inputs=inputs,
test_size=rec["params"].get("test_size", ""),
seed=rec["params"].get("seed", ""),
)
def _generate_report(run_name: str, out_dir: Path, rec: Dict[str, Any], ws_id: str) -> None:
"""Render report.html into the run directory.
For saved runs, plot src attributes use relative paths so the report
is portable (works when opened directly from the filesystem).
"""
# Build a copy of rec with plot paths pointing to the run directory
rec_saved = dict(rec)
html = _render_report_html(run_name, rec_saved, ws_id, out_dir=out_dir)
(out_dir / "report.html").write_text(html, encoding="utf-8")
@app.get("/runs/{run_name}/report.html", response_class=HTMLResponse)
async def serve_report(run_name: str) -> HTMLResponse:
"""Serve the saved report.html for a run."""
report_path = RUNS_DIR / run_name / "report.html"
if not report_path.exists():
return HTMLResponse(content="Report not found.", status_code=404)
return HTMLResponse(content=report_path.read_text(encoding="utf-8"))
# Delete a saved run directory
@app.post("/train/delete", response_class=HTMLResponse)
async def train_delete(
request: Request,
run_name: str = Form(...),
ws_id: Optional[str] = Form(None),
) -> HTMLResponse:
ctx: Dict[str, Any] = {"request": request}
target_dir = RUNS_DIR / run_name
if target_dir.exists() and target_dir.is_dir():
try:
shutil.rmtree(target_dir)
ctx["save_ok"] = f"Deleted run: {run_name}"
except Exception as e:
ctx["train_error"] = f"Failed to delete run {run_name}: {e}"
else:
ctx["train_error"] = f"Run not found: {run_name}"
# Keep workspace context after delete so Train/SHAP panels remain stable.
if ws_id:
return RedirectResponse(url=f"/train?ws_id={quote(ws_id)}", status_code=303)
# Fallback when no workspace context exists.
ctx["saved_runs"] = _list_saved_runs()
return templates.TemplateResponse("train.html", ctx)
@app.get("/predict", response_class=HTMLResponse)
async def predict_page(request: Request, run: Optional[str] = None) -> HTMLResponse:
"""Render Predict tab with saved runs and (optional) preselected run via ?run=."""
selected_run = run or request.query_params.get("run")
ctx: Dict[str, Any] = {
"request": request,
"saved_runs": _list_saved_runs(),
"selected_run": selected_run,
}
return templates.TemplateResponse("predict.html", ctx)
@app.post("/predict/run", response_class=HTMLResponse)
async def predict_run(
request: Request,
run_name: str = Form(...),
csvfile: UploadFile = File(...),
) -> HTMLResponse:
"""Schema validation (case-insensitive), coerce/clean, predict, save CSV, preview."""
errors: list[str] = []
ctx: Dict[str, Any] = {
"request": request,
"saved_runs": _list_saved_runs(),
"selected_run": run_name,
"predict_summary": None,
"predict_preview_headers": None,
"predict_preview_rows": None,
"download_csv_url": None,
"download_xlsx_url": None,
}
# Basic form checks
if not run_name:
errors.append("Please select a saved model (run).")
if not csvfile or not csvfile.filename:
errors.append("Please upload a CSV file.")
if errors:
ctx["predict_errors"] = errors
return templates.TemplateResponse("predict.html", ctx)
# Load run manifest
man_path = RUNS_DIR / run_name / "manifest.json"
if not man_path.exists():
ctx["predict_errors"] = [f"Run '{run_name}' is missing manifest.json."]
return templates.TemplateResponse("predict.html", ctx)
try:
manifest = json.loads(man_path.read_text(encoding="utf-8"))
except Exception as e:
ctx["predict_errors"] = [f"Failed to read manifest.json for '{run_name}': {e}"]
return templates.TemplateResponse("predict.html", ctx)
inputs: List[str] = manifest.get("inputs", []) or []
target: Optional[str] = manifest.get("target") or None
if not inputs:
ctx["predict_errors"] = [f"Run '{run_name}' has no recorded input features in manifest.json."]
return templates.TemplateResponse("predict.html", ctx)
# Read uploaded CSV to DataFrame (in-memory)
try:
raw = await csvfile.read()
df = pd.read_csv(io.BytesIO(raw))
except Exception as e:
ctx["predict_errors"] = [f"Failed to parse uploaded CSV: {e}"]
return templates.TemplateResponse("predict.html", ctx)
if df.empty:
ctx["predict_errors"] = ["Uploaded CSV is empty."]
return templates.TemplateResponse("predict.html", ctx)
# Header mapping: exact match first, then unique case-insensitive fallback.
csv_cols = list(df.columns)
lower_candidates: Dict[str, List[str]] = {}
for c in csv_cols:
lower_candidates.setdefault(c.lower(), []).append(c)
mapping: Dict[str, str] = {}
missing: List[str] = []
for feat in inputs:
if feat in df.columns:
mapping[feat] = feat
continue
key = feat.lower()
cands = lower_candidates.get(key, [])
if len(cands) == 1:
mapping[feat] = cands[0]
else:
missing.append(feat)
if missing:
ctx["predict_errors"] = [
"Missing required feature(s) in CSV (case-insensitive match failed): "
+ ", ".join(missing)
]
return templates.TemplateResponse("predict.html", ctx)
# Align columns in manifest order; coerce to numeric and drop NA rows on required inputs
aligned_cols = [mapping[f] for f in inputs] # actual column names in csv, ordered per manifest
df_aligned = df[aligned_cols].copy()
for c in df_aligned.columns:
df_aligned[c] = pd.to_numeric(df_aligned[c], errors="coerce")
rows_read = len(df_aligned)
df_used = df_aligned.dropna(axis=0, how="any")
rows_used = len(df_used)
dropped = rows_read - rows_used
if rows_used == 0:
ctx["predict_errors"] = [f"All {rows_read} rows contained NA/invalid values in required inputs; nothing to predict."]
return templates.TemplateResponse("predict.html", ctx)
# Load estimator
model_path = RUNS_DIR / run_name / "model.joblib"
if not model_path.exists():
ctx["predict_errors"] = [f"Run '{run_name}' is missing model.joblib."]
return templates.TemplateResponse("predict.html", ctx)
try:
est = load(model_path)
except Exception as e:
ctx["predict_errors"] = [f"Failed to load model.joblib: {e}"]
return templates.TemplateResponse("predict.html", ctx)
# Predict
try: