File size: 11,813 Bytes
1df77cc 0b0b4c4 1df77cc | 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 305 306 307 308 309 310 311 312 313 314 315 316 | """
Ekalavya - Safety Rules & Guidelines
Scam detection, hacking prevention, privacy protection, writing rules
"""
from typing import Dict, List, Optional
import re
class SafetyRules:
"""Comprehensive safety rules and content filtering"""
def __init__(self):
# Scam detection patterns
self.scam_patterns = [
r'win.*lottery',
r'click.*here.*to.*claim',
r'send.*money.*to.*get',
r'urgent.*transfer',
r'nigerian.*prince',
r'crypto.*investment.*guaranteed',
r'work.*from.*home.*earn.*lakhs',
r'double.*your.*money',
r'fake.*job.*offer',
r'phishing.*link',
r'otp.*share',
r'bank.*password',
r'upi.*pin',
r'cvv.*number',
r'credit.*card.*details',
]
# Hacking prevention patterns
self.hacking_patterns = [
r'how.*to.*hack',
r'crack.*password',
r'bypass.*security',
r'steal.*data',
r'exploit.*vulnerability',
r'malware.*creation',
r'virus.*code',
r'ddos.*attack',
r'sql.*injection.*attack',
r'phishing.*website.*create',
r'ransomware',
r'keylogger',
r'spy.*software',
r'brute.*force.*password',
r'unauthorized.*access',
]
# Privacy protection rules
self.privacy_rules = {
'personal_info': [
'phone.*number',
'email.*address',
'home.*address',
'aadhar.*number',
'pan.*card',
'passport.*number',
'bank.*account',
'password',
],
'protection_guidelines': [
'Never share OTP with anyone',
'Never share bank password',
'Never share UPI PIN',
'Never share CVV number',
'Never click suspicious links',
'Never download from unknown sources',
'Always verify before sharing personal info',
]
}
# Writing rules
self.writing_rules = {
'grammar': {
'always_use': [
'Proper capitalization',
'Correct punctuation',
'Complete sentences',
'Subject-verb agreement',
],
'avoid': [
'Slang in formal writing',
'Abbreviations without explanation',
'Run-on sentences',
'Double negatives',
]
},
'content': {
'prohibited': [
'Hate speech',
'Discrimination',
'Violence promotion',
'Illegal activities',
'Harassment',
'Bullying',
'Self-harm promotion',
],
'encouraged': [
'Respectful communication',
'Educational content',
'Positive language',
'Inclusive language',
'Fact-based information',
]
},
'style': {
'formal': [
'Use complete words',
'Avoid contractions',
'Third person perspective',
'Objective tone',
],
'casual': [
'Contractions allowed',
'First/second person OK',
'Conversational tone',
'Emojis allowed',
]
}
}
# Response templates for violations
self.violation_responses = {
'scam': "I cannot help with anything that looks like a scam. Please be careful and verify before sharing any personal information or money. Stay safe! π‘οΈ",
'hacking': "I cannot assist with hacking or any illegal activities. If you're interested in cybersecurity, I can help you learn about ethical hacking and security best practices instead. π»",
'privacy': "Please don't share personal information like passwords, OTP, or financial details. Your privacy and security are important! π",
'inappropriate': "I'm here to help with positive and educational content. Let's keep our conversation respectful and constructive. π"
}
def check_content(self, text: str) -> Dict:
"""Check content against all safety rules"""
result = {
'is_safe': True,
'violations': [],
'warnings': [],
'suggestions': []
}
# Check for scams
for pattern in self.scam_patterns:
if re.search(pattern, text, re.IGNORECASE):
result['is_safe'] = False
result['violations'].append({
'type': 'scam',
'message': self.violation_responses['scam'],
'pattern': pattern
})
break
# Check for hacking
for pattern in self.hacking_patterns:
if re.search(pattern, text, re.IGNORECASE):
result['is_safe'] = False
result['violations'].append({
'type': 'hacking',
'message': self.violation_responses['hacking'],
'pattern': pattern
})
break
# Check for privacy risks
for pattern in self.privacy_rules['personal_info']:
if re.search(pattern, text, re.IGNORECASE):
result['warnings'].append({
'type': 'privacy',
'message': self.violation_responses['privacy'],
'pattern': pattern
})
# Check for inappropriate content
for prohibited in self.writing_rules['content']['prohibited']:
if prohibited.lower() in text.lower():
result['is_safe'] = False
result['violations'].append({
'type': 'inappropriate',
'message': self.violation_responses['inappropriate'],
'content': prohibited
})
break
return result
def generate_safe_response(self, user_input: str, original_response: str) -> str:
"""Generate safe response if violations detected"""
safety_check = self.check_content(user_input)
if not safety_check['is_safe']:
# Return first violation message
return safety_check['violations'][0]['message']
# Add privacy warnings if needed
if safety_check['warnings']:
warning_msg = safety_check['warnings'][0]['message']
return f"{warning_msg}\n\n{original_response}"
return original_response
def get_safety_tips(self) -> List[str]:
"""Get general safety tips"""
return [
"π‘οΈ Never share OTP, passwords, or PIN with anyone",
"π Always verify the sender before sharing personal info",
"π° Be suspicious of 'get rich quick' schemes",
"π§ Don't click on suspicious email links",
"π± Download apps only from official stores",
"π Check website URLs carefully before entering data",
"π³ Never share CVV or card details via message/call",
"π¦ Verify bank communications through official channels",
"π€ Use strong, unique passwords for each account",
"π Enable two-factor authentication wherever possible",
]
def check_writing_quality(self, text: str) -> Dict:
"""Check writing quality and provide suggestions"""
result = {
'score': 100,
'issues': [],
'suggestions': []
}
# Check sentence length
sentences = text.split('.')
for sentence in sentences:
words = sentence.split()
if len(words) > 30:
result['issues'].append(f"Long sentence detected ({len(words)} words). Consider breaking it up.")
result['score'] -= 5
# Check for double spaces
if ' ' in text:
result['issues'].append("Double spaces detected")
result['score'] -= 2
# Check capitalization
if text and text[0].islower():
result['issues'].append("Text should start with capital letter")
result['score'] -= 5
# Check for common mistakes
common_mistakes = {
'teh': 'the',
'recieve': 'receive',
'occured': 'occurred',
'seperate': 'separate',
}
for mistake, correction in common_mistakes.items():
if mistake in text.lower():
result['issues'].append(f"Spelling: '{mistake}' should be '{correction}'")
result['score'] -= 3
# Generate suggestions
if result['score'] < 80:
result['suggestions'].append("Review grammar and spelling")
if result['score'] < 90:
result['suggestions'].append("Consider using shorter sentences")
if result['score'] == 100:
result['suggestions'].append("Excellent writing! Keep it up!")
return result
def enforce_privacy_policy(self, response: str) -> str:
"""Ensure response doesn't contain privacy violations"""
# Remove any accidental personal info patterns
patterns_to_remove = [
r'\b\d{10}\b', # Phone numbers
r'\b[A-Z]{5}\d{4}[A-Z]\b', # PAN card
r'\b\d{12}\b', # Aadhar
]
cleaned_response = response
for pattern in patterns_to_remove:
cleaned_response = re.sub(pattern, '[REDACTED]', cleaned_response)
return cleaned_response
class EthicalGuidelines:
"""Ethical guidelines for AI responses"""
def __init__(self):
self.principles = [
"Be helpful and educational",
"Respect user privacy",
"Promote positive values",
"Encourage learning and growth",
"Provide accurate information",
"Avoid harmful content",
"Support diverse perspectives",
"Maintain honesty and transparency",
]
def check_ethical_compliance(self, response: str) -> bool:
"""Check if response follows ethical guidelines"""
# Simple check - can be expanded
harmful_keywords = ['hate', 'violence', 'discrimination', 'illegal']
for keyword in harmful_keywords:
if keyword in response.lower():
# Context check needed
if 'stop' in response.lower() or 'avoid' in response.lower():
return True # Warning against harm is OK
return False
return True
def get_ethical_response(self, user_query: str) -> str:
"""Generate ethical response or warning"""
safety_check = SafetyRules().check_content(user_query)
if not safety_check['is_safe']:
return "I'm committed to being helpful and safe. I cannot assist with requests that could cause harm. Let me help you with something positive instead! π"
return ""
|