class Conversation(object):

    def __init__(self, persona, speaker, profile):
        self.persona = persona
        self.speaker = speaker
        self.profile = profile
        self.notifier = Notifier(profile)
        self.brain = Brain(speaker, profile)

    def handleForever(self):

        while True:

            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self.speaker.say(notif)

            threshold, transcribed = self.speaker.passiveListen(self.persona)
            if not threshold or not transcribed:
                continue

            input = self.speaker.activeListenToAllOptions(threshold)

            if input:
                self.brain.query(self.profile, transcribed)
Exemple #2
0
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        person = None
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            authen = self.mic.authentication_activated()

            if authen is False:
                auth = test5.Authentication(0, self.mic)
                auth.authenticate()
                person = auth.Person_ret()

            print(person)
            authen = self.mic.authentication_activated()
            print(authen)
            if authen is False:
                continue

            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                print("ok d5al")
                self.brain.query(input, person)
            else:
                self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile, isPassiveEnabled):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.isPassiveEnabled = isPassiveEnabled

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed, passivePhrases = \
                self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue

            self._logger.info("Keyword '%s' has been said!", self.persona)

            if self.isPassiveEnabled is True and len(passivePhrases) != 0:

                input = passivePhrases
                self._logger.debug("Checking for passive phrase '%s' with " +
                                   "threshold: %r", input, threshold)

            else:

                self._logger.debug("Started to listen actively with " +
                                   "threshold: %r", threshold)
                input = self.mic.activeListenToAllOptions(threshold)
                self._logger.debug("Stopped to listen actively with " +
                                   "threshold: %r", threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Exemple #4
0
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
            # check if mpd client is running
            try:
                client = MPDClient()
                client.timeout = None
                client.idletimeout = None
                client.connect("localhost", 6600)
            except:
                self.mic.say(
                    "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify."
                )
                return

            self.mic.say(
                "Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif

            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except NoDisturbanceDetectedException:
                print "No disturbance detected"
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile, house):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, house)
        self.notifier = Notifier(profile, house)
        self.house = house

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
            # check if mpd client is running
            try:
                client = MPDClient()
                client.timeout = None
                client.idletimeout = None
                client.connect("localhost", 6600)
            except:
                self.mic.say(
                    "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
                return

            self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif
                self.mic.say(notif)
            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
Exemple #6
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            # Word we listen for to self terminate
            TERMINATE = 'GOODBYE'

            self._logger.debug("Started listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)
            threshold, transcribed = self.mic.passiveListen(self.persona, TERMINATE)
            self._logger.debug("Stopped listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            # Terminate on goodbye
            if transcribed == TERMINATE:
                friendly.goodbye(self.mic, self.profile)
                sys.exit(0)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Exemple #7
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while on == True:

            nu()
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                messages = ["what?",
                            "what did you say",
                            "Say that again?", "speak the f**k up", "i cant f*****g hear you", "blah blah blah", "did you say something?"]

                message = random.choice(messages)
                zip2()
                self.mic.say(message)
class Conversation(object):
  def __init__(self, persona, mic, server, profile):
    self._logger = logging.getLogger(__name__)
    self.persona = persona
    self.mic = mic
    self.profile = profile
    self.brain = Brain(mic, profile)
    self.notifier = Notifier(profile)
    self.server = server

  def handleForever(self):
    """
    Delegates user input to the handling function when activated.
    """
    self._logger.info("Starting to handle conversation with keyword '%s'.",
                      self.persona)
    while True:
      # Print notifications until empty
      notifications = self.notifier.getAllNotifications()
      for notif in notifications:
        self._logger.info("Received notification: '%s'", str(notif))

      if 'jasper.server.enabled' in self.profile and self.profile['jasper.server.enabled']:
        inputDevice = self.server
        self._logger.debug("Listening to tcp socket with Jasper server")
      else:
        inputDevice = self.mic
        self._logger.debug("Listening to attached microphone")

      self._logger.debug("Started listening for keyword '%s'",
                         self.persona)
      threshold, transcribed = inputDevice.passiveListen(self.persona)
      self._logger.debug("Stopped listening for keyword '%s'",
                         self.persona)

      if not transcribed or not threshold:
        self._logger.info("Nothing has been said or transcribed.")
        continue
      self._logger.info("Keyword '%s' has been said!", self.persona)

      self._logger.debug("Started to listen actively with threshold: %r",
                         threshold)
      input = inputDevice.activeListenToAllOptions(threshold)
      self._logger.debug("Stopped to listen actively with threshold: %r",
                         threshold)

      if input:
        self.brain.query(input)
      else:
        inputDevice.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            try:
                notifications = self.notifier.getAllNotifications()
                for notif in notifications:
                    self._logger.info("Received notification: '%s'", str(notif))

                self._logger.debug("Started listening for keyword '%s'",
                                   self.persona)
                threshold, transcribed = self.mic.passiveListen(self.persona)
                self._logger.debug("Stopped listening for keyword '%s'",
                                   self.persona)

                if not transcribed or not threshold:
                    self._logger.info("Nothing has been said or transcribed.")
                    continue
                self._logger.info("Keyword '%s' has been said!", self.persona)

                self._logger.debug("Started to listen actively with threshold: %r",
                                   threshold)
                input = self.mic.activeListenToAllOptions(threshold)
                self._logger.debug("Stopped to listen actively with threshold: %r",
                                   threshold)

                if input:
                    self.brain.query(input)
                else:
                    self.mic.say("Pardon?")
            except KeyboardInterrupt:
                print "Keyboard Interrupt!"
                try:
                    sys.exit(0)
                except SystemExit:
                    os._exit(0)
Exemple #10
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        
        try_num =0
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            #msg = xbee.Receive()   #this is where we get our serial data during downtime
            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.shutdown = False

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while not self.shutdown:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            self.mic.say(random.choice(["your wish is my command", "what is thy bidding, my master", "I live to serve"]))
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Exemple #12
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Je vous demande pardon monsieur, j'ai mal compris")
Exemple #13
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        '''
	if any(x in text.upper() for x in ["SPOTIFY","MUSIC"]):
            self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return
        '''

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif

            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
Exemple #14
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY","MUSIC"]):
            self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return


        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif

            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
Exemple #15
0
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    global last_checked
    last_checked = -1

    def fetch_siri_command(self, mail):
        global last_checked
        mail.list()
        mail.select("Notes")
        result, uidlist = mail.search(None, "ALL")
        latest_email_id = uidlist[0].split()[-1]
        if latest_email_id == last_checked:
            return
        last_checked = latest_email_id
        result, data = mail.fetch(latest_email_id, "(RFC822)")
        voice_command = email.message_from_string(data[0][1].decode('utf-8'))
        c = str(voice_command.get_payload()).lower().strip()
        return c

    def main(self):
        global username
        global password
        x = 0
        mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
        mail.login(username, password)
        self.fetch_siri_command(mail)
        x = 1
        while x:
            try:
                c = str(self.fetch_siri_command(mail))
                if c != "None":
                    print("You said " + c)
                    self.brain.query(c, "siri")
            except Exception as exc:
                print("Received an exception while running: {exc}"
                      "\nRestarting...".format(**locals()))
            time.sleep(1)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        thread.start_new_thread(self.main, ())
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)

            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)

            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input, "stt")
            else:
                self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def delegateInput(self, texts):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        for text in texts:
            if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
                self._logger.debug("Preparing to start music module")
                # check if mpd client is running
                try:
                    client = MPDClient()
                    client.timeout = None
                    client.idletimeout = None
                    client.connect("localhost", 6600)
                except:
                    self._logger.critical("Can't connect to mpd client, cannot start music mode.", exc_info=True)
                    self.mic.say(
                        "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
                    return

                self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
                self._logger.debug("Starting music mode")
                music_mode = MusicMode(self.persona, self.mic)
                music_mode.handleForever()
                self._logger.debug("Exiting music mode")
                return

        self.brain.query(texts)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        self._logger.info("Starting to handle conversation with keyword '%s'.", self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'", self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'", self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r", threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r", threshold)
            
            if input:
                self.delegateInput(input)
            else:
                self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        # Load the aiml module
        self.aimlkernel = aiml.Kernel()

        # Load the aiml files
        folder = "/home/pi/jasper/client/modules/aiml/alice/"
        for file in os.listdir(folder):
            if file.endswith(".aiml"):
                self.aimlkernel.learn(folder+file)
                print(folder+file)
        folder = "/home/pi/jasper/client/modules/aiml/standard/"
        for file in os.listdir(folder):
            if file.endswith(".aiml"):
                self.aimlkernel.learn(folder+file)
                print(folder+file)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")

            # Call behaviour tree
            self._logger.debug("Calling next on the behaviour tree")
            print("Calling next on the behaviour tree")

            self.brain.tick()
class Conversation(object):
    def __init__(self, persona, mic, profile, pygm):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.pygm = pygm
        self.profile = profile
        self.brain = Brain(mic, profile, pygm)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)

        while self.pygm.on == True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    on = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        self.pygm.on = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.pygm.on = False

            self.pygm.blitimg(image, size, black, x, y)
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.pygm.blittxt('???', 400, red, black)

                messages = [
                    "what?", "what did you say", "Say that again?",
                    "speak the f**k up", "i cant f*****g hear you",
                    "blah blah blah", "did you say something?"
                ]

                message = random.choice(messages)
                self.mic.say(message)
        pygame.quit()
Exemple #19
0
class Conversation(object):
    def __init__(self, mic, profile, logger):
        self.persona = profile['persona']
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, logger)
        self.notifier = Notifier(profile, logger)
        self.logger = logger

    def delegateInput(self, text):
        """A wrapper for querying brain."""
        got_hit = False
        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
            # check if mpd client is running
            try:
                client = MPDClient()
                client.timeout = None
                client.idletimeout = None
                client.connect("localhost", 6600)
            except:
                self.logger.warning("Failed to init MPDClient")
                self.mic.say(
                    "Wybacz, ale najwyraźniej usługa Spotify nie działa")
                return

            self.logger.info("waiting for Spotify playlist")
            self.mic.say("Poczekaj chwilę, wczytuję listę utworów Spotify")
            music_mode = MusicMode(self.persona, self.mic, self.logger)
            music_mode.handleForever()
            return
        else:
            if " następnie " in lowerUTF8(text):
                l_text = text.split(" następnie ")
                for text in l_text:
                    new_got_hit = self.brain.query(text)
                    got_hit = got_hit or new_got_hit
            else:
                got_hit = self.brain.query(text)
        return got_hit

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        initial_threshold = None  #self.mic.fetchThreshold(RATE=48000, CHUNK=8192, THRESHOLD_TIME=4, AVERAGE_TIME=4)
        repeat = True
        while repeat:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                notif = str_formater.unicodeToUTF8(notif, self.logger)
                self.logger.info("Got new notification: %s" % notif)
                #self.mic.say(notif)

            try:
                threshold, transcribed = self.mic.passiveListen()
            except KeyboardInterrupt:
                threshold = None
                repeat = False
            except:
                self.logger.critical("fatal error processing passive listen",
                                     exc_info=True)
                continue

            if threshold:
                if transcribed:
                    input = transcribed
                else:
                    input = self.mic.activeListen(initial_threshold,
                                                  RATE=44100,
                                                  CHUNK=8196,
                                                  LISTEN_TIME=6,
                                                  AVERAGE_TIME=5)
                    input = str_formater.unicodeToUTF8(input, self.logger)

                self.logger.debug("got input %s" % (input))
                if input:
                    if any(x in input.upper() for x in ["KONIEC"]):
                        repeat = False
                        self.logger.info("Quiting after voice request")
                        self.mic.say("Kończę pracę. Do usłyszenia.")
                    #elif any(x in input.upper().replace('ł','Ł') for x in ["PRZEŁADUJ"]):
                    elif any(x in upperUTF8(input) for x in ["PRZEŁADUJ"]):
                        self.brain.reload_modules()
                    elif any(x in upperUTF8(input) for x in ["ECHO"]):
                        self.mic.say(input)
                        #self.mic.play(input)
                    else:
                        self.delegateInput(input)
                else:
                    self.mic.say("Powtórz proszę.")
