import gradio as gr from transformers import AutoTokenizer, AutoModelForSequenceClassification import torch import re import random import logging from typing import Dict, List, Tuple, Optional import numpy as np # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class HealthAnalysisNLG: def __init__(self): """Initialize the health analysis system with improved error handling and model loading""" self.model = None self.tokenizer = None self._load_model() # Enhanced response templates with more variety self.response_templates = { 'bmi_assessment': { 'optimal': [ "Your BMI appears to be in a healthy range, which is excellent for your overall health.", "Based on your height and weight, you're maintaining a healthy BMI that supports good metabolic function.", "Your body mass index is within the optimal range, indicating good weight management.", "Your current BMI suggests you're maintaining a healthy weight-to-height ratio." ], 'suboptimal': [ "Your BMI suggests there may be room for improvement in weight management.", "Your current BMI indicates you might benefit from modest lifestyle adjustments.", "Based on your measurements, focusing on healthy weight management could be beneficial.", "Your BMI is slightly outside the optimal range, but manageable with lifestyle changes." ], 'concerning': [ "Your BMI indicates significant health risks that should be addressed promptly.", "Your current BMI suggests urgent lifestyle changes may be needed for optimal health.", "Based on your measurements, consulting with a healthcare provider is strongly recommended.", "Your BMI falls into a range associated with increased health risks requiring attention." ] }, 'gut_health': { 'good': [ "Your dietary patterns suggest good intestinal health support.", "Based on your nutrition intake, your gut microbiome appears well-supported.", "Your current diet shows positive indicators for digestive wellness and gut barrier function.", "Your eating patterns indicate healthy gut bacteria diversity support." ], 'moderate': [ "Your gut health indicators show mixed results with room for improvement.", "Your digestive health could benefit from targeted dietary adjustments.", "There are opportunities to enhance your intestinal health through nutrition optimization.", "Your gut health profile suggests moderate support with potential for enhancement." ], 'poor': [ "Your dietary patterns suggest significant concerns for gut health and microbiome balance.", "Your current nutrition may be negatively impacting digestive wellness and gut integrity.", "Immediate attention to gut health through comprehensive dietary changes is recommended.", "Your eating patterns indicate substantial risk to gut microbiome health." ] }, 'diet_balance': { 'excellent': [ "Your dietary balance shows excellent nutritional variety and micronutrient density.", "You're maintaining an outstanding balance of macronutrients and essential vitamins.", "Your eating patterns reflect excellent nutritional awareness and food quality choices.", "Your diet demonstrates superior balance across all major food groups and nutrients." ], 'good': [ "Your diet shows good balance with minor opportunities for nutritional enhancement.", "You're doing well with nutritional balance, with some areas to optimize for peak health.", "Your dietary patterns are generally healthy with room for fine-tuning certain nutrients.", "Your eating habits demonstrate good awareness with potential for strategic improvements." ], 'needs_improvement': [ "Your dietary balance could significantly benefit from comprehensive nutritional adjustments.", "There are important nutritional gaps that should be addressed for optimal health outcomes.", "Your current eating patterns may not be supporting your body's full nutritional needs.", "Substantial improvements in dietary balance could dramatically enhance your health profile." ] } } # Enhanced risk indicators with more comprehensive keywords self.risk_indicators = { 'high_risk': [ 'diabetes', 'hypertension', 'obesity', 'smoking', 'high cholesterol', 'heart disease', 'stroke', 'cancer', 'kidney disease', 'liver disease', 'metabolic syndrome', 'sleep apnea', 'chronic pain', 'depression' ], 'moderate_risk': [ 'overweight', 'sedentary', 'stress', 'poor sleep', 'processed food', 'irregular meals', 'alcohol consumption', 'caffeine dependency', 'low fiber', 'high sodium', 'sugar addiction', 'inflammation' ], 'protective': [ 'exercise', 'vegetables', 'fruits', 'supplements', 'meditation', 'good sleep', 'hydration', 'omega-3', 'probiotics', 'fiber', 'antioxidants', 'yoga', 'walking', 'strength training' ] } # BMI calculation and categories self.bmi_categories = { 'underweight': (0, 18.5), 'normal': (18.5, 25), 'overweight': (25, 30), 'obese': (30, float('inf')) } def _load_model(self): """Load the model with proper error handling and fallback options""" try: # Try to load custom health analysis model logger.info("Attempting to load custom health analysis model...") self.tokenizer = AutoTokenizer.from_pretrained("Fahim18/health-analysis-biobert") self.model = AutoModelForSequenceClassification.from_pretrained("Fahim18/health-analysis-biobert") logger.info("Successfully loaded custom health analysis model") except Exception as e: logger.warning(f"Failed to load custom model: {e}") try: # Fallback to base BioBERT logger.info("Loading base BioBERT model as fallback...") self.tokenizer = AutoTokenizer.from_pretrained("dmis-lab/biobert-v1.1") self.model = AutoModelForSequenceClassification.from_pretrained("dmis-lab/biobert-v1.1") logger.info("Successfully loaded base BioBERT model") except Exception as e2: logger.error(f"Failed to load any model: {e2}") raise RuntimeError("Unable to load any suitable model for health analysis") def calculate_bmi(self, height_cm: float, weight_kg: float) -> Tuple[float, str]: """Calculate BMI and return category""" if height_cm <= 0 or weight_kg <= 0: return None, "invalid" bmi = weight_kg / ((height_cm / 100) ** 2) for category, (min_val, max_val) in self.bmi_categories.items(): if min_val <= bmi < max_val: return round(bmi, 1), category return round(bmi, 1), "unknown" def extract_health_info(self, text: str) -> Dict: """Enhanced health information extraction with better pattern matching""" text_lower = text.lower() health_info = { 'age': None, 'height_cm': None, 'weight_kg': None, 'bmi': None, 'bmi_category': None, 'gender': None, 'medical_conditions': [], 'medications': [], 'diet_quality_indicators': [], 'lifestyle_factors': [], 'supplements': [], 'risk_score': 0 } # Extract age with multiple patterns age_patterns = [ r'(\d+)\s*(?:years?\s*old|year|yr|y\.o\.)', r'age:?\s*(\d+)', r'(\d+)\s*yr', r'i\s*am\s*(\d+)' ] for pattern in age_patterns: age_match = re.search(pattern, text_lower) if age_match: health_info['age'] = int(age_match.group(1)) break # Extract height (multiple units and formats) height_patterns = [ r'(\d+(?:\.\d+)?)\s*cm', r'(\d+)\s*feet?\s*(\d+)\s*inch', r'(\d+)\'(\d+)\"', r'height:?\s*(\d+(?:\.\d+)?)\s*cm' ] for pattern in height_patterns: height_match = re.search(pattern, text_lower) if height_match: if 'feet' in pattern or '\'' in pattern: # Convert feet/inches to cm feet = int(height_match.group(1)) inches = int(height_match.group(2)) if height_match.group(2) else 0 health_info['height_cm'] = round((feet * 12 + inches) * 2.54, 1) else: health_info['height_cm'] = float(height_match.group(1)) break # Extract weight (multiple units) weight_patterns = [ r'(\d+(?:\.\d+)?)\s*kg', r'(\d+(?:\.\d+)?)\s*pound|lbs?', r'weight:?\s*(\d+(?:\.\d+)?)\s*kg' ] for pattern in weight_patterns: weight_match = re.search(pattern, text_lower) if weight_match: weight = float(weight_match.group(1)) if 'pound' in pattern or 'lb' in pattern: # Convert pounds to kg health_info['weight_kg'] = round(weight * 0.453592, 1) else: health_info['weight_kg'] = weight break # Calculate BMI if height and weight are available if health_info['height_cm'] and health_info['weight_kg']: bmi, category = self.calculate_bmi(health_info['height_cm'], health_info['weight_kg']) health_info['bmi'] = bmi health_info['bmi_category'] = category # Extract gender gender_patterns = [ r'\b(male|female|man|woman)\b', r'gender:?\s*(male|female|m|f)\b' ] for pattern in gender_patterns: gender_match = re.search(pattern, text_lower) if gender_match: gender = gender_match.group(1) health_info['gender'] = 'male' if gender in ['male', 'man', 'm'] else 'female' break # Extract medical conditions, medications, supplements self._extract_medical_info(text_lower, health_info) # Calculate risk score health_info['risk_score'] = self._calculate_risk_score(health_info, text_lower) return health_info def _extract_medical_info(self, text_lower: str, health_info: Dict): """Extract medical conditions, medications, and supplements""" # Medical conditions medical_conditions = [ 'diabetes', 'hypertension', 'high blood pressure', 'heart disease', 'obesity', 'depression', 'anxiety', 'arthritis', 'asthma', 'high cholesterol', 'kidney disease', 'liver disease' ] for condition in medical_conditions: if condition in text_lower: health_info['medical_conditions'].append(condition) # Common medications medications = [ 'lisinopril', 'metformin', 'atorvastatin', 'amlodipine', 'losartan', 'hydrochlorothiazide', 'simvastatin', 'omeprazole' ] for med in medications: if med in text_lower: health_info['medications'].append(med) # Supplements supplements = [ 'vitamin d', 'vitamin b12', 'vitamin c', 'magnesium', 'probiotics', 'omega-3', 'fish oil', 'multivitamin', 'calcium', 'iron', 'zinc', 'biotin' ] for supplement in supplements: if supplement in text_lower: health_info['supplements'].append(supplement) def _calculate_risk_score(self, health_info: Dict, text_lower: str) -> int: """Calculate a composite risk score based on extracted information""" score = 0 # Age factor if health_info['age']: if health_info['age'] > 65: score += 3 elif health_info['age'] > 50: score += 2 elif health_info['age'] > 30: score += 1 # BMI factor if health_info['bmi_category']: if health_info['bmi_category'] in ['obese']: score += 4 elif health_info['bmi_category'] in ['overweight']: score += 2 elif health_info['bmi_category'] in ['underweight']: score += 1 # Medical conditions score += len(health_info['medical_conditions']) * 2 # Risk factors from text for risk_factor in self.risk_indicators['high_risk']: if risk_factor in text_lower: score += 2 for risk_factor in self.risk_indicators['moderate_risk']: if risk_factor in text_lower: score += 1 # Protective factors (reduce score) for protective_factor in self.risk_indicators['protective']: if protective_factor in text_lower: score = max(0, score - 1) return min(score, 20) # Cap at 20 def generate_risk_assessment(self, probabilities: torch.Tensor, health_info: Dict) -> List[str]: """Generate detailed risk assessment based on model output and health info""" assessment_parts = [] if len(probabilities) >= 3: bmi_prob = probabilities[0].item() gut_prob = probabilities[1].item() diet_prob = probabilities[2].item() else: # Fallback if model output format is different avg_prob = probabilities.mean().item() bmi_prob = gut_prob = diet_prob = avg_prob # Enhanced BMI assessment incorporating actual BMI if available if health_info['bmi'] and health_info['bmi_category']: if health_info['bmi_category'] == 'normal': bmi_category = 'optimal' elif health_info['bmi_category'] in ['overweight', 'underweight']: bmi_category = 'suboptimal' else: bmi_category = 'concerning' else: # Use model probability if bmi_prob > 0.7: bmi_category = 'optimal' elif bmi_prob > 0.4: bmi_category = 'suboptimal' else: bmi_category = 'concerning' assessment_parts.append(random.choice(self.response_templates['bmi_assessment'][bmi_category])) # Gut Health Assessment if gut_prob > 0.6: gut_category = 'good' elif gut_prob > 0.3: gut_category = 'moderate' else: gut_category = 'poor' assessment_parts.append(random.choice(self.response_templates['gut_health'][gut_category])) # Diet Balance Assessment if diet_prob > 0.7: diet_category = 'excellent' elif diet_prob > 0.4: diet_category = 'good' else: diet_category = 'needs_improvement' assessment_parts.append(random.choice(self.response_templates['diet_balance'][diet_category])) return assessment_parts def generate_personalized_recommendations(self, health_info: Dict, probabilities: torch.Tensor) -> List[str]: """Generate comprehensive personalized recommendations""" recommendations = [] # Age-based recommendations if health_info['age']: if health_info['age'] > 65: recommendations.extend([ "Regular comprehensive health screenings are crucial at your age.", "Consider bone density testing and fall prevention strategies.", "Prioritize balance and flexibility exercises alongside cardiovascular fitness." ]) elif health_info['age'] > 50: recommendations.extend([ "Annual health screenings become increasingly important.", "Focus on maintaining muscle mass through resistance training." ]) elif health_info['age'] > 30: recommendations.append("This is an excellent time to establish healthy habits for long-term wellness.") # BMI-specific recommendations if health_info['bmi_category']: if health_info['bmi_category'] == 'obese': recommendations.extend([ "Consider working with a healthcare provider on a comprehensive weight management plan.", "Focus on sustainable lifestyle changes rather than rapid weight loss." ]) elif health_info['bmi_category'] == 'overweight': recommendations.append("Small, consistent changes in diet and exercise can help achieve a healthier weight.") elif health_info['bmi_category'] == 'underweight': recommendations.append("Consider consulting a nutritionist to safely increase muscle mass and overall weight.") # Medical condition-specific recommendations if 'diabetes' in health_info['medical_conditions']: recommendations.extend([ "Regular blood glucose monitoring and A1C testing are essential.", "Focus on complex carbohydrates and consistent meal timing." ]) if 'hypertension' in health_info['medical_conditions']: recommendations.extend([ "Monitor blood pressure regularly and follow DASH diet principles.", "Limit sodium intake and prioritize potassium-rich foods." ]) # Risk score-based recommendations if health_info['risk_score'] > 10: recommendations.append("Given multiple risk factors, working closely with healthcare providers is essential.") elif health_info['risk_score'] > 5: recommendations.append("Addressing current risk factors can significantly improve your long-term health outlook.") # Diet and lifestyle recommendations if len(probabilities) > 2 and probabilities[2].item() < 0.5: recommendations.extend([ "Increase intake of colorful vegetables and fruits to at least 5 servings daily.", "Reduce processed foods and added sugars for better metabolic health.", "Consider meal planning to ensure consistent nutrition quality." ]) if len(probabilities) > 1 and probabilities[1].item() < 0.4: recommendations.extend([ "Support gut health with prebiotic and probiotic foods.", "Increase fiber intake gradually to improve digestive wellness." ]) # Supplement recommendations if not health_info['supplements']: recommendations.append("Consider discussing basic supplementation (Vitamin D, B12) with your healthcare provider.") return recommendations[:8] # Limit to most important recommendations def generate_overall_risk_summary(self, probabilities: torch.Tensor, health_info: Dict) -> str: """Generate comprehensive overall risk summary""" if not probabilities.numel(): return "Unable to assess risk based on provided information." # Use risk score if available, otherwise use model probabilities if health_info['risk_score']: risk_score = health_info['risk_score'] if risk_score <= 3: risk_level = "low" summary = "Your overall health profile suggests you're managing well with low risk factors. Continue maintaining your current healthy practices while staying vigilant about preventive care." elif risk_score <= 8: risk_level = "moderate" summary = "Your health profile shows both strengths and areas for improvement. With targeted lifestyle modifications, you can significantly enhance your wellness and reduce future health risks." else: risk_level = "elevated" summary = "Your health indicators suggest several areas requiring immediate attention. Consider developing a comprehensive wellness plan with healthcare professionals to address multiple risk factors." else: # Fallback to model probabilities avg_score = probabilities.mean().item() if avg_score > 0.7: risk_level = "low" summary = "Your overall health indicators suggest you're on a positive trajectory. Continue maintaining your current healthy practices." elif avg_score > 0.4: risk_level = "moderate" summary = "Your health profile shows both strengths and areas for improvement. With some targeted changes, you can significantly enhance your wellness." else: risk_level = "elevated" summary = "Your health indicators suggest several areas that need attention. Consider consulting with healthcare professionals for a comprehensive wellness plan." return f"**Overall Risk Level: {risk_level.upper()}**\n\n{summary}" def process_outputs(self, outputs, text_input: str) -> str: """Enhanced output processing with comprehensive analysis""" try: logits = outputs.logits probabilities = torch.softmax(logits, dim=-1) # Extract detailed health information health_info = self.extract_health_info(text_input) # Generate assessment components risk_assessments = self.generate_risk_assessment(probabilities[0], health_info) recommendations = self.generate_personalized_recommendations(health_info, probabilities[0]) overall_summary = self.generate_overall_risk_summary(probabilities[0], health_info) # Construct comprehensive response response_parts = [ "# 🏥 Comprehensive Health Analysis\n", overall_summary, "\n## 📊 Health Profile Summary" ] # Add extracted health information if health_info['age']: response_parts.append(f"**Age:** {health_info['age']} years") if health_info['bmi']: response_parts.append(f"**BMI:** {health_info['bmi']} ({health_info['bmi_category'].title()})") if health_info['medical_conditions']: response_parts.append(f"**Medical Conditions:** {', '.join(health_info['medical_conditions']).title()}") if health_info['medications']: response_parts.append(f"**Medications:** {', '.join(health_info['medications']).title()}") response_parts.append("\n## 🔍 Detailed Health Assessment") for i, assessment in enumerate(risk_assessments, 1): response_parts.append(f"**{i}.** {assessment}") if recommendations: response_parts.append("\n## 💡 Personalized Recommendations") for i, rec in enumerate(recommendations, 1): response_parts.append(f"**{i}.** {rec}") # Technical scores response_parts.append("\n## 📈 Health Scores") if len(probabilities[0]) >= 3: response_parts.extend([ f"- **BMI Health Score:** {probabilities[0][0].item()*100:.1f}%", f"- **Gut Health Score:** {probabilities[0][1].item()*100:.1f}%", f"- **Diet Balance Score:** {probabilities[0][2].item()*100:.1f}%" ]) if health_info['risk_score']: response_parts.append(f"- **Overall Risk Score:** {health_info['risk_score']}/20") response_parts.extend([ "\n---", "⚠️ **Important Disclaimer:** This analysis is for informational purposes only and should not replace professional medical advice. Always consult with qualified healthcare providers for medical decisions." ]) return "\n".join(response_parts) except Exception as e: logger.error(f"Error in process_outputs: {e}") return f"An error occurred during analysis: {str(e)}\nPlease check your input and try again." def create_health_analyzer(): """Factory function to create health analyzer with error handling""" try: return HealthAnalysisNLG() except Exception as e: logger.error(f"Failed to initialize health analyzer: {e}") return None # Initialize the health analysis system health_analyzer = create_health_analyzer() def predict(text_input: str) -> str: """Main prediction function with enhanced error handling""" if not text_input or not text_input.strip(): return "Please provide your health information for analysis. Include details like age, height, weight, medical conditions, diet, exercise habits, etc." if not health_analyzer or not health_analyzer.model: return "❌ **System Error:** Health analysis model is not available. Please try again later." try: # Tokenize and predict with proper error handling inputs = health_analyzer.tokenizer( text_input, return_tensors="pt", padding=True, truncation=True, max_length=512 ) with torch.no_grad(): outputs = health_analyzer.model(**inputs) # Generate comprehensive response return health_analyzer.process_outputs(outputs, text_input) except Exception as e: logger.error(f"Prediction error: {e}") return f"❌ **Analysis Error:** {str(e)}\n\nPlease check your input format and try again. Ensure you include relevant health information like age, medical conditions, lifestyle factors, etc." def create_interface(): """Create an enhanced Gradio interface with better styling and examples""" enhanced_examples = [ [ "I am a 32-year-old male, 175cm tall, weighing 72kg. I have hypertension and high cholesterol. " "I take Lisinopril daily. My diet includes 2 servings of fruits and 3 servings of vegetables daily, " "with 1 serving of red meat per week and about 20g of sugar daily. I exercise 4 hours weekly, " "sleep 7 hours nightly, and have moderate stress levels. I take probiotics, Vitamin D, B12, and Magnesium supplements." ], [ "45-year-old female, 165cm, 78kg, diabetes type 2, taking metformin. Sedentary job, high stress, " "poor diet with lots of processed foods, irregular meals. Sleep 5-6 hours nightly. No supplements." ], [ "28-year-old female athlete, 170cm, 60kg, excellent physical condition, trains 6 days per week. " "Balanced Mediterranean diet, 8 hours sleep, low stress. Takes multivitamins and protein supplements." ], [ "67-year-old male, 180cm, 85kg, heart disease, arthritis, taking atorvastatin and ibuprofen. " "Limited mobility, walks 30 minutes daily. Diet includes fish twice weekly, vegetables daily, some processed foods." ] ] interface = gr.Interface( fn=predict, inputs=gr.Textbox( label="🩺 Enter Your Comprehensive Health Information", placeholder="Provide detailed information including: age, height, weight, gender, medical conditions, medications, diet details, exercise habits, sleep patterns, stress levels, supplements, etc. The more detailed your input, the more accurate and personalized your analysis will be.", lines=6, max_lines=10 ), outputs=gr.Textbox( label="📋 Comprehensive Health Analysis & Personalized Recommendations", lines=20, max_lines=30 ), title="🏥 AI-Powered Comprehensive Health Risk Assessment", description=""" **Welcome to your personalized health analysis system!** This advanced AI tool analyzes your health information using BioBERT (a specialized medical AI model) to provide: - ✅ Comprehensive health risk assessment - 📊 BMI analysis and categorization - 🦠 Gut health evaluation - 🥗 Dietary balance assessment - 💡 Personalized health recommendations - 📈 Detailed health scores and metrics **For best results, include:** demographics, medical history, current medications, detailed diet information, exercise habits, sleep patterns, stress levels, and any supplements you take. """, examples=enhanced_examples, theme=gr.themes.Soft(), css=""" .gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .gr-button-primary { background: linear-gradient(45deg, #2196F3, #21CBF3); border: none; } .gr-box { border-radius: 10px; } """, allow_flagging="never" ) return interface # Main execution if __name__ == "__main__": if health_analyzer: interface = create_interface() interface.launch( share=True, server_name="0.0.0.0", server_port=7860, show_error=True ) else: logger.error("Failed to initialize health analyzer. Cannot start interface.") print("❌ Failed to initialize the health analysis system. Please check the logs for details.")