File size: 7,266 Bytes
796a4ac |
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
# First, install required packages
#!pip install gradio pandas numpy scikit-learn
import gradio as gr
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
import json
from datetime import datetime, timedelta
class SimplePrecisionMedicineSystem:
def __init__(self):
self.scaler = StandardScaler()
def calculate_risk_score(self, genetic_score, lifestyle_score, age, symptom_severity):
"""Calculate overall risk score"""
try:
# Normalize age to 0-1 range (assuming max age of 100)
age_normalized = age / 100.0
# Weight factors (can be adjusted)
weights = {
'genetic': 0.4,
'lifestyle': 0.3,
'age': 0.2,
'symptoms': 0.1
}
# Calculate weighted risk score
risk_score = (
genetic_score * weights['genetic'] +
(1 - lifestyle_score) * weights['lifestyle'] + # Invert lifestyle score
age_normalized * weights['age'] +
(symptom_severity / 10) * weights['symptoms'] # Normalize to 0-1
)
return round(risk_score, 2)
except Exception as e:
print(f"Error in risk calculation: {str(e)}")
return 0.5 # Return middle value if error occurs
def get_treatment_recommendation(self, risk_score, current_medication, symptom_severity):
"""Generate treatment recommendations based on risk score and symptoms"""
try:
base_recommendations = []
# Risk-based recommendations
if risk_score < 0.3:
base_recommendations.append("Low risk profile - Continue monitoring")
elif risk_score < 0.6:
base_recommendations.append("Moderate risk - Regular check-ups recommended")
else:
base_recommendations.append("High risk - Intensive monitoring required")
# Symptom-based recommendations
if symptom_severity <= 3:
base_recommendations.append("Mild symptoms - Maintain current treatment")
elif symptom_severity <= 7:
base_recommendations.append("Moderate symptoms - Consider treatment adjustment")
else:
base_recommendations.append("Severe symptoms - Immediate medical review required")
# Medication-based recommendations
if current_medication.lower().strip() in ['none', 'no', '']:
if risk_score > 0.5:
base_recommendations.append("Consider initiating preventive treatment")
else:
base_recommendations.append("Review current medications at next appointment")
return base_recommendations
except Exception as e:
print(f"Error in treatment recommendation: {str(e)}")
return ["Unable to generate recommendations due to error"]
def generate_report(self, patient_data):
"""Generate patient report"""
try:
# Calculate risk score
risk_score = self.calculate_risk_score(
patient_data['genetic_score'],
patient_data['lifestyle_score'],
patient_data['age'],
patient_data['symptom_severity']
)
# Get treatment recommendations
recommendations = self.get_treatment_recommendation(
risk_score,
patient_data['current_medication'],
patient_data['symptom_severity']
)
# Create report
report = {
"Patient Information": {
"Age": patient_data['age'],
"Gender": patient_data['gender'],
"Current Medications": patient_data['current_medication']
},
"Risk Assessment": {
"Overall Risk Score": risk_score,
"Risk Category": "High" if risk_score > 0.6 else "Moderate" if risk_score > 0.3 else "Low",
"Genetic Risk": patient_data['genetic_score'],
"Lifestyle Score": patient_data['lifestyle_score']
},
"Current Status": {
"Symptom Severity": f"{patient_data['symptom_severity']}/10",
},
"Recommendations": recommendations,
"Next Steps": {
"Follow-up": "Within 1 week" if risk_score > 0.6 else "Within 1 month" if risk_score > 0.3 else "Within 3 months",
"Monitoring": "Daily" if patient_data['symptom_severity'] > 7 else "Weekly" if patient_data['symptom_severity'] > 4 else "Monthly"
},
"Report Generated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
return json.dumps(report, indent=2)
except Exception as e:
print(f"Error in report generation: {str(e)}")
return json.dumps({"error": "Failed to generate report", "message": str(e)})
def create_gradio_interface():
"""Create Gradio interface"""
system = SimplePrecisionMedicineSystem()
def process_patient(age, gender, genetic_score, lifestyle_score, current_medication, symptom_severity):
try:
# Create patient data dictionary
patient_data = {
'age': age,
'gender': gender,
'genetic_score': genetic_score,
'lifestyle_score': lifestyle_score,
'current_medication': current_medication,
'symptom_severity': symptom_severity
}
# Generate report
return system.generate_report(patient_data)
except Exception as e:
return json.dumps({
"error": "An error occurred while processing the patient data",
"details": str(e)
}, indent=2)
# Create interface
iface = gr.Interface(
fn=process_patient,
inputs=[
gr.Number(label="Age", minimum=0, maximum=120),
gr.Dropdown(choices=["Male", "Female", "Other"], label="Gender"),
gr.Slider(minimum=0, maximum=1, step=0.1, label="Genetic Risk Score (0-1)"),
gr.Slider(minimum=0, maximum=1, step=0.1, label="Lifestyle Score (0-1)"),
gr.Textbox(label="Current Medications (comma-separated or 'None')"),
gr.Slider(minimum=0, maximum=10, step=1, label="Symptom Severity (0-10)")
],
outputs=gr.JSON(label="Medical Report"),
title="Precision Medicine System",
description="Enter patient information to generate personalized medical recommendations",
examples=[
[45, "Female", 0.6, 0.7, "Metformin 500mg, Lisinopril 10mg", 4],
[72, "Male", 0.8, 0.4, "Warfarin 5mg, Atorvastatin 40mg", 7],
[28, "Other", 0.2, 0.9, "None", 2]
]
)
return iface
# Launch the interface
if __name__ == "__main__":
interface = create_gradio_interface()
interface.launch() |