Skip to content

Commit

Permalink
chatbot v.1
Browse files Browse the repository at this point in the history
  • Loading branch information
Claire Tolan committed Jun 23, 2021
1 parent 89f31f0 commit e2b6477
Show file tree
Hide file tree
Showing 33 changed files with 1,784 additions and 146 deletions.
45 changes: 37 additions & 8 deletions server/assistant/Brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ def __init__(self, online=True):
self.load_skill(skills_root_dir, 'spotify')
self.load_skill(skills_root_dir, 'youtube')
self.load_skill(skills_root_dir, 'tea')
self.load_skill(skills_root_dir, 'Menu')
self.load_skill(skills_root_dir, 'Personality')
self.load_skill(skills_root_dir, 'asmr')
self.load_skill(skills_root_dir, 'soother')

if online:
from RecordingsDatabase import RecordingsDatabase
Expand All @@ -33,6 +37,9 @@ def __init__(self, online=True):
initialize_skills_database_task.delay(self.list_skills())


def get_skill_instance(self, skill_name):
instance = self.skills[skillName]
return instance

def load_skill(self, skills_root_dir, skillname, active=True):
skill_python_module = importlib.import_module('skills.%s.%s' % (skillname, skillname))
Expand All @@ -53,7 +60,22 @@ def list_skills(self):
def get_unrecorded_sentence(self, uid):
return self.mysql_db.select_random_unrecorded_sentence(uid)

@cherrypy.expose

def handle_from_skill(self, text):
best_key, best_intent = self.determine_intent(text)
if best_key is not None:
cherrypy.log("BEST KEY")
cherrypy.log(best_key)
if len(best_key) > 0:
cherrypy.session["activeSkill"] = best_key


latitude=53.2303869
longitude=-4.1299242
if best_intent is not None:
return self.handle_intent(best_key, best_intent, text, latitude, longitude)


def handle(self, text, latitude=0.0, longitude=0.0):
# Bangor, Gwynedd
cherrypy.log('alpha')
Expand All @@ -62,29 +84,36 @@ def handle(self, text, latitude=0.0, longitude=0.0):
longitude=-4.1299242


if 'activeSkill' not in cherrypy.session:
if 'activeSkill' not in cherrypy.session or cherrypy.session['activeSkill'] is None:
best_key, best_intent = self.determine_intent(text)
if best_key is not None:
cherrypy.log(best_key)

if(self.skills[best_key].get_context()):
if len(best_key) > 0:
cherrypy.session["activeSkill"] = best_key

else:
currentSkill = cherrypy.session["activeSkill"]
cherrypy.log(currentSkill)
best_key, best_intent = self.determine_contextual_intent(text, currentSkill)

if best_intent:
if best_intent is not None:
skill_result=self.handle_intent(best_key, best_intent, text, latitude, longitude)
return cherrypy.session["activeSkill"], skill_result
return best_key, skill_result
else:
return '', None
return 'Sorry we could not find a match!', None


def handle_intent(self, handler_key, intent, text, latitude, longitude):
return self.skills[handler_key].handle(intent, text, latitude, longitude)

if(self.skills[handler_key].hasContext):
if handler_key == "Menu_skill":
ContextManager = self.skills["Personality_skill"].ContextManager
return self.skills[handler_key].handle(text, cManager=ContextManager)
else:
return self.skills[handler_key].handle(text)
else:
return self.skills[handler_key].handle_no_context(intent, text, latitude, longitude)

def determine_contextual_intent(self, text, skillName):

skillInstance = self.skills[skillName]
Expand Down
30 changes: 30 additions & 0 deletions server/assistant/Engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from adapt.engine import IntentDeterminationEngine
import cherrypy

# Create adapt engine
def create_engine(engineEntities):
"""
Returns an Adapt engine.
"""
engine = IntentDeterminationEngine()

# Register entities on engine
if engineEntities["entities"]:
cherrypy.log("ENTITIES")
for entity, keywords in engineEntities["entities"].items():
for keyword in keywords:
engine.register_entity(keyword, entity)

if engineEntities["single_regex_entities"]:
cherrypy.log("SINGLE REG ENT")
for entity in engineEntities["single_regex_entities"]:
engine.register_regex_entity(entity)

# Register intents on engine
if engineEntities["skill_intents"]:
cherrypy.log("INTENTS")
for intent in engineEntities["skill_intents"]:
engine.register_intent_parser(intent)

return engine

55 changes: 52 additions & 3 deletions server/assistant/Skill.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@

import itertools
from string import Formatter
import cherrypy

from adapt.intent import IntentBuilder
from adapt.engine import DomainIntentDeterminationEngine

from padatious import IntentContainer
from padatious.util import expand_parentheses

from SootherContext import SootherContextManager
from Engine import create_engine

