import numpy as np import pandas as pd import gradio as gr import matplotlib.pyplot as plt import seaborn as sns from typing import Dict, List, Tuple class HealthStandards: """Simplified health standards with error handling""" @staticmethod def get_bmi_status(bmi: float) -> Dict: try: if bmi < 18.5: return {"status": "Underweight", "risk": "High", "recommendation": "Consult nutritionist for weight gain plan"} elif bmi < 24.9: return {"status": "Normal", "risk": "Low", "recommendation": "Maintain healthy lifestyle"} elif bmi < 29.9: return {"status": "Overweight", "risk": "Moderate", "recommendation": "Consider diet and exercise plan"} else: return {"status": "Obese", "risk": "High", "recommendation": "Seek medical guidance"} except Exception as e: return {"status": "Error", "risk": "Unknown", "recommendation": f"Error processing BMI: {str(e)}"} @staticmethod def get_bp_status(bp: float) -> Dict: try: if bp < 120: return {"status": "Normal", "risk": "Low", "recommendation": "Maintain healthy lifestyle"} elif bp < 130: return {"status": "Elevated", "risk": "Moderate", "recommendation": "Monitor regularly"} elif bp < 140: return {"status": "Stage 1 Hypertension", "risk": "High", "recommendation": "Consult healthcare provider"} else: return {"status": "Stage 2 Hypertension", "risk": "Very High", "recommendation": "Immediate medical attention needed"} except Exception as e: return {"status": "Error", "risk": "Unknown", "recommendation": f"Error processing blood pressure: {str(e)}"} @staticmethod def get_glucose_status(glucose: float) -> Dict: try: if glucose < 100: return {"status": "Normal", "risk": "Low", "recommendation": "Maintain healthy diet"} elif glucose < 125: return {"status": "Prediabetes", "risk": "Moderate", "recommendation": "Lifestyle modifications needed"} else: return {"status": "Diabetes Range", "risk": "High", "recommendation": "Consult healthcare provider"} except Exception as e: return {"status": "Error", "risk": "Unknown", "recommendation": f"Error processing glucose: {str(e)}"} class HealthAnalyzer: """Analyzes health metrics with error handling""" def __init__(self): self.standards = HealthStandards() def analyze_metrics(self, age: float, bmi: float, bp: float, glucose: float) -> Tuple[Dict, str]: try: # Get individual assessments bmi_assessment = self.standards.get_bmi_status(bmi) bp_assessment = self.standards.get_bp_status(bp) glucose_assessment = self.standards.get_glucose_status(glucose) # Calculate risk score risk_factors = 0 if bmi_assessment["risk"] in ["High", "Very High"]: risk_factors += 1 if bp_assessment["risk"] in ["High", "Very High"]: risk_factors += 1 if glucose_assessment["risk"] in ["High", "Very High"]: risk_factors += 1 if age > 60: risk_factors += 1 risk_score = (risk_factors / 4) * 100 analysis = { "metrics": { "BMI": bmi_assessment, "Blood Pressure": bp_assessment, "Glucose": glucose_assessment }, "risk_score": risk_score } # Generate report report = self.generate_report(analysis, age) return analysis, report except Exception as e: return {"error": str(e)}, "Error occurred during analysis" def generate_report(self, analysis: Dict, age: float) -> str: try: report = [ "=== HEALTH ANALYSIS REPORT ===\n", f"Overall Risk Score: {analysis['risk_score']:.1f}%\n", f"Risk Level: {self.get_risk_level(analysis['risk_score'])}\n", "\nDetailed Analysis:" ] for metric, assessment in analysis["metrics"].items(): report.extend([ f"\n{metric}:", f"Status: {assessment['status']}", f"Risk Level: {assessment['risk']}", f"Recommendation: {assessment['recommendation']}" ]) return "\n".join(report) except Exception as e: return f"Error generating report: {str(e)}" @staticmethod def get_risk_level(risk_score: float) -> str: if risk_score < 33: return "Low" elif risk_score < 66: return "Moderate" else: return "High" def create_visualization(analysis: Dict) -> plt.Figure: """Create visualization with error handling""" try: sns.set_style("whitegrid") # Use seaborn style directly fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) # Metrics comparison metrics = list(analysis["metrics"].keys()) risk_levels = [assessment["risk"] for assessment in analysis["metrics"].values()] risk_values = [{"Low": 1, "Moderate": 2, "High": 3, "Very High": 4}.get(r, 0) for r in risk_levels] colors = ['green' if r == "Low" else 'yellow' if r == "Moderate" else 'red' for r in risk_levels] ax1.bar(metrics, risk_values, color=colors) ax1.set_title("Health Metrics Risk Levels") ax1.set_ylim(0, 4) ax1.set_yticks([1, 2, 3, 4]) ax1.set_yticklabels(['Low', 'Moderate', 'High', 'Very High']) # Risk gauge risk_score = analysis["risk_score"] colors = ['green', 'yellow', 'red'] ax2.pie([risk_score, 100-risk_score], colors=[colors[int(risk_score/33.34)], 'lightgray'], startangle=90, counterclock=False) ax2.set_title(f"Overall Risk Score: {risk_score:.1f}%") plt.tight_layout() return fig except Exception as e: # Create error figure fig, ax = plt.subplots(figsize=(8, 4)) ax.text(0.5, 0.5, f"Error creating visualization: {str(e)}", ha='center', va='center') ax.axis('off') return fig def analyze_health(age: float, bmi: float, bp: float, glucose: float) -> Tuple[plt.Figure, str]: """Main analysis function with error handling""" try: analyzer = HealthAnalyzer() analysis, report = analyzer.analyze_metrics(age, bmi, bp, glucose) if "error" in analysis: raise Exception(analysis["error"]) fig = create_visualization(analysis) return fig, report except Exception as e: error_fig, ax = plt.subplots(figsize=(8, 4)) ax.text(0.5, 0.5, f"Error: {str(e)}", ha='center', va='center') ax.axis('off') return error_fig, f"An error occurred: {str(e)}" # Create Gradio interface def create_gradio_interface(): interface = gr.Interface( fn=analyze_health, inputs=[ gr.Slider(20, 90, value=50, label="Age"), gr.Slider(15, 45, value=25, label="BMI"), gr.Slider(80, 200, value=120, label="Blood Pressure"), gr.Slider(70, 200, value=100, label="Glucose") ], outputs=[ gr.Plot(label="Health Analysis Dashboard"), gr.Textbox(label="Health Report", lines=10) ], title="Health Analysis System", description="Enter patient metrics for health analysis." ) return interface if __name__ == "__main__": # Launch the Gradio interface interface = create_gradio_interface() interface.launch()