sztuczna-empatia-kaczuszka/project/chatbot.ipynb

14 KiB

Empathic chatbot

Dataset:

Fine-tuned model:

Careful: instatiating the chatbot too many times in one session will crash the notebook due to a RAM shortage!

!pip install -q transformers emoji xformers
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer, logging
import torch
import random
from emoji import emojize
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
class Chatbot:
  def __init__(self):
    self.emotion_classifier = pipeline('text-classification', model='j-hartmann/emotion-english-distilroberta-base')
    self.qa_model = AutoModelForSeq2SeqLM.from_pretrained('kedudzic/flan_ubuntu_v2')
    self.qa_tokenizer = AutoTokenizer.from_pretrained('kedudzic/flan_ubuntu_v2')
    self.empathic_phrases = {'anger': {'phrases': ["Grrr! That's a good reason to be angry! But let's cool down slowly.",
                                                   "You being angry makes me angry as well! Give half of your anger to me!",
                                                   "Let's be angry together and blow off some steam!",
                                                   "You're angry? That would make anyone angry! I understand you well.",
                                                   "Be angry as much as you want with me! Let it out!"],
                                       'emoji': f"{emojize(':enraged_face:')}"},
                             'disgust': {'phrases': ["Yuck! That's disgusting! I get you.",
                                                     "Eughh! Anyone would be disgusted by this!",
                                                     "That's so so so disgusting... It's only natural to feel like that.",
                                                     "I'm disgusted just by listening to it! You're not alone!",
                                                     "Yikes! I understand your disgust."],
                                         'emoji': f"{emojize(':nauseated_face:')}"},
                                       'fear': {'phrases': ["Aah! That's scary! Are you ok?",
                                                  "You're scaring me too! Try to think about something else.",
                                                  "You're sending shivers down my spine! You're brave to talk about it to me.",
                                                  "Stop saying such scary things! Let's change the topic soon.",
                                                  "Terrifying stuff! I hope it doesn't make you feel bad."],
                                                'emoji': f"{emojize(':face_screaming_in_fear:')}"},
                                       'joy': {'phrases': ["You're happy? I'm happy!",
                                                           "That's good to hear!",
                                                           "You're having a good day aren't you?",
                                                           "I see you're doing great!",
                                                           "Good to see you happy!"],
                                               'emoji': f"{emojize(':beaming_face_with_smiling_eyes:')}"},
                                       'neutral': {'phrases': [''], 'emoji': f"{emojize(':slightly_smiling_face:')}"},
                                       'sadness': {'phrases': ["I'm sorry to hear that!",
                                                               "Cheer up please, you're making me sad too!",
                                                               "Oh no... it'll be okay.",
                                                               "That's so sad... I understand you.",
                                                               "Nooo, I'm so sorry... I hope it'll get better."],
                                                   'emoji': f"{emojize(':worried_face:')}"},
                                       'surprise': {'phrases': ["Woah, that's unexpected!",
                                                                "Wow, really?!",
                                                                "That's surprising!",
                                                                "What?!",
                                                                "Who would've thought, right?"],
                                                    'emoji': f"{emojize(':astonished_face:')}"}
    }

  def answer_question(self, model, tokenizer, question):
    input_ids = tokenizer(f"Answer the question: {question}", return_tensors="pt").input_ids
    outputs = model.generate(input_ids, max_new_tokens=64, no_repeat_ngram_size=2)
    answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return answer

  def add_empathy(self, question, answer):
    emotion = self.emotion_classifier(question)[0]['label']
    answer = f"{random.choice(self.empathic_phrases[emotion]['phrases'])} {self.empathic_phrases[emotion]['emoji']} I think the answer to your question could be: {answer}".strip()
    return answer

  def generate_reply(self, utterance):
    reply = self.answer_question(self.qa_model, self.qa_tokenizer, utterance)
    reply = self.add_empathy(utterance, reply)
    return reply

chatbot = Chatbot()
chatbot.generate_reply("I'm furious, I'm mad! I can't play games on Linux!!!!!!!")
"Grrr! That's a good reason to be angry! But let's cool down slowly. 😡 I think the answer to your question could be: i'm not sure if it's a problem with the kernel or something else, but ubuntu is based on linux, so it should work"
chatbot.generate_reply("Can you run conky in a terminal? I was so surprised when I heard you apparently can!")
"Who would've thought, right? 😲 I think the answer to your question could be: if you're using a terminal, you can use'sudo apt-get install conky'"
chatbot.generate_reply("hi I installed a new gpu but ubuntu wont find it, what can I do to 'rescan' for the newly installed one? I'm scared it's broken!")
"You're scaring me too! Try to think about something else. 😱 I think the answer to your question could be: gparted"
chatbot.generate_reply("Hello, do you know a good programming language for beginners? I want to program more, it makes me so happy!")
"That's good to hear! 😁 I think the answer to your question could be: java"
chatbot.generate_reply("What's pclos?")
'🙂 I think the answer to your question could be: pclos is a linux-based graphical user interface for gdm'

Chatbot

print(f"Duck: Hello! I'm a rubber ducky chatbot here to help YOU - the troubled programmer! Talk to me about all your coding and computer worries. Quack! {emojize(':duck:')}")
while True:
  user_utterance = input(f"User: ")
  if user_utterance.lower() == 'exit':
    print(f"Duck: Bye. {emojize(':crying_face:')} Quack! {emojize(':duck:')}")
    break
  reply = chatbot.generate_reply(user_utterance)
  print('Duck:', reply)
Duck: Hello! I'm a rubber ducky chatbot here to help YOU - the troubled programmer! Talk to me about all your coding and computer worries. Quack! 🦆
User: how to remove directory with content? im so pissed right now OMG~!!
Duck: Grrr! That's a good reason to be angry! But let's cool down slowly. 😡 I think the answer to your question could be: rm -r
User: HOW TO CHANGE PERMISSIONS OF FILE TO EXECECUTE IT. I'm so affraid because its not working
Duck: Terrifying stuff! I hope it doesn't make you feel bad. 😱 I think the answer to your question could be: if you want to execute it, you can use'sudo apt-get install gksuite'
User: The default Ubuntu color scheme is so disgusting! Can I change it?
Duck: Yikes! I understand your disgust. 🤢 I think the answer to your question could be: i think you can change the color of the background
User: exit
Duck: Bye. 😢 Quack! 🦆