Spaces:
Sleeping
Sleeping
Download src/utils/validators.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 1.33 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/utils/validators.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/src/utils/validators.py
-
curl -L -o validators.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/utils/validators.py
1.33 kB
| import re | |
| from pathlib import Path | |
| from typing import Tuple | |
| # ============================================================================ | |
| # ENHANCED VALIDATORS FOR PRODUCTION | |
| # ============================================================================ | |
| def validate_user_query(query: str, max_length: int = 2000) -> Tuple[bool, str]: | |
| """ | |
| Validate user query for safety and reasonableness. | |
| Checks for: | |
| - Empty input | |
| - Length limits | |
| - Potential prompt injection attacks | |
| Args: | |
| query: User input query | |
| max_length: Maximum allowed query length | |
| Returns: | |
| Tuple of (is_valid, error_message) | |
| """ | |
| if not query or not query.strip(): | |
| return False, "Query cannot be empty" | |
| if len(query) > max_length: | |
| return False, f"Query exceeds {max_length} character limit" | |
| # Check for prompt injection patterns | |
| dangerous_patterns = [ | |
| r"(?i:ignore.*instructions?|override.*system)", | |
| r"(?i:system.*prompt|show.*prompt)", | |
| r"(?i:forget.*previous|disregard.*instructions?)", | |
| r"(?i:as a.*jailbreak|prompt.*injection)", | |
| ] | |
| for pattern in dangerous_patterns: | |
| if re.search(pattern, query): | |
| return False, "Query contains potentially suspicious patterns" | |
| return True, "" | |