File size: 8,907 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
"""
Health Data Validators
Smart parsing and validation for health metrics with multiple input formats
"""

import re
from typing import Optional, Union, Tuple


class HealthDataParser:
    """Parse health data from various input formats"""
    
    @staticmethod
    def parse_height(value: Union[str, int, float]) -> Optional[float]:
        """
        Parse height from various formats to cm
        
        Supports:
        - 1.78m, 1.78 m → 178 cm
        - 178cm, 178 cm → 178 cm
        - 1,78m (comma) → 178 cm
        - 178 → 178 cm
        - 5'10" → 177.8 cm (feet/inches)
        
        Args:
            value: Height in various formats
            
        Returns:
            Height in cm or None if invalid
        """
        if value is None:
            return None
        
        # Convert to string and normalize
        value_str = str(value).strip().lower().replace(',', '.')
        
        # Remove spaces
        value_str = value_str.replace(' ', '')
        
        # Pattern 1: Meters (1.78m, 1.78)
        meter_match = re.match(r'^(\d+\.?\d*)m?$', value_str)
        if meter_match:
            meters = float(meter_match.group(1))
            # If value is between 0.5 and 3.0, assume it's in meters
            if 0.5 <= meters <= 3.0:
                return round(meters * 100, 1)
            # If value is > 50, assume it's already in cm
            elif meters >= 50:
                return round(meters, 1)
        
        # Pattern 2: Centimeters (178cm, 178)
        cm_match = re.match(r'^(\d+\.?\d*)cm?$', value_str)
        if cm_match:
            cm = float(cm_match.group(1))
            if 50 <= cm <= 300:
                return round(cm, 1)
        
        # Pattern 3: Feet and inches (5'10", 5ft10in)
        feet_match = re.match(r'^(\d+)[\'ft](\d+)[\"in]?$', value_str)
        if feet_match:
            feet = int(feet_match.group(1))
            inches = int(feet_match.group(2))
            total_inches = feet * 12 + inches
            cm = total_inches * 2.54
            return round(cm, 1)
        
        # Try direct float conversion
        try:
            num = float(value_str)
            # If between 0.5 and 3.0, assume meters
            if 0.5 <= num <= 3.0:
                return round(num * 100, 1)
            # If between 50 and 300, assume cm
            elif 50 <= num <= 300:
                return round(num, 1)
        except ValueError:
            pass
        
        return None
    
    @staticmethod
    def parse_weight(value: Union[str, int, float]) -> Optional[float]:
        """
        Parse weight from various formats to kg
        
        Supports:
        - 70kg, 70 kg → 70 kg
        - 70, 70.5 → 70 kg
        - 154lbs, 154 lbs → 69.9 kg
        - 11st 2lb → 70.8 kg (stones)
        
        Args:
            value: Weight in various formats
            
        Returns:
            Weight in kg or None if invalid
        """
        if value is None:
            return None
        
        value_str = str(value).strip().lower().replace(',', '.')
        value_str = value_str.replace(' ', '')
        
        # Pattern 1: Kilograms (70kg, 70)
        kg_match = re.match(r'^(\d+\.?\d*)kg?$', value_str)
        if kg_match:
            kg = float(kg_match.group(1))
            if 20 <= kg <= 300:
                return round(kg, 1)
        
        # Pattern 2: Pounds (154lbs, 154lb)
        lbs_match = re.match(r'^(\d+\.?\d*)lbs?$', value_str)
        if lbs_match:
            lbs = float(lbs_match.group(1))
            kg = lbs * 0.453592
            if 20 <= kg <= 300:
                return round(kg, 1)
        
        # Pattern 3: Stones (11st, 11stone)
        stone_match = re.match(r'^(\d+)st(?:one)?(\d+)?lbs?$', value_str)
        if stone_match:
            stones = int(stone_match.group(1))
            lbs = int(stone_match.group(2)) if stone_match.group(2) else 0
            total_lbs = stones * 14 + lbs
            kg = total_lbs * 0.453592
            return round(kg, 1)
        
        # Try direct float conversion
        try:
            num = float(value_str)
            if 20 <= num <= 300:
                return round(num, 1)
        except ValueError:
            pass
        
        return None
    
    @staticmethod
    def parse_age(value: Union[str, int, float]) -> Optional[int]:
        """
        Parse age from various formats
        
        Supports:
        - 25, "25" → 25
        - "25 tuổi", "25 years old" → 25
        
        Args:
            value: Age in various formats
            
        Returns:
            Age as integer or None if invalid
        """
        if value is None:
            return None
        
        value_str = str(value).strip().lower()
        
        # Extract number from string
        age_match = re.search(r'(\d+)', value_str)
        if age_match:
            age = int(age_match.group(1))
            if 0 <= age <= 150:
                return age
        
        return None
    
    @staticmethod
    def parse_bmi(value: Union[str, int, float]) -> Optional[float]:
        """Parse BMI value"""
        if value is None:
            return None
        
        try:
            bmi = float(str(value).strip())
            if 10 <= bmi <= 60:
                return round(bmi, 1)
        except ValueError:
            pass
        
        return None


