| """ |
| 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): |
| |
| 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', |
| ] |
| |
| |
| 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', |
| ] |
| |
| |
| 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', |
| ] |
| } |
| |
| |
| 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', |
| ] |
| } |
| } |
| |
| |
| 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': [] |
| } |
| |
| |
| 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 |
| |
| |
| 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 |
| |
| |
| 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 |
| }) |
| |
| |
| 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 safety_check['violations'][0]['message'] |
| |
| |
| 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': [] |
| } |
| |
| |
| 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 |
| |
| |
| if ' ' in text: |
| result['issues'].append("Double spaces detected") |
| result['score'] -= 2 |
| |
| |
| if text and text[0].islower(): |
| result['issues'].append("Text should start with capital letter") |
| result['score'] -= 5 |
| |
| |
| 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 |
| |
| |
| 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""" |
| |
| patterns_to_remove = [ |
| r'\b\d{10}\b', |
| r'\b[A-Z]{5}\d{4}[A-Z]\b', |
| r'\b\d{12}\b', |
| ] |
| |
| 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""" |
| |
| harmful_keywords = ['hate', 'violence', 'discrimination', 'illegal'] |
| |
| for keyword in harmful_keywords: |
| if keyword in response.lower(): |
| |
| if 'stop' in response.lower() or 'avoid' in response.lower(): |
| return True |
| 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 "" |
|
|