Spaces:
Configuration error
Configuration error
File size: 7,259 Bytes
33a15a9 a1bdec0 33a15a9 a1bdec0 33a15a9 a1bdec0 33a15a9 | 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 | """
Input validation utilities for user interface
"""
from typing import Tuple, Optional, List, Dict, Any
import re
from guardrails import Guard
from guardrails.validator_base import (
FailResult,
PassResult,
ValidationResult,
Validator,
register_validator,
)
# Common Indian states for validation
INDIAN_STATES = [
"Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh",
"Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jharkhand", "Karnataka",
"Kerala", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram",
"Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu",
"Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal",
"Andaman and Nicobar Islands", "Chandigarh", "Dadra and Nagar Haveli and Daman and Diu",
"Delhi", "Jammu and Kashmir", "Ladakh", "Lakshadweep", "Puducherry"
]
# Common employment statuses
EMPLOYMENT_STATUSES = [
"Employed (Full-time)", "Employed (Part-time)", "Self-Employed",
"Unemployed", "Student", "Retired", "Homemaker", "Daily Wage Worker", "Farmer"
]
# Education levels
EDUCATION_LEVELS = [
"No Formal Education", "Primary School", "Secondary School",
"Higher Secondary", "Graduate", "Post-Graduate", "Diploma/ITI", "Other"
]
# Social categories
SOCIAL_CATEGORIES = [
"General", "OBC", "SC", "ST", "EWS", "Prefer not to say"
]
@register_validator(name="jan-sahayak/relevance", data_type="string")
class IndianCivicRelevance(Validator):
"""
Validates if a query is related to Indian civic matters, schemes, or benefits.
"""
def validate(self, value: Any, metadata: Dict[str, Any]) -> ValidationResult:
# For a truly production-grade system, we'd use an LLM call here.
# But to keep it light and local (per user request):
keywords = [
"scheme", "yojana", "benefit", "eligibility", "apply", "policy",
"government", "india", "state", "aadhaar", "ration", "pension",
"farmer", "student", "scholarship", "healthcare", "insurance",
"pm-kisan", "ayushman", "svanidhi", "awas", "gramin", "urban"
]
# Check if any keyword matches (simple version)
if any(kw in value.lower() for kw in keywords):
return PassResult()
# Fallback: Check if it's a generic greeting or help request
if any(kw in value.lower() for kw in ["hi", "hello", "help", "who are you"]):
return PassResult()
return FailResult(
error_message="Query is out of scope for JanSahayak (Indian Civic Matters).",
fix_value="Please ask about Indian government schemes or social benefits."
)
@register_validator(name="jan-sahayak/grounding", data_type="string")
class GroundingValidator(Validator):
"""
Validates if the generated response is grounded in the provided context.
"""
def validate(self, value: Any, metadata: Dict[str, Any]) -> ValidationResult:
context = metadata.get("context", "")
if not context:
return PassResult() # Nothing to verify against
# Simplified grounding check: check for key terms from response in context
# In production, we'd use NLI or LLM-based grounding here.
return PassResult() # Placeholder for now, we'll keep the logic in graph.py for LLM check
def validate_age(age_input: str) -> Tuple[bool, Optional[int], Optional[str]]:
"""
Validates age input.
Returns:
(is_valid, age_value, error_message)
"""
if not age_input:
return False, None, "Age is required"
try:
age = int(age_input)
if age < 0:
return False, None, "Age cannot be negative"
if age > 120:
return False, None, "Please enter a valid age (0-120)"
return True, age, None
except ValueError:
return False, None, "Please enter a valid number for age"
def validate_income(income_input: str) -> Tuple[bool, Optional[float], Optional[str]]:
"""
Validates annual income input.
Returns:
(is_valid, income_value, error_message)
"""
if not income_input:
return False, None, "Income is required"
# Remove commas and spaces
income_str = income_input.replace(",", "").replace(" ", "")
try:
income = float(income_str)
if income < 0:
return False, None, "Income cannot be negative"
if income > 100000000: # 10 crore limit for sanity
return False, None, "Please enter a reasonable income amount"
return True, income, None
except ValueError:
return False, None, "Please enter a valid number for income"
def validate_location(location_input: str) -> Tuple[bool, Optional[str], Optional[str]]:
"""
Validates location/state input.
Returns:
(is_valid, location_value, error_message)
"""
if not location_input:
return False, None, "Location is required"
location = location_input.strip()
if len(location) < 2:
return False, None, "Please enter a valid location"
return True, location, None
def validate_family_size(family_input: str) -> Tuple[bool, Optional[int], Optional[str]]:
"""
Validates family size input.
Returns:
(is_valid, family_size, error_message)
"""
if not family_input:
return False, None, "Family size is required"
try:
family_size = int(family_input)
if family_size < 1:
return False, None, "Family size must be at least 1"
if family_size > 50:
return False, None, "Please enter a reasonable family size"
return True, family_size, None
except ValueError:
return False, None, "Please enter a valid number for family size"
def validate_scheme_name(scheme_input: str) -> Tuple[bool, Optional[str], Optional[str]]:
"""
Validates scheme name input.
Returns:
(is_valid, scheme_name, error_message)
"""
if not scheme_input:
return False, None, "Scheme name is required"
scheme = scheme_input.strip()
if len(scheme) < 3:
return False, None, "Please enter a valid scheme name (at least 3 characters)"
return True, scheme, None
def validate_policy_name(policy_input: str) -> Tuple[bool, Optional[str], Optional[str]]:
"""
Validates policy name input.
Returns:
(is_valid, policy_name, error_message)
"""
if not policy_input:
return False, None, "Policy name is required"
policy = policy_input.strip()
if len(policy) < 3:
return False, None, "Please enter a valid policy name (at least 3 characters)"
return True, policy, None
def format_currency(amount: float) -> str:
"""Format amount in Indian currency format."""
return f"₹{amount:,.2f}"
def validate_required_field(field_value: str, field_name: str) -> Tuple[bool, Optional[str]]:
"""
Generic required field validator.
Returns:
(is_valid, error_message)
"""
if not field_value or not field_value.strip():
return False, f"{field_name} is required"
return True, None
|