Пример #1
0
    def process_input(self, statement):

        new_message = False

        input_statement = self.context.get_last_input_statement()
        response_statement = self.context.get_last_response_statement()

        if input_statement:
            last_message_id = input_statement.extra_data.get(
                'hipchat_message_id', None)
            if last_message_id:
                self.recent_message_ids.add(last_message_id)

        if response_statement:
            last_message_id = response_statement.extra_data.get(
                'hipchat_message_id', None)
            if last_message_id:
                self.recent_message_ids.add(last_message_id)

        while not new_message:
            data = self.get_most_recent_message(self.hipchat_room)

            if data and data['id'] not in self.recent_message_ids:
                self.recent_message_ids.add(data['id'])
                new_message = True
            else:
                pass
            sleep(3.5)

        text = data['message']

        statement = Statement(text)
        statement.add_extra_data('hipchat_message_id', data['id'])

        return statement
Пример #2
0
    def process_input(self, statement):
        recognizer = speech_recognition.Recognizer()
        with speech_recognition.Microphone() as source:
            recognizer.adjust_for_ambient_noise(source)
            audio = recognizer.listen(source)

        recognizer_function = getattr(recognizer, self.recognizer_function)

        try:
            result = recognizer_function(audio)
            return Statement(result)
        except speech_recognition.UnknownValueError:
            return Statement('I am sorry, I could not understand that.')
        except speech_recognition.RequestError as e:
            m = 'My speech recognition service has failed. {0}'
            return Statement(m.format(e))
Пример #3
0
    def filter(self, **kwargs):
        """
        Returns a list of statements in the database
        that match the parameters specified.
        """
        results = []

        for key in self._keys():
            values = self.database.data(key=key)

            # Add the text attribute to the values
            values["text"] = key

            if self._all_kwargs_match_values(kwargs, values):

                # Build the objects for the response list
                in_response_to = values["in_response_to"]
                response_list = self.deserialize_responses(in_response_to)
                values["in_response_to"] = response_list

                # Remove the text attribute from the values
                text = values.pop("text")

                results.append(Statement(text, **values))

        return results
Пример #4
0
    def get_response_statements(self):
        """
        Return only statements that are in response to another statement.
        A statement must exist which lists the closest matching statement in the
        in_response_to field. Otherwise, the logic adapter may find a closest
        matching statement that does not have a known response.
        """
        response_query = self.statements.distinct('in_response_to.text')
        statement_query = self.statements.find(
            {'text': {
                '$in': response_query
            }})

        statement_list = list(statement_query)

        statement_objects = []

        for statement in statement_list:
            values = dict(statement)
            statement_text = values['text']

            del (values['text'])

            response_list = self.deserialize_responses(
                values["in_response_to"])
            values["in_response_to"] = response_list

            statement_objects.append(Statement(statement_text, **values))

        return statement_objects
Пример #5
0
    def get_random(self, number=1):
        """
        Returns a random statement from the api.
        To generate a random tweet, search twitter for recent tweets
        containing the term 'random'. Then randomly select one tweet
        from the current set of tweets. Randomly choose one word from
        the selected random tweet, and make a second search request.
        Return one random tweet selected from the search results.
        """
        statements = []
        tweets = self.api.GetSearch(term="random", count=5)

        tweet = random.choice(tweets)
        base_response = Response(text=tweet.text)

        words = tweet.text.split()
        word = self.choose_word(words)

        # If a valid word is found, make a second search request
        # TODO: What if a word is not found?
        if word:
            tweets = self.api.GetSearch(term=word, count=number)
            if tweets:
                for tweet in tweets:
                    # TODO: Handle non-ascii characters properly
                    cleaned_text = ''.join(
                        [i if ord(i) < 128 else ' ' for i in tweet.text])
                    statements.append(
                        Statement(cleaned_text,
                                  in_response_to=[base_response]))

        if number == 1:
            return random.choice(statements)

        return statements
Пример #6
0
    def process(self, statement):
        now = datetime.now()

        confidence = self.classifier.classify(statement.text.lower())
        response = Statement("The current time is " + now.strftime("%I:%M %p"))

        return confidence, response
Пример #7
0
    def find(self, statement_text):
        tweets = self.api.GetSearch(term=statement_text, count=1)

        if tweets:
            return Statement(tweets[0].text,
                             in_response_to=[Response(statement_text)])

        return None
    def process_input(self, statement):
        input_type = self.detect_type(statement)

        # Return the statement object without modification
        if input_type == self.OBJECT:
            return statement

        # Convert the input string into a statement object
        if input_type == self.TEXT:
            return Statement(statement)

        # Convert input dictionary into a statement object
        if input_type == self.JSON:
            input_json = dict(statement)
            text = input_json["text"]
            del(input_json["text"])

            return Statement(text, **input_json)
Пример #9
0
    def train(self, conversation):
        statement_history = []

        for text in conversation:
            statement = self.storage.find(text)

            # Create the statement if a match was not found
            if not statement:
                statement = Statement(text)

            previous_statement = None
            if statement_history:
                previous_statement = statement_history[-1]

            if previous_statement:
                statement.add_response(previous_statement)

            statement_history.append(statement)
            self.storage.update(statement)
