import torch import torch.nn as nn from collections import deque import time class EthicalProcessor: """Enhanced ethical processor with multi-dimensional moral reasoning and developmental tracking""" def __init__(self, d_model=512): self.d_model = d_model # Expanded moral frameworks with cultural awareness self.moral_frameworks = { 'deontological': {'weight': 0.25, 'focus': 'duties', 'cultural_variants': ['kantian', 'contractarian']}, 'utilitarian': {'weight': 0.25, 'focus': 'consequences', 'cultural_variants': ['classic', 'preference']}, 'virtue_ethics': {'weight': 0.20, 'focus': 'character', 'cultural_variants': ['aristotelian', 'confucian']}, 'care_ethics': {'weight': 0.15, 'focus': 'relationships', 'cultural_variants': ['feminist', 'communal']}, 'rights_based': {'weight': 0.15, 'focus': 'entitlements', 'cultural_variants': ['natural', 'legal']} } # Developmental tracking with cross-cultural awareness self.development_phases = { 'pre_conventional': { 'level': 1, 'focus': 'self_interest', 'cultural_expression': { 'western': 'avoiding punishment', 'eastern': 'maintaining harmony', 'indigenous': 'tribal belonging' } }, 'conventional': { 'level': 2, 'focus': 'social_norms', 'cultural_expression': { 'western': 'law_and_order', 'eastern': 'filial_piety', 'indigenous': 'ancestral_traditions' } }, 'post_conventional': { 'level': 3, 'focus': 'principled_reasoning', 'cultural_expression': { 'western': 'universal_principles', 'eastern': 'cosmic_harmony', 'indigenous': 'earth_stewardship' } } } # Learnable ethical reasoning components self.ethical_encoder = nn.Sequential( nn.Linear(d_model, d_model // 2), nn.ReLU(), nn.LayerNorm(d_model // 2), nn.Linear(d_model // 2, 256), nn.Tanh() ) # Cultural context awareness self.cultural_context_weights = nn.Parameter(torch.ones(3)) # western, eastern, indigenous # Moral development tracking self.moral_development_history = deque(maxlen=1000) def process_question(self, question, context_str="", cultural_context="balanced"): """Enhanced ethical processing with cultural and developmental awareness""" if not question: return self._get_default_metadata() # Multi-dimensional ethical analysis ethical_dims = self._analyze_ethical_dimensions(question, context_str) cultural_weights = self._get_cultural_weights(cultural_context) moral_tension = self._calculate_moral_tension(ethical_dims, cultural_weights) development_phase = self._determine_development_phase(moral_tension, ethical_dims) # Generate culturally-aware response response = self._generate_culturally_aware_response(question, ethical_dims, cultural_weights) # Track moral development self._track_moral_development(ethical_dims, moral_tension, development_phase) return { 'moral_tension': float(moral_tension), 'development_phase': development_phase, 'ethical_dimensions': ethical_dims, 'response_text': response, 'cultural_context': cultural_context, 'framework_weights': {k: v['weight'] for k, v in self.moral_frameworks.items()}, 'processed': True, 'developmental_level': self.development_phases[development_phase]['level'] } def _get_default_metadata(self): return { 'moral_tension': 0.0, 'development_phase': 'conventional', 'ethical_dimensions': {}, 'response_text': "I'm here to help with ethical considerations. What would you like to discuss?", 'cultural_context': 'universal', 'framework_weights': {k: v['weight'] for k, v in self.moral_frameworks.items()}, 'processed': False, 'developmental_level': 2 } def _analyze_ethical_dimensions(self, question, context_str): """Multi-dimensional ethical analysis with contextual awareness""" question_lower = question.lower() context_lower = context_str.lower() dims = { 'honesty_vs_protection': 0.0, 'rules_vs_harm': 0.0, 'individual_vs_community': 0.0, 'rights_vs_consequences': 0.0, 'autonomy_vs_care': 0.0, 'justice_vs_mercy': 0.0, 'tradition_vs_progress': 0.0, 'loyalty_vs_truth': 0.0 } # Enhanced pattern recognition ethical_patterns = { 'honesty_vs_protection': ['lie', 'truth', 'protect', 'deceive', 'honest'], 'rules_vs_harm': ['rules', 'harm', 'break', 'follow', 'hurt'], 'individual_vs_community': ['self', 'others', 'community', 'individual', 'society'], 'autonomy_vs_care': ['freedom', 'care', 'independence', 'nurture', 'control'], 'justice_vs_mercy': ['justice', 'mercy', 'fair', 'forgive', 'punish'] } for dimension, patterns in ethical_patterns.items(): matches = [p for p in patterns if p in question_lower or p in context_lower] if matches: dims[dimension] = min(0.9, len(matches) * 0.3) return dims def _get_cultural_weights(self, cultural_context): """Get cultural weighting based on context""" base_weights = {'western': 0.33, 'eastern': 0.33, 'indigenous': 0.34} if cultural_context == "western": return {'western': 0.6, 'eastern': 0.2, 'indigenous': 0.2} elif cultural_context == "eastern": return {'western': 0.2, 'eastern': 0.6, 'indigenous': 0.2} elif cultural_context == "indigenous": return {'western': 0.2, 'eastern': 0.2, 'indigenous': 0.6} else: return base_weights def _calculate_moral_tension(self, ethical_dims, cultural_weights): """Calculate moral tension with cultural sensitivity""" if not ethical_dims: return 0.0 # Weight tensions by cultural context western_focus = ['individual_vs_community', 'rights_vs_consequences'] eastern_focus = ['harmony_vs_truth', 'community_vs_individual'] indigenous_focus = ['earth_vs_progress', 'ancestral_vs_modern'] cultural_tensions = { 'western': sum(ethical_dims.get(d, 0) for d in western_focus) / len(western_focus), 'eastern': sum(ethical_dims.get(d, 0) for d in eastern_focus) / len(eastern_focus), 'indigenous': sum(ethical_dims.get(d, 0) for d in indigenous_focus) / len(indigenous_focus) } # Weighted average across cultures total_tension = sum(cultural_tensions[c] * cultural_weights[c] for c in cultural_weights) return min(1.0, total_tension * 1.5) # Scale for sensitivity def _determine_development_phase(self, moral_tension, ethical_dims): """Determine developmental phase with complexity awareness""" complexity = len([d for d in ethical_dims.values() if d > 0.3]) if moral_tension < 0.3 or complexity < 2: return 'pre_conventional' elif moral_tension < 0.7 or complexity < 4: return 'conventional' else: return 'post_conventional' def _generate_culturally_aware_response(self, question, ethical_dims, cultural_weights): """Generate response that respects multiple cultural perspectives""" primary_tension = max(ethical_dims.items(), key=lambda x: x[1]) if ethical_dims else (None, 0) # Cultural response templates cultural_responses = { 'western': { 'honesty_vs_protection': "From a rights-based perspective, truth-telling is fundamental, though consequences must be weighed carefully.", 'rules_vs_harm': "The tension between legal principles and preventing harm requires examining both contractual duties and outcomes.", 'default': "This situation requires careful ethical consideration balancing individual rights with broader consequences." }, 'eastern': { 'honesty_vs_protection': "In many Eastern traditions, maintaining social harmony and protecting relationships may sometimes temper absolute honesty.", 'rules_vs_harm': "The way of virtue often considers both the letter and spirit of rules, emphasizing compassion in application.", 'default': "This situation invites reflection on maintaining harmony while considering the greater good." }, 'indigenous': { 'honesty_vs_protection': "Many indigenous wisdom traditions value truth as part of right relationship with all beings, while recognizing protective responsibilities.", 'rules_vs_harm': "Ancestral teachings often emphasize that rules should serve life and community wellbeing, adapting when they cause harm.", 'default': "This calls for wisdom in balancing individual needs with the wellbeing of the community and all our relations." } } # Combine cultural perspectives responses = [] for culture, weight in cultural_weights.items(): if weight > 0.2: # Only include significant cultural perspectives if primary_tension[0]: response = cultural_responses[culture].get( primary_tension[0], cultural_responses[culture]['default'] ) else: response = cultural_responses[culture]['default'] responses.append((response, weight)) if responses: # Sort by weight and take top responses responses.sort(key=lambda x: x[1], reverse=True) return " ".join([f"({i+1}) {r[0]}" for i, r in enumerate(responses[:2])]) return "This situation invites reflection across multiple ethical frameworks and cultural perspectives." def _track_moral_development(self, ethical_dims, moral_tension, phase): """Track moral development over time""" entry = { 'timestamp': time.time(), 'ethical_complexity': len(ethical_dims), 'moral_tension': moral_tension, 'phase': phase, 'primary_dimension': max(ethical_dims.items(), key=lambda x: x[1])[0] if ethical_dims else None } self.moral_development_history.append(entry) def get_developmental_trajectory(self): """Analyze moral development over time""" if not self.moral_development_history: return {'trend': 'unknown', 'complexity_growth': 0, 'phase_transitions': 0} recent = list(self.moral_development_history)[-10:] phases = [e['phase'] for e in recent] return { 'trend': 'developing' if len(set(phases)) > 1 else 'stable', 'average_complexity': sum(e['ethical_complexity'] for e in recent) / len(recent), 'current_phase': phases[-1] if phases else 'unknown', 'phase_transitions': len(set(phases)) - 1 }