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
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
# webapp/services/training.py
from __future__ import annotations
import copy
import os
import uuid
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import joblib
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import re
import pandas as pd
from typing import Callable
from django.conf import settings
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import (
    GradientBoostingClassifier,
    RandomForestClassifier,
    StackingClassifier,
    VotingClassifier,
)
from sklearn.feature_selection import RFECV, SelectKBest, mutual_info_classif
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, roc_auc_score
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, StandardScaler
from sklearn.svm import SVC

# ------------------------------------------------------------------------------
# Optional dependencies (best-effort; gracefully degrade if missing)
# ------------------------------------------------------------------------------
try:
    from xgboost import XGBClassifier
    _XGB_OK = True
except Exception:
    _XGB_OK = False

try:
    # Try (ctgan >= 0.6)
    from ctgan import CTGAN as _CTGANClass
    _CTGAN_OK = True
except Exception:
    try:
        # Fallback for very old ctgan (< 0.6)
        from ctgan import CTGANSynthesizer as _CTGANClass
        _CTGAN_OK = True
    except Exception:
        _CTGAN_OK = False


try:
    import shap
    _SHAP_OK = True
except Exception:
    _SHAP_OK = False

try:
    from scikeras.wrappers import KerasClassifier
    import tensorflow as tf
    from tensorflow.keras import Input
    from tensorflow.keras.layers import Dense, Dropout
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.optimizers import Adam
    _MLP_OK = True
except Exception:
    _MLP_OK = False

# Matplotlib backend for headless servers
matplotlib.use("Agg")

# ------------------------------------------------------------------------------
# Data structures
# ------------------------------------------------------------------------------
@dataclass
class TrainOptions:
    scaler: str                       # 'standard' | 'minmax'
    base_models: List[str]            # e.g. ['rf','svm',...]
    ensemble_type: str                # 'none' | 'voting' | 'stacking'
    meta_learner: Optional[str] = None  # 'lr' | 'rf' | 'gb' (for stacking)
    voting_type: Optional[str] = None   # 'hard' | 'soft' (for voting)
    balancing: str = "none"             # 'none' | 'over' | 'smote' | 'gans'
    augmentation: str = "none"          # 'none' | 'gans'
    target_samples: Optional[int] = None  # for augmentation == 'gans'
    random_state: int = 42
    test_size: float = 0.2
    val_size: float = 0.25


@dataclass
class TrainResult:
    val_auc: Optional[float]
    val_f1: float
    test_auc: Optional[float]
    test_f1: float
    summary: Dict[str, Any]
    model_path: Optional[str]
    artifact: Dict[str, Any]
    shap_relpath: Optional[str] = None  # (may point to SHAP or permutation plot)

# ------------------------------------------------------------------------------
# Model registry & small helpers
# ------------------------------------------------------------------------------

# --- JSON-safe helpers (put after imports) ---
# --- JSON-safe helpers ---
def _to_py_scalar(x):
    if isinstance(x, (np.integer,)):
        return int(x)
    if isinstance(x, (np.floating,)):
        return float(x)
    if isinstance(x, (np.bool_,)):
        return bool(x)
    if isinstance(x, (np.ndarray,)):
        return x.tolist()
    if isinstance(x, (pd.Series,)):
        return x.astype(object).where(~x.isna(), None).tolist()
    if isinstance(x, (pd.DataFrame,)):
        return x.to_dict(orient="list")
    return x

def _json_safe(obj):
    # recursively convert to JSON-serializable Python types
    if isinstance(obj, dict):
        return {str(k): _json_safe(v) for k, v in obj.items()}
    if isinstance(obj, (list, tuple, set)):
        return [_json_safe(v) for v in obj]
    return _to_py_scalar(obj)