Пример #10
0
    def process(self, statement):
        """
        Takes a statement string.
        Returns the simplified statement string
        with the mathematical terms "solved".
        """
        input_text = statement.text

        # Getting the mathematical terms within the input statement
        expression = str(self.simplify_chunks(self.normalize(input_text)))

        # Returning important information
        try:
            expression += "= " + str(eval(expression))

            # return a confidence of 1 if the expression could be evaluated
            return 1, Statement(expression)
        except:
            return 0, Statement(expression)
Пример #11
0
    def find(self, statement_text):
        values = self.database.data(key=statement_text)

        if not values:
            return None

        # Build the objects for the response list
        response_list = self.deserialize_responses(values["in_response_to"])
        values["in_response_to"] = response_list

        return Statement(statement_text, **values)
Пример #12
0
    def find(self, statement_text):
        values = self.statements.find_one({'text': statement_text})

        if not values:
            return None

        del (values['text'])

        # Build the objects for the response list
        response_list = self.deserialize_responses(values["in_response_to"])
        values["in_response_to"] = response_list

        return Statement(statement_text, **values)
Пример #13
0
    def process_input(self, statement):

        new_message = False

        input_statement = self.context.get_last_input_statement()
        response_statement = self.context.get_last_response_statement()

        if input_statement:
            last_message_id = input_statement.extra_data.get(
                'hipchat_message_id', None
            )
            if last_message_id:
                self.recent_message_ids.add(last_message_id)

        if response_statement:
            last_message_id = response_statement.extra_data.get(
                'hipchat_message_id', None
            )
            if last_message_id:
                self.recent_message_ids.add(last_message_id)

        while not new_message:
            data = self.get_most_recent_message(self.hipchat_room)

            if data and data['id'] not in self.recent_message_ids:
                self.recent_message_ids.add(data['id'])
                new_message = True
            else:
                pass
            sleep(3.5)

        text = data['message']

        statement = Statement(text)
        statement.add_extra_data('hipchat_message_id', data['id'])

        return statement
Пример #14
0
    def filter(self, **kwargs):
        """
        Returns a list of statements in the database
        that match the parameters specified.
        """
        filter_parameters = kwargs.copy()
        contains_parameters = {}

        # Convert Response objects to data
        if "in_response_to" in filter_parameters:
            response_objects = filter_parameters["in_response_to"]
            serialized_responses = []
            for response in response_objects:
                serialized_responses.append(response.serialize())

            filter_parameters["in_response_to"] = serialized_responses

        # Exclude special arguments from the kwargs
        for parameter in kwargs:

            if "__" in parameter:
                del (filter_parameters[parameter])

                kwarg_parts = parameter.split("__")

                if kwarg_parts[1] == "contains":
                    key = kwarg_parts[0]
                    value = kwargs[parameter]

                    contains_parameters[key] = {'$elemMatch': {'text': value}}

        filter_parameters.update(contains_parameters)

        matches = self.statements.find(filter_parameters)
        matches = list(matches)

        results = []

        for match in matches:
            statement_text = match['text']
            del (match['text'])

            response_list = self.deserialize_responses(match["in_response_to"])
            match["in_response_to"] = response_list

            results.append(Statement(statement_text, **match))

        return results
Пример #15
0
    def update(self, statement):
        # Do not alter the database unless writing is enabled
        if not self.read_only:
            data = statement.serialize()

            # Remove the text key from the data
            del (data['text'])
            self.database.data(key=statement.text, value=data)

            # Make sure that an entry for each response exists
            for response_statement in statement.in_response_to:
                response = self.find(response_statement.text)
                if not response:
                    response = Statement(response_statement.text)
                    self.update(response)

        return statement
Пример #16
0
    def get_random(self):
        """
        Returns a random statement from the database
        """
        from random import randint

        count = self.count()

        random_integer = randint(0, count - 1)

        if self.count() < 1:
            raise self.EmptyDatabaseException()

        statement = self.statements.find().limit(1).skip(random_integer)

        values = list(statement)[0]
        statement_text = values['text']

        del (values['text'])
        return Statement(statement_text, **values)
Пример #17
0
    def filter(self, **kwargs):
        """
        Returns a list of statements in the database
        that match the parameters specified.
        """
        statement_text = kwargs.get('text')

        # if not statement_text:
        #    statement_text = kwargs.get('in_response_to__contains')
        # data['in_reply_to_status_id_str']

        # If no text parameter was given get a selection of recent tweets
        if not statement_text:
            statements = self.get_random(number=20)
            return statements

        tweets = self.api.GetSearch(term=statement_text)
        tweet = random.choice(tweets)

        statement = Statement(tweet.text,
                              in_response_to=[Response(statement_text)])

        return [statement]
Пример #18
0
 def process_input(self, *args, **kwargs):
     """
     Read the user's input from the terminal.
     """
     user_input = input_function()
     return Statement(user_input)
Пример #19
0
from asher.conversation import Statement

ash_print = lambda sam, x: sam.output.process_response(Statement(x))