Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pandas as pd
|
3 |
+
import sklearn
|
4 |
+
from sklearn.preprocessing import StandardScaler
|
5 |
+
from sklearn.cluster import KMeans
|
6 |
+
from sklearn.ensemble import RandomForestClassifier
|
7 |
+
import gradio as gr
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
import seaborn as sns
|
10 |
+
|
11 |
+
# Create sample training data
|
12 |
+
def create_sample_data(n_samples=100):
|
13 |
+
np.random.seed(42)
|
14 |
+
|
15 |
+
sample_data = pd.DataFrame({
|
16 |
+
'genetic_marker_1': np.random.uniform(0, 1, n_samples),
|
17 |
+
'genetic_marker_2': np.random.uniform(0, 1, n_samples),
|
18 |
+
'biomarker_1': np.random.uniform(4.0, 14.0, n_samples),
|
19 |
+
'biomarker_2': np.random.uniform(70, 400, n_samples),
|
20 |
+
'age': np.random.uniform(18, 90, n_samples),
|
21 |
+
'bmi': np.random.uniform(16, 45, n_samples)
|
22 |
+
})
|
23 |
+
|
24 |
+
# Create treatment response based on data patterns
|
25 |
+
sample_data['treatment_response'] = np.where(
|
26 |
+
(sample_data['genetic_marker_1'] > 0.7) &
|
27 |
+
(sample_data['biomarker_1'] > 6.5), 1, 0
|
28 |
+
)
|
29 |
+
|
30 |
+
return sample_data
|
31 |
+
|
32 |
+
# Initialize and train models
|
33 |
+
def initialize_models(data):
|
34 |
+
X = data.drop('treatment_response', axis=1)
|
35 |
+
y = data['treatment_response']
|
36 |
+
|
37 |
+
# Train KMeans model
|
38 |
+
kmeans = KMeans(n_clusters=4, random_state=42)
|
39 |
+
kmeans.fit(X)
|
40 |
+
|
41 |
+
# Train RandomForest model
|
42 |
+
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
|
43 |
+
rf_model.fit(X, y)
|
44 |
+
|
45 |
+
return kmeans, rf_model
|
46 |
+
|
47 |
+
def process_patient(genetic_marker_1, genetic_marker_2, biomarker_1, biomarker_2, age, bmi):
|
48 |
+
try:
|
49 |
+
# Create patient data
|
50 |
+
patient_data = pd.DataFrame({
|
51 |
+
'genetic_marker_1': [float(genetic_marker_1)],
|
52 |
+
'genetic_marker_2': [float(genetic_marker_2)],
|
53 |
+
'biomarker_1': [float(biomarker_1)],
|
54 |
+
'biomarker_2': [float(biomarker_2)],
|
55 |
+
'age': [float(age)],
|
56 |
+
'bmi': [float(bmi)]
|
57 |
+
})
|
58 |
+
|
59 |
+
# Get predictions
|
60 |
+
profile = PROFILE_MODEL.predict(patient_data)[0]
|
61 |
+
treatment_prob = TREATMENT_MODEL.predict_proba(patient_data)[0]
|
62 |
+
|
63 |
+
# Define treatment recommendations
|
64 |
+
treatment_recommendations = {
|
65 |
+
0: "Standard medication with regular monitoring",
|
66 |
+
1: "Intensive lifestyle intervention with medication",
|
67 |
+
2: "Alternative medication combination",
|
68 |
+
3: "Close monitoring with adjusted medication doses"
|
69 |
+
}
|
70 |
+
|
71 |
+
# Risk assessment
|
72 |
+
risk_level = "High Risk" if treatment_prob[1] > 0.7 else "Moderate Risk" if treatment_prob[1] > 0.3 else "Low Risk"
|
73 |
+
|
74 |
+
# Create visualization
|
75 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
|
76 |
+
|
77 |
+
# Marker profile plot
|
78 |
+
values = [genetic_marker_1, genetic_marker_2, biomarker_1/14, biomarker_2/400] # Normalize values
|
79 |
+
labels = ['Genetic 1', 'Genetic 2', 'HbA1c/14', 'Glucose/400']
|
80 |
+
sns.barplot(x=labels, y=values, ax=ax1)
|
81 |
+
ax1.set_title('Patient Markers Profile (Normalized)')
|
82 |
+
ax1.set_ylim(0, 1)
|
83 |
+
|
84 |
+
# Risk assessment plot
|
85 |
+
risk_values = [treatment_prob[0], treatment_prob[1]]
|
86 |
+
risk_labels = ['Low Risk', 'High Risk']
|
87 |
+
sns.barplot(x=risk_labels, y=risk_values, ax=ax2)
|
88 |
+
ax2.set_title('Risk Assessment')
|
89 |
+
ax2.set_ylim(0, 1)
|
90 |
+
|
91 |
+
plt.tight_layout()
|
92 |
+
|
93 |
+
# Prepare detailed report
|
94 |
+
report = f"""
|
95 |
+
Patient Risk Assessment Report
|
96 |
+
-----------------------------
|
97 |
+
Risk Level: {risk_level}
|
98 |
+
Profile Group: {profile}
|
99 |
+
|
100 |
+
Recommended Treatment Plan:
|
101 |
+
{treatment_recommendations[profile]}
|
102 |
+
|
103 |
+
Key Metrics Analysis:
|
104 |
+
- Genetic Risk Score: {(genetic_marker_1 + genetic_marker_2)/2:.2f}/1.00
|
105 |
+
- HbA1c Level: {biomarker_1:.1f} (Normal: 4.0-5.7, Pre-diabetes: 5.7-6.4, Diabetes: >6.5)
|
106 |
+
- Blood Glucose: {biomarker_2:.0f} mg/dL (Normal: <100, Pre-diabetes: 100-125, Diabetes: >126)
|
107 |
+
- BMI Status: {
|
108 |
+
'Underweight' if bmi < 18.5
|
109 |
+
else 'Normal' if bmi < 25
|
110 |
+
else 'Overweight' if bmi < 30
|
111 |
+
else 'Obese'} ({bmi:.1f})
|
112 |
+
|
113 |
+
Confidence Score: {max(treatment_prob):.2%}
|
114 |
+
"""
|
115 |
+
|
116 |
+
return report, fig
|
117 |
+
|
118 |
+
except Exception as e:
|
119 |
+
return f"Error processing data: {str(e)}", None
|
120 |
+
|
121 |
+
# Initialize Gradio interface with sample data
|
122 |
+
sample_data = create_sample_data()
|
123 |
+
PROFILE_MODEL, TREATMENT_MODEL = initialize_models(sample_data)
|
124 |
+
|
125 |
+
# Create Gradio interface
|
126 |
+
with gr.Blocks(title="Genetic and Biomarker Analysis System") as demo:
|
127 |
+
gr.Markdown("# Personalized Diabetes Treatment Recommendation System")
|
128 |
+
gr.Markdown("Enter patient genetic markers and biomarkers to receive personalized treatment recommendations.")
|
129 |
+
|
130 |
+
with gr.Row():
|
131 |
+
with gr.Column():
|
132 |
+
genetic_marker_1 = gr.Number(label="Genetic Marker 1 (0-1)", value=0.85)
|
133 |
+
genetic_marker_2 = gr.Number(label="Genetic Marker 2 (0-1)", value=0.42)
|
134 |
+
biomarker_1 = gr.Number(label="HbA1c Level (4.0-14.0)", value=6.8)
|
135 |
+
biomarker_2 = gr.Number(label="Fasting Glucose (70-400)", value=145)
|
136 |
+
age = gr.Number(label="Age (18-90)", value=45)
|
137 |
+
bmi = gr.Number(label="BMI (16-45)", value=28.5)
|
138 |
+
submit_btn = gr.Button("Generate Recommendations")
|
139 |
+
|
140 |
+
with gr.Column():
|
141 |
+
output_text = gr.Textbox(label="Analysis Report", lines=10)
|
142 |
+
output_plot = gr.Plot(label="Patient Profile Visualization")
|
143 |
+
|
144 |
+
submit_btn.click(
|
145 |
+
fn=process_patient,
|
146 |
+
inputs=[genetic_marker_1, genetic_marker_2, biomarker_1, biomarker_2, age, bmi],
|
147 |
+
outputs=[output_text, output_plot]
|
148 |
+
)
|
149 |
+
|
150 |
+
# Launch the interface
|
151 |
+
if __name__ == "__main__":
|
152 |
+
demo.launch(share=True)
|