Exemple #20
0
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.wxbot = None

    def is_proper_time(self):
        """
        whether it's the proper time to gather notifications without disturb user
        """
        if 'do_not_bother' not in self.profile:
            return True
        else:
            if self.profile['do_not_bother']['enable']:
                if 'since' not in self.profile['do_not_bother'] or \
                   'till' not in self.profile['do_not_bother']:
                    return True
                else:
                    since = self.profile['do_not_bother']['since']
                    till = self.profile['do_not_bother']['till']
                    current = time.localtime(time.time()).tm_hour
                    if till > since:
                        return not current in range(since, till)
                    else:
                        return not (current in range(since, 25)
                                    or current in range(-1, till))
            else:
                return True

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            if self.is_proper_time():
                notifications = self.notifier.getAllNotifications()
                for notif in notifications:
                    self._logger.info("Received notification: '%s'",
                                      str(notif))
                    self.mic.say(str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input, self.wxbot)
            else:
                self.mic.say("什么?")
class Conversation(object):

    def __init__(self, mic, profile, logger):
        self.persona = profile['persona']
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, logger)
        self.notifier = Notifier(profile, logger)
        self.logger = logger

    def delegateInput(self, text):
        """A wrapper for querying brain."""
        got_hit = False
        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
            # check if mpd client is running
            try:
                client = MPDClient()
                client.timeout = None
                client.idletimeout = None
                client.connect("localhost", 6600)
            except:
                self.logger.warning("Failed to init MPDClient")
                self.mic.say("Wybacz, ale najwyraźniej usługa Spotify nie działa")
                return
            
            self.logger.info("waiting for Spotify playlist")
            self.mic.say("Poczekaj chwilę, wczytuję listę utworów Spotify")
            music_mode = MusicMode(self.persona, self.mic, self.logger)
            music_mode.handleForever()
            return
        else:
          if " następnie " in lowerUTF8(text):
            l_text = text.split(" następnie ")
            for text in l_text:
              new_got_hit = self.brain.query(text)
              got_hit = got_hit or new_got_hit
          else:
            got_hit = self.brain.query(text)
        return got_hit

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        initial_threshold = None #self.mic.fetchThreshold(RATE=48000, CHUNK=8192, THRESHOLD_TIME=4, AVERAGE_TIME=4)
        repeat = True
        while repeat:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                notif = str_formater.unicodeToUTF8(notif, self.logger)
                self.logger.info("Got new notification: %s" % notif )
                #self.mic.say(notif)

            try:
                threshold, transcribed = self.mic.passiveListen()
            except KeyboardInterrupt:
                threshold = None
                repeat = False
            except:
                self.logger.critical("fatal error processing passive listen", exc_info=True)
                continue

            if threshold:
                if transcribed:
                  input = transcribed
                else:
                  input = self.mic.activeListen(initial_threshold, RATE=44100, CHUNK=8196, LISTEN_TIME=6, AVERAGE_TIME=5)
                  input = str_formater.unicodeToUTF8(input, self.logger)

                self.logger.debug("got input %s" % (input))
                if input:
                    if any(x in input.upper() for x in ["KONIEC"]):
                      repeat = False
                      self.logger.info("Quiting after voice request")
                      self.mic.say("Kończę pracę. Do usłyszenia.")
                    #elif any(x in input.upper().replace('ł','Ł') for x in ["PRZEŁADUJ"]):
                    elif any(x in upperUTF8(input) for x in ["PRZEŁADUJ"]):
                      self.brain.reload_modules()
                    elif any(x in upperUTF8(input) for x in ["ECHO"]):
                            self.mic.say(input)
                            #self.mic.play(input)
                    else:
                      self.delegateInput(input)
                else:
                    self.mic.say("Powtórz proszę.")
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.radioPaused = False

    def determineIntent(self, input):
        if (len(input) == 0):
            return {}
        
        print input[0]
        parameters = {"q" : input[0].lower()}
        r = requests.post('https://api.wit.ai/message?v=20150524',
                      headers={ 'Authorization': 'Bearer TBYTRFCCBMHAKHHDKDCR7JTPMKNSVLOS',
                     'accept': 'application/json'},
                     params=parameters)
                     
        print r.url
        
        try:
            r.raise_for_status()
            text = r.json()['outcomes']
            self._logger.info(len(r.json()["outcomes"]))
        except requests.exceptions.HTTPError:
            self._logger.critical('Request failed with response: %r',
                                  r.text,
                                  exc_info=True)
            return []
        except requests.exceptions.RequestException:
            self._logger.critical('Request failed.', exc_info=True)
            return []
        except ValueError as e:
            self._logger.critical('Cannot parse response: %s',
                                  e.args[0])
            return []
        except KeyError:
            self._logger.critical('Cannot parse response.',
                                  exc_info=True)
            return []
        else:
            transcribed = text[0]
            self._logger.info('Intent: %r', transcribed)
            return transcribed

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            
            # Pause the radio
            if House.radioPlaying():
                self.radioPaused = True
                self._logger.info("Pausing radio...")
                House.stopRadio()
            
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)
            
            if (len(input) > 1):
                intent = input[1]
                input = [input[0]]
            else:
                intent = self.determineIntent(input)
            
            if input:
                self.brain.query(input,intent)
            else:
                self.mic.say("Pardon?")
            
            # Resume if necessary
            if self.radioPaused == True:
                self.radioPaused = False
                self._logger.info("Resuming radio...")
                House.startRadio()
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            found = (transcribed + [''])[0]
            if 'AMOS' not in found: continue

            if 'BOUNCE' in found or 'BALANCE' in found:
                print("BOUNCEING...")
                bounce()
            if 'REC' in found or 'RECORD' in found or 'START' in found:
                print("RECORDING...")
                record()
            if 'STOP' in found or 'END' in found:
                print("STOPPING...")
                stop_req()
            if 'DUPLICATE' in found or 'COPY' in found:
                print("COPYING...")
                copy_track()
            if 'FRONT' in found or 'BEGINING' in found or 'FRONT' in found:
                print("BRINGING BEGIN...")
                bring_begin()
            if 'CONFIRM' in found or 'YES' in found or 'ENTER' in found or 'CONTINUE' in found:
                print("CONFIRMING...")
                confirm()

            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile, pygm):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.pygm = pygm
        self.profile = profile
        self.brain = Brain(mic, profile, pygm)
        self.notifier = Notifier(profile)
    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)


        while self.pygm.on == True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    on = False
                if event.type == pygame.KEYDOWN:           
                    if event.key == pygame.K_RIGHT:
                        self.pygm.on = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.pygm.on = False
                    
            self.pygm.blitimg(image, size, black, x, y)   
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.pygm.blittxt('???', 400, red, black)

                messages = ["what?",
                            "what did you say",
                            "Say that again?", "speak the f**k up", "i cant f*****g hear you", "blah blah blah", "did you say something?"]

                message = random.choice(messages)
                self.mic.say(message)
        pygame.quit()
