""" 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 ""