class HealthDataValidator:
    """Validate health data for abnormal values"""
    
    @staticmethod
    def validate_height(height: float) -> Tuple[bool, Optional[str]]:
        """
        Validate height in cm
        
        Returns:
            (is_valid, error_message)
        """
        if height is None:
            return True, None
        
        if height < 50:
            return False, "Chiều cao quá thấp (< 50cm). Vui lòng kiểm tra lại."
        
        if height > 300:
            return False, "Chiều cao quá cao (> 300cm). Vui lòng kiểm tra lại."
        
        if height < 100:
            return False, f"Chiều cao {height}cm có vẻ không đúng. Bạn có muốn nhập {height*100}cm không?"
        
        return True, None
    
    @staticmethod
    def validate_weight(weight: float) -> Tuple[bool, Optional[str]]:
        """
        Validate weight in kg
        
        Returns:
            (is_valid, error_message)
        """
        if weight is None:
            return True, None
        
        if weight < 20:
            return False, "Cân nặng quá nhẹ (< 20kg). Vui lòng kiểm tra lại."
        
        if weight > 300:
            return False, "Cân nặng quá nặng (> 300kg). Vui lòng kiểm tra lại."
        
        return True, None
    
    @staticmethod
    def validate_age(age: int) -> Tuple[bool, Optional[str]]:
        """
        Validate age
        
        Returns:
            (is_valid, error_message)
        """
        if age is None:
            return True, None
        
        if age < 0:
            return False, "Tuổi không thể âm."
        
        if age > 150:
            return False, "Tuổi quá cao (> 150). Vui lòng kiểm tra lại."
        
        if age < 13:
            return False, "Hệ thống chỉ hỗ trợ người từ 13 tuổi trở lên."
        
        return True, None
    
    @staticmethod
    def validate_bmi(bmi: float) -> Tuple[bool, Optional[str]]:
        """
        Validate BMI
        
        Returns:
            (is_valid, error_message)
        """
        if bmi is None:
            return True, None
        
        if bmi < 10:
            return False, "BMI quá thấp (< 10). Vui lòng kiểm tra lại."
        
        if bmi > 60:
            return False, "BMI quá cao (> 60). Vui lòng kiểm tra lại."
        
        return True, None
    
    @staticmethod
    def calculate_bmi(weight: Optional[float], height: Optional[float]) -> Optional[float]:
        """
        Calculate BMI from weight (kg) and height (cm)
        
        Returns:
            BMI or None if data is missing
        """
        if weight is None or height is None:
            return None
        
        if height <= 0 or weight <= 0:
            return None
        
        # Convert height from cm to meters
        height_m = height / 100
        bmi = weight / (height_m ** 2)
        
        return round(bmi, 1)
    
    @staticmethod
    def get_bmi_category(bmi: Optional[float]) -> str:
        """Get BMI category (Vietnamese)"""
        if bmi is None:
            return "Chưa xác định"
        
        if bmi < 18.5:
            return "Thiếu cân"
        elif bmi < 23:  # Asian BMI standards
            return "Bình thường"
        elif bmi < 25:
            return "Thừa cân nhẹ"
        elif bmi < 30:
            return "Thừa cân"
        else:
            return "Béo phì"