def _balance_training_raw(
    X_train_raw: pd.DataFrame,
    y_train: pd.Series,
    balancing_mode: str,          # 'none' | 'over' | 'smote' | 'gans'
    augmentation_mode: str,       # 'none' | 'gans'
    categorical_cols: List[str],
    target_samples: Optional[int],
    random_state: int,
    progress_fn: Optional[Callable[[float, str], None]] = None,
) -> Tuple[pd.DataFrame, pd.Series]:
    """
    Modify ONLY THE TRAINING SPLIT, in RAW space (pre-scaling, pre-encoding).

    Steps:
    1. balance (if requested)
    2. then augment (if requested)

    Returns new (X_train_raw_balanced_augmented, y_train_balanced_augmented).
    """

    Xb = X_train_raw.reset_index(drop=True).copy()
    yb = y_train.reset_index(drop=True).astype(int)

        # let the UI know we entered balancing
    if progress_fn:
        progress_fn(15, "Balancing training split...")

    # --- 1. BALANCING -------------------------------------------------
    if balancing_mode == 'none':
        if progress_fn:
            progress_fn(16, "No class balancing requested.")

    elif balancing_mode == 'over':
        if progress_fn:
            progress_fn(16, "Applying random oversampling...")
        # bootstrap minority class to match majority
        train_df = Xb.copy()
        train_df['__y__'] = yb.values
        counts = train_df['__y__'].value_counts()
        if len(counts) >= 2:
            maj_class = counts.idxmax()
            maj_df = train_df[train_df['__y__'] == maj_class]
            min_df = train_df[train_df['__y__'] != maj_class]

            if len(min_df) > 0 and len(maj_df) > 0:
                from sklearn.utils import resample
                min_up = resample(
                    min_df,
                    replace=True,
                    n_samples=len(maj_df),
                    random_state=random_state,
                )
                up_df = pd.concat([maj_df, min_up]).sample(
                    frac=1, random_state=random_state
                )
                yb = up_df['__y__'].astype(int).reset_index(drop=True)
                Xb = up_df.drop(columns=['__y__']).reset_index(drop=True)

    elif balancing_mode == 'smote':
        if progress_fn:
            progress_fn(16, "Running SMOTE...")
        # figure out categorical col indices
        cat_idx = [Xb.columns.get_loc(c) for c in categorical_cols if c in Xb.columns]

        if len(cat_idx) == 0:
            # all features are numeric -> use regular SMOTE
            from imblearn.over_sampling import SMOTE
            sm = SMOTE(random_state=random_state)
        else:
            from imblearn.over_sampling import SMOTENC
            sm = SMOTENC(
                categorical_features=cat_idx,
                random_state=random_state,
            )

        X_res, y_res = sm.fit_resample(Xb, yb)

        Xb = pd.DataFrame(X_res, columns=Xb.columns).reset_index(drop=True)
        yb = pd.Series(y_res, name=yb.name).astype(int).reset_index(drop=True)

    elif balancing_mode == 'gans':
        if progress_fn:
            progress_fn(16, "Training CTGAN to balance minority class...")
        # CTGAN upsample minority class to match majority
        Xb, yb = _apply_ctgan_on_raw(
            X_train_raw=Xb,
            y_train=yb,
            categorical_cols=categorical_cols,
            do_balance=True,      # <-- balance minority up to majority
            do_augment=False,     # <-- NOT doing bulk growth yet
            target_samples=None,
            random_state=random_state,
        )

    else:
        raise ValueError(f"Unknown balancing mode: {balancing_mode}")

    if progress_fn:
        progress_fn(17, "Balancing complete.")

    # --- 2. AUGMENTATION ----------------------------------------------
    # still ONLY training data, just making more rows if requested
    if augmentation_mode == 'gans':
        if progress_fn:
            progress_fn(18, "Generating extra synthetic samples (augmentation)...")
        
        Xb, yb = _apply_ctgan_on_raw(
            X_train_raw=Xb,
            y_train=yb,
            categorical_cols=categorical_cols,
            do_balance=False,          # don't rebalance again
            do_augment=True,           # add extra synthetic samples
            target_samples=target_samples,
            random_state=random_state,
        )

        if progress_fn:
            progress_fn(18, "Augmentation complete.")

    elif augmentation_mode == 'none':
        if progress_fn:
            progress_fn(19.0, "No augmentation requested.")
        pass
    else:
        raise ValueError(f"Unknown augmentation mode: {augmentation_mode}")

    return (
        Xb.reset_index(drop=True),
        yb.reset_index(drop=True).astype(int),
    )


def _create_mlp(input_dim: int, dropout_rate: float = 0.2, learning_rate: float = 0.001):
    model = Sequential()
    model.add(Input(shape=(input_dim,)))
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(dropout_rate))
    model.add(Dense(64, activation='relu'))
    model.add(Dropout(dropout_rate))
    model.add(Dense(1, activation='sigmoid'))
    model.compile(
        optimizer=Adam(learning_rate=learning_rate),
        loss='binary_crossentropy',
        metrics=[tf.keras.metrics.AUC(name='auc')]
    )
    return model



