Files changed (1) hide show
  1. app.py +127 -124
app.py CHANGED
@@ -1,128 +1,131 @@
1
- import gradio as gr
2
- import pandas as pd
3
  import numpy as np
4
- import pickle
 
 
5
  from sklearn.preprocessing import StandardScaler
6
- import sklearn
7
- import os
8
-
9
- print(f"Prediction environment scikit-learn version: {sklearn.__version__}")
10
-
11
- def decode_file(file_path):
12
- with open(file_path, 'rb') as file:
13
- obj = pickle.load(file)
14
- return obj
15
-
16
- # Load the model without try/except
17
- model = decode_file('./model.pkl')
18
-
19
- def preprocess_input(data_dict):
20
- """Preprocess input data to match the training format"""
21
- # First create DataFrame with original columns
22
- df = pd.DataFrame([data_dict])
23
-
24
- # Store original features before transformation
25
- original_df = df.copy()
26
-
27
- # Numeric features
28
- numeric_features = ['age', 'avg_glucose_level', 'bmi']
29
-
30
- # Scale numeric features and add prefix
31
- scaler = StandardScaler()
32
- scaled_features = scaler.fit_transform(df[numeric_features])
33
- for i, feat in enumerate(numeric_features):
34
- df[f'num__{feat}'] = scaled_features[:, i]
35
-
36
- # Create categorical features
37
- # Gender
38
- df['cat__gender_Male'] = (df['gender'] == 'Male').astype(float)
39
- df['cat__gender_Other'] = 0.0
40
-
41
- # Hypertension
42
- df['cat__hypertension_1'] = df['hypertension'].astype(float)
43
-
44
- # Heart Disease
45
- df['cat__heart_disease_1'] = df['heart_disease'].astype(float)
46
-
47
- # Ever Married
48
- df['cat__ever_married_Yes'] = (df['ever_married'] == 'Yes').astype(float)
49
-
50
- # Work Type
51
- df['cat__work_type_Never_worked'] = (df['work_type'] == 'Never_worked').astype(float)
52
- df['cat__work_type_Private'] = (df['work_type'] == 'Private').astype(float)
53
- df['cat__work_type_Self-employed'] = (df['work_type'] == 'Self-employed').astype(float)
54
- df['cat__work_type_children'] = (df['work_type'] == 'children').astype(float)
55
-
56
- # Residence Type
57
- df['cat__Residence_type_Urban'] = (df['Residence_type'] == 'Urban').astype(float)
58
-
59
- # Smoking Status
60
- df['cat__smoking_status_formerly smoked'] = (df['smoking_status'] == 'formerly smoked').astype(float)
61
- df['cat__smoking_status_never smoked'] = (df['smoking_status'] == 'never smoked').astype(float)
62
- df['cat__smoking_status_smokes'] = (df['smoking_status'] == 'smokes').astype(float)
63
-
64
- # Select only the transformed columns in the correct order
65
- feature_columns = [
66
- 'num__age', 'num__avg_glucose_level', 'num__bmi',
67
- 'cat__gender_Male', 'cat__gender_Other', 'cat__hypertension_1',
68
- 'cat__heart_disease_1', 'cat__ever_married_Yes',
69
- 'cat__work_type_Never_worked', 'cat__work_type_Private',
70
- 'cat__work_type_Self-employed', 'cat__work_type_children',
71
- 'cat__Residence_type_Urban', 'cat__smoking_status_formerly smoked',
72
- 'cat__smoking_status_never smoked', 'cat__smoking_status_smokes'
73
- ]
74
-
75
- return df[feature_columns]
76
-
77
- def predict(gender, age, hypertension, ever_married, work_type, heart_disease,
78
- avg_glucose_level, bmi, smoking_status, Residence_type):
79
- """Make prediction using the loaded model"""
80
- if model is None:
81
- return "Error: Model not loaded"
82
-
83
- # Create input dictionary
84
- input_data = {
85
- 'gender': gender,
86
- 'age': float(age), # Ensure numeric
87
- 'hypertension': 1 if hypertension == 'Yes' else 0,
88
- 'heart_disease': 1 if heart_disease == 'Yes' else 0,
89
- 'ever_married': ever_married,
90
- 'work_type': work_type,
91
- 'Residence_type': Residence_type,
92
- 'avg_glucose_level': float(avg_glucose_level), # Ensure numeric
93
- 'bmi': float(bmi), # Ensure numeric
94
- 'smoking_status': smoking_status
95
- }
96
-
97
- # Preprocess the input
98
- processed_input = preprocess_input(input_data)
99
-
100
- # Use the loaded model
101
- try:
102
- prediction = model.predict_proba(processed_input)[0][1]
103
- return f"The probability of stroke is {prediction:.2%}"
104
- except Exception as e:
105
- return f"Error making prediction: {str(e)}, model is not valid" # updated here
106
-
107
- # Create the Gradio interface
108
- iface = gr.Interface(
109
- fn=predict,
110
- inputs=[
111
- gr.Radio(choices=['Female', 'Male'], label="Gender"),
112
- gr.Slider(minimum=0, maximum=100, label="Age"),
113
- gr.Radio(choices=['Yes', 'No'], label="Hypertension"),
114
- gr.Radio(choices=['Yes', 'No'], label="Ever Married"),
115
- gr.Radio(choices=['Private', 'Self-employed', 'Govt_job', 'children', 'Never_worked'], label="Work Type"),
116
- gr.Radio(choices=['Yes', 'No'], label="Heart Disease"),
117
- gr.Number(label="Average Glucose Level"),
118
- gr.Slider(minimum=10, maximum=50, label="BMI"),
119
- gr.Radio(choices=['formerly smoked', 'never smoked', 'smokes', 'Unknown'], label="Smoking Status"),
120
- gr.Radio(choices=['Urban', 'Rural'], label="Residence Type")
121
- ],
122
- outputs='text',
123
- title='Stroke Probability Predictor',
124
- description='Predicts the probability of having a stroke based on input features.'
125
- )
 
 
 
126
 
127
  if __name__ == "__main__":
128
- iface.launch()
 
 
 
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()