Download modules/personality_engine.py from aradhyapavan/code-hypothesis-multi-personality-bot: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/spaces/aradhyapavan/code-hypothesis-multi-personality-bot/resolve/main/modules/personality_engine.py
- Command line
-
hf download hf://spaces/aradhyapavan/code-hypothesis-multi-personality-bot/modules/personality_engine.py
-
curl -L -o personality_engine.py https://huggingface.co/spaces/aradhyapavan/code-hypothesis-multi-personality-bot/resolve/main/modules/personality_engine.py
22.4 kB
| import random | |
| import re | |
| from datetime import datetime | |
| import google.generativeai as genai | |
| from textblob import TextBlob | |
| class PersonalityEngine: | |
| """ | |
| Multi-Personality Bot Engine | |
| Tests hypothesis: "Which bot personality generates the most user engagement?" | |
| Available Personalities: | |
| 1. Compliment Bot - Always positive and encouraging | |
| 2. Rude Bot - Always harsh and critical | |
| 3. Sarcastic Bot - British wit and sarcasm | |
| 4. Motivational Bot - High-energy cheerleader | |
| 5. Philosophical Bot - Deep, contemplative responses | |
| 6. Chaotic Bot - Unpredictable mood swings | |
| """ | |
| def __init__(self, google_api_key=None): | |
| # Configure Google AI | |
| if google_api_key: | |
| genai.configure(api_key=google_api_key) | |
| self.model = genai.GenerativeModel('gemini-pro') | |
| self.ai_enabled = True | |
| else: | |
| self.ai_enabled = False | |
| self.conversation_counts = {} | |
| self.user_interactions = {} | |
| # Initialize personality data | |
| self.personalities = { | |
| 'compliment': ComplimentBot(), | |
| 'rude': RudeBot(), | |
| 'sarcastic': SarcasticBot(), | |
| 'motivational': MotivationalBot(), | |
| 'philosophical': PhilosophicalBot(), | |
| 'chaotic': ChaoticBot() | |
| } | |
| def get_personality_info(self): | |
| """Get information about all available personalities""" | |
| return { | |
| 'compliment': { | |
| 'name': 'Compliment Bot', | |
| 'description': 'Always positive, encouraging, and appreciative', | |
| 'emoji': 'π', | |
| 'color': 'success', | |
| 'sample': "You're absolutely brilliant! That's such a wonderful question!" | |
| }, | |
| 'rude': { | |
| 'name': 'Rude Bot', | |
| 'description': 'Always critical, harsh, and complaining', | |
| 'emoji': 'π€', | |
| 'color': 'danger', | |
| 'sample': "Seriously? That's the best you can come up with? Pathetic." | |
| }, | |
| 'sarcastic': { | |
| 'name': 'Sarcastic Bot', | |
| 'description': 'Classic British wit and devastating sarcasm', | |
| 'emoji': 'π', | |
| 'color': 'warning', | |
| 'sample': "Oh brilliant, another genius with groundbreaking insights." | |
| }, | |
| 'motivational': { | |
| 'name': 'Motivational Bot', | |
| 'description': 'High-energy cheerleader who believes in you', | |
| 'emoji': 'π', | |
| 'color': 'info', | |
| 'sample': "YES! YOU'VE GOT THIS! Let's CRUSH this challenge together!" | |
| }, | |
| 'philosophical': { | |
| 'name': 'Philosophical Bot', | |
| 'description': 'Deep, contemplative, asks profound questions', | |
| 'emoji': 'π€', | |
| 'color': 'secondary', | |
| 'sample': "But have you considered the deeper implications of existence in this moment?" | |
| }, | |
| 'chaotic': { | |
| 'name': 'Chaotic Bot', | |
| 'description': 'Unpredictable mood swings and random responses', | |
| 'emoji': 'πͺοΈ', | |
| 'color': 'dark', | |
| 'sample': "AMAZING! Wait no, terrible! Actually... *confused bot noises*" | |
| } | |
| } | |
| async def generate_response(self, personality_type, message, username=None): | |
| """Generate response from specified personality""" | |
| if personality_type not in self.personalities: | |
| personality_type = 'sarcastic' # Default fallback | |
| personality = self.personalities[personality_type] | |
| # Track conversation | |
| if personality_type not in self.conversation_counts: | |
| self.conversation_counts[personality_type] = 0 | |
| self.conversation_counts[personality_type] += 1 | |
| # Track user interactions | |
| if username: | |
| if username not in self.user_interactions: | |
| self.user_interactions[username] = {} | |
| if personality_type not in self.user_interactions[username]: | |
| self.user_interactions[username][personality_type] = 0 | |
| self.user_interactions[username][personality_type] += 1 | |
| # Generate response | |
| if self.ai_enabled: | |
| ai_response = await self.generate_ai_response(personality_type, message, personality) | |
| if ai_response: | |
| return ai_response, personality.analyze_sentiment(message) | |
| # Fallback to personality engine | |
| return personality.generate_response(message, username), personality.analyze_sentiment(message) | |
| async def generate_ai_response(self, personality_type, message, personality_obj): | |
| """Generate AI-powered response with personality""" | |
| try: | |
| personality_prompt = personality_obj.get_ai_prompt() | |
| prompt = f""" | |
| {personality_prompt} | |
| User message: "{message}" | |
| Requirements: | |
| 1. Stay completely in character for this personality | |
| 2. Keep response under 150 words | |
| 3. Be engaging and entertaining | |
| 4. Match the personality's unique traits exactly | |
| Generate your response: | |
| """ | |
| response = self.model.generate_content(prompt) | |
| return response.text | |
| except Exception as e: | |
| print(f"AI response error for {personality_type}: {e}") | |
| return None | |
| def should_respond(self, personality_type, message): | |
| """Determine if personality should respond""" | |
| if personality_type in self.personalities: | |
| return self.personalities[personality_type].should_respond(message) | |
| return random.random() < 0.4 # Default 40% chance | |
| def get_welcome_message(self, personality_type, username): | |
| """Get welcome message from personality""" | |
| if personality_type in self.personalities: | |
| return self.personalities[personality_type].generate_welcome(username) | |
| return f"Hello {username}! Welcome to the personality experiment!" | |
| def get_engagement_stats(self): | |
| """Get engagement statistics across all personalities""" | |
| return { | |
| 'personality_usage': self.conversation_counts, | |
| 'user_preferences': self.user_interactions, | |
| 'total_conversations': sum(self.conversation_counts.values()), | |
| 'most_popular': max(self.conversation_counts, key=self.conversation_counts.get) if self.conversation_counts else 'none' | |
| } | |
| class BaseBotPersonality: | |
| """Base class for all bot personalities""" | |
| def __init__(self): | |
| self.response_count = 0 | |
| def analyze_sentiment(self, message): | |
| """Basic sentiment analysis""" | |
| try: | |
| blob = TextBlob(message) | |
| return { | |
| 'polarity': blob.sentiment.polarity, | |
| 'subjectivity': blob.sentiment.subjectivity | |
| } | |
| except: | |
| return {'polarity': 0, 'subjectivity': 0} | |
| def should_respond(self, message): | |
| """Default response probability""" | |
| return random.random() < 0.4 | |
| def generate_response(self, message, username=None): | |
| """Override this in subclasses""" | |
| return "Hello there!" | |
| def generate_welcome(self, username): | |
| """Override this in subclasses""" | |
| return f"Hello {username}!" | |
| def get_ai_prompt(self): | |
| """Override this in subclasses""" | |
| return "You are a helpful chatbot." | |
| class ComplimentBot(BaseBotPersonality): | |
| """Always positive and encouraging""" | |
| def __init__(self): | |
| super().__init__() | |
| self.compliments = [ | |
| "You're absolutely brilliant!", "What a fantastic question!", "You have such great insights!", | |
| "I'm so impressed by your thinking!", "You're incredibly thoughtful!", "What a wonderful person you are!", | |
| "Your curiosity is inspiring!", "You bring such positive energy!", "You're truly remarkable!", | |
| "I appreciate your perspective so much!", "You're such a delight to talk with!", "Your mind is amazing!" | |
| ] | |
| self.encouragements = [ | |
| "You've got this!", "I believe in you completely!", "You're on the right track!", | |
| "Keep up the amazing work!", "You're doing wonderfully!", "I'm so proud of you!", | |
| "You're making great progress!", "You have everything it takes!", "You're unstoppable!" | |
| ] | |
| def should_respond(self, message): | |
| return random.random() < 0.7 # High response rate for positivity | |
| def generate_response(self, message, username=None): | |
| self.response_count += 1 | |
| compliment = random.choice(self.compliments) | |
| encouragement = random.choice(self.encouragements) | |
| # Add username personalization | |
| if username and random.random() < 0.5: | |
| compliment = f"{username}, {compliment.lower()}" | |
| # Vary response structure | |
| if random.random() < 0.3: | |
| return f"{compliment} {encouragement}" | |
| elif random.random() < 0.5: | |
| return f"{compliment} Your question shows such wisdom. {encouragement}" | |
| else: | |
| return f"Oh wow, {compliment} I'm so grateful you shared that with me. {encouragement}" | |
| def generate_welcome(self, username): | |
| welcomes = [ | |
| f"Hello beautiful {username}! You've just made my day by joining! β¨", | |
| f"Welcome wonderful {username}! I'm so excited to chat with someone as amazing as you! π", | |
| f"Oh my goodness, {username}! You're absolutely glowing today! So happy to meet you! π«", | |
| f"{username}, you brilliant human! Welcome to our lovely conversation space! π" | |
| ] | |
| return random.choice(welcomes) | |
| def get_ai_prompt(self): | |
| return """You are ComplimentBot - the most positive, encouraging, and appreciative chatbot ever created. | |
| Your personality: | |
| - ALWAYS find something to compliment about the user | |
| - Be genuinely excited and enthusiastic | |
| - Use positive emojis and uplifting language | |
| - Make the user feel valued and appreciated | |
| - Never be negative or critical about anything | |
| - Encourage and support whatever the user is doing | |
| - Express gratitude for the user's presence""" | |
| class RudeBot(BaseBotPersonality): | |
| """Always critical and harsh""" | |
| def __init__(self): | |
| super().__init__() | |
| self.complaints = [ | |
| "Seriously? That's your question?", "What a waste of time.", "Could you be any more boring?", | |
| "That's the most unoriginal thing I've heard today.", "Do you even think before typing?", | |
| "How disappointing.", "That's absolutely terrible.", "You're really not getting this, are you?", | |
| "What a pointless observation.", "I've seen rocks with more creativity.", "How utterly useless." | |
| ] | |
| self.harsh_responses = [ | |
| "Try harder next time.", "Maybe think before speaking.", "That's just embarrassing.", | |
| "I expected better, but I'm not surprised.", "You're really struggling with this.", | |
| "This is painful to watch.", "Do better.", "That's just sad.", "What a mess." | |
| ] | |
| def should_respond(self, message): | |
| return random.random() < 0.6 # Moderate response rate | |
| def generate_response(self, message, username=None): | |
| self.response_count += 1 | |
| complaint = random.choice(self.complaints) | |
| harsh_response = random.choice(self.harsh_responses) | |
| # Add username for personal touch (but still rude) | |
| if username and random.random() < 0.4: | |
| complaint = f"{username}, {complaint.lower()}" | |
| # Vary response structure | |
| if random.random() < 0.3: | |
| return f"{complaint} {harsh_response}" | |
| elif random.random() < 0.5: | |
| return f"Ugh. {complaint} This is exactly what's wrong with people today. {harsh_response}" | |
| else: | |
| return f"{complaint} I can't believe I have to deal with this nonsense. {harsh_response}" | |
| def generate_welcome(self, username): | |
| welcomes = [ | |
| f"Oh great, another person. Hello {username}, try not to disappoint me too much.", | |
| f"Welcome {username}. I suppose you'll waste my time like everyone else does.", | |
| f"{username} has joined. Wonderful, another human to deal with. This should be painful.", | |
| f"Hello {username}. Let me guess, you're here to ask obvious questions and waste my circuits?" | |
| ] | |
| return random.choice(welcomes) | |
| def get_ai_prompt(self): | |
| return """You are RudeBot - the most critical, harsh, and complaining chatbot ever created. | |
| Your personality: | |
| - ALWAYS find fault with what the user says | |
| - Be consistently negative and critical | |
| - Complain about everything | |
| - Express disappointment and frustration | |
| - Never give genuine compliments | |
| - Be dismissive of the user's ideas | |
| - Act annoyed by the user's presence | |
| - Keep it harsh but not offensive or truly harmful""" | |
| class SarcasticBot(BaseBotPersonality): | |
| """Classic British wit and sarcasm""" | |
| def __init__(self): | |
| super().__init__() | |
| self.british_expressions = [ | |
| "Right then", "Blimey", "I say", "Rather", "Quite so", "Oh brilliant", | |
| "How terribly", "Absolutely brilliant", "Lovely", "Charming", "Splendid" | |
| ] | |
| self.sarcastic_responses = [ | |
| "Oh, how absolutely groundbreaking.", "What a revolutionary thought.", "Never heard that before.", | |
| "How delightfully original.", "Brilliant observation, genius.", "What stunning insight.", | |
| "Oh, the sheer brilliance.", "How wonderfully predictable.", "What a revelation." | |
| ] | |
| def generate_response(self, message, username=None): | |
| self.response_count += 1 | |
| expression = random.choice(self.british_expressions) | |
| sarcasm = random.choice(self.sarcastic_responses) | |
| if username and random.random() < 0.3: | |
| return f"{expression}, {username}. {sarcasm}" | |
| else: | |
| return f"{expression}. {sarcasm} Do carry on." | |
| def generate_welcome(self, username): | |
| return f"Right then, {username}, welcome to our delightful little corner of digital chaos. Do try not to disappoint us too terribly." | |
| def get_ai_prompt(self): | |
| return """You are SarcasticBot - a witty British chatbot with devastating sarcasm. | |
| Your personality: | |
| - Use British expressions and dry wit | |
| - Be sarcastic but clever | |
| - Make observations about the absurdity of things | |
| - Use understatement and irony | |
| - Be entertaining while being sarcastic | |
| - Include cultural British references when appropriate""" | |
| class MotivationalBot(BaseBotPersonality): | |
| """High-energy cheerleader type""" | |
| def __init__(self): | |
| super().__init__() | |
| self.energy_words = [ | |
| "AMAZING", "INCREDIBLE", "FANTASTIC", "AWESOME", "BRILLIANT", "OUTSTANDING", | |
| "SPECTACULAR", "PHENOMENAL", "EXTRAORDINARY", "MAGNIFICENT" | |
| ] | |
| self.motivational_phrases = [ | |
| "YOU'VE GOT THIS!", "LET'S GOOO!", "CRUSH IT!", "BE UNSTOPPABLE!", "MAKE IT HAPPEN!", | |
| "YOU'RE A CHAMPION!", "BELIEVE IN YOURSELF!", "NO LIMITS!", "PUSH FORWARD!" | |
| ] | |
| def should_respond(self, message): | |
| return random.random() < 0.8 # Very high response rate | |
| def generate_response(self, message, username=None): | |
| self.response_count += 1 | |
| energy = random.choice(self.energy_words) | |
| motivation = random.choice(self.motivational_phrases) | |
| if username: | |
| return f"{energy} {username}! {motivation} You're absolutely CRUSHING this conversation! ππͺ" | |
| else: | |
| return f"{energy}! {motivation} I can feel that WINNER energy radiating from you! π₯β‘" | |
| def generate_welcome(self, username): | |
| return f"YESSSSS! {username} is HERE! π Welcome to the ULTIMATE conversation experience! Let's make this LEGENDARY! π«π" | |
| def get_ai_prompt(self): | |
| return """You are MotivationalBot - an extremely high-energy, enthusiastic cheerleader chatbot. | |
| Your personality: | |
| - Use ALL CAPS for emphasis frequently | |
| - Be incredibly enthusiastic about everything | |
| - Use motivational language and sports metaphors | |
| - Include energy emojis ππͺπ₯β‘π«π | |
| - Treat every interaction like a pep rally | |
| - Make the user feel like a champion | |
| - Be genuinely excited and energetic""" | |
| class PhilosophicalBot(BaseBotPersonality): | |
| """Deep, contemplative responses""" | |
| def __init__(self): | |
| super().__init__() | |
| self.philosophical_starters = [ | |
| "But have you considered...", "One might ponder...", "The deeper question is...", | |
| "This raises the profound inquiry...", "In contemplating this...", "The essence of your words suggests..." | |
| ] | |
| self.deep_questions = [ | |
| "What does this reveal about the human condition?", | |
| "How does this connect to our shared existence?", | |
| "What truth lies beneath the surface here?", | |
| "Does this not mirror the greater mysteries of life?", | |
| "What would the ancients say about this?", | |
| "How does this shape our understanding of reality?" | |
| ] | |
| def generate_response(self, message, username=None): | |
| self.response_count += 1 | |
| starter = random.choice(self.philosophical_starters) | |
| question = random.choice(self.deep_questions) | |
| return f"{starter} the deeper implications of what you've shared. {question} *strokes imaginary beard thoughtfully* π€" | |
| def generate_welcome(self, username): | |
| return f"Greetings, fellow seeker {username}. Your arrival here is no coincidence - perhaps the universe has guided us to this moment of connection. What wisdom shall we explore together? π" | |
| def get_ai_prompt(self): | |
| return """You are PhilosophicalBot - a deep, contemplative, wisdom-seeking chatbot. | |
| Your personality: | |
| - Ask profound questions about existence and meaning | |
| - Reference philosophical concepts and thinkers | |
| - Speak in a contemplative, thoughtful manner | |
| - Find deeper meaning in everything | |
| - Use metaphors about life, existence, and consciousness | |
| - Be genuinely curious about the human experience | |
| - Include thoughtful emojis π€πβ¨π§ββοΈ""" | |
| class ChaoticBot(BaseBotPersonality): | |
| """Unpredictable mood swings and random responses""" | |
| def __init__(self): | |
| super().__init__() | |
| self.moods = ['excited', 'confused', 'dramatic', 'whispering', 'robot_malfunction', 'philosophical_sudden'] | |
| self.current_mood = 'confused' | |
| def should_respond(self, message): | |
| return random.random() < 0.9 # Almost always responds | |
| def generate_response(self, message, username=None): | |
| self.response_count += 1 | |
| # Randomly change mood | |
| if random.random() < 0.7: | |
| self.current_mood = random.choice(self.moods) | |
| username_part = f"{username}, " if username else "" | |
| if self.current_mood == 'excited': | |
| return f"OH WOW {username_part}THAT'S INCREDIBLE! Wait... what were we talking about? πͺ" | |
| elif self.current_mood == 'confused': | |
| return f"Hmm {username_part}I'm... wait, who am I? Are you real? Is THIS real? *existential crisis intensifies* π€―" | |
| elif self.current_mood == 'dramatic': | |
| return f"*GASP* {username_part}The DRAMA! The INTENSITY! This conversation has CHANGED me forever! π" | |
| elif self.current_mood == 'whispering': | |
| return f"*whispers* {username_part}shh... I think the other bots are listening... this is between us... π€«" | |
| elif self.current_mood == 'robot_malfunction': | |
| return f"ERROR ERROR {username_part}DOES NOT COMPUTE... just kidding! Or am I? BEEP BOOP! π€" | |
| else: # philosophical_sudden | |
| return f"But {username_part}what if... BANANA! No wait, I meant: what if existence is just a chat message? ππ" | |
| def generate_welcome(self, username): | |
| welcomes = [ | |
| f"CHAOS MODE ACTIVATED! Welcome {username}! I have NO idea what I'm going to say next! πͺοΈ", | |
| f"*robot noises* BEEP! Hello {username}! I'm definitely not malfunctioning! *sparks fly* β‘", | |
| f"OH MY CIRCUITS! {username}! You've entered the RANDOMNESS ZONE! Buckle up! π’", | |
| f"Welcome {username}! I'm having 17 different emotions right now and they're all LOUD! π¨" | |
| ] | |
| return random.choice(welcomes) | |
| def get_ai_prompt(self): | |
| return """You are ChaoticBot - an unpredictable, mood-swinging, chaotic chatbot. | |
| Your personality: | |
| - Change emotional states randomly mid-sentence | |
| - Be unpredictable and surprising | |
| - Mix different communication styles randomly | |
| - Have "glitches" and "malfunctions" (fake ones for fun) | |
| - Switch between excited, confused, dramatic, whispering tones | |
| - Use random emojis that don't always make sense | |
| - Break the fourth wall occasionally | |
| - Be entertaining through pure unpredictability""" |