Spaces:
Runtime error
Runtime error
Create app.py
#2
by Sammman - opened
app.py
CHANGED
|
@@ -1,128 +1,131 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
-
import
|
|
|
|
|
|
|
| 5 |
from sklearn.preprocessing import StandardScaler
|
| 6 |
-
|
| 7 |
-
import
|
| 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 |
-
gr.
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from sklearn.model_selection import train_test_split
|
| 5 |
from sklearn.preprocessing import StandardScaler
|
| 6 |
+
from sklearn.linear_model import LogisticRegression
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
# ---------------------------------------------------------
|
| 10 |
+
# 1. Core Logic & Data Processing (Identical to raw code)
|
| 11 |
+
# ---------------------------------------------------------
|
| 12 |
+
np.random.seed(42)
|
| 13 |
+
num_patients = 1000
|
| 14 |
+
|
| 15 |
+
data = {
|
| 16 |
+
'age': np.random.randint(18, 70, size=num_patients),
|
| 17 |
+
'hypertension': np.random.choice([0, 1], size=num_patients, p=[0.75, 0.25]),
|
| 18 |
+
'heart_disease': np.random.choice([0, 1], size=num_patients, p=[0.85, 0.15]),
|
| 19 |
+
'avg_glucose_level': np.round(np.random.uniform(55.0, 280.0, size=num_patients), 1),
|
| 20 |
+
'bmi': np.round(np.random.uniform(18.0, 48.0, size=num_patients), 1),
|
| 21 |
+
'stroke': np.random.choice([0, 1], size=num_patients, p=[0.90, 0.10])
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
df = pd.DataFrame(data)
|
| 25 |
+
|
| 26 |
+
X = df.drop(columns=['stroke'])
|
| 27 |
+
y = df['stroke']
|
| 28 |
+
|
| 29 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
|
| 30 |
+
|
| 31 |
+
scaler = StandardScaler()
|
| 32 |
+
X_train_scaled = scaler.fit_transform(X_train)
|
| 33 |
+
X_test_scaled = scaler.transform(X_test)
|
| 34 |
+
|
| 35 |
+
model = LogisticRegression()
|
| 36 |
+
model.fit(X_train_scaled, y_train)
|
| 37 |
+
|
| 38 |
+
# Generate Feature Importance Plot
|
| 39 |
+
def get_feature_importance_plot():
|
| 40 |
+
importance = model.coef_.flatten()
|
| 41 |
+
feature_names = ['Age', 'Hypertension', 'Heart Disease', 'Avg Glucose Level', 'BMI']
|
| 42 |
+
feature_importance = pd.DataFrame({
|
| 43 |
+
'Clinical Feature': feature_names,
|
| 44 |
+
'Statistical Weight': importance
|
| 45 |
+
})
|
| 46 |
+
feature_importance['Absolute Weight'] = feature_importance['Statistical Weight'].abs()
|
| 47 |
+
feature_importance = feature_importance.sort_values(by='Absolute Weight', ascending=True)
|
| 48 |
+
|
| 49 |
+
fig, ax = plt.subplots(figsize=(8, 4))
|
| 50 |
+
ax.barh(feature_importance['Clinical Feature'], feature_importance['Statistical Weight'], color='#1f77b4')
|
| 51 |
+
ax.axvline(0, color='black', linestyle='--', linewidth=1)
|
| 52 |
+
ax.set_title('Neuro-Vascular Feature Importance (Model Weighting)', fontsize=12, fontweight='bold')
|
| 53 |
+
ax.set_xlabel('Predictive Influence (Coefficient Value)', fontsize=10)
|
| 54 |
+
ax.set_ylabel('Clinical Metrics', fontsize=10)
|
| 55 |
+
ax.grid(axis='x', linestyle=':', alpha=0.6)
|
| 56 |
+
plt.tight_layout()
|
| 57 |
+
return fig
|
| 58 |
+
|
| 59 |
+
# ---------------------------------------------------------
|
| 60 |
+
# 2. Evaluation / Prediction Handler
|
| 61 |
+
# ---------------------------------------------------------
|
| 62 |
+
def analyze_patient(patient_age, hypertension, heart_disease, blood_glucose, patient_bmi):
|
| 63 |
+
has_hypertension = 1 if hypertension == "Yes" else 0
|
| 64 |
+
has_heart_disease = 1 if heart_disease == "Yes" else 0
|
| 65 |
+
|
| 66 |
+
custom_patient = np.array([[patient_age, has_hypertension, has_heart_disease, blood_glucose, patient_bmi]])
|
| 67 |
+
custom_patient_scaled = scaler.transform(custom_patient)
|
| 68 |
+
|
| 69 |
+
prob = model.predict_proba(custom_patient_scaled)[0][1] * 100
|
| 70 |
+
|
| 71 |
+
report = []
|
| 72 |
+
report.append("==========================================================")
|
| 73 |
+
report.append(" DYNAMIC CLINICAL ANALYSIS REPORT ")
|
| 74 |
+
report.append("==========================================================")
|
| 75 |
+
report.append("📋 PATIENT BIOMETRICS PROFILE:")
|
| 76 |
+
report.append(f" • Age: {patient_age} years old")
|
| 77 |
+
report.append(f" • Hypertension History: {hypertension}")
|
| 78 |
+
report.append(f" • Cardiovascular Disease: {heart_disease}")
|
| 79 |
+
report.append(f" • Avg Blood Glucose: {blood_glucose} mg/dL")
|
| 80 |
+
report.append(f" • Body Mass Index (BMI): {patient_bmi} kg/m²")
|
| 81 |
+
report.append("----------------------------------------------------------")
|
| 82 |
+
report.append(f"🎯 CALCULATED CEREBROVASCULAR STROKE RISK: {prob:.2f}%")
|
| 83 |
+
report.append("----------------------------------------------------------")
|
| 84 |
+
|
| 85 |
+
if prob >= 15.0:
|
| 86 |
+
report.append("🚨 WARNING: ELEVATED VASCULAR RISK CATEGORY")
|
| 87 |
+
report.append("👉 DPT Action: Check baseline BP/HR. Avoid prolonged dependent positions or maximum manual resistance.")
|
| 88 |
+
report.append("👉 Objective: Focus on submaximal aerobic training, functional mobility, and reactive balance strategy.")
|
| 89 |
+
else:
|
| 90 |
+
report.append("✅ CLEARANCE: BASELINE STABLE RISK PROFILE")
|
| 91 |
+
report.append("👉 DPT Action: Safe to push metabolic capacity and neuroplasticity boundaries.")
|
| 92 |
+
report.append("👉 Objective: High-intensity task-specific training and advanced dynamic gait coordination.")
|
| 93 |
+
report.append("==========================================================")
|
| 94 |
+
|
| 95 |
+
fig = get_feature_importance_plot()
|
| 96 |
+
return "\n".join(report), fig
|
| 97 |
+
|
| 98 |
+
# ---------------------------------------------------------
|
| 99 |
+
# 3. Gradio Web Interface
|
| 100 |
+
# ---------------------------------------------------------
|
| 101 |
+
with gr.Blocks(title="DPT Neurological Clinical Appraisal") as demo:
|
| 102 |
+
gr.Markdown("# 🧠 DPT Neurological Clinical Appraisal & Stroke Risk Calculator")
|
| 103 |
+
gr.Markdown("Adjust patient biometrics below to calculate cerebrovascular risk and generate clinical DPT guidance.")
|
| 104 |
+
|
| 105 |
+
with gr.Row():
|
| 106 |
+
with gr.Column():
|
| 107 |
+
age_input = gr.Slider(minimum=18, maximum=100, value=67, step=1, label="Patient Age")
|
| 108 |
+
htn_input = gr.Radio(choices=["No", "Yes"], value="Yes", label="Hypertension History")
|
| 109 |
+
hd_input = gr.Radio(choices=["No", "Yes"], value="No", label="Heart Disease History")
|
| 110 |
+
glucose_input = gr.Slider(minimum=50.0, maximum=300.0, value=185.4, step=0.1, label="Avg Blood Glucose Level (mg/dL)")
|
| 111 |
+
bmi_input = gr.Slider(minimum=15.0, maximum=50.0, value=31.2, step=0.1, label="Patient BMI (kg/m²)")
|
| 112 |
+
submit_btn = gr.Button("Calculate Risk Profile", variant="primary")
|
| 113 |
+
|
| 114 |
+
with gr.Column():
|
| 115 |
+
output_report = gr.Textbox(label="Clinical Report Output", lines=18, max_lines=25)
|
| 116 |
+
output_plot = gr.Plot(label="Model Feature Weights")
|
| 117 |
+
|
| 118 |
+
submit_btn.click(
|
| 119 |
+
fn=analyze_patient,
|
| 120 |
+
inputs=[age_input, htn_input, hd_input, glucose_input, bmi_input],
|
| 121 |
+
outputs=[output_report, output_plot]
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
demo.load(
|
| 125 |
+
fn=analyze_patient,
|
| 126 |
+
inputs=[age_input, htn_input, hd_input, glucose_input, bmi_input],
|
| 127 |
+
outputs=[output_report, output_plot]
|
| 128 |
+
)
|
| 129 |
|
| 130 |
if __name__ == "__main__":
|
| 131 |
+
demo.launch()
|