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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# First, install required packages
|
| 2 |
+
#!pip install gradio pandas numpy scikit-learn
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.preprocessing import StandardScaler
|
| 8 |
+
import json
|
| 9 |
+
from datetime import datetime, timedelta
|
| 10 |
+
|
| 11 |
+
class SimplePrecisionMedicineSystem:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.scaler = StandardScaler()
|
| 14 |
+
|
| 15 |
+
def calculate_risk_score(self, genetic_score, lifestyle_score, age, symptom_severity):
|
| 16 |
+
"""Calculate overall risk score"""
|
| 17 |
+
try:
|
| 18 |
+
# Normalize age to 0-1 range (assuming max age of 100)
|
| 19 |
+
age_normalized = age / 100.0
|
| 20 |
+
|
| 21 |
+
# Weight factors (can be adjusted)
|
| 22 |
+
weights = {
|
| 23 |
+
'genetic': 0.4,
|
| 24 |
+
'lifestyle': 0.3,
|
| 25 |
+
'age': 0.2,
|
| 26 |
+
'symptoms': 0.1
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
# Calculate weighted risk score
|
| 30 |
+
risk_score = (
|
| 31 |
+
genetic_score * weights['genetic'] +
|
| 32 |
+
(1 - lifestyle_score) * weights['lifestyle'] + # Invert lifestyle score
|
| 33 |
+
age_normalized * weights['age'] +
|
| 34 |
+
(symptom_severity / 10) * weights['symptoms'] # Normalize to 0-1
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
return round(risk_score, 2)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"Error in risk calculation: {str(e)}")
|
| 40 |
+
return 0.5 # Return middle value if error occurs
|
| 41 |
+
|
| 42 |
+
def get_treatment_recommendation(self, risk_score, current_medication, symptom_severity):
|
| 43 |
+
"""Generate treatment recommendations based on risk score and symptoms"""
|
| 44 |
+
try:
|
| 45 |
+
base_recommendations = []
|
| 46 |
+
|
| 47 |
+
# Risk-based recommendations
|
| 48 |
+
if risk_score < 0.3:
|
| 49 |
+
base_recommendations.append("Low risk profile - Continue monitoring")
|
| 50 |
+
elif risk_score < 0.6:
|
| 51 |
+
base_recommendations.append("Moderate risk - Regular check-ups recommended")
|
| 52 |
+
else:
|
| 53 |
+
base_recommendations.append("High risk - Intensive monitoring required")
|
| 54 |
+
|
| 55 |
+
# Symptom-based recommendations
|
| 56 |
+
if symptom_severity <= 3:
|
| 57 |
+
base_recommendations.append("Mild symptoms - Maintain current treatment")
|
| 58 |
+
elif symptom_severity <= 7:
|
| 59 |
+
base_recommendations.append("Moderate symptoms - Consider treatment adjustment")
|
| 60 |
+
else:
|
| 61 |
+
base_recommendations.append("Severe symptoms - Immediate medical review required")
|
| 62 |
+
|
| 63 |
+
# Medication-based recommendations
|
| 64 |
+
if current_medication.lower().strip() in ['none', 'no', '']:
|
| 65 |
+
if risk_score > 0.5:
|
| 66 |
+
base_recommendations.append("Consider initiating preventive treatment")
|
| 67 |
+
else:
|
| 68 |
+
base_recommendations.append("Review current medications at next appointment")
|
| 69 |
+
|
| 70 |
+
return base_recommendations
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"Error in treatment recommendation: {str(e)}")
|
| 73 |
+
return ["Unable to generate recommendations due to error"]
|
| 74 |
+
|
| 75 |
+
def generate_report(self, patient_data):
|
| 76 |
+
"""Generate patient report"""
|
| 77 |
+
try:
|
| 78 |
+
# Calculate risk score
|
| 79 |
+
risk_score = self.calculate_risk_score(
|
| 80 |
+
patient_data['genetic_score'],
|
| 81 |
+
patient_data['lifestyle_score'],
|
| 82 |
+
patient_data['age'],
|
| 83 |
+
patient_data['symptom_severity']
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Get treatment recommendations
|
| 87 |
+
recommendations = self.get_treatment_recommendation(
|
| 88 |
+
risk_score,
|
| 89 |
+
patient_data['current_medication'],
|
| 90 |
+
patient_data['symptom_severity']
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# Create report
|
| 94 |
+
report = {
|
| 95 |
+
"Patient Information": {
|
| 96 |
+
"Age": patient_data['age'],
|
| 97 |
+
"Gender": patient_data['gender'],
|
| 98 |
+
"Current Medications": patient_data['current_medication']
|
| 99 |
+
},
|
| 100 |
+
"Risk Assessment": {
|
| 101 |
+
"Overall Risk Score": risk_score,
|
| 102 |
+
"Risk Category": "High" if risk_score > 0.6 else "Moderate" if risk_score > 0.3 else "Low",
|
| 103 |
+
"Genetic Risk": patient_data['genetic_score'],
|
| 104 |
+
"Lifestyle Score": patient_data['lifestyle_score']
|
| 105 |
+
},
|
| 106 |
+
"Current Status": {
|
| 107 |
+
"Symptom Severity": f"{patient_data['symptom_severity']}/10",
|
| 108 |
+
},
|
| 109 |
+
"Recommendations": recommendations,
|
| 110 |
+
"Next Steps": {
|
| 111 |
+
"Follow-up": "Within 1 week" if risk_score > 0.6 else "Within 1 month" if risk_score > 0.3 else "Within 3 months",
|
| 112 |
+
"Monitoring": "Daily" if patient_data['symptom_severity'] > 7 else "Weekly" if patient_data['symptom_severity'] > 4 else "Monthly"
|
| 113 |
+
},
|
| 114 |
+
"Report Generated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
return json.dumps(report, indent=2)
|
| 118 |
+
except Exception as e:
|
| 119 |
+
print(f"Error in report generation: {str(e)}")
|
| 120 |
+
return json.dumps({"error": "Failed to generate report", "message": str(e)})
|
| 121 |
+
|
| 122 |
+
def create_gradio_interface():
|
| 123 |
+
"""Create Gradio interface"""
|
| 124 |
+
system = SimplePrecisionMedicineSystem()
|
| 125 |
+
|
| 126 |
+
def process_patient(age, gender, genetic_score, lifestyle_score, current_medication, symptom_severity):
|
| 127 |
+
try:
|
| 128 |
+
# Create patient data dictionary
|
| 129 |
+
patient_data = {
|
| 130 |
+
'age': age,
|
| 131 |
+
'gender': gender,
|
| 132 |
+
'genetic_score': genetic_score,
|
| 133 |
+
'lifestyle_score': lifestyle_score,
|
| 134 |
+
'current_medication': current_medication,
|
| 135 |
+
'symptom_severity': symptom_severity
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
# Generate report
|
| 139 |
+
return system.generate_report(patient_data)
|
| 140 |
+
|
| 141 |
+
except Exception as e:
|
| 142 |
+
return json.dumps({
|
| 143 |
+
"error": "An error occurred while processing the patient data",
|
| 144 |
+
"details": str(e)
|
| 145 |
+
}, indent=2)
|
| 146 |
+
|
| 147 |
+
# Create interface
|
| 148 |
+
iface = gr.Interface(
|
| 149 |
+
fn=process_patient,
|
| 150 |
+
inputs=[
|
| 151 |
+
gr.Number(label="Age", minimum=0, maximum=120),
|
| 152 |
+
gr.Dropdown(choices=["Male", "Female", "Other"], label="Gender"),
|
| 153 |
+
gr.Slider(minimum=0, maximum=1, step=0.1, label="Genetic Risk Score (0-1)"),
|
| 154 |
+
gr.Slider(minimum=0, maximum=1, step=0.1, label="Lifestyle Score (0-1)"),
|
| 155 |
+
gr.Textbox(label="Current Medications (comma-separated or 'None')"),
|
| 156 |
+
gr.Slider(minimum=0, maximum=10, step=1, label="Symptom Severity (0-10)")
|
| 157 |
+
],
|
| 158 |
+
outputs=gr.JSON(label="Medical Report"),
|
| 159 |
+
title="Precision Medicine System",
|
| 160 |
+
description="Enter patient information to generate personalized medical recommendations",
|
| 161 |
+
examples=[
|
| 162 |
+
[45, "Female", 0.6, 0.7, "Metformin 500mg, Lisinopril 10mg", 4],
|
| 163 |
+
[72, "Male", 0.8, 0.4, "Warfarin 5mg, Atorvastatin 40mg", 7],
|
| 164 |
+
[28, "Other", 0.2, 0.9, "None", 2]
|
| 165 |
+
]
|
| 166 |
+
)
|
| 167 |
+
return iface
|
| 168 |
+
|
| 169 |
+
# Launch the interface
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
interface = create_gradio_interface()
|
| 172 |
+
interface.launch()
|