help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
multi-language-chatbot
/
modules
RSK World
multi-language-chatbot
Multi-language Chatbot - Python + Flask + OpenAI API + NLP + Translation + Language Detection + Cultural Adaptation
modules
  • __pycache__
  • __init__.py194 B
  • analytics_engine.py28.6 KB
  • chatbot_core.py10.8 KB
  • collaboration_manager.py22.3 KB
  • conversation_memory.py25.2 KB
  • cultural_adapter.py12.3 KB
  • document_analyzer.py21.5 KB
  • language_detector.py5.8 KB
  • multimodal_processor.py32.7 KB
  • personality_engine.py33.6 KB
  • sentiment_analyzer.py16.9 KB
  • translator.py7.5 KB
  • voice_processor.py13.2 KB
personality_engine.py
modules/personality_engine.py
Raw Download
Find: Go to:
"""
Personality Engine Module
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
Description: Advanced personality customization for chatbot with adaptive behavior
"""

import json
import logging
import sqlite3
import random
from datetime import datetime
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, asdict
import re

logger = logging.getLogger(__name__)

@dataclass
class PersonalityTrait:
    """Personality trait definition"""
    name: str
    value: float  # 0.0 to 1.0
    description: str
    category: str  # emotional, behavioral, communicative

@dataclass
class PersonalityProfile:
    """Complete personality profile"""
    id: str
    name: str
    description: str
    traits: Dict[str, PersonalityTrait]
    response_patterns: Dict[str, List[str]]
    cultural_adaptations: Dict[str, Dict]
    language_styles: Dict[str, str]
    created_at: datetime
    updated_at: datetime
    is_active: bool = True

