Spaces:
Paused
Paused
File size: 6,312 Bytes
57e75c6 | 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 | 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() |