File size: 5,156 Bytes
e50f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# webapp/services/testing.py
from __future__ import annotations
import io
from typing import Dict, Any, Tuple, Optional
import numpy as np
import pandas as pd
import joblib
from sklearn.metrics import f1_score, roc_auc_score, accuracy_score, confusion_matrix

NON_FEATURE_COLS = {"healthy", "label", "target", "sample_id", "id"}

def _read_txt_like(uploaded_file) -> pd.DataFrame:
    raw = uploaded_file.read().decode("utf-8", errors="replace")
    lines = [ln for ln in raw.splitlines() if not ln.strip().startswith("#")]
    if not lines:
        raise ValueError("No data rows found (file only contains comments).")
    txt = "\n".join(lines)
    try:
        df = pd.read_csv(io.StringIO(txt))
    except Exception:
        df = pd.read_csv(io.StringIO(txt), sep="\t")
    if df.empty:
        raise ValueError("Parsed an empty table. Check delimiter and header.")
    return df

def _align_numeric(df: pd.DataFrame) -> pd.DataFrame:
    X = df.drop(columns=[c for c in NON_FEATURE_COLS if c in df.columns], errors="ignore").copy()
    for c in X.columns:
        X[c] = pd.to_numeric(X[c], errors="coerce").fillna(0.0)
    return X

def _load_artifact(model_file) -> Dict[str, Any]:
    art = joblib.load(model_file)
    for k in ["model","scaler","final_feature_names","pre_selection_feature_names"]:
        if k not in art:
            raise ValueError(f"Model artifact is missing '{k}'.")
    return art

def _transform_like_training(art: Dict[str, Any], X_raw: pd.DataFrame) -> pd.DataFrame:
    # 1) align to pre-selection space
    X_pre = X_raw.reindex(columns=art["pre_selection_feature_names"], fill_value=0.0)
    # 2) scale with training scaler
    X_scaled = art["scaler"].transform(X_pre)
    X_scaled = pd.DataFrame(X_scaled, columns=art["pre_selection_feature_names"]).astype(np.float32)
    # 3) feature selection
    if art.get("selector") is not None:
        X_sel_arr = art["selector"].transform(X_scaled)
        X_sel = pd.DataFrame(X_sel_arr, columns=art["final_feature_names"])
    else:
        X_sel = X_scaled[art["final_feature_names"]]
    return X_sel

def run_inference(model_file, test_file) -> Tuple[np.ndarray, Dict[str, Any]]:
    """Unlabeled data → predictions."""
    art = _load_artifact(model_file)
    df = _read_txt_like(test_file)
    X = _align_numeric(df)
    X_sel = _transform_like_training(art, X)
    preds = art["model"].predict(X_sel)
    meta = {
        "scaler_type": art.get("scaler_type"),
        "feature_method": art.get("feature_method"),
        "k": art.get("k"),
        "ensemble_type": art.get("ensemble_type"),
        "base_models": art.get("base_models"),
        "meta_learner": art.get("meta_learner"),
        "voting_type": art.get("voting_type"),
        "balancing_method": art.get("balancing_method"),
        "augmentation": art.get("augmentation"),
    }
    return preds, meta

def evaluate(model_file, labeled_test_file) -> Tuple[Dict[str, Any], np.ndarray, Dict[str, Any]]:
    """
    Labeled data with a 'healthy' column → metrics + predictions.
    """
    art = _load_artifact(model_file)
    df = _read_txt_like(labeled_test_file)
    if "healthy" not in df.columns:
        raise ValueError("Evaluation requires a 'healthy' column in the uploaded file.")
    y_true = df["healthy"].astype(int).values
    X = _align_numeric(df)
    X_sel = _transform_like_training(art, X)
    model = art["model"]

    y_pred = model.predict(X_sel)

    # Probabilities for AUC if available
    auc = None
    if hasattr(model, "predict_proba"):
        try:
            y_prob = model.predict_proba(X_sel)[:, 1]
            auc = roc_auc_score(y_true, y_prob)
        except ValueError:
            auc = None

    acc = accuracy_score(y_true, y_pred)
    f1  = f1_score(y_true, y_pred)
    cm  = confusion_matrix(y_true, y_pred).tolist()

    metrics = {"accuracy": acc, "f1": f1, "auc": auc, "confusion_matrix": cm}
    meta = {
        "scaler_type": art.get("scaler_type"),
        "feature_method": art.get("feature_method"),
        "k": art.get("k"),
        "ensemble_type": art.get("ensemble_type"),
        "base_models": art.get("base_models"),
        "meta_learner": art.get("meta_learner"),
        "voting_type": art.get("voting_type"),
        "balancing_method": art.get("balancing_method"),
        "augmentation": art.get("augmentation"),
    }
    return metrics, y_pred, meta

def auto_test(model_file, test_file) -> Dict[str, Any]:
    """
    Convenience: if file has 'healthy', run evaluate(); otherwise run_inference().
    Views can call only this and stay skinny.
    """
    # We need to read once to detect label, then rewind for the actual loader.
    # Duplicate the file object using bytes to reuse:
    raw = test_file.read()
    buf1 = io.BytesIO(raw)
    buf2 = io.BytesIO(raw)

    df_probe = _read_txt_like(buf1)
    if "healthy" in df_probe.columns:
        metrics, preds, meta = evaluate(model_file, buf2)
        return {"metrics": metrics, "preds": preds, "meta": meta, "labeled": True}
    else:
        preds, meta = run_inference(model_file, buf2)
        return {"metrics": None, "preds": preds, "meta": meta, "labeled": False}