def _pretty_feature_names(names: List[str]) -> List[str]:
    out = []
    for n in names:
        s = str(n)
        # drop ColumnTransformer prefixes like "num__", "num_", "cat__", "cat_"
        s = re.sub(r'^(num|cat)_{1,2}', '', s)
        # keep it tidy
        out.append(s if len(s) <= 40 else s[:37] + '…')
    return out



def _stratify_or_none(y: pd.Series):
    vc = y.value_counts(dropna=False)
    return y if (len(vc) >= 2 and vc.min() >= 2) else None


def _get_base_model(key: str, input_dim: Optional[int] = None):
    if key == 'rf':
        return RandomForestClassifier()
    if key == 'svm':
        return SVC(probability=True)
    if key == 'knn':
        return KNeighborsClassifier()
    if key == 'lr':
        return LogisticRegression(max_iter=10_000)
    if key == 'gb':
        return GradientBoostingClassifier()
    if key == 'xgb' and _XGB_OK:
        return XGBClassifier(eval_metric='logloss')
    if key == 'mlp' and _MLP_OK and input_dim is not None:
        return KerasClassifier(model=_create_mlp, model__input_dim=input_dim, verbose=0)
    return None


def _ctgan_sample_raw(df_raw: pd.DataFrame, discrete_cols: List[str], n: int, epochs: int = 300, seed: int = 42) -> pd.DataFrame:
    if n <= 0:
        return pd.DataFrame(columns=df_raw.columns)
    if not _CTGAN_OK:
        raise RuntimeError("CTGAN requested but the 'ctgan' package is not installed.")

    synth = _CTGANClass(epochs=epochs, verbose=False)
    synth.fit(df_raw, discrete_columns=discrete_cols)
    out = synth.sample(n)
    return out.reset_index(drop=True)


def _apply_ctgan_on_raw(
    X_train_raw: pd.DataFrame,
    y_train: pd.Series,
    categorical_cols: List[str],
    do_balance: bool,
    do_augment: bool,
    target_samples: Optional[int],
    random_state: int,
) -> Tuple[pd.DataFrame, pd.Series]:
    """
    Mirror the script: balance minority to majority on RAW columns (with categoricals),
    then optionally augment to target_samples. Returns new (X_raw, y).
    """
    train_df = X_train_raw.copy()
    train_df['__y__'] = y_train.values.astype(int)

    # Balance
    if do_balance:
        vc = train_df['__y__'].value_counts()
        if len(vc) >= 2:
            minority = int(vc.idxmin())
            majority_n = int(vc.max())
            need = majority_n - int((train_df['__y__'] == minority).sum())
            if need > 0:
                minority_df = train_df[train_df['__y__'] == minority].reset_index(drop=True)
                synth = _ctgan_sample_raw(
                    minority_df,
                    discrete_cols=categorical_cols + ['__y__'],
                    n=need,
                    epochs=300,
                    seed=random_state,
                )
                train_df = pd.concat([train_df, synth], ignore_index=True)

    # Augment
    if do_augment and target_samples is not None and target_samples > len(train_df):
        need_total = int(target_samples - len(train_df))
        vc = train_df['__y__'].value_counts()
        ratio = vc / vc.sum()
        alloc = {int(cls): int(round(need_total * p)) for cls, p in ratio.items()}
        diff = need_total - sum(alloc.values())
        if diff:
            alloc[int(vc.idxmax())] = alloc.get(int(vc.idxmax()), 0) + diff

        # Fit once on the current (balanced) RAW table and sample in batches
        # (simple approach: sample, then filter by class)
        parts = [train_df]
        for cls, n_add in alloc.items():
            if n_add <= 0:
                continue
            got = pd.DataFrame()
            tries = 0
            while len(got) < n_add and tries < 5:
                batch = _ctgan_sample_raw(
                    train_df, discrete_cols=categorical_cols + ['__y__'],
                    n=max(n_add * 2, 200), epochs=300, seed=random_state + tries
                )
                batch = batch[batch['__y__'] == cls]
                got = pd.concat([got, batch], ignore_index=True).head(n_add)
                tries += 1
            if len(got) < n_add:
                # fallback: unconditional sample (keep whatever class proportion arrives)
                got = _ctgan_sample_raw(
                    train_df, discrete_cols=categorical_cols + ['__y__'],
                    n=n_add, epochs=300, seed=random_state + 99
                )
                # best-effort: trim/keep to n_add
                got = got.head(n_add)
            parts.append(got)
        train_df = pd.concat(parts, ignore_index=True)

    y_out = train_df['__y__'].astype(int).reset_index(drop=True)
    X_out = train_df.drop(columns=['__y__']).reset_index(drop=True)
    return X_out, y_out


