Spaces:
Runtime error
Runtime error
File size: 7,322 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 220 221 222 223 224 225 226 227 228 229 230 231 232 |
"""
Pydantic Validation Example
Demonstrates automatic parsing and validation of health data
"""
from health_data import (
PydanticUserHealthProfile,
PydanticHealthRecord,
NutritionRecord,
ExerciseRecord,
HealthDataParser,
merge_records,
RecordType
)
from datetime import datetime, timedelta
def test_height_parsing():
"""Test parsing height from various formats"""
print("=" * 60)
print("HEIGHT PARSING TEST")
print("=" * 60)
test_cases = [
"1.78m", # Meters
"1,78m", # Comma separator
"178cm", # Centimeters
"178", # Just number
"1.78", # Decimal
"5'10\"", # Feet/inches
]
for test in test_cases:
result = HealthDataParser.parse_height(test)
print(f"Input: {test:15} β {result} cm")
def test_weight_parsing():
"""Test parsing weight from various formats"""
print("\n" + "=" * 60)
print("WEIGHT PARSING TEST")
print("=" * 60)
test_cases = [
"70kg", # Kilograms
"70", # Just number
"154lbs", # Pounds
"70.5", # Decimal
]
for test in test_cases:
result = HealthDataParser.parse_weight(test)
print(f"Input: {test:15} β {result} kg")
def test_pydantic_validation():
"""Test Pydantic automatic validation"""
print("\n" + "=" * 60)
print("PYDANTIC VALIDATION TEST")
print("=" * 60)
# Test 1: Valid data with various formats
print("\nβ
Test 1: Valid data with mixed formats")
try:
profile = PydanticUserHealthProfile(
user_id="user123",
age="25 tuα»i", # Will parse to 25
gender="male",
weight="70kg", # Will parse to 70.0
height="1.78m" # Will parse to 178.0
)
print(f" Age: {profile.age}")
print(f" Weight: {profile.weight} kg")
print(f" Height: {profile.height} cm")
print(f" BMI: {profile.bmi} ({profile.get_bmi_category()})")
print(" β
Success!")
except Exception as e:
print(f" β Error: {e}")
# Test 2: Invalid height (too high)
print("\nβ Test 2: Invalid height (too high)")
try:
profile = PydanticUserHealthProfile(
user_id="user456",
height="500cm" # Too high!
)
print(" β Should have failed!")
except Exception as e:
print(f" β
Caught error: {e}")
# Test 3: Invalid age (too young)
print("\nβ Test 3: Invalid age (too young)")
try:
profile = PydanticUserHealthProfile(
user_id="user789",
age=10 # Too young!
)
print(" β Should have failed!")
except Exception as e:
print(f" β
Caught error: {e}")
# Test 4: Auto BMI calculation
print("\nβ
Test 4: Auto BMI calculation")
profile = PydanticUserHealthProfile(
user_id="user999",
weight="70kg",
height="1,75m" # Comma separator!
)
print(f" Weight: {profile.weight} kg")
print(f" Height: {profile.height} cm")
print(f" BMI: {profile.bmi} (auto-calculated)")
print(f" Category: {profile.get_bmi_category()}")
def test_health_records():
"""Test health records with validation"""
print("\n" + "=" * 60)
print("HEALTH RECORDS TEST")
print("=" * 60)
# Create nutrition record
print("\nπ Creating Nutrition Record")
nutrition = NutritionRecord(
user_id="user123",
height="1.78m",
weight="70kg",
data={
'calories': 2000,
'protein': 150,
'carbs': 200,
'fat': 60
}
)
print(f" Height: {nutrition.height} cm")
print(f" Weight: {nutrition.weight} kg")
print(f" BMI: {nutrition.bmi}")
print(f" Calories: {nutrition.data['calories']}")
# Create exercise record
print("\nπ Creating Exercise Record")
exercise = ExerciseRecord(
user_id="user123",
data={
'exercise_type': 'cardio',
'duration_minutes': 30,
'calories_burned': 300
}
)
print(f" Type: {exercise.data['exercise_type']}")
print(f" Duration: {exercise.data['duration_minutes']} min")
print(f" Calories: {exercise.data['calories_burned']}")
def test_merge_records():
"""Test merging records from multiple days"""
print("\n" + "=" * 60)
print("MERGE RECORDS TEST")
print("=" * 60)
# Create sample records over 7 days
records = []
base_date = datetime.now() - timedelta(days=7)
for i in range(7):
# Nutrition record
nutrition = NutritionRecord(
user_id="user123",
weight=70 - i * 0.2, # Gradually losing weight
height=178,
data={
'calories': 1800 + i * 50,
'protein': 140 + i * 5,
}
)
nutrition.timestamp = base_date + timedelta(days=i)
records.append(nutrition)
# Exercise record
exercise = ExerciseRecord(
user_id="user123",
data={
'exercise_type': 'cardio' if i % 2 == 0 else 'strength',
'duration_minutes': 30 + i * 5,
'calories_burned': 250 + i * 20
}
)
exercise.timestamp = base_date + timedelta(days=i)
records.append(exercise)
print(f"\nπ¦ Created {len(records)} records over 7 days")
# Merge with average strategy
print("\nπ Merging with 'average' strategy:")
merged = merge_records(records, strategy='average')
print(f"\nTotal records: {merged['total_records']}")
print(f"Date range: {merged['date_range']['start'][:10]} to {merged['date_range']['end'][:10]}")
if 'nutrition' in merged['by_type']:
nutrition_data = merged['by_type']['nutrition']
print(f"\nπ Nutrition Summary:")
print(f" Average calories: {nutrition_data['average_daily']['calories']}")
print(f" Average protein: {nutrition_data['average_daily']['protein']}g")
if 'exercise' in merged['by_type']:
exercise_data = merged['by_type']['exercise']
print(f"\nπ Exercise Summary:")
print(f" Total workouts: {exercise_data['total_workouts']}")
print(f" Total duration: {exercise_data['total_duration_minutes']} min")
print(f" Total calories burned: {exercise_data['total_calories_burned']}")
print(f" Exercise types: {exercise_data['exercise_types']}")
if 'health_metrics' in merged and 'weight' in merged['health_metrics']:
weight_data = merged['health_metrics']['weight']
print(f"\nβοΈ Weight Progress:")
print(f" Start: {weight_data['max']} kg")
print(f" End: {weight_data['latest']} kg")
print(f" Change: {weight_data['change']} kg")
print(f" Average: {weight_data['average']} kg")
if __name__ == '__main__':
test_height_parsing()
test_weight_parsing()
test_pydantic_validation()
test_health_records()
test_merge_records()
print("\n" + "=" * 60)
print("β
ALL TESTS COMPLETE!")
print("=" * 60)
|