-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2375 lines (2109 loc) · 123 KB
/
app.py
File metadata and controls
2375 lines (2109 loc) · 123 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
import streamlit as st
import pandas as pd
import numpy as np
import os
import io
import sys
import logging
import importlib
import queue
from src.task_catalog import DATA_CATEGORIES, get_framework_options, get_task_options, infer_multimodal_columns
def _compat_fragment(*args, **kwargs):
"""Use st.fragment when available, otherwise behave as a no-op decorator."""
fragment_fn = getattr(st, "fragment", None)
if fragment_fn is not None:
return fragment_fn(*args, **kwargs)
def _decorator(func):
return func
# Support bare decorator usage: @_compat_fragment
if args and callable(args[0]) and len(args) == 1 and not kwargs:
return args[0]
return _decorator
# Development Cache Optimization (optional via URL ?dev=true)
dev_mode = st.query_params.get("dev", "false").lower() == "true"
if dev_mode:
st.sidebar.info("🛠️ Dev Mode: Reload active")
modules_to_reload = [
'src.autogluon_utils',
'src.flaml_utils',
'src.h2o_utils',
'src.tpot_utils',
'src.mlflow_cache'
]
for module in modules_to_reload:
if module in sys.modules:
importlib.reload(sys.modules[module])
# Functions with cache for Performance
@st.cache_data(show_spinner="Loading data...")
def cached_load_data(file_path_or_obj, no_header=False):
from src.data_utils import load_data
return load_data(file_path_or_obj, no_header=no_header)
@st.cache_data
def cached_get_data_summary(df):
from src.data_utils import get_data_summary
return get_data_summary(df)
@st.cache_data(ttl=60) # 1 Minute Cache for file list
def cached_get_data_lake_files():
from src.data_utils import get_data_lake_files
return get_data_lake_files()
# ── EDA stat helpers (cached per-DataFrame) ───────────────────────────────────
@st.cache_data(show_spinner=False)
def _compute_missing_stats(df: pd.DataFrame) -> pd.Series:
return df.isnull().mean().sort_values(ascending=False) * 100
@st.cache_data(show_spinner=False)
def _compute_type_counts(df: pd.DataFrame) -> pd.Series:
return df.dtypes.astype(str).value_counts()
@st.cache_data(show_spinner=False)
def _compute_column_summary(df: pd.DataFrame) -> pd.DataFrame:
return pd.DataFrame({
"Column": df.columns.tolist(),
"Type": df.dtypes.astype(str).tolist(),
"Missing": df.isnull().sum().tolist(),
"Unique": df.nunique().tolist(),
})
@st.cache_data(show_spinner=False)
def _compute_overview_stats(df: pd.DataFrame):
"""Returns (missing_pct_mean, memory_mb) — avoids scanning DF on every rerun."""
missing = df.isnull().mean().mean() * 100
memory = df.memory_usage(deep=True).sum() / 1024 ** 2
return missing, memory
# ── Cached matplotlib figures ─────────────────────────────────────────────────
@st.cache_data(show_spinner=False)
def _make_missing_fig(miss_series: pd.Series):
import matplotlib.pyplot as _plt
miss_df = miss_series[miss_series > 0]
if len(miss_df) == 0:
return None
fig, ax = _plt.subplots(figsize=(9, max(2.5, len(miss_df) * 0.4)))
fig.patch.set_facecolor("#161b22"); ax.set_facecolor("#0d1117")
ax.barh(miss_df.index.tolist(), miss_df.tolist(),
color=["#f85149" if v > 30 else "#d29922" for v in miss_df.tolist()],
edgecolor="#30363d")
ax.set_xlabel("Missing %", color="#8b949e")
ax.set_title("Missing Values per Column", color="#f0f6fc", fontsize=11)
ax.tick_params(colors="#8b949e", labelsize=8)
for sp in ax.spines.values(): sp.set_edgecolor("#30363d")
_plt.tight_layout()
return fig
@st.cache_data(show_spinner=False)
def _make_type_pie(type_counts: pd.Series):
import matplotlib.pyplot as _plt
colors_t = ["#58a6ff", "#3fb950", "#d29922", "#bc8cff", "#f85149"]
fig, ax = _plt.subplots(figsize=(6, 4))
fig.patch.set_facecolor("#161b22"); ax.set_facecolor("#161b22")
_, _, autotexts = ax.pie(
type_counts.values, labels=type_counts.index.tolist(),
colors=colors_t[:len(type_counts)], autopct="%1.1f%%",
textprops={"color": "#c9d1d9", "fontsize": 10}
)
for w in autotexts: w.set_color("#f0f6fc")
ax.set_title("Column Data Types", color="#f0f6fc", fontsize=11)
_plt.tight_layout()
return fig
@st.cache_data(show_spinner=False)
def _make_dist_fig(col_data: pd.Series, col_name: str):
import matplotlib.pyplot as _plt
fig, ax = _plt.subplots(figsize=(9, 3))
fig.patch.set_facecolor("#161b22"); ax.set_facecolor("#0d1117")
ax.hist(col_data.dropna(), bins=40, color="#58a6ff", edgecolor="#30363d", linewidth=0.4, alpha=0.85)
ax.set_title(f"Distribution: {col_name}", color="#f0f6fc", fontsize=11)
ax.set_xlabel(col_name, color="#8b949e"); ax.set_ylabel("Count", color="#8b949e")
ax.tick_params(colors="#8b949e", labelsize=8)
for sp in ax.spines.values(): sp.set_edgecolor("#30363d")
_plt.tight_layout()
return fig
@st.cache_data(show_spinner=False)
def _make_metrics_bar(metrics_items: tuple):
"""metrics_items = tuple of (key, value) pairs — hashable for cache."""
import matplotlib.pyplot as _plt
import matplotlib.ticker as _mticker
keys = [k for k, _ in metrics_items]
values = [v for _, v in metrics_items]
colors = ["#3fb950" if v >= 0 else "#f85149" for v in values]
fig, ax = _plt.subplots(figsize=(9, max(2.5, len(keys) * 0.45)))
fig.patch.set_facecolor("#161b22"); ax.set_facecolor("#0d1117")
ax.barh(keys, values, color=colors, edgecolor="#30363d", linewidth=0.5)
ax.set_title("MLflow Metrics", color="#f0f6fc", fontsize=12, pad=12)
ax.tick_params(colors="#8b949e", labelsize=9)
for sp in ax.spines.values(): sp.set_edgecolor("#30363d")
ax.xaxis.set_major_formatter(_mticker.FormatStrFormatter("%.4g"))
_plt.tight_layout()
return fig
@st.cache_data(show_spinner=False)
def _make_leaderboard_bar(labels: tuple, values: tuple, xlabel: str, title: str, color: str):
"""Generic horizontal bar chart for leaderboard tables."""
import matplotlib.pyplot as _plt
fig, ax = _plt.subplots(figsize=(9, max(2.5, len(labels) * 0.45)))
fig.patch.set_facecolor("#161b22"); ax.set_facecolor("#0d1117")
ax.barh(list(labels), list(values), color=color, edgecolor="#30363d")
ax.set_xlabel(xlabel, color="#8b949e")
ax.set_title(title, color="#f0f6fc", fontsize=11)
ax.tick_params(colors="#8b949e", labelsize=8)
for sp in ax.spines.values(): sp.set_edgecolor("#30363d")
_plt.tight_layout()
return fig
# ── MLflow data getters (top-level so @st.cache_data is effective) ────────────
@st.cache_data(ttl=30, show_spinner=False)
def _get_mlflow_run(run_id: str):
return mlflow.get_run(run_id)
@st.cache_data(ttl=60, show_spinner=False)
def _get_mlflow_artifacts(run_id: str):
return mlflow.MlflowClient().list_artifacts(run_id)
# ── Disk usage (cached 30 s to avoid high-frequency I/O in the 5 s fragment) ──
@st.cache_data(ttl=30, show_spinner=False)
def _get_disk_usage():
import shutil
return shutil.disk_usage(".")
# ── Log HTML builder (cached by content — avoids rebuilding every 5 s) ────────
@st.cache_data(show_spinner=False, max_entries=100)
def _build_log_html(log_tuple: tuple, max_lines: int = 80) -> str:
keywords_error = ["error", "exception", "traceback", "critical", "failed", "errno"]
keywords_warning = ["warning", "warn", "deprecated", "no space", "could not"]
keywords_success = ["success", "complete", "best model", "finished", "saved", "logged"]
keywords_info = ["info:", "[worker]", "starting", "initialized", "loading", "fitting"]
keywords_metric = ["accuracy", "f1", "score", "auc", "rmse", "mse", "r2", "loss"]
lines_html = []
for line in log_tuple[-max_lines:]:
ll = line.lower()
if any(k in ll for k in keywords_error):
cls = "log-line-error"
elif any(k in ll for k in keywords_warning):
cls = "log-line-warning"
elif any(k in ll for k in keywords_success):
cls = "log-line-success"
elif any(k in ll for k in keywords_metric):
cls = "log-line-metric"
elif any(k in ll for k in keywords_info):
cls = "log-line-info"
else:
cls = "log-line-normal"
safe_line = line.replace("&", "&").replace("<", "<").replace(">", ">")
lines_html.append(f'<div class="{cls}">{safe_line}</div>')
return '<div class="log-panel">' + "".join(lines_html) + '</div>'
# ── Pipeline steps (cached so log parsing doesn't run on every 5 s tick) ──────
@st.cache_data(show_spinner=False, max_entries=200)
def _get_pipeline_steps(framework_key: str, log_tuple: tuple, status: str):
from src.pipeline_parser import infer_pipeline_steps
return infer_pipeline_steps(framework_key, list(log_tuple), status)
@st.cache_data(show_spinner=False, max_entries=50)
def _get_column_nunique(df: pd.DataFrame, col: str) -> int:
"""Cached nunique for target column — avoids scanning the column on every rerun."""
return int(df[col].nunique()) if col in df.columns else 2
from src.log_utils import setup_logging_to_queue, StdoutRedirector
from src.mlflow_utils import heal_mlruns
from src.mlflow_cache import mlflow_cache, get_cached_experiment_list
from src.experiment_manager import get_or_create_manager, ExperimentEntry
from src.training_worker import run_training_worker
from src.ui_state import init_session_state
from src.navigation import NAV_ITEMS, init_navigation_state, sync_navigation_selection
from src.prediction_service import load_model_by_framework, run_predictions
import mlflow
import time
import threading
st.set_page_config(
page_title="Multi-AutoML Interface",
page_icon="🚀",
layout="wide",
initial_sidebar_state="expanded"
)
# ─── Premium CSS Design System ─────────────────────────────────────────────────
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
/* ── Base & Reset ─────────────────────────────────────────── */
html, body, [class*="css"] { font-family: 'Inter', sans-serif !important; }
.stApp { background: #080c12 !important; color: #c9d1d9 !important; }
/* remove default streamlit header padding */
.block-container { padding-top: 1.5rem !important; padding-bottom: 2rem !important; max-width: 1400px; }
/* ── Sidebar ─────────────────────────────────────────────── */
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #050b19 0%, #091429 100%) !important;
border-right: 1px solid #1f324e !important;
min-width: 260px;
}
[data-testid="stSidebar"] > div:first-child { padding-top: 0 !important; }
[data-testid="stSidebar"] .stSelectbox label,
[data-testid="stSidebar"] h1, [data-testid="stSidebar"] h2,
[data-testid="stSidebar"] h3, [data-testid="stSidebar"] p,
[data-testid="stSidebar"] label { color: #c9d1d9 !important; }
/* sidebar brand */
.sidebar-brand {
background: linear-gradient(135deg, #071225 0%, #0d213f 100%);
border-bottom: 1px solid #1f3e69;
padding: 28px 20px 22px;
margin: -16px -16px 20px;
position: relative;
overflow: hidden;
}
.sidebar-brand::before {
content: '';
position: absolute;
bottom: 0; left: 0; right: 0; height: 2px;
background: linear-gradient(90deg, #2563eb, #38bdf8, #60a5fa, #2563eb);
background-size: 300% 100%;
animation: brand-shimmer 4s linear infinite;
}
@keyframes brand-shimmer { 0%{background-position:0% 0%} 100%{background-position:300% 0%} }
.sidebar-brand-logo { font-size: 32px; margin-bottom: 8px; }
.sidebar-brand-title {
font-size: 18px; font-weight: 700;
background: linear-gradient(90deg, #e2edff, #8bd1ff);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
line-height: 1.2; margin-bottom: 4px;
}
.sidebar-brand-sub { font-size: 11px; color: #8ca7c7; letter-spacing: 0.08em; text-transform: uppercase; }
.sidebar-nav-title {
font-size: 11px;
font-weight: 600;
letter-spacing: 0.12em;
color: #7f97b8;
text-transform: uppercase;
margin: 6px 0 8px;
}
/* Sidebar navigation list (styled radio) */
[data-testid="stSidebar"] div[role="radiogroup"] {
display: flex;
flex-direction: column;
gap: 8px;
}
[data-testid="stSidebar"] div[role="radiogroup"] > label {
margin: 0;
background: transparent;
border: 1px solid transparent;
border-radius: 14px;
padding: 10px 12px;
transition: background 0.2s, border-color 0.2s, box-shadow 0.2s;
}
[data-testid="stSidebar"] div[role="radiogroup"] > label:hover {
background: #0c1a33;
border-color: #1f3962;
}
[data-testid="stSidebar"] div[role="radiogroup"] > label [data-testid="stMarkdownContainer"] p {
margin: 0;
color: #91add3;
font-size: 15px;
font-weight: 600;
letter-spacing: 0.01em;
}
[data-testid="stSidebar"] div[role="radiogroup"] > label:has(input[type="radio"]:checked) {
background: linear-gradient(90deg, #122949 0%, #173258 100%);
border-color: #3a8ed8;
box-shadow: inset 0 0 0 1px #1f5ea0;
}
[data-testid="stSidebar"] div[role="radiogroup"] > label:has(input[type="radio"]:checked) [data-testid="stMarkdownContainer"] p {
color: #e5f0ff;
}
[data-testid="stSidebar"] div[role="radiogroup"] input[type="radio"] {
display: none;
}
/* sidebar separator */
.sidebar-sep {
font-size: 10px; font-weight: 600; color: #374151;
text-transform: uppercase; letter-spacing: 0.12em;
padding: 12px 0 6px;
border-top: 1px solid #1e2736;
margin-top: 8px;
}
/* ── Page Title (replaces main-header) ───────────────────── */
.page-title {
display: flex; align-items: center; gap: 14px;
padding: 0 0 20px;
border-bottom: 1px solid #1e2736;
margin-bottom: 24px;
}
.page-title-icon {
width: 48px; height: 48px;
border-radius: 12px;
display: flex; align-items: center; justify-content: center;
font-size: 22px;
background: linear-gradient(135deg, #1e1b4b, #1e3a5f);
border: 1px solid #3730a3;
flex-shrink: 0;
}
.page-title-text h1 {
font-size: 22px; font-weight: 700; color: #f0f6fc; margin: 0 0 2px;
line-height: 1.2;
}
.page-title-text p { font-size: 13px; color: #6b7280; margin: 0; }
/* ── Cards ───────────────────────────────────────────────── */
.stat-card {
background: linear-gradient(135deg, #0f1729 0%, #111c30 100%);
border: 1px solid #1e2d45;
border-radius: 12px;
padding: 20px 16px;
text-align: center;
transition: border-color 0.2s, box-shadow 0.2s, transform 0.15s;
}
.stat-card:hover {
border-color: #4f46e5;
box-shadow: 0 4px 24px #4f46e520;
transform: translateY(-2px);
}
.stat-card .number { font-size: 38px; font-weight: 700; color: #f0f6fc; line-height: 1; }
.stat-card .label { font-size: 11px; color: #6b7280; margin-top: 8px; text-transform: uppercase; letter-spacing: 0.1em; }
/* ── Status Badges ───────────────────────────────────────── */
.badge {
display: inline-block; padding: 3px 10px;
border-radius: 20px; font-size: 11px; font-weight: 600;
letter-spacing: 0.05em; text-transform: uppercase;
}
.badge-running { background: #052e16; color: #4ade80; border: 1px solid #166534; animation: pulse-green 2s ease-in-out infinite; }
.badge-completed { background: #0c1a3d; color: #60a5fa; border: 1px solid #1e40af; }
.badge-failed { background: #2d0a0a; color: #f87171; border: 1px solid #7f1d1d; }
.badge-cancelled { background: #18181b; color: #71717a; border: 1px solid #27272a; }
.badge-queued { background: #1c1007; color: #fbbf24; border: 1px solid #78350f; }
@keyframes pulse-green { 0%,100%{box-shadow:0 0 0 0 #4ade8040} 50%{box-shadow:0 0 0 5px #4ade8010} }
/* ── Framework Badges ────────────────────────────────────── */
.fw-badge { display:inline-block; padding:3px 10px; border-radius:6px; font-size:11px; font-weight:700; }
.fw-autogluon { background: linear-gradient(135deg,#0c2340,#0f3460); color:#60a5fa; border:1px solid #1e40af; }
.fw-flaml { background: linear-gradient(135deg,#0a1628,#0d2348); color:#7dd3fc; border:1px solid #1e4e8c; }
.fw-h2o { background: linear-gradient(135deg,#052e16,#064e24); color:#4ade80; border:1px solid #166534; }
.fw-tpot { background: linear-gradient(135deg,#2d0a4a,#3b0f63); color:#c084fc; border:1px solid #7e22ce; }
.fw-pycaret { background: linear-gradient(135deg,#2d0a1b,#3c0e25); color:#fbcfe8; border:1px solid #be185d; }
.fw-lale { background: linear-gradient(135deg,#0f1f2e,#1a3650); color:#bae6fd; border:1px solid #0284c7; }
/* ── Pipeline Visualizer ─────────────────────────────────── */
.pipeline-container {
display: flex; align-items: center; gap: 0;
padding: 20px 4px; overflow-x: auto;
background: #0b1120; border-radius: 12px;
border: 1px solid #1e2736;
margin: 8px 0 16px;
}
.pipeline-step {
display: flex; flex-direction: column; align-items: center;
min-width: 110px; position: relative;
}
.pipeline-step-icon {
width: 46px; height: 46px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-size: 18px; border: 2px solid #1e2736;
background: #0b1120; z-index: 1; transition: all 0.3s;
}
.pipeline-step-icon.done { background:#052e16; border-color:#166534; }
.pipeline-step-icon.active { background:#0c1a3d; border-color:#3b82f6; box-shadow:0 0 18px #3b82f660; animation:glow-blue 2s ease-in-out infinite; }
.pipeline-step-icon.pending { opacity:0.45; }
.pipeline-step-icon.failed { background:#2d0a0a; border-color:#7f1d1d; }
.pipeline-step-icon.cancelled{ background:#18181b; border-color:#3f3f46; }
@keyframes glow-blue { 0%,100%{box-shadow:0 0 10px #3b82f650} 50%{box-shadow:0 0 26px #3b82f690} }
.pipeline-step-label { font-size:10px; text-align:center; margin-top:8px; color:#6b7280; max-width:90px; line-height:1.3; }
.pipeline-step-label.active { color:#60a5fa; font-weight:600; }
.pipeline-step-label.done { color:#4ade80; }
.pipeline-step-label.failed { color:#f87171; }
.pipeline-connector { flex:1; height:2px; min-width:20px; max-width:44px; background:#1e2736; margin-top:-20px; }
.pipeline-connector.done { background: linear-gradient(90deg,#166534,#4ade80); }
.pipeline-connector.active { background: linear-gradient(90deg,#166534,#3b82f6); }
/* ── Log Panel ───────────────────────────────────────────── */
.log-panel {
background: #020408;
border: 1px solid #1e2736;
border-radius: 10px;
padding: 16px;
font-family: 'JetBrains Mono', 'Consolas', monospace;
font-size: 12px; line-height: 1.65;
max-height: 360px; overflow-y: auto;
}
.log-line-normal { color: #64748b; }
.log-line-success { color: #4ade80; }
.log-line-warning { color: #fbbf24; }
.log-line-error { color: #f87171; }
.log-line-info { color: #60a5fa; }
.log-line-metric { color: #c084fc; }
.log-panel::-webkit-scrollbar { width:5px; }
.log-panel::-webkit-scrollbar-track { background:#0b1120; }
.log-panel::-webkit-scrollbar-thumb { background:#1e2736; border-radius:3px; }
.log-panel::-webkit-scrollbar-thumb:hover { background:#3b82f6; }
/* ── Experiment Card ─────────────────────────────────────── */
.exp-timer { font-family:'JetBrains Mono',monospace; font-size:11px; color:#fbbf24; }
/* ── Metric Pills ────────────────────────────────────────── */
.metric-pill {
display: inline-flex; align-items: center; gap: 8px;
background: #0f1729; border: 1px solid #1e2d45;
border-radius: 10px; padding: 12px 18px; margin: 4px;
}
.metric-pill .m-label { font-size:11px; color:#4b5563; text-transform:uppercase; letter-spacing:0.08em; }
.metric-pill .m-value { font-size:20px; font-weight:700; color:#e2e8f0; }
/* ── Preview Card ────────────────────────────────────────── */
.preview-card {
background: #0f1729; border: 1px solid #1e2d45;
border-radius: 12px; padding: 18px;
margin-bottom: 10px; transition: border-color 0.2s;
}
.preview-card:hover { border-color: #4f46e5; }
.preview-card h4 { color:#e2e8f0; font-size:13px; font-weight:600; margin:0 0 6px; }
.preview-card p { color:#6b7280; font-size:12px; margin:0; line-height:1.5; }
/* ── Buttons ─────────────────────────────────────────────── */
.stButton > button {
border-radius: 8px !important; font-weight: 500 !important;
font-family: 'Inter', sans-serif !important; transition: all 0.2s !important;
font-size: 13px !important;
}
.stButton > button[kind="primary"] {
background: linear-gradient(135deg, #4f46e5, #6366f1) !important;
border: none !important; color: white !important;
box-shadow: 0 4px 14px #4f46e540 !important;
}
.stButton > button[kind="primary"]:hover {
box-shadow: 0 6px 20px #4f46e570 !important;
transform: translateY(-1px);
}
.stButton > button[kind="secondary"] {
background: #0f1729 !important; border: 1px solid #1e2d45 !important;
color: #94a3b8 !important;
}
.stButton > button[kind="secondary"]:hover {
border-color: #4f46e5 !important; color: #a78bfa !important;
background: #1e1b4b !important;
}
/* ── Expanders ───────────────────────────────────────────── */
[data-testid="stExpander"] {
background: #0f1729 !important;
border: 1px solid #1e2d45 !important;
border-radius: 12px !important;
margin-bottom: 10px !important;
}
[data-testid="stExpander"]:hover {
border-color: #4f46e5 !important;
}
[data-testid="stExpander"] details summary {
font-weight: 500 !important; color: #94a3b8 !important;
font-size: 14px !important; padding: 14px 16px !important;
}
/* ── Tabs ────────────────────────────────────────────────── */
[data-testid="stTabs"] [data-testid="stTab"] {
background: transparent !important; color: #6b7280 !important;
font-size: 13px; font-weight: 500;
border-radius: 6px 6px 0 0; padding: 8px 16px;
transition: color 0.15s;
}
[data-testid="stTabs"] [aria-selected="true"] {
color: #a78bfa !important;
border-bottom: 2px solid #7c3aed !important;
}
[data-testid="stTabs"] { border-bottom: 1px solid #1e2736 !important; }
/* ── Inputs & Selects ────────────────────────────────────── */
.stTextInput input, .stSelectbox select, .stNumberInput input,
.stTextArea textarea {
background: #0b1120 !important;
border: 1px solid #1e2736 !important;
border-radius: 8px !important;
color: #c9d1d9 !important;
font-size: 13px !important;
}
.stTextInput input:focus, .stSelectbox select:focus {
border-color: #6366f1 !important;
box-shadow: 0 0 0 3px #6366f120 !important;
}
[data-testid="stSlider"] {
padding: 0 4px;
}
/* ── Dataframes ──────────────────────────────────────────── */
[data-testid="stDataFrame"] { border-radius: 10px; overflow: hidden; }
[data-testid="stDataFrame"] [data-testid="data-grid-canvas"] {
background: #0b1120 !important;
}
/* ── Alerts ──────────────────────────────────────────────── */
[data-testid="stAlert"] {
border-radius: 10px !important;
font-size: 13px !important;
}
/* ── Metrics ─────────────────────────────────────────────── */
[data-testid="stMetric"] {
background: #0f1729; border: 1px solid #1e2d45;
border-radius: 10px; padding: 16px !important;
}
[data-testid="stMetricLabel"] { color: #6b7280 !important; font-size: 12px !important; }
[data-testid="stMetricValue"] { color: #e2e8f0 !important; }
/* ── Section Headers ─────────────────────────────────────── */
.section-header {
font-size: 15px; font-weight: 600;
color: #94a3b8;
padding: 4px 0 10px;
border-bottom: 1px solid #1e2736;
margin-bottom: 18px;
display: flex; align-items: center; gap: 8px;
}
/* ── Info Cards ──────────────────────────────────────────── */
.info-card {
background: #0c1628; border: 1px solid #1e3a5f;
border-left: 3px solid #3b82f6;
border-radius: 8px; padding: 14px 18px;
font-size: 13px; color: #7dd3fc;
margin: 8px 0;
}
.info-card strong { color: #93c5fd; }
/* ── Horizontal Rule ─────────────────────────────────────── */
hr { border: none; border-top: 1px solid #1e2736 !important; margin: 20px 0 !important; }
/* scrollbar global */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: #0b1120; }
::-webkit-scrollbar-thumb { background: #1e2736; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #6366f1; }
</style>
""", unsafe_allow_html=True)
# ─── UI Helper Functions ────────────────────────────────────────────────────
def render_pipeline_visualization(framework_key: str, logs: list, status: str):
"""Render an interactive horizontal pipeline step visualization."""
steps = _get_pipeline_steps(framework_key, tuple(logs), status)
if not steps:
return
html_parts = ['<div class="pipeline-container">']
for i, step in enumerate(steps):
s = step["status"] # done | active | pending | failed | cancelled
icon_map = {"done": step["icon"], "active": step["icon"], "pending": step["icon"], "failed": "❌", "cancelled": "⛔"}
icon = icon_map.get(s, step["icon"])
if i > 0:
connector_cls = "done" if steps[i-1]["status"] == "done" else ("active" if steps[i-1]["status"] == "active" else "")
html_parts.append(f'<div class="pipeline-connector {connector_cls}"></div>')
tooltip = step.get("description", "")
html_parts.append(f'''
<div class="pipeline-step" title="{tooltip}">
<div class="pipeline-step-icon {s}">{icon}</div>
<div class="pipeline-step-label {s}">{step["label"]}</div>
</div>''')
html_parts.append('</div>')
st.markdown("".join(html_parts), unsafe_allow_html=True)
def render_colored_logs(logs: list, max_lines: int = 80):
"""Render logs in a styled dark terminal panel with color-coded lines."""
html = _build_log_html(tuple(logs), max_lines)
st.markdown(html, unsafe_allow_html=True)
def render_stat_cards(running: int, completed: int, failed: int, cancelled: int):
"""Render animated status metric cards."""
col1, col2, col3, col4 = st.columns(4)
cards = [
(col1, running, "🟢", "Running", "#3fb950"),
(col2, completed, "✅", "Completed", "#58a6ff"),
(col3, failed, "❌", "Failed", "#f85149"),
(col4, cancelled, "🚫", "Cancelled", "#d29922"),
]
for col, val, icon, lbl, color in cards:
with col:
st.markdown(f'''
<div class="stat-card">
<div class="number" style="color:{color}">{val}</div>
<div class="label">{icon} {lbl}</div>
</div>''', unsafe_allow_html=True)
def fw_badge_html(framework: str) -> str:
"""Return colored framework badge HTML."""
key = framework.lower().replace(" ", "").replace("automl", "")
label_map = {
"autogluon": ("AutoGluon", "fw-autogluon"),
"flaml": ("FLAML", "fw-flaml"),
"h2o": ("H2O", "fw-h2o"),
"tpot": ("TPOT", "fw-tpot"),
"pycaret": ("PyCaret", "fw-pycaret"),
"lale": ("Lale", "fw-lale"),
}
label, cls = label_map.get(key, (framework, ""))
return f'<span class="fw-badge {cls}">{label}</span>'
def status_badge_html(status: str) -> str:
"""Return colored status badge HTML."""
labels = {
"running": "🟢 Running",
"completed": "✅ Completed",
"failed": "❌ Failed",
"cancelled": "🚫 Cancelled",
"queued": "⏳ Queued",
}
label = labels.get(status, status.capitalize())
return f'<span class="badge badge-{status}">{label}</span>'
def render_metrics_pills(metrics: dict):
"""Render metric pills for key metrics."""
if not metrics:
return
pill_html = '<div style="display:flex;flex-wrap:wrap;">'
for k, v in metrics.items():
val_str = f"{v:.4f}" if isinstance(v, float) else str(v)
pill_html += f'''
<div class="metric-pill">
<div><div class="m-label">{k}</div><div class="m-value">{val_str}</div></div>
</div>'''
pill_html += '</div>'
st.markdown(pill_html, unsafe_allow_html=True)
# ─── End helpers ──────────────────────────────────────────────────────────────
# ── One-time startup: heal MLflow + set experiment (runs once per server session)
@st.cache_resource
def _startup_init():
"""Runs once when the server starts — keeps costly I/O out of the hot rerun path."""
from src.mlflow_utils import heal_mlruns, safe_set_experiment
try:
heal_mlruns()
except Exception:
pass
try:
safe_set_experiment("Multi_AutoML_Project")
except Exception:
pass
_startup_init()
# ── Session state initialisation (single consolidated pass) ───────────────────
init_session_state(st.session_state)
# Initialise the experiment manager singleton
exp_manager = get_or_create_manager(st.session_state)
# ── Sidebar brand ──────────────────────────────────────────────────────────
st.sidebar.markdown("""
<div class="sidebar-brand">
<div class="sidebar-brand-title">Multi-AutoML<br>Interface</div>
<div class="sidebar-brand-sub">Intelligent MLOps Workspace</div>
</div>""", unsafe_allow_html=True)
st.sidebar.markdown('<div class="sidebar-nav-title">Navigation</div>', unsafe_allow_html=True)
# Persist navigation state explicitly to avoid one-click lag/rerun race on hosted environments.
init_navigation_state(st.session_state, NAV_ITEMS)
_default_nav_label = st.session_state.get('menu_label', "🏠 Overview")
selected_nav_label = st.sidebar.radio(
label="Main navigation",
options=list(NAV_ITEMS.keys()),
index=list(NAV_ITEMS.keys()).index(_default_nav_label),
key="_main_nav_radio",
label_visibility="collapsed",
)
menu = sync_navigation_selection(st.session_state, selected_nav_label, NAV_ITEMS)
st.sidebar.markdown('<div class="sidebar-sep">Integrations</div>', unsafe_allow_html=True)
st.sidebar.header("🔗 DagsHub Integration (Optional)")
use_dagshub = st.sidebar.checkbox("Enable DagsHub")
if use_dagshub:
dagshub_user = st.sidebar.text_input("DagsHub Username")
dagshub_repo = st.sidebar.text_input("Repository Name")
dagshub_token = st.sidebar.text_input("Access Token (DagsHub)", type="password")
if st.sidebar.button("Connect to DagsHub"):
if dagshub_user and dagshub_repo and dagshub_token:
try:
import dagshub
import os
os.environ["MLFLOW_TRACKING_USERNAME"] = dagshub_user
os.environ["MLFLOW_TRACKING_PASSWORD"] = dagshub_token
dagshub.init(repo_owner=dagshub_user, repo_name=dagshub_repo, mlflow=True)
st.sidebar.success("Successfully connected to DagsHub!")
except ImportError:
st.sidebar.error("dagshub library not found. Add 'dagshub' to requirements.txt and install it.")
except Exception as e:
st.sidebar.error(f"Connection error: {e}")
else:
st.sidebar.warning("Please fill all DagsHub fields.")
st.sidebar.markdown("---")
if menu == "Data Upload":
st.markdown("""
<div class="page-title">
<div class="page-title-icon">📂</div>
<div class="page-title-text">
<h1>Data Upload & Lake</h1>
<p>Upload datasets to the versioned Data Lake — available in Training and Prediction tabs.</p>
</div>
</div>""", unsafe_allow_html=True)
upload_tab, cv_upload_tab = st.tabs(["📄 Tabular Data (CSV/Excel)", "🖼️ Computer Vision Data (Images/ZIP)"])
with upload_tab:
upload_col, info_col = st.columns([2, 1])
with upload_col:
uploaded_file = st.file_uploader("Upload CSV or Excel File", type=["csv", "xlsx", "xls"])
no_header_upload = st.checkbox(
"📋 This file has no header row (auto-generate col_0, col_1…)",
value=False, key="upload_no_header",
help="Check this if the first row of your file contains data, not column names."
)
filename_prefix = st.text_input("File prefix (name in Data Lake)", value="dataset", key="prefix_tab")
upload_btn = st.button("💾 Process & Save Tabular Data", type="primary")
with info_col:
st.markdown("""
<div class="preview-card">
<h4>📖 About the Data Lake</h4>
<p>Files are versioned using DVC and stored with a content hash. The same dataset at different times can be compared by hash. All frameworks read from this shared storage.</p>
</div>""", unsafe_allow_html=True)
if upload_btn and uploaded_file is not None:
try:
with st.spinner("Processing and versioning tabular data…"):
from src.data_utils import init_dvc, save_to_data_lake
init_dvc()
df = cached_load_data(uploaded_file, no_header=no_header_upload)
t_path, t_tag, t_hash = save_to_data_lake(df, filename_prefix)
st.cache_data.clear()
st.success(f"✅ Saved to Data Lake! Hash: `{t_hash}`")
st.session_state['_just_uploaded'] = df
except Exception as e:
st.error(f"Error processing tabular data: {e}")
with cv_upload_tab:
cv_col, cv_info_col = st.columns([2, 1])
with cv_col:
st.info("Upload multiple images (PNG/JPG) or a single ZIP archive containing your images.")
uploaded_images = st.file_uploader("Upload Images or ZIP", type=["png", "jpg", "jpeg", "zip"], accept_multiple_files=True)
dataset_name = st.text_input("Computer Vision Dataset Name", value="image_dataset")
cv_upload_btn = st.button("📸 Extract & Save Image Dataset", type="primary")
with cv_info_col:
st.markdown("""
<div class="preview-card">
<h4>🖼️ CV Datasets</h4>
<p>Images are stored in a dedicated <code>data_lake/images/</code> structured directory. Frameworks like AutoGluon and AutoKeras will automatically traverse these dirs for training.</p>
</div>""", unsafe_allow_html=True)
if cv_upload_btn and uploaded_images:
try:
with st.spinner("Processing and transferring images to Data Lake…"):
from src.data_utils import process_image_upload
is_zip = len(uploaded_images) == 1 and uploaded_images[0].name.endswith('.zip')
cv_dir, full_hash, short_hash = process_image_upload(uploaded_images, dataset_name, is_zip)
st.cache_data.clear()
st.success(f"✅ Image Dataset ready in Data Lake! Hash: `{short_hash}`")
except Exception as e:
st.error(f"Error processing images: {e}")
st.markdown("<hr/>", unsafe_allow_html=True)
st.subheader("2. Preview & Profiling")
available_files = cached_get_data_lake_files()
if not available_files and st.session_state.get('_just_uploaded') is None:
st.info("Upload a file above to see its preview and profiling.")
else:
df = None
if st.session_state.get('_just_uploaded') is not None:
df = st.session_state['_just_uploaded']
st.info("Previewing most recently uploaded dataset. Select another file from the dropdown to dismiss this.")
prev_file = st.selectbox("Select file to preview", available_files, index=0 if available_files else None)
if prev_file:
try:
st.session_state.pop('_just_uploaded', None)
df = cached_load_data(prev_file)
except Exception:
pass
else:
prev_file = st.selectbox("Select file to preview", available_files)
if prev_file:
try:
df = cached_load_data(prev_file)
except Exception as e:
st.error(f"Error loading preview file: {e}")
if df is not None:
try:
# ── Quick EDA panels ─────────────────────────────────────
st.markdown('<div class="section-header">📊 Dataset Overview</div>', unsafe_allow_html=True)
summary = cached_get_data_summary(df)
_missing_pct_mean, _memory_mb = _compute_overview_stats(df)
ov_col1, ov_col2, ov_col3, ov_col4 = st.columns(4)
for col, label, val, color in [
(ov_col1, "Rows", summary['rows'], "#58a6ff"),
(ov_col2, "Columns", summary['columns'], "#3fb950"),
(ov_col3, "Missing %", f"{_missing_pct_mean:.1f}%", "#d29922"),
(ov_col4, "Memory", f"{_memory_mb:.1f} MB", "#bc8cff"),
]:
with col:
st.markdown(f"""
<div class="stat-card">
<div class="number" style="color:{color}">{val}</div>
<div class="label">{label}</div>
</div>""", unsafe_allow_html=True)
st.markdown("<div style='height:12px'></div>", unsafe_allow_html=True)
tab_preview, tab_missing, tab_types, tab_dist = st.tabs([
"🔍 Preview", "❓ Missing Values", "📐 Data Types", "📊 Distribution"
])
with tab_preview:
st.dataframe(df.head(10), use_container_width=True)
with tab_missing:
miss_series = _compute_missing_stats(df)
miss_df = miss_series[miss_series > 0]
if len(miss_df) == 0:
st.success("✅ No missing values found!")
else:
_fig_m = _make_missing_fig(miss_series)
if _fig_m is not None:
st.pyplot(_fig_m, use_container_width=True)
st.dataframe(pd.DataFrame({"Column": miss_df.index, "Missing %": miss_df.values.round(2)}), use_container_width=True)
with tab_types:
type_counts = _compute_type_counts(df)
_fig_t = _make_type_pie(type_counts)
st.pyplot(_fig_t, use_container_width=True)
summary_df = _compute_column_summary(df)
st.dataframe(summary_df, use_container_width=True)
with tab_dist:
num_cols_list = df.select_dtypes(include="number").columns.tolist()
if num_cols_list:
dist_col = st.selectbox("Select column for distribution", num_cols_list, key="dist_col_sel")
_fig_d = _make_dist_fig(df[dist_col], dist_col)
st.pyplot(_fig_d, use_container_width=True)
st.dataframe(df[[dist_col]].describe().T, use_container_width=True)
else:
st.info("No numeric columns found for distribution plot.")
except Exception as e:
st.error(f"Error loading UI previews: {e}")
elif menu == "Data Exploration":
st.markdown("""
<div class="page-title">
<div class="page-title-icon">🔍</div>
<div class="page-title-text">
<h2>Data Exploration & Auto-EDA</h2>
<p>Automatically profile your datasets to find correlations, missing values, and imbalances before training.</p>
</div>
</div>
""", unsafe_allow_html=True)
st.info("Select a dataset from the Data Lake to generate a comprehensive Exploratory Data Analysis (EDA) report.")
available_files = cached_get_data_lake_files()
if not available_files:
st.warning("No files in Data Lake. Please upload data first in the 'Data Upload' tab.")
else:
file_options = [os.path.basename(f) for f in available_files]
file_paths_map = {os.path.basename(f): f for f in available_files}
selected_file = st.selectbox("Select Dataset to Profile", file_options)
if st.button("Generate Auto-EDA Report", type="primary"):
try:
import ydata_profiling
from streamlit_pandas_profiling import st_profile_report
with st.spinner("Generating EDA Report... This may take a moment for large datasets."):
file_path = file_paths_map[selected_file]
df_eda = cached_load_data(file_path)
# Basic Health Checks built-in warnings
n_rows = len(df_eda)
missing_cells = df_eda.isnull().sum().sum()
missing_pct = (missing_cells / (df_eda.shape[0] * df_eda.shape[1])) * 100
if missing_pct > 5:
st.warning(f"⚠️ Health Alert: Your dataset has {missing_pct:.1f}% missing values overall. Consider imputation before training.")
# Generate and display report
pr = ydata_profiling.ProfileReport(df_eda, explorative=True, minimal=n_rows > 10000)
st_profile_report(pr)
except ImportError:
st.error("Missing dependency. Please ensure `ydata-profiling` and `streamlit-pandas-profiling` are installed in your environment.")
except Exception as e:
st.error(f"Error generating report: {e}")
elif menu == "Training":
st.markdown("""
<div class="main-header">
<h1>🧠 Model Training</h1>
<p>Configure and launch an AutoML experiment. Training runs in the background — you can start multiple at once.</p>
</div>""", unsafe_allow_html=True)
available_files = cached_get_data_lake_files()
if not available_files:
st.warning("No datasets found in Data Lake. Please add them in the 'Data Upload' tab first.")
st.stop()
st.subheader("1. Data Lake Dataset Selection")
# UI mapping filenames
file_options = ["None"] + [os.path.basename(f) for f in available_files]
file_paths_map = {os.path.basename(f): f for f in available_files}
col1, col2, col3 = st.columns(3)
with col1:
train_file_selection = st.selectbox("Training (Required)", file_options[1:])
with col2:
valid_file_selection = st.selectbox("Validation (Optional)", file_options)
with col3:
test_file_selection = st.selectbox("Test/Holdout (Optional)", file_options)