def _param_grid(key: str, input_dim: Optional[int] = None) -> Dict[str, List[Any]]:
    grids = {
    'rf': { 'n_estimators': [100, 200, 300], 'max_depth': [None, 10, 20, 30],'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4],'bootstrap': [True, False] },
    'svm': {'C': [0.1, 1, 10, 100], 'kernel': ['linear', 'rbf', 'poly'], 'gamma': ['scale', 'auto'],  'degree': [3, 4, 5]},
    'knn': {'n_neighbors': [3, 5, 7, 11], 'weights': ['uniform', 'distance'], 'metric': ['euclidean', 'manhattan'] },
    'lr': {'C': [0.01, 0.1, 1, 10, 100],'penalty': ['l1', 'l2'],'solver': ['liblinear', 'saga'],'max_iter': [100, 500, 1000]},
    'gb': {'n_estimators': [100, 200],'learning_rate': [0.01, 0.1, 0.2],'max_depth': [3, 5, 7],'subsample': [0.8, 1.0],'min_samples_split': [2, 5],'min_samples_leaf': [1, 2]},
    'xgb': {'n_estimators': [100, 200],'learning_rate': [0.01, 0.1, 0.2],'max_depth': [3, 5, 7],'subsample': [0.8, 1.0],'colsample_bytree': [0.6, 0.8, 1.0],'gamma': [0, 0.1, 0.2]},
    'mlp': {'model__hidden_layers': [[64],[128, 64],[128, 64, 32]],'model__dropout_rate': [0.2, 0.3],'model__learning_rate': [0.001, 0.0005],'epochs': [30, 50],'batch_size': [16, 32]}
}
    if key == 'mlp' and _MLP_OK and input_dim is not None:
        return {
            'model__input_dim':   [input_dim],
            'model__dropout_rate': [0.2, 0.3],
            'model__learning_rate': [0.001, 0.0005],
            'epochs':             [25, 40],
            'batch_size':         [16, 32],
        }
    return grids.get(key, {})


def _get_meta_learner(key: str):
    if key == 'lr':
        return LogisticRegression(max_iter=10_000)
    if key == 'rf':
        return RandomForestClassifier()
    if key == 'gb':
        return GradientBoostingClassifier()
    return LogisticRegression(max_iter=10_000)


def _score_auc_f1(estimator, X: pd.DataFrame, y: pd.Series) -> Tuple[Optional[float], float]:
    """Uniform scoring helper that returns plain-Python floats (JSON-safe)."""
    y_pred = estimator.predict(X)
    f1 = float(f1_score(y, y_pred))
    auc = None
    if hasattr(estimator, "predict_proba"):
        try:
            auc = float(roc_auc_score(y, estimator.predict_proba(X)[:, 1]))
        except ValueError:
            auc = None
    return auc, f1

# ------------------------------------------------------------------------------
# Explainability plots
# ------------------------------------------------------------------------------
def _make_shap_plot_if_possible(
    model, X_bg: pd.DataFrame, X_eval: pd.DataFrame, feature_names: List[str], run_id: str
) -> Optional[str]:
    """Return MEDIA-relative path to SHAP bar summary, or None on failure."""
    if not _SHAP_OK:
        return None

    bg = X_bg.sample(min(50, len(X_bg)), random_state=0).reset_index(drop=True)
    ev = X_eval.sample(min(200, len(X_eval)), random_state=1).reset_index(drop=True)

    try:
        explainer = shap.Explainer(model, bg)
        sv = explainer(ev)
        shap.summary_plot(sv, features=ev, feature_names=feature_names, plot_type="bar", show=False)
    except Exception:
        try:
            def _f(X):
                Xdf = pd.DataFrame(X, columns=feature_names)
                if hasattr(model, "predict_proba"):
                    return model.predict_proba(Xdf)[:, 1]
                return model.predict(Xdf)

            kexp = shap.KernelExplainer(_f, bg)
            sv = kexp.shap_values(ev, nsamples=100)
            shap.summary_plot(sv, ev, feature_names=feature_names, plot_type="bar", show=False)
        except Exception:
            try:
                plt.close()
            except Exception:
                pass
            return None

    plt.tight_layout()
    rel_dir = os.path.join("train_runs")
    abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir)
    os.makedirs(abs_dir, exist_ok=True)
    rel_path = os.path.join(rel_dir, f"{run_id}_shap.svg")  # needs to be SVG to then be responsive
    plt.gcf().set_size_inches(8, 5) 
    plt.savefig(os.path.join(abs_dir, f"{run_id}_shap.svg"),format="svg", bbox_inches="tight")          # ← SVG export
    plt.close()
    return rel_path


