示例#1
0
def startTrainingHandler(dogName, sexFromIntent):
    dogFromDynamoDB = getDogFromDynamoDB(session.user.userId)

    # If we don't know the dogname at all, ask again
    if not dogName:
        try:
            dogName = dogFromDynamoDB[DOG_NAME]
        except:
            printDebug(
                "Name not in intent, and dog not in DB. Asking name first.")
            session.attributes[LAST_QUESTION] = DOG_NAME_ASKED
            speech_output = render_template("lets_train_get_name")
            printDebug("Starting elicit of DOG")
            return elicit_slot('Dog', speech_output)

    if sexFromIntent:
        sex = getUniqueSlotID(request.intent.slots.Sex)
        if not sex:
            printDebug("Invalid sex. Re-asking")
            del request.intent.slots.Sex['value']
            del request.intent.slots.Sex['resolutions']
            printDebug(
                "Updated request to remove invalid sex: {}".format(request))
            session.attributes[LAST_QUESTION] = DOG_NAME_ASKED
            speech_output = render_template("invalid_sex_ask_again",
                                            dog=dogName)
            return elicit_slot('Sex',
                               speech_output,
                               updated_intent=request.intent)
    else:
        try:
            if dogName == dogFromDynamoDB[DOG_NAME]:
                printDebug("getting sex from active dog")
                sex = dogFromDynamoDB[SEX]
            else:
                printDebug("getting sex from previous dog")
                sex = dogFromDynamoDB[PREVIOUS_DOGS][dogName]
            printDebug("found sex as: {}".format(sex))
            assert sex != UNKNOWN
        except:
            session.attributes[LAST_QUESTION] = SEX_ASKED
            printDebug("Sex is not known. Asking.")
            request.intent.slots.Dog.value = dogName
            return delegate(updated_intent=request.intent)

    printDebug("Sex finally known: {}".format(sex))

    dog = saveDogForUser(session.user.userId, dogName=dogName, sex=sex)

    if dog[NUMBER_OF_TRAININGS] < 2:
        return explainAndAskConfirmation(dog)
    else:
        return train(dog)
示例#2
0
def suggest_theme(yes_no):
    global themeNumber

    if yes_no is None:
        themeNumber = random.randint(0, len(themes) - 1)
        return elicit_slot(
            'yes_no', '<speak><s>How about ' + themes[themeNumber] +
            '?</s> Would you like to use this theme for your party?</speak>')

    answer = request.intent.slots.yes_no.resolutions.resolutionsPerAuthority[
        0]['values'][0]['value']['name']
    if answer == 'describe':
        return elicit_slot(
            'yes_no', themesDescriptions[themeNumber] +
            ' So, would you like to use this theme for your party?')
    if answer == 'yes':
        Event.update_event_description(themeNumber)
        return statement('The theme has been added to your calendar event.')
    else:
        themeNumber = 20
        return statement(
            '<speak><emphasis level="strong">Okay.</emphasis></speak>')
def createPlaylist(s_one,s_two,s_three,playlistName):
    if not any([s_one,s_two,s_three]):
        message = 'What would you like in your playlist?'
    else:
        if s_one:
            s_one = str(request.intent.slots.s_one.resolutions.resolutionsPerAuthority[0]['values'][0]['value']['name'])
        if s_two:
            s_two = str(request.intent.slots.s_two.resolutions.resolutionsPerAuthority[0]['values'][0]['value']['name'])
        if s_three:
            s_three = str(request.intent.slots.s_three.resolutions.resolutionsPerAuthority[0]['values'][0]['value']['name'])
        seeds = [i for i in [s_one,s_two,s_three] if i]

        if 'genres' in seeds and not request.intent.slots.g_one.value:
            return elicit_slot('g_one','Which genres would you like to use as seeds?')
        genreSeeds = availableGenreSeeds()
        genres = []
        for key in ['g_one','g_two','g_three','g_four','g_five']:
            slot = request.intent.slots[key]
            if 'value' in slot:
                genre = slot['value']
                if genre not in genreSeeds:
                    return elicit_slot(key,'{} is an invalid Genre. Please choose a valid genre from the card in the Alexa App.'.format(genre))
#        genres = [request.intent.slots[key]['value'] for key in ['g_one','g_two','g_three','g_four','g_five'] if 'value' in request.intent.slots[key]]
#        genreSeeds = availableGenreSeeds()
#        invalids = '\n'.join('{} is an invalid genre. '.format(g) for g in genres if g not in genreSeeds)
#        if invalids:
#            return elicit_slot('g_one',invalids+'Please choose valid genres.')
            
        if 'artists' in seeds and not request.intent.slots.a_one.value:
            return elicit_slot('a_one','Which artists would you like to use as seeds?')
        
        if 'tracks' in seeds and not request.intent.slots.t_one.value:
            return elicit_slot('t_one','Which tracks would you like to use as seeds?')
        
        slots = request.intent.slots
        genres = [slots[key]['value'] for key in ['g_one','g_two','g_three','g_four','g_five'] if 'value' in slots[key]]
        artists = [slots[key]['value'] for key in ['a_one','a_two','a_three','a_four','a_five'] if 'value' in slots[key]]
        tracks = [slots[key]['value'] for key in ['t_one','t_two','t_three','t_four','t_five'] if 'value' in slots[key]]
        #message = 'i heard {},{},{}'.format(genres,artists,tracks)
        #message = '{},{},{}'.format(request.intent.slots.genres['value'],request.intent.slots.artists['value'],request.intent.slots.tracks['value'])
        
        elicit_slot('filters','Would you like any filters?')
        
        recs = getRecs(genres=genres,artists=artists,tracks=tracks)
        if not request.intent.slots.playlistName.value:
            return elicit_slot('playlistName','What would you like to name your playlist?')
        pl = u.recPlaylist(playlistName,recs)
