RafaelFonseca
Add Django Django_webapp project to HF space
e50f22e
Raw History Blame Contribute Delete
5.16 kB
# 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}