Spaces:
Sleeping
Sleeping
| """Input validation utilities.""" | |
| from typing import Dict, Any, Tuple | |
| from pydantic import ValidationError | |
| import json | |
| class ValidationResult: | |
| """Structured validation result.""" | |
| def __init__(self, is_valid: bool, errors: list = None, data: Any = None): | |
| self.is_valid = is_valid | |
| self.errors = errors or [] | |
| self.data = data | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| "valid": self.is_valid, | |
| "errors": self.errors, | |
| "data": self.data | |
| } | |
| def validate_json_input(input_str: str) -> ValidationResult: | |
| """Validate that input is valid JSON.""" | |
| try: | |
| data = json.loads(input_str) | |
| return ValidationResult(is_valid=True, data=data) | |
| except json.JSONDecodeError as e: | |
| return ValidationResult( | |
| is_valid=False, | |
| errors=[f"Invalid JSON format: {str(e)}"] | |
| ) | |
| except Exception as e: | |
| return ValidationResult( | |
| is_valid=False, | |
| errors=[f"Unexpected error: {str(e)}"] | |
| ) | |
| def validate_claim_schema(claim_data: Dict[str, Any], schema_class) -> ValidationResult: | |
| """Validate claim data against Pydantic schema.""" | |
| try: | |
| validated = schema_class(**claim_data) | |
| return ValidationResult(is_valid=True, data=validated.model_dump()) | |
| except ValidationError as e: | |
| errors = [] | |
| for error in e.errors(): | |
| field = '.'.join(str(x) for x in error['loc']) | |
| errors.append(f"{field}: {error['msg']}") | |
| return ValidationResult(is_valid=False, errors=errors) | |
| except Exception as e: | |
| return ValidationResult( | |
| is_valid=False, | |
| errors=[f"Schema validation failed: {str(e)}"] | |
| ) | |
| def validate_required_fields(data: Dict[str, Any], required_fields: list) -> ValidationResult: | |
| """Check for required fields.""" | |
| missing = [field for field in required_fields if field not in data or not data[field]] | |
| if missing: | |
| return ValidationResult( | |
| is_valid=False, | |
| errors=[f"Missing required fields: {', '.join(missing)}"] | |
| ) | |
| return ValidationResult(is_valid=True, data=data) | |