File size: 5,507 Bytes
eecd8b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, re
import numpy as np
import pandas as pd
import joblib

DEPLOY_DIR = os.path.join(os.path.dirname(__file__), "..", "models")

DOMAIN_WEIGHTS = {
    "METABOLIC": 0.35, "REPRODUCTIVE": 0.40,
    "HYPERANDROGENIC": 0.20, "GENERAL": 0.05,
}

BIOMARKER_DIRECTIONS = {
    "FSH(mIU/mL)": 1, "LH(mIU/mL)": -1, "FSH/LH": 1,
    "AMH(ng/mL)": -1, "Follicle No. (L)": -1, "Follicle No. (R)": -1,
    "Endometrium (mm)": -1, "PRG(ng/mL)": -1, "Cycle(R/I)": 1,
}

BIOMARKER_WEIGHTS = {
    "FSH(mIU/mL)": 0.18, "LH(mIU/mL)": 0.08, "FSH/LH": 0.15,
    "AMH(ng/mL)": 0.22, "Follicle No. (L)": 0.10, "Follicle No. (R)": 0.10,
    "Endometrium (mm)": 0.08, "PRG(ng/mL)": 0.05, "Cycle(R/I)": 0.04,
}

CLINICAL_RANGES = {
    "FSH(mIU/mL)": (1.0, 30.0), "LH(mIU/mL)": (0.5, 40.0),
    "FSH/LH": (0.1, 5.0), "AMH(ng/mL)": (0.1, 15.0),
    "Follicle No. (L)": (0.0, 25.0), "Follicle No. (R)": (0.0, 25.0),
    "Endometrium (mm)": (2.0, 16.0), "PRG(ng/mL)": (0.1, 25.0),
    "Cycle(R/I)": (0.0, 1.0),
}

def clean_name(n):
    return re.sub(r"[^0-9a-zA-Z_]", "_", n.strip())

def load_tabular_artifacts():
    arts = {}
    for key, fname in [
        ("meta", "ensemble_meta.pkl"), ("base_models", "base_models.pkl"),
        ("domain_models", "domain_models.pkl"), ("mice", "mice_imputer.pkl"),
        ("scaler", "scaler.pkl"), ("stats", "train_stats.pkl"),
        ("feat_cols", "feature_columns.pkl"), ("threshold", "best_threshold.pkl"),
    ]:
        path = os.path.join(DEPLOY_DIR, fname)
        arts[key] = joblib.load(path) if os.path.exists(path) else None
    return arts

def _apply_severity(domain_models, stats, X_sc):
    result = pd.DataFrame(index=X_sc.index)
    for d, (model, fc) in domain_models.items():
        avail = [c for c in fc if c in X_sc.columns]
        if not avail:
            result[f"{d}_SEV"] = 0.0
            continue
        p = model.predict_proba(X_sc[avail])[:, 1]
        mn, mx = stats[d]["min"], stats[d]["max"]
        result[f"{d}_SEV"] = np.clip((p - mn) / (mx - mn + 1e-6), 0, 1)
    result = result.fillna(0)
    result["OVERALL_SEV"] = sum(
        result[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
        for d in DOMAIN_WEIGHTS if f"{d}_SEV" in result.columns
    )
    return result

def predict_tabular(arts, patient_dict):
    feat_cols = arts["feat_cols"]

    raw = pd.DataFrame([patient_dict])
    if "FSH(mIU/mL)" in raw and "LH(mIU/mL)" in raw:
        raw["FSH_LH_Ratio"] = raw["FSH(mIU/mL)"] / (raw["LH(mIU/mL)"] + 1e-6)
    if "Follicle No. (L)" in raw and "Follicle No. (R)" in raw:
        raw["Total_Follicles"] = raw["Follicle No. (L)"].fillna(0) + raw["Follicle No. (R)"].fillna(0)
    if "AMH(ng/mL)" in raw and "FSH(mIU/mL)" in raw:
        raw["AMH_FSH_Ratio"] = raw["AMH(ng/mL)"] / (raw["FSH(mIU/mL)"] + 1e-6)
    if "BMI" in raw and "Waist(inch)" in raw:
        raw["BMI_Waist_Ratio"] = raw["BMI"] / (raw["Waist(inch)"] + 1e-6)
    andro = ["hair growth(Y/N)", "Skin darkening (Y/N)", "Hair loss(Y/N)", "Pimples(Y/N)", "PRL(ng/mL)"]
    present = [f for f in andro if f in raw.columns]
    if present:
        raw["Androgenic_Score"] = raw[present].sum(axis=1)

    raw_clean = raw.copy()
    raw_clean.columns = [clean_name(c) for c in raw_clean.columns]

    X = pd.DataFrame(columns=feat_cols)
    X = pd.concat([X, raw_clean.reindex(columns=feat_cols)], ignore_index=True)
    X = X.astype(float)

    X_imp = pd.DataFrame(arts["mice"].transform(X), columns=X.columns, index=X.index)
    X_sc  = X_imp.copy()
    num_c = X_sc.select_dtypes(include=np.number).columns
    X_sc[num_c] = arts["scaler"].transform(X_imp[num_c])

    sev = _apply_severity(arts["domain_models"], arts["stats"], X_sc)
    X_final = pd.concat([X_sc, sev], axis=1)

    base_probs = {}
    for name, model in arts["base_models"].items():
        try:
            base_probs[name] = float(model.predict_proba(X_final)[:, 1][0])
        except:
            base_probs[name] = 0.5

    meta_input = pd.DataFrame([base_probs])
    pcos_prob  = float(arts["meta"].predict_proba(meta_input)[:, 1][0])
    threshold  = float(arts["threshold"])

    if pcos_prob < 0.33:   pcos_tier = "Low"
    elif pcos_prob < 0.66: pcos_tier = "Moderate"
    else:                  pcos_tier = "High"

    domain_scores = {
        d: round(float(sev[f"{d}_SEV"].iloc[0]), 4)
        for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev.columns
    }

    # Infertility risk
    score = 0.0; total_w = 0.0
    for feat, val in patient_dict.items():
        if feat not in BIOMARKER_WEIGHTS or val is None: continue
        lo, hi = CLINICAL_RANGES.get(feat, (0, 1))
        norm = np.clip((float(val) - lo) / (hi - lo + 1e-6), 0, 1)
        if BIOMARKER_DIRECTIONS.get(feat, 1) == -1: norm = 1 - norm
        w = BIOMARKER_WEIGHTS[feat]
        score += w * norm; total_w += w
    inf_score = score / total_w if total_w > 0 else 0.5
    if inf_score < 0.33:   inf_tier = "Low"
    elif inf_score < 0.66: inf_tier = "Moderate"
    else:                  inf_tier = "High"

    return {
        "pcos_prob"        : round(pcos_prob, 4),
        "pcos_prediction"  : "PCOS" if pcos_prob >= threshold else "Not PCOS",
        "pcos_tier"        : pcos_tier,
        "threshold"        : round(threshold, 4),
        "base_probs"       : {k: round(v, 4) for k, v in base_probs.items()},
        "domain_scores"    : domain_scores,
        "overall_severity" : round(float(sev["OVERALL_SEV"].iloc[0]), 4),
        "infertility_score": round(inf_score, 4),
        "infertility_tier" : inf_tier,
    }