def _make_perm_plot_if_possible(
    model, X_eval: pd.DataFrame, y_eval: pd.Series, feature_names: List[str], run_id: str
) -> Optional[str]:
    """Return MEDIA-relative path to permutation-importance plot, or None on failure."""
    try:
        res = permutation_importance(model, X_eval, y_eval, n_repeats=10, random_state=0, scoring="roc_auc")
        names = feature_names if feature_names and len(feature_names) == X_eval.shape[1] else list(X_eval.columns)
        names = _pretty_feature_names(names)
        imps = pd.Series(res.importances_mean, index=names).fillna(0.0)

        top = imps.sort_values().tail(25)
        plt.figure(figsize=(12, 6), dpi=140)
        colors = ['tab:red' if v < 0 else 'tab:green' for v in top.values]
        plt.barh(top.index, top.values, color=colors, alpha=0.9)
        plt.axvline(0, linestyle='--', linewidth=1, alpha=0.6)
        plt.title("Permutation importance (validation)")
        plt.xlabel("Mean change in ROC AUC when permuted")
        plt.tight_layout()

        rel_dir = os.path.join("train_runs")
        abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir)
        os.makedirs(abs_dir, exist_ok=True)
        rel_path = os.path.join(rel_dir, f"{run_id}_perm.svg")
        plt.savefig(os.path.join(abs_dir, f"{run_id}_perm.svg"), format="svg", bbox_inches="tight")
        plt.close()
        return rel_path
    except Exception:
        try:
            plt.close()
        except Exception:
            pass
        return None

# ------------------------------------------------------------------------------
# Feature selection helpers
# ------------------------------------------------------------------------------
def _rfecv_k_per_base(X_train_proc: pd.DataFrame, y_train: pd.Series) -> Tuple[Dict[str, int], Dict[str, RFECV]]:
    """Run RFECV with a few base estimators to infer a sensible k (cap at 20)."""
    bases = {
        'lr': LogisticRegression(max_iter=10_000),
        'rf': RandomForestClassifier(),
        'svm': SVC(kernel='linear', probability=True),
    }
    k_map, model_map = {}, {}
    for name, est in bases.items():
        rfecv = RFECV(estimator=est, step=1, cv=3, scoring='roc_auc', n_jobs=-1)
        rfecv.fit(X_train_proc, y_train)
        k = min(20, getattr(rfecv, "n_features_", X_train_proc.shape[1]))
        k_map[name] = k
        model_map[name] = rfecv
    return k_map, model_map


def _select_features(
    method: str,
    X_train_proc: pd.DataFrame,
    y_train: pd.Series,
    X_val_proc: pd.DataFrame,
    k: int,
    rfecv_model: Optional[RFECV] = None
) -> Tuple[pd.DataFrame, pd.DataFrame, Optional[SelectKBest], List[str]]:
    """
    Returns train/val reduced, optional selector object (only for kbest), and feature names.
    """
    selector_obj = None
    if method == 'rfe':
        ranking = rfecv_model.ranking_
        ranks = pd.Series(ranking, index=X_train_proc.columns).sort_values()
        feats = list(ranks.index[:k])
        return X_train_proc[feats], X_val_proc[feats], selector_obj, feats

    selector_obj = SelectKBest(score_func=mutual_info_classif, k=k)
    selector_obj.fit(X_train_proc, y_train)
    scores = pd.Series(selector_obj.scores_, index=X_train_proc.columns).sort_values(ascending=False)
    feats = list(scores.index[:k])
    return X_train_proc[feats], X_val_proc[feats], selector_obj, feats

