Spaces:
Runtime error
Runtime error
File size: 8,237 Bytes
eeb0f9c |
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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
"""
Health Context - Unified access to all user health data
Central hub for agents to access and update health information
"""
from typing import List, Optional, Dict, Any
from datetime import datetime
from .data_store import HealthDataStore
from .models import (
UserHealthProfile, HealthRecord, UserPreferences,
FitnessProgress, HealthMetrics
)
class HealthContext:
"""
Unified access to all user health data
Provides a single interface for agents to access and update health information
"""
def __init__(self, user_id: str, data_store: Optional[HealthDataStore] = None):
self.user_id = user_id
self.data_store = data_store or HealthDataStore()
# Load data from storage
self.profile = self.data_store.get_user_profile(user_id)
if not self.profile:
self.profile = UserHealthProfile(user_id)
self.data_store.save_user_profile(self.profile)
self.preferences = self.data_store.get_preferences(user_id)
if not self.preferences:
self.preferences = UserPreferences(user_id)
self.data_store.save_preferences(self.preferences)
# ===== Profile Access =====
def get_user_profile(self) -> UserHealthProfile:
"""Get user's health profile"""
return self.profile
def update_profile(self, **kwargs) -> None:
"""Update user profile fields"""
for key, value in kwargs.items():
if hasattr(self.profile, key):
setattr(self.profile, key, value)
self.profile.updated_at = datetime.now()
self.data_store.save_user_profile(self.profile)
def get_profile_dict(self) -> Dict[str, Any]:
"""Get profile as dictionary"""
return self.profile.to_dict()
# ===== Health History Access =====
def get_health_history(self, days: int = 30) -> List[HealthRecord]:
"""Get health history for last N days"""
return self.data_store.get_health_history(self.user_id, days)
def get_records_by_type(self, record_type: str) -> List[HealthRecord]:
"""Get records of specific type"""
return self.data_store.get_records_by_type(self.user_id, record_type)
def add_health_record(self, record_type: str, data: Dict[str, Any],
agent_name: Optional[str] = None,
confidence: float = 0.5) -> None:
"""Add health record"""
record = HealthRecord(self.user_id, record_type, data)
record.agent_name = agent_name
record.confidence = confidence
self.data_store.add_health_record(record)
# ===== Preferences Access =====
def get_preferences(self) -> UserPreferences:
"""Get user preferences"""
return self.preferences
def update_preferences(self, **kwargs) -> None:
"""Update preferences"""
for key, value in kwargs.items():
if hasattr(self.preferences, key):
setattr(self.preferences, key, value)
self.preferences.updated_at = datetime.now()
self.data_store.save_preferences(self.preferences)
def add_goal(self, goal: str) -> None:
"""Add health goal"""
if goal not in self.preferences.goals:
self.preferences.goals.append(goal)
self.data_store.save_preferences(self.preferences)
def add_exercise_preference(self, exercise_type: str) -> None:
"""Add exercise preference"""
if exercise_type not in self.preferences.preferred_exercise_types:
self.preferences.preferred_exercise_types.append(exercise_type)
self.data_store.save_preferences(self.preferences)
# ===== Fitness Access =====
def get_fitness_history(self, days: int = 30) -> List[FitnessProgress]:
"""Get fitness history"""
return self.data_store.get_fitness_history(self.user_id, days)
def add_fitness_record(self, workout_data: Dict[str, Any]) -> None:
"""Add fitness record"""
record = FitnessProgress(self.user_id)
for key, value in workout_data.items():
if hasattr(record, key):
setattr(record, key, value)
self.data_store.add_fitness_record(record)
def get_workout_adherence(self, days: int = 30) -> float:
"""Calculate workout adherence rate (0-1)"""
history = self.get_fitness_history(days)
if not history:
return 0.0
# Simple adherence: workouts completed / expected workouts
# Assuming 3-4 workouts per week is ideal
expected_workouts = (days / 7) * 3.5
actual_workouts = len(history)
adherence = min(actual_workouts / expected_workouts, 1.0) if expected_workouts > 0 else 0.0
return round(adherence, 2)
# ===== Metrics Access =====
def get_metrics(self, metric_type: Optional[str] = None) -> List[HealthMetrics]:
"""Get health metrics"""
return self.data_store.get_metrics(self.user_id, metric_type)
def add_metric(self, metric_type: str, value: float, unit: str) -> None:
"""Add health metric"""
metric = HealthMetrics(self.user_id, metric_type, value, unit)
self.data_store.add_metric(metric)
def get_latest_metric(self, metric_type: str) -> Optional[HealthMetrics]:
"""Get latest metric of specific type"""
metrics = self.get_metrics(metric_type)
return metrics[0] if metrics else None
# ===== Context Summary =====
def get_context_summary(self) -> str:
"""Get summary of current context for agents"""
summary_parts = []
# Profile summary
profile = self.profile
if profile.age:
summary_parts.append(f"Age: {profile.age}")
if profile.gender:
summary_parts.append(f"Gender: {profile.gender}")
if profile.weight and profile.height:
summary_parts.append(f"Weight: {profile.weight}kg, Height: {profile.height}cm")
if profile.bmi:
summary_parts.append(f"BMI: {profile.bmi}")
# Health conditions
if profile.health_conditions:
summary_parts.append(f"Conditions: {', '.join(profile.health_conditions)}")
# Goals
if self.preferences.goals:
summary_parts.append(f"Goals: {', '.join(self.preferences.goals)}")
# Recent activity
recent_records = self.get_health_history(days=7)
if recent_records:
summary_parts.append(f"Recent interactions: {len(recent_records)}")
return " | ".join(summary_parts) if summary_parts else "No context yet"
def get_personalization_context(self) -> str:
"""Get context for personalization"""
context = []
# User profile
profile = self.profile
context.append(f"User Profile: {profile.age}yo, {profile.gender}, BMI {profile.bmi}")
# Health conditions
if profile.health_conditions:
context.append(f"Health Conditions: {', '.join(profile.health_conditions)}")
# Goals
if self.preferences.goals:
context.append(f"Goals: {', '.join(self.preferences.goals)}")
# Recent interactions
recent = self.get_health_history(days=7)
if recent:
context.append(f"Recent interactions: {len(recent)} in last 7 days")
# Fitness adherence
adherence = self.get_workout_adherence(days=30)
context.append(f"Fitness adherence (30d): {adherence*100:.0f}%")
return "\n".join(context)
# ===== Data Export & Management =====
def export_data(self) -> Dict[str, Any]:
"""Export all user data"""
return self.data_store.export_user_data(self.user_id)
def delete_all_data(self) -> None:
"""Delete all user data (GDPR compliance)"""
self.data_store.delete_user_data(self.user_id)
def __repr__(self) -> str:
return f"<HealthContext: {self.user_id} - {self.get_context_summary()}>"
|