#        echo_devID = [i['id'] for i in u.getDevices() if i['name'] == "Zach's Echo Dot"][0]
#        pl.startPlayback(echo_devID)
        
    return statement('Made your playlist called {} with the following seeds: {},{},{}'.format(playlistName,genres,artists,tracks))
示例#4
0
def setSex(sexFromIntent, dogName):
    if not dogName:
        try:
            dogFromDynamoDB = getDogFromDynamoDB(session.user.userId)
            dogName = dogFromDynamoDB[DOG_NAME]
            printDebug("Fetched dog name from DB: {}".format(dogName))
        except:
            printDebug(
                "SetSexIntent started, but I don't know the name yet. First asking that before asking sex"
            )
            return setDogNameHandler(None)
    else:
        printDebug("Dog name taken from intent: {}".format(dogName))

    if not sexFromIntent:
        printDebug("Could not get sex from intent.")
        return delegate()

    sex = getUniqueSlotID(request.intent.slots.Sex)

    # Sex is given, but is invalid. Explicitely ask for it
    if not sex:
        printDebug("Invalid sex. Re-asking")
        del request.intent.slots.Sex['value']
        del request.intent.slots.Sex['resolutions']
        printDebug("Updated request to remove invalid sex: {}".format(request))
        session.attributes[LAST_QUESTION] = DOG_NAME_ASKED
        speech_output = render_template("invalid_sex_ask_again", dog=dogName)
        return elicit_slot("Sex", speech_output, updated_intent=request.intent)

    saveDogForUser(session.user.userId, dogName=dogName, sex=sex)

    session.attributes[LAST_QUESTION] = SHOULD_START_TRAINING
    speech_output = render_template('sex_set',
                                    dog=dogName,
                                    sex=render_template(sex))
    reprompt = render_template('should_start_training')

    return question(speech_output).reprompt(reprompt)
示例#5
0
def start_survey():

    dialog_state = get_dialog_state()
    session.attributes_encoder = json.JSONEncoder

    if dialog_state == "STARTED":
        session.attributes["COUNT"] = 0
        session.attributes["BONUS_COUNT"] = 0
        session.attributes["HAMD_SCORE"] = 0
        session.attributes["QUESTION"] = 'One'
        session.attributes["PREV_QUESTION"] = 'BonusOne'
        session.attributes["STATE"] = 'Survey'
        return delegate()
    elif dialog_state == "IN_PROGRESS":
        # If do not want to continue survey:
        if request["intent"]["slots"]["StartSurvey"]["value"] == 'no':
            return stop()

        survey_question = session.attributes["QUESTION"]
        # For bonus question
        previous_question = session.attributes["PREV_QUESTION"]
        # If regular survey questions
        if not re.match("Bonus", survey_question):
            if 'value' in request["intent"]["slots"][survey_question]:

                if str(request["intent"]["slots"][survey_question]
                       ["value"]) not in ('0', '1', '2', '3', '4'):
                    reprompt_answer = render_template("reprompt_survey")
                    return elicit_slot(survey_question, reprompt_answer)

                # Record answer for question
                session.attributes[survey_question] = int(
                    request["intent"]["slots"][survey_question]["value"])
                # Add each score to get total survey score
                session.attributes["HAMD_SCORE"] += int(
                    request["intent"]["slots"][survey_question]["value"])
        # If Bonus Questions
        else:
            survey_wait = survey_question + "Wait"
            bonus_wait = request["intent"]["slots"][survey_wait]

            # If bonus wait question
            if 'value' in bonus_wait:
                if request["intent"]["slots"][survey_wait]["value"] == 'no':
                    if session.attributes["BONUS_COUNT"] > 0:
                        session.attributes["BONUS_COUNT"] -= 1
                    bonus_question = render_template(survey_wait)
                    return elicit_slot(survey_wait, bonus_question)

            if previous_question in request["intent"]["slots"]:
                # If actual bonus question
                bonus_question = request["intent"]["slots"][previous_question]
                if 'value' in bonus_question:
                    words = request["intent"]["slots"][previous_question][
                        "value"]
                    session.attributes[previous_question] = words

        # Increment question count for both regular and bonus questions
        if session.attributes["COUNT"] < 16:
            session.attributes["COUNT"] += 1
            survey_question = num2words(
                session.attributes["COUNT"]).capitalize()
        elif session.attributes["BONUS_COUNT"] < 3:
            previous_question = "Bonus" + num2words(
                session.attributes["BONUS_COUNT"]).capitalize()
            session.attributes["BONUS_COUNT"] += 1
            survey_question = "Bonus" + num2words(
                session.attributes["BONUS_COUNT"]).capitalize()

        session.attributes["QUESTION"] = survey_question
        session.attributes["PREV_QUESTION"] = previous_question

        return delegate()
    elif dialog_state == "COMPLETED":
        # Get last bonus question answer
        last_question = session.attributes.get("QUESTION")
        session.attributes[last_question] = \
            request["intent"]["slots"][last_question]["value"]
        session.attributes['STATE'] = 'SurveyDone'

    # Bonus section calculation of score using sentiment analysis
    bonus_list = ['BonusOne', 'BonusTwo', 'BonusThree']
    for bonus in bonus_list:
        words = session.attributes[bonus]
        word_list = words.split()
        bonus_score = 0
        for word in word_list:
            analysis = TextBlob(word)
            bonus_score += analysis.sentiment.polarity

        # Normalize scores based on three adjectives
        bonus_score = bonus_score / 3

        # Increase score based on negative sentiment analysis of words in bonus section
        if bonus_score < 0:
            session.attributes["HAMD_SCORE"] += (2 / 3) * (-bonus_score)

    score = round(float(session.attributes["HAMD_SCORE"]), 2)

    session.attributes["HAMD_SCORE"] = score

    if score >= 0 and score <= 7:
        # Normal
        score_message = render_template('normal', score=score)
        session.attributes['Severity'] = 'normal'
    elif score > 7 and score <= 13:
        # Mild Depression
        score_message = render_template('mild', score=score)
        session.attributes['Severity'] = 'mild'
    elif score > 13 and score <= 18:
        # Moderate Depression
        score_message = render_template('moderate', score=score)
        session.attributes['Severity'] = 'moderate'
    elif score > 18 and score <= 22:
        # Severe Depression (Will categorize in the same category as very severe depression)
        score_message = render_template('severe', score=score)
        session.attributes['Severity'] = 'severe'
    elif score > 22:
        # Very Severe Depression
        score_message = render_template('very_severe', score=score)
        session.attributes['Severity'] = 'very severe'

    return question(score_message).simple_card(
        title='Your Hamilton Depression Rating Survey Score',
        content=render_template('HAMD_display_card',
                                score=score,
                                level=session.attributes['Severity']))
