Anupam202224's picture
Create app.py
ce40e09 verified
import numpy as np
import pandas as pd
import sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.ensemble import RandomForestClassifier
import gradio as gr
import matplotlib.pyplot as plt
import seaborn as sns
# Create sample training data
def create_sample_data(n_samples=100):
np.random.seed(42)
sample_data = pd.DataFrame({
'genetic_marker_1': np.random.uniform(0, 1, n_samples),
'genetic_marker_2': np.random.uniform(0, 1, n_samples),
'biomarker_1': np.random.uniform(4.0, 14.0, n_samples),
'biomarker_2': np.random.uniform(70, 400, n_samples),
'age': np.random.uniform(18, 90, n_samples),
'bmi': np.random.uniform(16, 45, n_samples)
})
# Create treatment response based on data patterns
sample_data['treatment_response'] = np.where(
(sample_data['genetic_marker_1'] > 0.7) &
(sample_data['biomarker_1'] > 6.5), 1, 0
)
return sample_data
# Initialize and train models
def initialize_models(data):
X = data.drop('treatment_response', axis=1)
y = data['treatment_response']
# Train KMeans model
kmeans = KMeans(n_clusters=4, random_state=42)
kmeans.fit(X)
# Train RandomForest model
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
rf_model.fit(X, y)
return kmeans, rf_model
def process_patient(genetic_marker_1, genetic_marker_2, biomarker_1, biomarker_2, age, bmi):
try:
# Create patient data
patient_data = pd.DataFrame({
'genetic_marker_1': [float(genetic_marker_1)],
'genetic_marker_2': [float(genetic_marker_2)],
'biomarker_1': [float(biomarker_1)],
'biomarker_2': [float(biomarker_2)],
'age': [float(age)],
'bmi': [float(bmi)]
})
# Get predictions
profile = PROFILE_MODEL.predict(patient_data)[0]
treatment_prob = TREATMENT_MODEL.predict_proba(patient_data)[0]
# Define treatment recommendations
treatment_recommendations = {
0: "Standard medication with regular monitoring",
1: "Intensive lifestyle intervention with medication",
2: "Alternative medication combination",
3: "Close monitoring with adjusted medication doses"
}
# Risk assessment
risk_level = "High Risk" if treatment_prob[1] > 0.7 else "Moderate Risk" if treatment_prob[1] > 0.3 else "Low Risk"
# Create visualization
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
# Marker profile plot
values = [genetic_marker_1, genetic_marker_2, biomarker_1/14, biomarker_2/400] # Normalize values
labels = ['Genetic 1', 'Genetic 2', 'HbA1c/14', 'Glucose/400']
sns.barplot(x=labels, y=values, ax=ax1)
ax1.set_title('Patient Markers Profile (Normalized)')
ax1.set_ylim(0, 1)
# Risk assessment plot
risk_values = [treatment_prob[0], treatment_prob[1]]
risk_labels = ['Low Risk', 'High Risk']
sns.barplot(x=risk_labels, y=risk_values, ax=ax2)
ax2.set_title('Risk Assessment')
ax2.set_ylim(0, 1)
plt.tight_layout()
# Prepare detailed report
report = f"""
Patient Risk Assessment Report
-----------------------------
Risk Level: {risk_level}
Profile Group: {profile}
Recommended Treatment Plan:
{treatment_recommendations[profile]}
Key Metrics Analysis:
- Genetic Risk Score: {(genetic_marker_1 + genetic_marker_2)/2:.2f}/1.00
- HbA1c Level: {biomarker_1:.1f} (Normal: 4.0-5.7, Pre-diabetes: 5.7-6.4, Diabetes: >6.5)
- Blood Glucose: {biomarker_2:.0f} mg/dL (Normal: <100, Pre-diabetes: 100-125, Diabetes: >126)
- BMI Status: {
'Underweight' if bmi < 18.5
else 'Normal' if bmi < 25
else 'Overweight' if bmi < 30
else 'Obese'} ({bmi:.1f})
Confidence Score: {max(treatment_prob):.2%}
"""
return report, fig
except Exception as e:
return f"Error processing data: {str(e)}", None
# Initialize Gradio interface with sample data
sample_data = create_sample_data()
PROFILE_MODEL, TREATMENT_MODEL = initialize_models(sample_data)
# Create Gradio interface
with gr.Blocks(title="Genetic and Biomarker Analysis System") as demo:
gr.Markdown("# Personalized Diabetes Treatment Recommendation System")
gr.Markdown("Enter patient genetic markers and biomarkers to receive personalized treatment recommendations.")
with gr.Row():
with gr.Column():
genetic_marker_1 = gr.Number(label="Genetic Marker 1 (0-1)", value=0.85)
genetic_marker_2 = gr.Number(label="Genetic Marker 2 (0-1)", value=0.42)
biomarker_1 = gr.Number(label="HbA1c Level (4.0-14.0)", value=6.8)
biomarker_2 = gr.Number(label="Fasting Glucose (70-400)", value=145)
age = gr.Number(label="Age (18-90)", value=45)
bmi = gr.Number(label="BMI (16-45)", value=28.5)
submit_btn = gr.Button("Generate Recommendations")
with gr.Column():
output_text = gr.Textbox(label="Analysis Report", lines=10)
output_plot = gr.Plot(label="Patient Profile Visualization")
submit_btn.click(
fn=process_patient,
inputs=[genetic_marker_1, genetic_marker_2, biomarker_1, biomarker_2, age, bmi],
outputs=[output_text, output_plot]
)
# Launch the interface
if __name__ == "__main__":
demo.launch(share=True)