Spaces:
Running on Zero
Running on Zero
Download backend/validation.py from unnati14/myopia-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 5.56 kB
-
https://huggingface.co/spaces/unnati14/myopia-risk-api/resolve/main/backend/validation.py
- Command line
-
hf download hf://spaces/unnati14/myopia-risk-api/backend/validation.py
-
curl -L -o validation.py https://huggingface.co/spaces/unnati14/myopia-risk-api/resolve/main/backend/validation.py
5.56 kB
| """ | |
| Input validation schemas for API endpoints | |
| """ | |
| from typing import Optional, Literal | |
| class ValidationError(Exception): | |
| """Raised when input validation fails""" | |
| pass | |
| def validate_screening_data(data: dict) -> dict: | |
| """ | |
| Validate and sanitize screening form data | |
| Args: | |
| data: Raw request body from frontend | |
| Returns: | |
| Validated and type-cast data | |
| Raises: | |
| ValidationError: If validation fails | |
| """ | |
| errors = [] | |
| # ββ Required fields ββ | |
| required = ['age', 'sex', 'screenTime', 'nearWork', 'outdoorTime', 'sports'] | |
| for field in required: | |
| if field not in data: | |
| errors.append(f"Missing required field: {field}") | |
| if errors: | |
| raise ValidationError("; ".join(errors)) | |
| validated = {} | |
| # ββ Age: 5-18 years ββ | |
| try: | |
| age = int(data['age']) | |
| if not 5 <= age <= 18: | |
| errors.append("Age must be between 5 and 18 years") | |
| validated['age'] = age | |
| except (ValueError, TypeError): | |
| errors.append("Age must be a valid integer") | |
| # ββ Sex: male/female ββ | |
| sex = str(data.get('sex', '')).lower() | |
| if sex not in ['male', 'female']: | |
| errors.append("Sex must be 'male' or 'female'") | |
| validated['sex'] = sex | |
| # ββ Height: 80-200 cm (optional) ββ | |
| height = data.get('height', 0) | |
| try: | |
| height = float(height) if height else 0 | |
| if height != 0 and not 80 <= height <= 200: | |
| errors.append("Height must be between 80-200 cm or 0 if unknown") | |
| validated['height'] = height | |
| except (ValueError, TypeError): | |
| errors.append("Height must be a valid number") | |
| # ββ Weight: 15-100 kg (optional) ββ | |
| weight = data.get('weight', 0) | |
| try: | |
| weight = float(weight) if weight else 0 | |
| if weight != 0 and not 15 <= weight <= 100: | |
| errors.append("Weight must be between 15-100 kg or 0 if unknown") | |
| validated['weight'] = weight | |
| except (ValueError, TypeError): | |
| errors.append("Weight must be a valid number") | |
| # ββ Screen time: 0-24 hours/day ββ | |
| try: | |
| screen_time = float(data['screenTime']) | |
| if not 0 <= screen_time <= 24: | |
| errors.append("Screen time must be between 0-24 hours/day") | |
| validated['screenTime'] = screen_time | |
| except (ValueError, TypeError): | |
| errors.append("Screen time must be a valid number") | |
| # ββ Near work: 0-24 hours/day ββ | |
| try: | |
| near_work = float(data['nearWork']) | |
| if not 0 <= near_work <= 24: | |
| errors.append("Near work must be between 0-24 hours/day") | |
| validated['nearWork'] = near_work | |
| except (ValueError, TypeError): | |
| errors.append("Near work must be a valid number") | |
| # ββ Outdoor time: 0-24 hours/day ββ | |
| try: | |
| outdoor_time = float(data['outdoorTime']) | |
| if not 0 <= outdoor_time <= 24: | |
| errors.append("Outdoor time must be between 0-24 hours/day") | |
| validated['outdoorTime'] = outdoor_time | |
| except (ValueError, TypeError): | |
| errors.append("Outdoor time must be a valid number") | |
| # ββ Logical constraint: total time β€ 24 hours ββ | |
| if 'screenTime' in validated and 'nearWork' in validated and 'outdoorTime' in validated: | |
| total = validated['screenTime'] + validated['nearWork'] + validated['outdoorTime'] | |
| if total > 24: | |
| errors.append(f"Total screen + near work + outdoor time ({total:.1f}h) cannot exceed 24 hours/day") | |
| # ββ Sports: regular/occasional/rare ββ | |
| sports = str(data.get('sports', '')).lower() | |
| if sports not in ['regular', 'occasional', 'rare']: | |
| errors.append("Sports must be 'regular', 'occasional', or 'rare'") | |
| validated['sports'] = sports | |
| # ββ Family history: boolean or null ββ | |
| family_history = data.get('familyHistory') | |
| if family_history is None or family_history in ['null', None]: | |
| validated['familyHistory'] = None | |
| elif family_history in [True, 'true']: | |
| validated['familyHistory'] = True | |
| elif family_history in [False, 'false']: | |
| validated['familyHistory'] = False | |
| else: | |
| errors.append("Family history must be true, false, or null") | |
| # ββ Parents myopic: none/one/both ββ | |
| parents = str(data.get('parentsMyopic', 'none')).lower() | |
| if parents not in ['none', 'one', 'both']: | |
| errors.append("Parents myopic must be 'none', 'one', or 'both'") | |
| validated['parentsMyopic'] = parents | |
| # ββ Vitamin D: boolean or null ββ | |
| vitamin_d = data.get('vitaminD') | |
| if vitamin_d is None or vitamin_d in ['null', None]: | |
| validated['vitaminD'] = None | |
| elif vitamin_d in [True, 'true']: | |
| validated['vitaminD'] = True | |
| elif vitamin_d in [False, 'false']: | |
| validated['vitaminD'] = False | |
| else: | |
| errors.append("Vitamin D must be true, false, or null") | |
| # ββ State: valid Indian state (optional) ββ | |
| valid_states = [ | |
| 'Andhra Pradesh', 'Karnataka', 'Kerala', 'Tamil Nadu', | |
| 'Telangana', 'Maharashtra', 'Gujarat', 'Delhi' | |
| ] | |
| state = data.get('state', 'Andhra Pradesh') | |
| if state not in valid_states: | |
| # Default to Andhra Pradesh instead of erroring | |
| validated['state'] = 'Andhra Pradesh' | |
| else: | |
| validated['state'] = state | |
| if errors: | |
| raise ValidationError("; ".join(errors)) | |
| return validated | |