class EntitiesDict(dict):
def __missing__(self, key):
Expand All @@ -32,7 +35,7 @@ def __init__(self, root_dir, name, nlp, active, hasContext):
self._adapt_intent_engine = None

self.initialize_intent_parser()

self.ContextManager = SootherContextManager()

def is_active(self):
return self._active
Expand Down Expand Up @@ -182,7 +185,53 @@ def calculate_intent(self, text):

return adapt_best_confidence, padatious_result


def handle(self, intent, text, latitude, longitude):
def act_on_intent(self, intent, text):
pass

def run_intent(self, text, engineEntities):
cherrypy.log("run intent")
engine = create_engine(engineEntities)
# determine intents in text
intents = [intent for intent in engine.determine_intent(text, include_tags=True, context_manager=self.ContextManager)]

responseArr = []

# if there are intents in the text
if intents:
# act on them
# this should only be one for our usecase
for intent in intents:
response = self.act_on_intent(intent, text)
if isinstance(response, str):
responseArr.append(response)
else:
responseArr = response
else:
if 'LastUtteranceCount' not in cherrypy.session:
cherrypy.session["LastUtteranceCount"] = 1
else:
cherrypy.session["LastUtteranceCount"] = cherrypy.session.get("LastUtteranceCount") + 1

if 'LastUtterance' not in cherrypy.session:
response = "Sorry, cunt, could you repeat that cunt?"
else:
if cherrypy.session.get("LastUtteranceCount") > 2 and cherrypy.session.get("LastUtteranceCount") < 5:
response = "I said " + cherrypy.session.get("LastUtterance") + ". To return to the menu, say 'menu'."
responseArr.append(response)

elif cherrypy.session.get("LastUtteranceCount") >= 5:
responseArr = self.run_intent("menu", engineEntities)
cherrypy.session["LastUtteranceCount"] = 0
else:
response = "Sorry cunt, I said " + str(cherrypy.session.get("LastUtterance"))
responseArr.append(response)


return responseArr

def handle_no_context(self, intent, text, latitude, longitude):
pass

def handle(self, text, **kwargs):
pass

Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class SootherContextManager:
"""
def __init__(self):
self.frame_stack = []
self.timeout = 20 * 60 # minutes to seconds
self.timeout = 1 * 60 # minutes to seconds

def clear_context(self):
"""Remove all contexts."""
Expand Down
77 changes: 77 additions & 0 deletions server/assistant/skills/Menu/Menu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
import requests
import cherrypy
from padatious import IntentContainer
from adapt.engine import IntentDeterminationEngine

from Skill import Skill
from Brain import Brain

from .intents import (entities, single_regex_entities, skill_intents)

class Menu_skill(Skill):

def __init__(self, root_dir, name, nlp, active, hasContext):
hasContext = True
super(Menu_skill, self).__init__(root_dir, name, nlp, active, hasContext)

def act_on_intent(self, intent, text):
response = ""

"""
Chooses proper action to take based on intent.
:param dict intent:
"""
cherrypy.log("ACT ON INTENT")


intent_type = intent['intent_type']
cherrypy.log(intent_type)
if intent_type == 'QuitIntent':
self.ContextManager.clear_context()
cherrypy.lib.sessions.expire()
response = f"BITCH BYE!!"

elif intent_type == 'DogMenuIntent':
cherrypy.session["activeSkill"] = None
cherrypy.session["LastUtteranceCount"] = 0
# trigger menu skill here
menu = intent["MenuKeyword"]
response = "I'm your dog, I'm your therapist, here are your options: I can do a therapy role-play, tell you more about myself, tell you about SOOTHER, or recommend ASMR content."

elif intent_type == 'AlienMenuIntent':
cherrypy.session["activeSkill"] = None
cherrypy.session["LastUtteranceCount"] = 0
# trigger menu skill here
menu = intent["MenuKeyword"]
response = "I'm an alien, I'm on your head. Here are your options: I can guide you through a role-play, tell you more about myself, tell you about SOOTHER, or recommend ASMR content."

elif intent_type == 'FriendMenuIntent':
cherrypy.session["activeSkill"] = None
cherrypy.session["LastUtteranceCount"] = 0
# trigger menu skill here
menu = intent["MenuKeyword"]
response = "I'm your friend, I'm trapped in time. Here are your options: I can guide you through a role-play, tell you more about myself, tell you about SOOTHER, or recommend ASMR content."

cherrypy.session["LastUtterance"] = response
return response


def handle(self, text):

skill_response = []

context = cherrypy.session.get("RolePlayContext")
self.ContextManager.handle_add_context(context)

engineEntities = {"entities" : entities, "single_regex_entities" : single_regex_entities, "skill_intents": skill_intents}

skill_response = self.run_intent(text, engineEntities)

return skill_response

Empty file.
Loading

0 comments on commit e2b6477

Please sign in to comment.