# ------------------------------------------------------------------------------
# Public entry point
# ------------------------------------------------------------------------------
def train_dataset(
    file_obj,
    opts: TrainOptions,
    save_to: Optional[str] = None,
    progress_cb: Optional[Callable[[float, str], None]] = None,   # <— NEW
) -> TrainResult:
    def _emit(pct: float, msg: str):
        if progress_cb:
            try:
                progress_cb(float(pct), str(msg))
            except Exception:
                pass

    # --- sanitize target_samples (form can send '') ---
    if isinstance(opts.target_samples, str):
        target_samples = int(opts.target_samples) if opts.target_samples.strip() else None
    else:
        target_samples = opts.target_samples


    # ---- Load & sanitize
    _emit(1, "Reading CSV...")
    df = pd.read_csv(file_obj)
    if 'healthy' not in df.columns:
        raise ValueError("CSV must include a 'healthy' column (0/1).")

    drop_cols = [c for c in ['sample_id', 'id'] if c in df.columns]
    if drop_cols:
        df = df.drop(columns=drop_cols)

    # coerce object columns that look numeric
    for c in df.columns:
        if df[c].dtype == object:
            coerced = pd.to_numeric(df[c], errors='coerce')
            if coerced.notna().sum() > 0:
                df[c] = coerced

    
    df = df.dropna(axis=0, how='any').reset_index(drop=True)

    raw_feature_cols = [c for c in df.columns if c != 'healthy']
    X = df[raw_feature_cols].copy()
    y = df['healthy'].astype(int)

   
    # ---- Split (fit preprocessors on TRAIN only)
    _emit(8, "Splitting train/val/test...")
    X_dev, X_test, y_dev, y_test = train_test_split(
        X, y, test_size=opts.test_size, stratify=_stratify_or_none(y), random_state=opts.random_state
    )
    X_train_raw, X_val_raw, y_train, y_val = train_test_split(
        X_dev, y_dev, test_size=opts.val_size, stratify=_stratify_or_none(y_dev), random_state=opts.random_state
    )

    # ---- Identify numeric vs categorical on TRAIN RAW (before balancing) ----
    numeric_cols = X_train_raw.select_dtypes(include=[np.number, bool]).columns.tolist()
    categorical_cols = X_train_raw.columns.difference(numeric_cols).tolist()

    _emit(15, "Balancing / augmentation on training split...")

    X_train_raw, y_train = _balance_training_raw(
        X_train_raw=X_train_raw,
        y_train=y_train,
        balancing_mode=opts.balancing,
        augmentation_mode=opts.augmentation,
        categorical_cols=categorical_cols,
        target_samples=target_samples,
        random_state=opts.random_state,
        progress_fn=_emit,
    )

    num_pipe = Pipeline(steps=[
    ('scale', StandardScaler() if opts.scaler == 'standard' else MinMaxScaler()),
    ])


    try:
        ohe = OneHotEncoder(handle_unknown='ignore', sparse_output=False)  
    except TypeError:
        ohe = OneHotEncoder(handle_unknown='ignore', sparse=False)         

    cat_pipe = Pipeline(steps=[
        ('ohe', ohe),
    ])

    preprocessor = ColumnTransformer(
        transformers=[
            ('num', num_pipe, numeric_cols),
            ('cat', cat_pipe, categorical_cols),
        ],
        remainder='drop'
    )
    
    _emit(25, "Fitting preprocessors...")
    preprocessor.fit(X_train_raw)

    def _to_df(arr):
        names = preprocessor.get_feature_names_out().tolist()
        return pd.DataFrame(arr, columns=names).astype(np.float32)

    X_train_proc = _to_df(preprocessor.transform(X_train_raw))
    X_val_proc   = _to_df(preprocessor.transform(X_val_raw))
    X_test_proc  = _to_df(preprocessor.transform(X_test))

    # Ensure labels align with 0..n-1 indices produced by transform()
    y_train = y_train.reset_index(drop=True)
    y_val   = y_val.reset_index(drop=True)
    y_test  = y_test.reset_index(drop=True)

    # keep tidy indices after any resampling
    X_train_proc = X_train_proc.reset_index(drop=True)
    y_train = y_train.reset_index(drop=True).astype(int)

    # ---- Feature selection candidates
    _emit(35, "Running RFECV...")
    k_map, rfecv_map = _rfecv_k_per_base(X_train_proc, y_train)  # k cap at 20 per base
    selection_methods = ['rfe', 'kbest']
    done_slices = 0
    total_slices = max(1, len(selection_methods) * len(k_map))

    # if multiple base models but 'none' ensemble, nudge to stacking
    ensemble_type = 'stacking' if (len(opts.base_models) >= 2 and opts.ensemble_type == 'none') else opts.ensemble_type

    best_val_key = None
    best_val_metrics = (-1.0, -1.0)  # (auc, f1)
    best_pack: Dict[str, Any] = {}

    for method in selection_methods:
        for k_base_name, k in k_map.items():
            done_slices += 1
            _emit(35 + 45 * (done_slices - 1) / total_slices, f"Training {method} / {k_base_name} (k={k})...")
            Xtr_sel, Xv_sel, selector_obj, feats = _select_features(
                method, X_train_proc, y_train, X_val_proc, k, rfecv_map.get(k_base_name)
            )

            # Instantiate requested base models
            chosen_models = []
            for key in opts.base_models:
                mdl = _get_base_model(key, input_dim=Xtr_sel.shape[1])
                if mdl is not None:
                    chosen_models.append((key, mdl))

            # Hyperparam tune or fit directly
            best_estimators: Dict[str, Any] = {}
            for key, mdl in chosen_models:
                grid_params = copy.deepcopy(_param_grid(key, input_dim=Xtr_sel.shape[1]))
                if grid_params:
                    gs = GridSearchCV(mdl, grid_params, cv=3, scoring='roc_auc', n_jobs=-1)
                    gs.fit(Xtr_sel, y_train)
                    best_est = gs.best_estimator_
                else:
                    mdl.fit(Xtr_sel, y_train)
                    best_est = mdl
                best_estimators[key] = best_est

            if len(best_estimators) == 0:
                continue

            # Build final model for this feature slice
            if len(best_estimators) == 1 or ensemble_type == 'none':
                # choose best single model by (AUC, F1) on VAL
                auc_f1_list = []
                for key, est in best_estimators.items():
                    auc, f1 = _score_auc_f1(est, Xv_sel, y_val)
                    auc_f1_list.append((auc if auc is not None else -1, f1, key, est))
                auc_f1_list.sort(reverse=True)
                _, _, label, final_model = auc_f1_list[0]

            elif ensemble_type == 'voting':
                voting = opts.voting_type or 'hard'
                final_model = VotingClassifier(estimators=list(best_estimators.items()), voting=voting)
                final_model.fit(Xtr_sel, y_train)
                label = f"Voting({voting})"

            else:  # 'stacking'
                meta = _get_meta_learner(opts.meta_learner or 'lr')
                final_model = StackingClassifier(
                    estimators=list(best_estimators.items()),
                    final_estimator=clone(meta),
                    passthrough=True, cv=3, n_jobs=-1
                )
                final_model.fit(Xtr_sel, y_train)
                label = f"Stacking({opts.meta_learner or 'lr'})"

            # Validate
            val_auc, val_f1 = _score_auc_f1(final_model, Xv_sel, y_val)
            key_tuple = (val_auc if val_auc is not None else -1, val_f1)

            if key_tuple > best_val_metrics:
                best_val_metrics = key_tuple
                best_val_key = (method, k_base_name, k, label)
                best_pack = {
                    "model": final_model,
                    "selector": selector_obj if method == 'kbest' else None,
                    "final_features": feats,
                    "pre_features": list(X_train_proc.columns),
                    "preprocessor": preprocessor,
                    "scaler_type": opts.scaler,
                    "feature_method": method,
                    "k_from": k_base_name,
                    "k": k,
                    "ensemble": ensemble_type,
                    "base_models": list(best_estimators.keys()),
                    "meta_learner": (opts.meta_learner if ensemble_type == "stacking" else None),
                    "voting_type": (opts.voting_type if ensemble_type == "voting" else None),
                    "balancing": opts.balancing,
                    "augmentation": opts.augmentation,
                }

    if not best_pack:
        raise RuntimeError("No valid model configuration could be trained.")

    # ---- Test once on held-out
    if best_pack["selector"] is not None:
        X_test_aligned = X_test_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0)
        Xte_sel_arr = best_pack["selector"].transform(X_test_aligned)
        Xte_sel = pd.DataFrame(Xte_sel_arr, columns=best_pack["final_features"])
    else:
        Xte_sel = X_test_proc[best_pack["final_features"]]

    _emit(85, "Testing on hold-out...")
    test_auc, test_f1 = _score_auc_f1(best_pack["model"], Xte_sel, y_test)
    val_auc, val_f1 = best_val_metrics

    # Plain-Python scalars for anything we might serialize/store
    val_auc_py  = None if (val_auc is None or val_auc < 0) else float(val_auc)
    val_f1_py   = float(val_f1)
    test_auc_py = None if test_auc is None else float(test_auc)
    test_f1_py  = float(test_f1)

    # best_val_key = (method, k_base_name, k, label)
    selection_py = None
    if best_val_key is not None:
        selection_py = [
            None if best_val_key[0] is None else str(best_val_key[0]),
            None if best_val_key[1] is None else str(best_val_key[1]),
            None if best_val_key[2] is None else int(best_val_key[2]),
            None if best_val_key[3] is None else str(best_val_key[3]),
        ]


    # ---- Explainability (best-effort)
    run_id = uuid.uuid4().hex

    if best_pack["selector"] is not None:
        X_train_aligned = X_train_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0)
        X_val_aligned = X_val_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0)
        Xtr_sel_final = pd.DataFrame(best_pack["selector"].transform(X_train_aligned), columns=best_pack["final_features"])
        Xv_sel_final  = pd.DataFrame(best_pack["selector"].transform(X_val_aligned),   columns=best_pack["final_features"])
    else:
        Xtr_sel_final = X_train_proc[best_pack["final_features"]]
        Xv_sel_final  = X_val_proc[best_pack["final_features"]]

    explain_relpath = None
    explain_type = None
    feature_importances = None
    pretty_names = _pretty_feature_names(best_pack["final_features"])


    _emit(90, "Building explainability plot...")
    shap_relpath = _make_shap_plot_if_possible(
        model=best_pack["model"], X_bg=Xtr_sel_final, X_eval=Xv_sel_final,
        feature_names=pretty_names, run_id=run_id,
    )
    if shap_relpath:
        explain_relpath = shap_relpath
        explain_type = "shap"

        # Also compute mean absolute SHAP values (top features) to store in summary
        try:
            import shap
            explainer = shap.Explainer(best_pack["model"], Xtr_sel_final)
            sv = explainer(Xv_sel_final)
            vals = np.abs(sv.values).mean(0)
            feature_importances = [(str(f), float(v)) for f, v in zip(pretty_names, vals)]

        except Exception:
            feature_importances = None

    else:
        perm_relpath = _make_perm_plot_if_possible(
            model=best_pack["model"], X_eval=Xv_sel_final, y_eval=y_val,
            feature_names=pretty_names, run_id=run_id,
        )

        if perm_relpath:
            explain_relpath = perm_relpath
            explain_type = "permutation"

            # Also compute permutation importances numerically for the summary
            try:
                res_pi = permutation_importance(
                    best_pack["model"], Xv_sel_final, y_val,
                    n_repeats=10, random_state=0, scoring="roc_auc"
                )
                feature_importances = [(str(f), float(s)) for f, s in zip(pretty_names, res_pi.importances_mean)]


            except Exception:
                feature_importances = None


    artifact = {
    "model": best_pack["model"],
    "selector": best_pack["selector"],
    "preprocessor": best_pack["preprocessor"],
    "pre_selection_feature_names": best_pack["pre_features"],
    "final_feature_names": best_pack["final_features"],
    "feature_method": best_pack["feature_method"],
    "k_from": best_pack["k_from"],
    "k": int(best_pack["k"]),  # ensure plain int
    "shap_relpath": shap_relpath,
    "scaler_type": best_pack["scaler_type"],
    "ensemble_type": best_pack["ensemble"],
    "base_models": best_pack["base_models"],
    "meta_learner": best_pack["meta_learner"],
    "voting_type": best_pack["voting_type"],
    "balancing_method": best_pack["balancing"],
    "augmentation": best_pack["augmentation"],
    "explain_relpath": explain_relpath,
    "explain_type": explain_type,
    "target_samples": target_samples,
    "val_auc": val_auc_py,
    "val_f1": val_f1_py,
    "test_auc": test_auc_py,
    "test_f1": test_f1_py,}
    
    summary_raw = {
        "selection": selection_py,  # list not tuple, already py types
        "ensemble": artifact["ensemble_type"],
        "base_models": artifact["base_models"],
        "meta_learner": artifact["meta_learner"],
        "voting_type": artifact["voting_type"],
        "balancing": artifact["balancing_method"],
        "augmentation": artifact["augmentation"],
        "scaler": artifact["scaler_type"],
        "explain_type": explain_type,
        "target_samples": artifact["target_samples"],
        "k": int(best_pack["k"]),
        "k_from": best_pack["k_from"],
        "feature_method": best_pack["feature_method"],
        # NEW: numeric importances so results_view/_extract_top_taxa can build NCBI links
        "permutation_importance": feature_importances if explain_type == "permutation" else None,
        "shap_importance": feature_importances if explain_type == "shap" else None,
    }

    summary_py = _json_safe(summary_raw)


    saved = None
    if save_to:
        joblib.dump(artifact, save_to)
        saved = save_to

    _emit(100, "Done")
    return TrainResult(
    val_auc=val_auc_py,
    val_f1=val_f1_py,
    test_auc=test_auc_py,
    test_f1=test_f1_py,
    shap_relpath=explain_relpath,
    summary=summary_py,
    model_path=saved,
    artifact=artifact,
)