Exemple #25
0
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def delegateInput(self, text, FoundPersona=True):
        """A wrapper for querying brain."""

        if FoundPersona:

            # check if input is meant to start the music module
            if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
                self.mic.say(
                    "Please give me a moment, I'm loading your Spotify playlists."
                )
                music_mode = MusicMode(self.persona, self.mic)
                music_mode.handleForever()
                return

            # Timer module needs to have the notifier instance.
            # so this module has a different format that the normal ones.
            # The notifier module will also check more quickly for a timer event.
            # this will ensure that timer events occur inline with normal program flow
            # and will call the timer module first
            # Timer.isValid (text)
            # Timer.handle(text, self.mic, self.profile, self.notifier):
            #      the handle will now be able to call function in notifier to push on queue.
            print("testing if timer is valid")
            if Timer.isValid(text):
                print("timer is valid")
                try:
                    Timer.handle(text, self.mic, self.profile, self.notifier)
                    return
                except:
                    self.mic.say(
                        "I'm sorry. I had some trouble with the timer module. Please try again later."
                    )
                    return

            # Query the brain to check if other modules are ok.
            self.brain.query(text)

        else:
            self.brain.passivequery(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Announce notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self.mic.say(notif)
#               print notif

# GPIO On
#	    GPIO.output(16, GPIO.LOW)
            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue
# Off
#	    GPIO.output(16, GPIO.HIGH)

# If threshold is false and transcribed value is a string.
# then I should look at values
            if not threshold:
                if isinstance(transcribed, list):
                    if len(transcribed) == 2:
                        self.delegateInput(transcribed[0], False)
                        print(transcribed[0], ' we did not detect erica')

            print("in Handleforever")

            if threshold:
                input = self.mic.activeListen(threshold)
                print(input)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say(
                        "Pardon?.  I did not recognize that command.  try to say it louder"
                    )
Exemple #26
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            # Add reveil
            now = datetime.now()

            if now.hour == 8 and now.minute == 35 and now.weekday() < 5:
                self.mic.say("Debout là dedans c'est l'heure")
                self._logger.info("Reveil")
                music = self.getRandomMusic()
                self._logger.debug("Start playing" + music[0])
                call(["mpsyt", "playurl", music[1]])


            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")

    def getRandomMusic(self, filename=jasperpath.data('text', 'YOUTUBE.txt')):
        youtubeFile = open(filename, "r")
        musics = []
        start = ""
        end = ""
        for line in youtubeFile.readlines():
            line = line.replace("\n", "")

            if start == "":
                start = line
                continue

            if end == "":
                end = line
                continue

            musics.append((start, end))
            start = ""
            end = ""

        musics.append((start, end))
        music = random.choice(musics)
        return music
Exemple #27
0
class Conversation(object):
    def off_pressed(self, input_pin):
        '''Removes dependencies and terminates the script'''
        self.mic.say("2001 Quote")
        GPIO.remove_event_detect(3)
        GPIO.remove_event_detect(5)
        os.system("sudo service motion stop")
        raise SystemExit("Quit button pressed")

    def reset_pressed(self, input_pin):
        '''Removes dependecies and restarts the script'''
        self.mic.say("Toby, I'm scared.")
        GPIO.remove_event_detect(3)
        GPIO.remove_event_detect(5)
        os.execl(sys.executable, sys.executable, *sys.argv)

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)  #Reset switch
        GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)  #Off switch
        GPIO.add_event_detect(3, GPIO.BOTH, callback=self.off_pressed)
        GPIO.add_event_detect(5, GPIO.BOTH, callback=self.reset_pressed)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")