import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression import gradio as gr # --------------------------------------------------------- # 1. Core Logic & Data Processing (Identical to raw code) # --------------------------------------------------------- np.random.seed(42) num_patients = 1000 data = { 'age': np.random.randint(18, 70, size=num_patients), 'hypertension': np.random.choice([0, 1], size=num_patients, p=[0.75, 0.25]), 'heart_disease': np.random.choice([0, 1], size=num_patients, p=[0.85, 0.15]), 'avg_glucose_level': np.round(np.random.uniform(55.0, 280.0, size=num_patients), 1), 'bmi': np.round(np.random.uniform(18.0, 48.0, size=num_patients), 1), 'stroke': np.random.choice([0, 1], size=num_patients, p=[0.90, 0.10]) } df = pd.DataFrame(data) X = df.drop(columns=['stroke']) y = df['stroke'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) model = LogisticRegression() model.fit(X_train_scaled, y_train) # Generate Feature Importance Plot def get_feature_importance_plot(): importance = model.coef_.flatten() feature_names = ['Age', 'Hypertension', 'Heart Disease', 'Avg Glucose Level', 'BMI'] feature_importance = pd.DataFrame({ 'Clinical Feature': feature_names, 'Statistical Weight': importance }) feature_importance['Absolute Weight'] = feature_importance['Statistical Weight'].abs() feature_importance = feature_importance.sort_values(by='Absolute Weight', ascending=True) fig, ax = plt.subplots(figsize=(8, 4)) ax.barh(feature_importance['Clinical Feature'], feature_importance['Statistical Weight'], color='#1f77b4') ax.axvline(0, color='black', linestyle='--', linewidth=1) ax.set_title('Neuro-Vascular Feature Importance (Model Weighting)', fontsize=12, fontweight='bold') ax.set_xlabel('Predictive Influence (Coefficient Value)', fontsize=10) ax.set_ylabel('Clinical Metrics', fontsize=10) ax.grid(axis='x', linestyle=':', alpha=0.6) plt.tight_layout() return fig # --------------------------------------------------------- # 2. Evaluation / Prediction Handler # --------------------------------------------------------- def analyze_patient(patient_age, hypertension, heart_disease, blood_glucose, patient_bmi): has_hypertension = 1 if hypertension == "Yes" else 0 has_heart_disease = 1 if heart_disease == "Yes" else 0 custom_patient = np.array([[patient_age, has_hypertension, has_heart_disease, blood_glucose, patient_bmi]]) custom_patient_scaled = scaler.transform(custom_patient) prob = model.predict_proba(custom_patient_scaled)[0][1] * 100 report = [] report.append("==========================================================") report.append(" DYNAMIC CLINICAL ANALYSIS REPORT ") report.append("==========================================================") report.append("📋 PATIENT BIOMETRICS PROFILE:") report.append(f" • Age: {patient_age} years old") report.append(f" • Hypertension History: {hypertension}") report.append(f" • Cardiovascular Disease: {heart_disease}") report.append(f" • Avg Blood Glucose: {blood_glucose} mg/dL") report.append(f" • Body Mass Index (BMI): {patient_bmi} kg/m²") report.append("----------------------------------------------------------") report.append(f"🎯 CALCULATED CEREBROVASCULAR STROKE RISK: {prob:.2f}%") report.append("----------------------------------------------------------") if prob >= 15.0: report.append("🚨 WARNING: ELEVATED VASCULAR RISK CATEGORY") report.append("👉 DPT Action: Check baseline BP/HR. Avoid prolonged dependent positions or maximum manual resistance.") report.append("👉 Objective: Focus on submaximal aerobic training, functional mobility, and reactive balance strategy.") else: report.append("✅ CLEARANCE: BASELINE STABLE RISK PROFILE") report.append("👉 DPT Action: Safe to push metabolic capacity and neuroplasticity boundaries.") report.append("👉 Objective: High-intensity task-specific training and advanced dynamic gait coordination.") report.append("==========================================================") fig = get_feature_importance_plot() return "\n".join(report), fig # --------------------------------------------------------- # 3. Gradio Web Interface # --------------------------------------------------------- with gr.Blocks(title="DPT Neurological Clinical Appraisal") as demo: gr.Markdown("# 🧠 DPT Neurological Clinical Appraisal & Stroke Risk Calculator") gr.Markdown("Adjust patient biometrics below to calculate cerebrovascular risk and generate clinical DPT guidance.") with gr.Row(): with gr.Column(): age_input = gr.Slider(minimum=18, maximum=100, value=67, step=1, label="Patient Age") htn_input = gr.Radio(choices=["No", "Yes"], value="Yes", label="Hypertension History") hd_input = gr.Radio(choices=["No", "Yes"], value="No", label="Heart Disease History") glucose_input = gr.Slider(minimum=50.0, maximum=300.0, value=185.4, step=0.1, label="Avg Blood Glucose Level (mg/dL)") bmi_input = gr.Slider(minimum=15.0, maximum=50.0, value=31.2, step=0.1, label="Patient BMI (kg/m²)") submit_btn = gr.Button("Calculate Risk Profile", variant="primary") with gr.Column(): output_report = gr.Textbox(label="Clinical Report Output", lines=18, max_lines=25) output_plot = gr.Plot(label="Model Feature Weights") submit_btn.click( fn=analyze_patient, inputs=[age_input, htn_input, hd_input, glucose_input, bmi_input], outputs=[output_report, output_plot] ) demo.load( fn=analyze_patient, inputs=[age_input, htn_input, hd_input, glucose_input, bmi_input], outputs=[output_report, output_plot] ) if __name__ == "__main__": demo.launch()