示例#6
0
def setDogNameHandler(dogName, sexFromIntent):
    if not dogName:
        printDebug(
            "SetDogNameIntent started without filled name slot. Re-asking.")
        return delegate()

    if sexFromIntent:
        sex = getUniqueSlotID(request.intent.slots.Sex)

        # Sex is given, but is invalid. Explicitely ask for it
        if not sex:
            printDebug("Invalid sex. Re-asking")
            del request.intent.slots.Sex['value']
            del request.intent.slots.Sex['resolutions']
            printDebug(
                "Updated request to remove invalid sex: {}".format(request))
            session.attributes[LAST_QUESTION] = SEX_ASKED
            speech_output = render_template("invalid_sex_ask_again",
                                            dog=dogName)
            return elicit_slot("Sex",
                               speech_output,
                               updated_intent=request.intent)
        saveDogForUser(session.user.userId, dogName=dogName, sex=sex)

        speech_output = render_template('dog_name_set_sex_set',
                                        dog=dogName,
                                        pronoun=render_template(sex +
                                                                '_pronoun'))
        reprompt = render_template('should_start_training')
        card_title = render_template('dog_name_set_card_title', dog=dogName)
        card_content = render_template('dog_name_set_card_content',
                                       dog=dogName)
        session.attributes[LAST_QUESTION] = SHOULD_START_TRAINING

        return question(speech_output).reprompt(reprompt).simple_card(
            card_title, card_content)

    else:
        try:
            existingDog = getDogFromDynamoDB(session.user.userId)
            oldSex = existingDog[PREVIOUS_DOGS][dogName]
            print(oldSex)
            assert oldSex != UNKNOWN
            saveDogForUser(session.user.userId, dogName=dogName, sex=oldSex)
            session.attributes[LAST_QUESTION] = SHOULD_START_TRAINING

            speech_output = render_template(
                'dog_name_set_again',
                dog=dogName,
                pronoun=render_template(oldSex + '_pronoun'))
            reprompt = render_template('should_start_training')
            card_title = render_template('dog_name_set_card_title',
                                         dog=dogName)
            card_content = render_template('dog_name_set_again_card_content',
                                           dog=dogName)
            return question(speech_output).reprompt(reprompt).simple_card(
                card_title, card_content)

        except Exception as e:
            printDebug(
                "The old sex was invalid or did not exist, asking again.")
            saveDogForUser(session.user.userId, dogName=dogName, sex=UNKNOWN)
            session.attributes[LAST_QUESTION] = SEX_ASKED
            speech_output = render_template("dog_name_set", dog=dogName)
            return elicit_slot("Sex", speech_output)