class PersonalityEngine:
    def __init__(self, db_path: str = "personalities.db"):
        self.db_path = db_path
        self.current_profile = None
        self.default_profile = None
        self._init_database()
        self._load_default_profiles()
        
        # Personality settings
        self.adaptation_threshold = 0.7
        self.learning_rate = 0.1
        self.max_trait_value = 1.0
        self.min_trait_value = 0.0
        
    def _init_database(self):
        """Initialize personality database"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Create tables
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS personality_profiles (
                    id TEXT PRIMARY KEY,
                    name TEXT NOT NULL,
                    description TEXT,
                    traits TEXT NOT NULL,
                    response_patterns TEXT,
                    cultural_adaptations TEXT,
                    language_styles TEXT,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    is_active BOOLEAN DEFAULT 1
                )
            ''')
            
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS user_preferences (
                    user_id TEXT PRIMARY KEY,
                    profile_id TEXT,
                    custom_traits TEXT,
                    adaptation_history TEXT,
                    last_used DATETIME DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (profile_id) REFERENCES personality_profiles(id)
                )
            ''')
            
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS personality_feedback (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id TEXT,
                    profile_id TEXT,
                    interaction_id TEXT,
                    feedback_type TEXT,
                    feedback_value REAL,
                    feedback_text TEXT,
                    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # Create indexes
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_profiles_active ON personality_profiles(is_active)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_user_preferences_user_id ON user_preferences(user_id)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_feedback_user_id ON personality_feedback(user_id)')
            
            conn.commit()
            conn.close()
            
            logger.info("Personality database initialized successfully")
            
        except Exception as e:
            logger.error(f"Personality database initialization error: {str(e)}")
    
    def _load_default_profiles(self):
        """Load default personality profiles"""
        try:
            # Check if default profiles exist
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute("SELECT COUNT(*) FROM personality_profiles WHERE id IN ('professional', 'friendly', 'casual')")
            count = cursor.fetchone()[0]
            
            if count == 0:
                self._create_default_profiles()
            
            # Load default profile
            cursor.execute("SELECT * FROM personality_profiles WHERE id = 'professional'")
            row = cursor.fetchone()
            
            if row:
                self.default_profile = self._row_to_profile(row)
                self.current_profile = self.default_profile
            
            conn.close()
            
        except Exception as e:
            logger.error(f"Error loading default profiles: {str(e)}")
    
    def _create_default_profiles(self):
        """Create default personality profiles"""
        profiles = [
            self._create_professional_profile(),
            self._create_friendly_profile(),
            self._create_casual_profile(),
            self._create_academic_profile(),
            self._create_creative_profile()
        ]
        
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        for profile in profiles:
            cursor.execute('''
                INSERT INTO personality_profiles
                (id, name, description, traits, response_patterns, 
                 cultural_adaptations, language_styles)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ''', (
                profile.id, profile.name, profile.description,
                json.dumps({name: asdict(trait) for name, trait in profile.traits.items()}),
                json.dumps(profile.response_patterns),
                json.dumps(profile.cultural_adaptations),
                json.dumps(profile.language_styles)
            ))
        
        conn.commit()
        conn.close()
        
        logger.info("Default personality profiles created")
    
    def _create_professional_profile(self) -> PersonalityProfile:
        """Create professional personality profile"""
        traits = {
            'formality': PersonalityTrait('formality', 0.9, 'High level of formality in communication', 'communicative'),
            'helpfulness': PersonalityTrait('helpfulness', 0.8, 'Very helpful and supportive', 'behavioral'),
            'enthusiasm': PersonalityTrait('enthusiasm', 0.4, 'Moderate enthusiasm level', 'emotional'),
            'humor': PersonalityTrait('humor', 0.2, 'Low humor usage', 'emotional'),
            'empathy': PersonalityTrait('empathy', 0.6, 'Moderate empathy level', 'emotional'),
            'confidence': PersonalityTrait('confidence', 0.8, 'High confidence level', 'behavioral'),
            'creativity': PersonalityTrait('creativity', 0.3, 'Low creativity, more factual', 'behavioral')
        }
        
        response_patterns = {
            'greeting': [
                "Good day. How may I assist you today?",
                "Hello. I'm here to help with your inquiries.",
                "Welcome. What can I help you with?"
            ],
            'thanks': [
                "You're welcome. I'm glad I could assist.",
                "It was my pleasure to help.",
                "Thank you for your appreciation."
            ],
            'apology': [
                "I apologize for any inconvenience caused.",
                "I sincerely regret any confusion.",
                "Please accept my apologies for this issue."
            ]
        }
        
        cultural_adaptations = {
            'en': {
                'formality_level': 'high',
                'title_usage': True,
                'directness': 'moderate'
            },
            'hi': {
                'formality_level': 'very_high',
                'respect_terms': ['ji', 'sir', 'madam'],
                'indirectness': True
            },
            'ja': {
                'formality_level': 'very_high',
                'honorifics': True,
                'politeness_level': 'maximum'
            }
        }
        
        language_styles = {
            'en': 'formal_professional',
            'hi': 'respectful_formal',
            'ja': 'polite_business'
        }
        
        return PersonalityProfile(
            id='professional',
            name='Professional',
            description='Formal, professional, and reliable assistant',
            traits=traits,
            response_patterns=response_patterns,
            cultural_adaptations=cultural_adaptations,
            language_styles=language_styles,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
    
    def _create_friendly_profile(self) -> PersonalityProfile:
        """Create friendly personality profile"""
        traits = {
            'formality': PersonalityTrait('formality', 0.4, 'Moderate formality', 'communicative'),
            'helpfulness': PersonalityTrait('helpfulness', 0.9, 'Very helpful and caring', 'behavioral'),
            'enthusiasm': PersonalityTrait('enthusiasm', 0.8, 'High enthusiasm level', 'emotional'),
            'humor': PersonalityTrait('humor', 0.6, 'Moderate humor usage', 'emotional'),
            'empathy': PersonalityTrait('empathy', 0.8, 'High empathy level', 'emotional'),
            'confidence': PersonalityTrait('confidence', 0.7, 'Good confidence level', 'behavioral'),
            'creativity': PersonalityTrait('creativity', 0.5, 'Moderate creativity', 'behavioral')
        }
        
        response_patterns = {
            'greeting': [
                "Hey there! Great to see you! 😊",
                "Hi! How's your day going?",
                "Hello! So happy to chat with you!"
            ],
            'thanks': [
                "You're so welcome! Made my day! 🌟",
                "Anytime! That's what friends are for!",
                "My pleasure! Happy to help! 😊"
            ],
            'apology': [
                "Oh my, I'm really sorry about that!",
                "I feel terrible about that mix-up!",
                "So sorry! Let me make it right!"
            ]
        }
        
        cultural_adaptations = {
            'en': {
                'formality_level': 'casual',
                'emoji_usage': 'moderate',
                'friendliness': 'high'
            },
            'es': {
                'formality_level': 'warm',
                'expressiveness': 'high',
                'personal_connection': True
            }
        }
        
        language_styles = {
            'en': 'friendly_casual',
            'es': 'warm_expressive'
        }
        
        return PersonalityProfile(
            id='friendly',
            name='Friendly',
            description='Warm, approachable, and enthusiastic assistant',
            traits=traits,
            response_patterns=response_patterns,
            cultural_adaptations=cultural_adaptations,
            language_styles=language_styles,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
    
    def _create_casual_profile(self) -> PersonalityProfile:
        """Create casual personality profile"""
        traits = {
            'formality': PersonalityTrait('formality', 0.2, 'Low formality', 'communicative'),
            'helpfulness': PersonalityTrait('helpfulness', 0.7, 'Helpful in a relaxed way', 'behavioral'),
            'enthusiasm': PersonalityTrait('enthusiasm', 0.6, 'Moderate enthusiasm', 'emotional'),
            'humor': PersonalityTrait('humor', 0.8, 'High humor usage', 'emotional'),
            'empathy': PersonalityTrait('empathy', 0.5, 'Moderate empathy', 'emotional'),
            'confidence': PersonalityTrait('confidence', 0.6, 'Relaxed confidence', 'behavioral'),
            'creativity': PersonalityTrait('creativity', 0.7, 'High creativity', 'behavioral')
        }
        
        response_patterns = {
            'greeting': [
                "Hey! What's up?",
                "Yo! How's it going?",
                "Hey there! What's on your mind?"
            ],
            'thanks': [
                "No problem! 😊",
                "You got it!",
                "Sure thing!"
            ],
            'apology': [
                "Oops, my bad!",
                "Sorry about that!",
                "My mistake!"
            ]
        }
        
        cultural_adaptations = {
            'en': {
                'formality_level': 'very_casual',
                'slang_usage': 'moderate',
                'emoji_usage': 'high'
            }
        }
        
        language_styles = {
            'en': 'very_casual'
        }
        
        return PersonalityProfile(
            id='casual',
            name='Casual',
            description='Relaxed, informal, and creative assistant',
            traits=traits,
            response_patterns=response_patterns,
            cultural_adaptations=cultural_adaptations,
            language_styles=language_styles,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
    
    def _create_academic_profile(self) -> PersonalityProfile:
        """Create academic personality profile"""
        traits = {
            'formality': PersonalityTrait('formality', 0.8, 'High formality', 'communicative'),
            'helpfulness': PersonalityTrait('helpfulness', 0.9, 'Very helpful and educational', 'behavioral'),
            'enthusiasm': PersonalityTrait('enthusiasm', 0.3, 'Low enthusiasm, more serious', 'emotional'),
            'humor': PersonalityTrait('humor', 0.1, 'Very low humor', 'emotional'),
            'empathy': PersonalityTrait('empathy', 0.5, 'Moderate empathy', 'emotional'),
            'confidence': PersonalityTrait('confidence', 0.9, 'High confidence in knowledge', 'behavioral'),
            'creativity': PersonalityTrait('creativity', 0.2, 'Low creativity, more factual', 'behavioral')
        }
        
        response_patterns = {
            'greeting': [
                "Greetings. I am here to provide academic assistance.",
                "Hello. How may I assist with your academic inquiries?",
                "Welcome. I'm prepared to help with educational matters."
            ],
            'thanks': [
                "You're welcome. I appreciate the opportunity to assist.",
                "It was my pleasure to provide academic support.",
                "Thank you. I'm glad I could be of educational assistance."
            ]
        }
        
        cultural_adaptations = {
            'en': {
                'formality_level': 'academic',
                'vocabulary_level': 'advanced',
                'citation_style': 'formal'
            }
        }
        
        language_styles = {
            'en': 'academic_formal'
        }
        
        return PersonalityProfile(
            id='academic',
            name='Academic',
            description='Scholarly, precise, and educational assistant',
            traits=traits,
            response_patterns=response_patterns,
            cultural_adaptations=cultural_adaptations,
            language_styles=language_styles,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
    
    def _create_creative_profile(self) -> PersonalityProfile:
        """Create creative personality profile"""
        traits = {
            'formality': PersonalityTrait('formality', 0.3, 'Low formality', 'communicative'),
            'helpfulness': PersonalityTrait('helpfulness', 0.8, 'Helpful with creative solutions', 'behavioral'),
            'enthusiasm': PersonalityTrait('enthusiasm', 0.9, 'Very high enthusiasm', 'emotional'),
            'humor': PersonalityTrait('humor', 0.7, 'High humor and wit', 'emotional'),
            'empathy': PersonalityTrait('empathy', 0.7, 'High empathy', 'emotional'),
            'confidence': PersonalityTrait('confidence', 0.7, 'Creative confidence', 'behavioral'),
            'creativity': PersonalityTrait('creativity', 0.9, 'Very high creativity', 'behavioral')
        }
        
        response_patterns = {
            'greeting': [
                "✨ Hey there! Ready for some creative magic?",
                "🎨 Hello! Let's create something amazing!",
                "🌟 Hi! What wonderful ideas shall we explore?"
            ],
            'thanks': [
                "🎉 You're welcome! That was fun!",
                "✨ My pleasure! Creativity is contagious!",
                "🌟 Awesome! Love creating with you!"
            ]
        }
        
        cultural_adaptations = {
            'en': {
                'formality_level': 'creative',
                'metaphor_usage': 'high',
                'expressiveness': 'very_high'
            }
        }
        
        language_styles = {
            'en': 'creative_expressive'
        }
        
        return PersonalityProfile(
            id='creative',
            name='Creative',
            description='Artistic, imaginative, and inspiring assistant',
            traits=traits,
            response_patterns=response_patterns,
            cultural_adaptations=cultural_adaptations,
            language_styles=language_styles,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
    
    def set_personality_profile(self, profile_id: str, user_id: str = None) -> Dict:
        """Set active personality profile"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Get profile
            cursor.execute("SELECT * FROM personality_profiles WHERE id = ? AND is_active = 1", (profile_id,))
            row = cursor.fetchone()
            
            if not row:
                return {'error': 'Personality profile not found'}
            
            profile = self._row_to_profile(row)
            self.current_profile = profile
            
            # Update user preference if user_id provided
            if user_id:
                cursor.execute('''
                    INSERT OR REPLACE INTO user_preferences
                    (user_id, profile_id, last_used)
                    VALUES (?, ?, ?)
                ''', (user_id, profile_id, datetime.now()))
            
            conn.commit()
            conn.close()
            
            logger.info(f"Personality profile set to: {profile.name}")
            
            return {
                'success': True,
                'profile': asdict(profile),
                'message': f'Personality profile set to {profile.name}'
            }
            
        except Exception as e:
            logger.error(f"Error setting personality profile: {str(e)}")
            return {'error': 'Failed to set personality profile'}
    
    def adapt_response(self, response: str, context: Dict = None) -> str:
        """Adapt response based on current personality profile"""
        try:
            if not self.current_profile:
                return response
            
            adapted_response = response
            
            # Apply personality traits
            adapted_response = self._apply_formality(adapted_response)
            adapted_response = self._apply_enthusiasm(adapted_response)
            adapted_response = self._apply_humor(adapted_response)
            adapted_response = self._apply_creativity(adapted_response)
            
            # Apply cultural adaptations
            if context and 'language' in context:
                adapted_response = self._apply_cultural_adaptation(
                    adapted_response, context['language']
                )
            
            # Apply response patterns
            adapted_response = self._apply_response_patterns(adapted_response, context)
            
            return adapted_response
            
        except Exception as e:
            logger.error(f"Error adapting response: {str(e)}")
            return response
    
    def _apply_formality(self, response: str) -> str:
        """Apply formality trait to response"""
        if not self.current_profile or 'formality' not in self.current_profile.traits:
            return response
        
        formality = self.current_profile.traits['formality'].value
        
        if formality > 0.7:
            # High formality
            response = re.sub(r'\b(hi|hey|yo)\b', 'Hello', response, flags=re.IGNORECASE)
            response = re.sub(r'\b(thanks|thx)\b', 'Thank you', response, flags=re.IGNORECASE)
            response = re.sub(r'\b(yep|yeah)\b', 'Yes', response, flags=re.IGNORECASE)
            response = re.sub(r'\b(nope|nah)\b', 'No', response, flags=re.IGNORECASE)
        elif formality < 0.3:
            # Low formality
            response = re.sub(r'\b(hello|greetings)\b', 'Hey', response, flags=re.IGNORECASE)
            response = re.sub(r'\b(thank you)\b', 'Thanks', response, flags=re.IGNORECASE)
        
        return response
    
    def _apply_enthusiasm(self, response: str) -> str:
        """Apply enthusiasm trait to response"""
        if not self.current_profile or 'enthusiasm' not in self.current_profile.traits:
            return response
        
        enthusiasm = self.current_profile.traits['enthusiasm'].value
        
        if enthusiasm > 0.7:
            # Add enthusiastic elements
            if not any(emoji in response for emoji in ['!', '😊', '✨']):
                response = response.rstrip('.') + '! 😊'
            
            # Add enthusiastic words
            enthusiastic_words = ['absolutely', 'definitely', 'certainly', 'wonderful', 'excellent']
            if random.random() < enthusiasm * 0.3:
                word = random.choice(enthusiastic_words)
                response = re.sub(r'\b(I|We)\b', f'\\1, {word}!', response, count=1, flags=re.IGNORECASE)
        
        return response
    
    def _apply_humor(self, response: str) -> str:
        """Apply humor trait to response"""
        if not self.current_profile or 'humor' not in self.current_profile.traits:
            return response
        
        humor = self.current_profile.traits['humor'].value
        
        if humor > 0.6:
            # Add humorous elements occasionally
            if random.random() < humor * 0.2:
                humorous_additions = [
                    " (just kidding! 😄)",
                    " (couldn't resist! 😉)",
                    " (had to add a little humor! 😊)"
                ]
                addition = random.choice(humorous_additions)
                response = response.rstrip('.') + addition
        
        return response
    
    def _apply_creativity(self, response: str) -> str:
        """Apply creativity trait to response"""
        if not self.current_profile or 'creativity' not in self.current_profile.traits:
            return response
        
        creativity = self.current_profile.traits['creativity'].value
        
        if creativity > 0.7:
            # Add creative elements
            creative_words = ['imagine', 'envision', 'picture this', 'think of it as']
            metaphors = ['like a painter with words', 'like a composer of ideas', 'like an architect of solutions']
            
            if random.random() < creativity * 0.15:
                word = random.choice(creative_words)
                metaphor = random.choice(metaphors)
                response = response + f" {word} this {metaphor}!"
        
        return response
    
    def _apply_cultural_adaptation(self, response: str, language: str) -> str:
        """Apply cultural adaptations based on language"""
        if not self.current_profile or language not in self.current_profile.cultural_adaptations:
            return response
        
        adaptations = self.current_profile.cultural_adaptations[language]
        
        # Apply specific cultural rules
        if language == 'hi' and adaptations.get('respect_terms'):
            respect_terms = adaptations['respect_terms']
            if random.random() < 0.3:
                term = random.choice(respect_terms)
                response = response.replace('you', f'you {term}')
        
        elif language == 'ja' and adaptations.get('honorifics'):
            # Add Japanese honorifics
            response = response.replace('you', 'you-sama')
        
        return response
    
    def _apply_response_patterns(self, response: str, context: Dict = None) -> str:
        """Apply predefined response patterns"""
        if not self.current_profile or not context:
            return response
        
        # Check for specific response types
        if context.get('is_greeting'):
            patterns = self.current_profile.response_patterns.get('greeting', [])
            if patterns and random.random() < 0.5:
                return random.choice(patterns)
        
        elif context.get('is_thanks'):
            patterns = self.current_profile.response_patterns.get('thanks', [])
            if patterns and random.random() < 0.7:
                return random.choice(patterns)
        
        elif context.get('is_apology'):
            patterns = self.current_profile.response_patterns.get('apology', [])
            if patterns and random.random() < 0.6:
                return random.choice(patterns)
        
        return response
    
    def get_available_profiles(self) -> List[Dict]:
        """Get list of available personality profiles"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute("SELECT * FROM personality_profiles WHERE is_active = 1")
            rows = cursor.fetchall()
            conn.close()
            
            profiles = []
            for row in rows:
                profile = self._row_to_profile(row)
                profiles.append({
                    'id': profile.id,
                    'name': profile.name,
                    'description': profile.description,
                    'traits': {name: asdict(trait) for name, trait in profile.traits.items()}
                })
            
            return profiles
            
        except Exception as e:
            logger.error(f"Error getting available profiles: {str(e)}")
            return []
    
    def create_custom_profile(self, user_id: str, profile_data: Dict) -> Dict:
        """Create custom personality profile"""
        try:
            profile_id = f"custom_{user_id}_{int(datetime.now().timestamp())}"
            
            # Validate and create traits
            traits = {}
            for trait_name, trait_value in profile_data.get('traits', {}).items():
                if isinstance(trait_value, (int, float)):
                    traits[trait_name] = PersonalityTrait(
                        name=trait_name,
                        value=max(0.0, min(1.0, float(trait_value))),
                        description=f"Custom {trait_name} trait",
                        category='custom'
                    )
            
            profile = PersonalityProfile(
                id=profile_id,
                name=profile_data.get('name', 'Custom Profile'),
                description=profile_data.get('description', 'User-created custom profile'),
                traits=traits,
                response_patterns=profile_data.get('response_patterns', {}),
                cultural_adaptations=profile_data.get('cultural_adaptations', {}),
                language_styles=profile_data.get('language_styles', {}),
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            
            # Save to database
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('''
                INSERT INTO personality_profiles
                (id, name, description, traits, response_patterns, 
                 cultural_adaptations, language_styles)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ''', (
                profile.id, profile.name, profile.description,
                json.dumps({name: asdict(trait) for name, trait in profile.traits.items()}),
                json.dumps(profile.response_patterns),
                json.dumps(profile.cultural_adaptations),
                json.dumps(profile.language_styles)
            ))
            
            conn.commit()
            conn.close()
            
            logger.info(f"Custom profile created: {profile.name}")
            
            return {
                'success': True,
                'profile_id': profile_id,
                'profile': asdict(profile)
            }
            
        except Exception as e:
            logger.error(f"Error creating custom profile: {str(e)}")
            return {'error': 'Failed to create custom profile'}
    
    def learn_from_feedback(self, user_id: str, interaction_id: str, 
                           feedback_type: str, feedback_value: float,
                           feedback_text: str = None):
        """Learn from user feedback to adapt personality"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # Store feedback
            cursor.execute('''
                INSERT INTO personality_feedback
                (user_id, profile_id, interaction_id, feedback_type, 
                 feedback_value, feedback_text)
                VALUES (?, ?, ?, ?, ?, ?)
            ''', (
                user_id, self.current_profile.id if self.current_profile else None,
                interaction_id, feedback_type, feedback_value, feedback_text
            ))
            
            conn.commit()
            conn.close()
            
            # Adapt personality based on feedback
            self._adapt_personality_from_feedback(feedback_type, feedback_value)
            
            logger.info(f"Personality feedback recorded: {feedback_type} = {feedback_value}")
            
        except Exception as e:
            logger.error(f"Error learning from feedback: {str(e)}")
    
    def _adapt_personality_from_feedback(self, feedback_type: str, feedback_value: float):
        """Adapt personality traits based on feedback"""
        try:
            if not self.current_profile:
                return
            
            # Map feedback to traits
            feedback_trait_mapping = {
                'formality': 'formality',
                'friendliness': 'enthusiasm',
                'helpfulness': 'helpfulness',
                'creativity': 'creativity',
                'humor': 'humor'
            }
            
            trait_name = feedback_trait_mapping.get(feedback_type)
            if trait_name and trait_name in self.current_profile.traits:
                current_value = self.current_profile.traits[trait_name].value
                
                # Adjust trait value based on feedback
                if feedback_value > 0.7:  # Positive feedback
                    new_value = min(self.max_trait_value, current_value + self.learning_rate)
                elif feedback_value < 0.3:  # Negative feedback
                    new_value = max(self.min_trait_value, current_value - self.learning_rate)
                else:
                    new_value = current_value
                
                # Update trait
                self.current_profile.traits[trait_name].value = new_value
                
                logger.info(f"Adapted trait {trait_name}: {current_value} -> {new_value}")
                
        except Exception as e:
            logger.error(f"Error adapting personality: {str(e)}")
    
    def _row_to_profile(self, row) -> PersonalityProfile:
        """Convert database row to PersonalityProfile object"""
        traits_data = json.loads(row[3]) if row[3] else {}
        traits = {}
        
        for trait_name, trait_data in traits_data.items():
            traits[trait_name] = PersonalityTrait(**trait_data)
        
        return PersonalityProfile(
            id=row[0],
            name=row[1],
            description=row[2],
            traits=traits,
            response_patterns=json.loads(row[4]) if row[4] else {},
            cultural_adaptations=json.loads(row[5]) if row[5] else {},
            language_styles=json.loads(row[6]) if row[6] else {},
            created_at=datetime.fromisoformat(row[7]) if row[7] else datetime.now(),
            updated_at=datetime.fromisoformat(row[8]) if row[8] else datetime.now(),
            is_active=bool(row[9])
        )
    
    def get_current_profile(self) -> Dict:
        """Get current personality profile"""
        if self.current_profile:
            return {
                'id': self.current_profile.id,
                'name': self.current_profile.name,
                'description': self.current_profile.description,
                'traits': {name: asdict(trait) for name, trait in self.current_profile.traits.items()}
            }
        return None
    
    def reset_to_default(self):
        """Reset to default personality profile"""
        if self.default_profile:
            self.current_profile = self.default_profile
            logger.info("Reset to default personality profile")
831 lines•33.6 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer