import numpy as np import pandas as pd import gradio as gr import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import seaborn as sns class ComprehensiveHealthModel: def __init__(self): self.model = None self.scaler = None self.feature_names = [ 'Mindset', 'Exercise', 'Diet', 'Environment', 'Rest', 'Extra Health Factors' ] def generate_synthetic_data(self, num_samples=5000): """Generate more sophisticated synthetic health data""" np.random.seed(42) # More nuanced data generation features = np.zeros((num_samples, 6)) # Mindset: Correlated with stress and mental health features[:, 0] = np.random.beta(5, 2, num_samples) # Exercise: Normal distribution of activity levels features[:, 1] = np.clip(np.random.normal(0.5, 0.2, num_samples), 0, 1) # Diet: Skewed towards healthier choices features[:, 2] = np.random.gamma(7, 0.15, num_samples) features[:, 2] = np.clip(features[:, 2] / features[:, 2].max(), 0, 1) # Environment: More uniform but with some bias features[:, 3] = np.random.uniform(0.3, 1, num_samples) # Rest: Correlated with lifestyle factors features[:, 4] = np.clip(np.random.normal(0.6, 0.2, num_samples), 0, 1) # Extra Health Factors: Complex interactions features[:, 5] = (features[:, 0] * 0.3 + features[:, 1] * 0.2 + features[:, 2] * 0.2 + np.random.uniform(0, 0.3, num_samples)) features[:, 5] = np.clip(features[:, 5], 0, 1) # Compute health score with weighted factors weights = [0.2, 0.2, 0.2, 0.1, 0.2, 0.1] health_score = np.sum(features * weights, axis=1) health_score = np.clip(health_score, 0, 1) return features, health_score def create_ml_model(self, input_size=6): """Create a more sophisticated neural network""" class AdvancedHealthPredictor(nn.Module): def __init__(self, input_size): super().__init__() self.network = nn.Sequential( nn.Linear(input_size, 128), nn.BatchNorm1d(128), nn.ReLU(), nn.Dropout(0.4), nn.Linear(128, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Dropout(0.3), nn.Linear(64, 32), nn.BatchNorm1d(32), nn.ReLU(), nn.Linear(32, 1), nn.Sigmoid() ) def forward(self, x): return self.network(x) return AdvancedHealthPredictor(input_size) def train_model(self): """Comprehensive model training pipeline""" # Generate data X, y = self.generate_synthetic_data() # Split and scale X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) self.scaler = StandardScaler() X_train_scaled = self.scaler.fit_transform(X_train) X_test_scaled = self.scaler.transform(X_test) # Prepare datasets train_dataset = torch.utils.data.TensorDataset( torch.FloatTensor(X_train_scaled), torch.FloatTensor(y_train).unsqueeze(1) ) test_dataset = torch.utils.data.TensorDataset( torch.FloatTensor(X_test_scaled), torch.FloatTensor(y_test).unsqueeze(1) ) train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=64) # Initialize model self.model = self.create_ml_model() # Loss and optimizer criterion = nn.MSELoss() optimizer = torch.optim.Adam(self.model.parameters(), lr=0.001, weight_decay=1e-5) # Training loop with early stopping best_loss = float('inf') patience = 5 patience_counter = 0 for epoch in range(100): self.model.train() total_train_loss = 0 for batch_features, batch_labels in train_loader: optimizer.zero_grad() outputs = self.model(batch_features) loss = criterion(outputs, batch_labels) loss.backward() optimizer.step() total_train_loss += loss.item() # Validation self.model.eval() total_val_loss = 0 with torch.no_grad(): for batch_features, batch_labels in test_loader: val_outputs = self.model(batch_features) val_loss = criterion(val_outputs, batch_labels) total_val_loss += val_loss.item() avg_val_loss = total_val_loss / len(test_loader) # Early stopping if avg_val_loss < best_loss: best_loss = avg_val_loss patience_counter = 0 else: patience_counter += 1 if patience_counter >= patience: print(f"Early stopping at epoch {epoch}") break return self.model def predict_health_score(self, input_features): """Predict health score with detailed analysis""" # Ensure model is trained if self.model is None: self.train_model() # Prepare input input_scaled = self.scaler.transform( np.array(input_features).reshape(1, -1) ) # Predict with torch.no_grad(): self.model.eval() prediction = self.model(torch.FloatTensor(input_scaled)).numpy()[0][0] # Detailed analysis analysis = self.generate_detailed_analysis( input_features, prediction ) return prediction, analysis def generate_detailed_analysis(self, input_features, health_score): """Generate comprehensive health analysis""" analysis = { 'overall_score': health_score, 'category': self._categorize_health_score(health_score), 'factor_breakdown': {}, 'recommendations': [] } # Analyze each factor for i, (name, value) in enumerate(zip(self.feature_names, input_features)): factor_analysis = self._analyze_factor(name, value) analysis['factor_breakdown'][name] = factor_analysis # Generate recommendations analysis['recommendations'] = self._generate_recommendations(analysis) return analysis def _categorize_health_score(self, score): """Categorize health score with detailed descriptions""" if score < 0.3: return { 'label': 'Low Health Status', 'description': 'Significant improvements needed across multiple health dimensions' } elif score < 0.6: return { 'label': 'Moderate Health Status', 'description': 'Some positive health practices, room for targeted improvements' } else: return { 'label': 'Optimal Health Status', 'description': 'Strong health practices with potential for fine-tuning' } def _analyze_factor(self, factor_name, value): """Provide nuanced analysis for each health factor""" analysis_templates = { 'Mindset': { 'low': 'High stress levels, potential mental health challenges', 'medium': 'Moderate mental resilience, some stress management skills', 'high': 'Strong mental well-being, effective stress coping mechanisms' }, 'Exercise': { 'low': 'Insufficient physical activity, sedentary lifestyle risks', 'medium': 'Moderate activity level, potential for improvement', 'high': 'Consistent and balanced physical activity' }, 'Diet': { 'low': 'Nutritional gaps, potential for dietary improvements', 'medium': 'Balanced diet with some areas for optimization', 'high': 'Nutritionally rich diet supporting overall health' }, 'Environment': { 'low': 'Potential environmental health challenges', 'medium': 'Moderate environmental health conditions', 'high': 'Supportive and health-promoting environment' }, 'Rest': { 'low': 'Significant sleep and recovery challenges', 'medium': 'Moderate sleep quality, some disruptions', 'high': 'Excellent sleep patterns and recovery' }, 'Extra Health Factors': { 'low': 'Additional health factors may require attention', 'medium': 'Some supplementary health considerations', 'high': 'Strong additional health supporting factors' } } # Categorize value if value < 0.3: status = 'low' elif value < 0.7: status = 'medium' else: status = 'high' return { 'value': value, 'status': status, 'description': analysis_templates[factor_name][status] } def _generate_recommendations(self, analysis): """Generate personalized health recommendations""" recommendations = [] # Overall health recommendations if analysis['overall_score'] < 0.4: recommendations.append("Comprehensive health intervention recommended") # Factor-specific recommendations for factor, details in analysis['factor_breakdown'].items(): if details['status'] == 'low': recommendations.append(f"Focus on improving {factor.lower()} through targeted strategies") # Additional contextual recommendations if analysis['overall_score'] > 0.7: recommendations.append("Continue maintaining your excellent health practices") return recommendations def create_gradio_interface(): """Create a professional, comprehensive Gradio interface""" health_model = ComprehensiveHealthModel() health_model.train_model() # Pre-train model def predict_and_analyze(mindset, exercise, diet, environment, rest, extra): input_features = [mindset, exercise, diet, environment, rest, extra] # Predict health score health_score, analysis = health_model.predict_health_score(input_features) # Format output output_text = f"Overall Health Score: {health_score:.2f}\n\n" output_text += f"Health Category: {analysis['category']['label']}\n" output_text += f"Description: {analysis['category']['description']}\n\n" # Factor Breakdown output_text += "Factor Breakdown:\n" for factor, details in analysis['factor_breakdown'].items(): output_text += f"{factor}: {details['value']:.2f} - {details['description']}\n" output_text += "\nRecommendations:\n" for rec in analysis['recommendations']: output_text += f"• {rec}\n" return output_text # Gradio Interface with enhanced styling iface = gr.Interface( fn=predict_and_analyze, inputs=[ gr.Slider(0, 1, value=0.5, label="Mindset (Mental Health)", step=0.01), gr.Slider(0, 1, value=0.5, label="Exercise Level", step=0.01), gr.Slider(0, 1, value=0.5, label="Diet Quality", step=0.01), gr.Slider(0, 1, value=0.5, label="Environment", step=0.01), gr.Slider(0, 1, value=0.5, label="Rest/Sleep Quality", step=0.01), gr.Slider(0, 1, value=0.5, label="Extra Health Factors", step=0.01) ], outputs=gr.Textbox(label="Comprehensive Health Analysis"), title="🌟 MEDERX Advanced Health Management System", description="A holistic AI-powered health assessment tool", theme='huggingface', css=""" .gradio-container { background-color: #f0f4f8; font-family: 'Inter', sans-serif; } .output-header { color: #2c3e50; font-weight: bold; } """ ) return iface # Launch the interface if __name__ == '__main__': interface = create_gradio_interface() interface.launch(debug=True)