import gradio as gr import pickle import numpy as np # Load the model and label encoder with open("model.pkl", "rb") as f: model = pickle.load(f) with open("label_encoder.pkl", "rb") as f: label_encoder = pickle.load(f) # DXMPTR mapping: Yes=1, Maybe=0.5, No=0 DXMPTR_MAP = {"Yes": 1, "Maybe": 0.5, "No": 0} def predict( # DXMDES dxmdes, # Biomarkers (8) ab40, ab42, ptau181, ptau217, nptau217, gfap, nfl, ab_ratio, # Clinical Markers (5) mmse_score, dha, formic_acid, lactoferrin, ntp, # Cognitive Assessment - DXMPTR (6) dxmptr1, dxmptr2, dxmptr3, dxmptr4, dxmptr5, dxmptr6 ): """ Predict Alzheimer's disease risk based on biomarkers, clinical markers, and cognitive assessment. Total: 19 raw inputs + 7 engineered features = 26 features """ # Convert DXMPTR values dxmptr1_val = DXMPTR_MAP[dxmptr1] dxmptr2_val = DXMPTR_MAP[dxmptr2] dxmptr3_val = DXMPTR_MAP[dxmptr3] dxmptr4_val = DXMPTR_MAP[dxmptr4] dxmptr5_val = DXMPTR_MAP[dxmptr5] dxmptr6_val = DXMPTR_MAP[dxmptr6] # ======================================================================== # FEATURE ENGINEERING (same as training notebook) # ======================================================================== # 1. pTau217/Aβ42 ratio ptau217_ab42_ratio = ptau217 / (ab42 + 1e-10) # 2. pTau181/Aβ42 ratio ptau181_ab42_ratio = ptau181 / (ab42 + 1e-10) # 3. NfL/GFAP ratio (neurodegeneration vs neuroinflammation) nfl_gfap_ratio = nfl / (gfap + 1e-10) # 4. Composite biomarker burden score biomarker_burden = ptau217 + gfap + nfl - (ab42 * 0.01) # 5. DXMPTR aggregations dxmptr_values = [dxmptr1_val, dxmptr2_val, dxmptr3_val, dxmptr4_val, dxmptr5_val, dxmptr6_val] dxmptr_mean = np.mean(dxmptr_values) dxmptr_std = np.std(dxmptr_values) # Create feature array with all 26 features # Order MUST match FEATURE_COLUMNS from training notebook: # ['DXMDES', 'DXMPTR1-6', 'Abeta40', 'Abeta42', 'Abeta_ratio', 'GFAP', 'NfL', # 'npTau217', 'pTau181', 'pTau217', 'DHA', 'FORMICACID', 'LACTOFERRIN', 'MMSE', 'NTP'] # + 6 engineered features # DXMDES value (from user input) dxmdes_val = dxmdes features = np.array([[ # Raw features (20) - exact order from FEATURE_COLUMNS dxmdes_val, dxmptr1_val, dxmptr2_val, dxmptr3_val, dxmptr4_val, dxmptr5_val, dxmptr6_val, ab40, ab42, ab_ratio, gfap, nfl, nptau217, ptau181, ptau217, dha, formic_acid, lactoferrin, mmse_score, ntp, # Engineered features (6) ptau217_ab42_ratio, ptau181_ab42_ratio, nfl_gfap_ratio, biomarker_burden, dxmptr_mean, dxmptr_std ]]) # Get probability predictions probabilities = model.predict_proba(features)[0] # Get class names from label encoder class_names = label_encoder.classes_ # Create probability dictionary prob_dict = {} for i, class_name in enumerate(class_names): prob_dict[class_name] = probabilities[i] * 100 # Find highest risk highest_risk_idx = np.argmax(probabilities) highest_risk_class = class_names[highest_risk_idx] highest_risk_prob = probabilities[highest_risk_idx] * 100 # Format result strings prob_results = "" for class_name in ["AD", "MCI", "CN"]: if class_name in prob_dict: prob_results += f"**{class_name}**: {prob_dict[class_name]:.2f}%\n\n" # Final verdict with styling final_result = f"## 🎯 Highest Risk: **{highest_risk_class}** ({highest_risk_prob:.2f}%)" # Risk interpretation risk_interpretation = "" if highest_risk_class == "AD": risk_interpretation = "⚠️ **Alzheimer's Disease (AD)** - High probability of Alzheimer's Disease. Please consult a neurologist for further evaluation." elif highest_risk_class == "MCI": risk_interpretation = "⚡ **Mild Cognitive Impairment (MCI)** - Moderate cognitive decline detected. Regular monitoring and lifestyle modifications recommended." else: risk_interpretation = "✅ **Cognitively Normal (CN)** - No significant cognitive impairment detected. Continue with healthy lifestyle practices." return prob_results, final_result, risk_interpretation # Create the Gradio interface with gr.Blocks(title="Alzheimer's Disease Risk Predictor") as demo: gr.Markdown( """ # 🧠 Alzheimer's Disease Risk Predictor AI-powered assessment using biomarkers, clinical markers, and cognitive evaluation """ ) with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 🧬 Biomarkers") with gr.Row(): ab40 = gr.Number(label="Aβ40 (pg/mL)", value=0.12, info="Amyloid-beta 40 concentration") ab42 = gr.Number(label="Aβ42 (pg/mL)", value=0.154, info="Amyloid-beta 42 concentration") with gr.Row(): ptau181 = gr.Number(label="pTau181 (pg/mL)", value=0.65, info="Phosphorylated Tau 181") ptau217 = gr.Number(label="pTau217 (pg/mL)", value=1.78, info="Phosphorylated Tau 217") with gr.Row(): nptau217 = gr.Number(label="npTau217 (pg/mL)", value=0.42, info="Non-phosphorylated Tau 217") gfap = gr.Number(label="GFAP (pg/mL)", value=0.79, info="Glial Fibrillary Acidic Protein") with gr.Row(): nfl = gr.Number(label="NfL (pg/mL)", value=1.84, info="Neurofilament Light Chain") ab_ratio = gr.Number(label="Aβ Ratio (Aβ42/Aβ40)", value=0.44, info="Amyloid-beta 42/40 ratio") gr.Markdown("### 🏥 Clinical Markers") with gr.Row(): mmse_score = gr.Number(label="MMSE Score", value=20, minimum=0, maximum=30, info="Mini-Mental State Examination (0-30)") dha = gr.Number(label="DHA (μg/mL)", value=35633.35, info="Docosahexaenoic Acid") with gr.Row(): formic_acid = gr.Number(label="Formic Acid (μM)", value=489.7, info="Formic Acid concentration") lactoferrin = gr.Number(label="Lactoferrin (ng/mL)", value=7099.47, info="Lactoferrin level") ntp = gr.Number(label="NTP (μM)", value=2.39, info="Nucleotide Triphosphate") with gr.Column(scale=1): gr.Markdown("### 📋 Diagnostic Criteria") dxmdes = gr.Radio( choices=[1, -9], value=1, label="DXMDES: MCI Criteria Met", info="1 = Yes (criteria met), -9 = Missing/Unknown" ) gr.Markdown("### 📋 Cognitive Assessment (DXMPTR)") dxmptr1 = gr.Radio( choices=["Yes", "Maybe", "No"], value="Yes", label="DXMPTR1: Subjective memory complaint", info="Patient reports memory issues" ) dxmptr2 = gr.Radio( choices=["Yes", "Maybe", "No"], value="Yes", label="DXMPTR2: Informant memory complaint", info="Family/caregiver reports memory issues" ) dxmptr3 = gr.Radio( choices=["Yes", "Maybe", "No"], value="Yes", label="DXMPTR3: Change in general cognitive function", info="Observable cognitive changes" ) dxmptr4 = gr.Radio( choices=["Yes", "Maybe", "No"], value="Yes", label="DXMPTR4: Change in activities of daily living", info="Impact on daily activities" ) dxmptr5 = gr.Radio( choices=["Yes", "Maybe", "No"], value="Yes", label="DXMPTR5: Objective memory impairment", info="For age/education adjusted" ) dxmptr6 = gr.Radio( choices=["Yes", "Maybe", "No"], value="Yes", label="DXMPTR6: Not demented by clinical criteria", info="Clinical dementia criteria not met" ) gr.Markdown("---") predict_btn = gr.Button("🔍 Analyze Risk", variant="primary", size="lg") gr.Markdown("### 📊 Results") with gr.Row(): with gr.Column(): prob_output = gr.Markdown(label="Probability Distribution") with gr.Column(): final_output = gr.Markdown(label="Final Assessment") interpretation_output = gr.Markdown(label="Clinical Interpretation") predict_btn.click( fn=predict, inputs=[ dxmdes, ab40, ab42, ptau181, ptau217, nptau217, gfap, nfl, ab_ratio, mmse_score, dha, formic_acid, lactoferrin, ntp, dxmptr1, dxmptr2, dxmptr3, dxmptr4, dxmptr5, dxmptr6 ], outputs=[prob_output, final_output, interpretation_output] ) gr.Markdown( """ --- ### ℹ️ About This Tool This AI-powered tool analyzes multiple biomarkers and clinical indicators to assess Alzheimer's disease risk: - **AD (Alzheimer's Disease)**: Indicates high probability of Alzheimer's Disease - **MCI (Mild Cognitive Impairment)**: Indicates moderate cognitive decline - **CN (Cognitively Normal)**: Indicates normal cognitive function > ⚠️ **Disclaimer**: This tool is for educational and research purposes only. It should not be used as a substitute for professional medical diagnosis. Always consult qualified healthcare professionals for medical advice. """ ) if __name__ == "__main__": demo.launch(css=".gradio-container { max-width: 1000px !important; margin: auto !important; }")