Example #1
0
def suggestCommand(inCmd=[], inStr="", perform=False, fromAuto=False, matches=[[],[]]):
	CMDHIST = GLOB['CMDHIST']

	if not perform:
		perform = wordSim(inStr, "do what you want") >= 0.85

	cmdList, nameList = generateCmdList()

	if len(cmdList) == 0:
		if not fromAuto:
			say("I'm not sure what to do.", more=False, moodUpdate=True, speak=setting("SPEAK"))
		return True

	topCmd, topDelta, topUserCmd = longTermSatisfactionMaximization(cmdList, nameList)
	
	# only do something autonomously if the need has enough weight
	#   and you are not too lazy

	if not perform:
		
		rStr=processResponse(getResponse(inCmd), [topCmd])

		#print "top cmd: ", topUserCmd 
		rStr += ' ('+'%s'%k.sf(topDelta,2)+')'
		say(rStr, more=False, moodUpdate=True, speak=setting("SPEAK"))

	else:
		# say same thing as user when he issued command
		#print "top cmd: ", topUserCmd
		# only do thing if outcome is expected to be positive
		offLimits = ["suggestCommand", "none", "wrongCmd", "goodbye", "reminders"] # not allowed to do these
		if topDelta >= setting('LAZINESS') and topCmd not in offLimits:
			#print "performing: ", topUserCmd
			toSay='*'+topUserCmd+'*'
			say(toSay, more=False, moodUpdate=True, fromAuto=False, describeFace=True, speak=False, location="top")

			
			if fromAuto:

				# AI manually calls determineFunction
				retVal, cmd = determineFunction(topUserCmd)
				if retVal == "new prompt":
					newInput(findCMD("newInput"))
			else:
				# suggestion was called by determineFunction
				return [topUserCmd, True]

		else:
			if not fromAuto:
				retStr = "I'm okay."
				say(retStr, more=False, moodUpdate=True, speak=setting("SPEAK"))

	return True
Example #2
0
def intro():
	cmd=findCMD("intro")
	replacements=[]
	hour=datetime.datetime.now().hour

	# good morning
	if hour >= 5 and hour <= 11: 		replacements.append("Good morning")
	elif hour > 11 and hour <= 1+12:	replacements.append("Hello")
	elif hour > 1+12 and hour <= 4+12:	replacements.append("Good afternoon")
	elif hour > 4+12 and hour <= 24:	replacements.append("Good evening")
	else:								replacements.append("Good to see you")

	timeStr=datetime.datetime.now().strftime("%r, %A %d")
	replacements.append(timeStr)
	rStr=processResponse(getResponse(cmd), replacements)


	introAnimation()
	initCC()

	say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=False)
Example #3
0
def intro():
    cmd = findCMD("intro")
    replacements = []
    hour = datetime.datetime.now().hour

    # good morning
    if hour >= 5 and hour <= 11: replacements.append("Good morning")
    elif hour > 11 and hour <= 1 + 12: replacements.append("Hello")
    elif hour > 1 + 12 and hour <= 4 + 12:
        replacements.append("Good afternoon")
    elif hour > 4 + 12 and hour <= 24:
        replacements.append("Good evening")
    else:
        replacements.append("Good to see you")

    timeStr = datetime.datetime.now().strftime("%r, %A %d")
    replacements.append(timeStr)
    rStr = processResponse(getResponse(cmd), replacements)

    introAnimation()
    initCC()

    say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=False)
Example #4
0
def ingest(inCmd,
           inStr,
           mood=[],
           weight=[],
           isCmd=False,
           isMem=False,
           matches=[[], []]):
    from common import wordSim, processResponse, getResponse, say
    #from loadFile import load
    from determineFunction import findCMD, refineMatches
    from Fermi import substituteBiographicMemory

    if not (isCmd or isMem):
        matches = refineMatches(inCmd, inStr)
        matches = substituteBiographicMemory(matches, queryType='what is')

    if len(matches[0]) == 0 and not (isCmd or isMem):
        say(getResponse(findCMD("rephrase")),
            more=False,
            speak=setting("SPEAK"),
            moodUpdate=True)
        return False
    '''
	Algorithm:
		- load substance from list
		- record ingestion time
		- append to INGESTED list

	'''

    if isCmd:
        ingestionTime = time.time()

        taskProfile = "pow(2.0, -1.0*T*T/(900.0*900.0))"  # ~15 minute half life

        taskDetails = [[inCmd[0]], mood, weight, taskProfile]
        #print "appending: ", taskDetails

        GLOB['INGESTED'].append([taskDetails, ingestionTime, "COMMAND"])
        GLOB['MOOD'] = updateMood(GLOB['MOOD'], weight=[0] * GLOB['MOODDIM'])

        #print "AFTER CMD ADD"
        #print GLOB['MOOD']

        return  # no return value if adding a cmd mood modifier

    if isMem:
        #print "ADDING MEMORY MOOD"

        ingestionTime = time.time()

        memProfile = "pow(2.0, -1.0*T*T/(900.0*900.0))"  # ~15 minute half life

        memDetails = [[inStr], mood, weight, memProfile]
        #print "appending: ", taskDetails

        GLOB['INGESTED'].append([memDetails, ingestionTime, "MEMORY"])
        GLOB['MOOD'] = updateMood(GLOB['MOOD'], weight=[0] * GLOB['MOODDIM'])

        #print "AFTER CMD ADD"
        #print GLOB['MOOD']

        return  # no return value if adding a cmd mood modifier

    substances = load(SETS_DIR + "substances.txt", LPC=5)
    # line 0: name(s)
    # line 1: effect
    # line 2: weight
    # line 3: profile equations
    # line 4: response formats
    '''
	for matchStr in inCmd[1]:
		matchStr= matchStr.replace('juice','')
		inStr = inStr.replace(matchStr, '')
	'''

    # find top match

    maxMatch = 0
    topSubstance = []
    for substance in substances:
        for matchPhrase in substance[0]:
            matchScore = wordSim(matches[0][0], matchPhrase, useInScore=True)
            #print matchPhrase, inStr, matchScore
            if matchScore >= maxMatch:
                maxMatch = matchScore
                topSubstance = substance

    if setting('DEBUG'):
        print "INGESTION SCORE:", topSubstance[0], " - ", maxMatch

    # topSubstance[4]:

    #replacements = [topSubstance[0][randint(0,len(topSubstance[0])-1)]]
    replacements = topSubstance[0][randint(0,
                                           len(topSubstance[0]) -
                                           1)]  #matches[0][0] #
    #rStr = processResponse(getResponse(inCmd), replacements)
    responseForm = topSubstance[4][randint(0, len(topSubstance[4]) - 1)]
    rStr = processResponse(responseForm, [replacements])

    say(rStr, more=False, speak=setting("SPEAK"))

    # now modify mood accordingly
    ingestionTime = time.time()

    #print "appending: ", topSubstance

    GLOB['INGESTED'].append([topSubstance, ingestionTime, "SUBSTANCE"])

    #print "BEFORE UPDATE"
    #print GLOB['MOOD']

    GLOB['MOOD'] = updateMood(GLOB['MOOD'], weight=[0] * GLOB['MOODDIM'])

    #print "AFTER SUBSTANCE ADD"
    #print GLOB['MOOD']

    return [topSubstance[0][0], True]
Example #5
0
def ingest(inCmd, inStr, mood=[], weight=[], isCmd=False, isMem=False, matches=[[],[]]):
	from common import wordSim, processResponse, getResponse, say
	#from loadFile import load
	from determineFunction import findCMD, refineMatches
	from Fermi import substituteBiographicMemory

	if not (isCmd or isMem):
		matches = refineMatches(inCmd, inStr)
		matches = substituteBiographicMemory(matches, queryType='what is')

	if len(matches[0]) ==0 and not (isCmd or isMem):
		say(getResponse(findCMD("rephrase")), more=False, speak=setting("SPEAK"), moodUpdate=True)
		return False

	'''
	Algorithm:
		- load substance from list
		- record ingestion time
		- append to INGESTED list

	'''

	if isCmd:
		ingestionTime = time.time()
		
		taskProfile="pow(2.0, -1.0*T*T/(900.0*900.0))" # ~15 minute half life
		
		taskDetails = [[inCmd[0]], mood, weight, taskProfile]
		#print "appending: ", taskDetails

		GLOB['INGESTED'].append([taskDetails, ingestionTime, "COMMAND"])
		GLOB['MOOD']=updateMood(GLOB['MOOD'], weight=[0]*GLOB['MOODDIM'])
		
		#print "AFTER CMD ADD"
		#print GLOB['MOOD']

		return # no return value if adding a cmd mood modifier

	if isMem:
		#print "ADDING MEMORY MOOD"

		ingestionTime = time.time()
		
		memProfile="pow(2.0, -1.0*T*T/(900.0*900.0))" # ~15 minute half life
		


		memDetails = [[inStr], mood, weight, memProfile]
		#print "appending: ", taskDetails

		GLOB['INGESTED'].append([memDetails, ingestionTime, "MEMORY"])
		GLOB['MOOD']=updateMood(GLOB['MOOD'], weight=[0]*GLOB['MOODDIM'])
		
		#print "AFTER CMD ADD"
		#print GLOB['MOOD']

		return # no return value if adding a cmd mood modifier




	substances = load(SETS_DIR+"substances.txt", LPC=5)
	# line 0: name(s)
	# line 1: effect
	# line 2: weight
	# line 3: profile equations
	# line 4: response formats

	'''
	for matchStr in inCmd[1]:
		matchStr= matchStr.replace('juice','')
		inStr = inStr.replace(matchStr, '')
	'''

	# find top match

	maxMatch=0
	topSubstance=[]
	for substance in substances:
		for matchPhrase in substance[0]:
			matchScore = wordSim(matches[0][0], matchPhrase, useInScore=True)
			#print matchPhrase, inStr, matchScore
			if matchScore >= maxMatch:
				maxMatch = matchScore
				topSubstance = substance

	if setting('DEBUG'):
		print "INGESTION SCORE:", topSubstance[0], " - ", maxMatch

	# topSubstance[4]: 

	#replacements = [topSubstance[0][randint(0,len(topSubstance[0])-1)]]
	replacements = topSubstance[0][randint(0,len(topSubstance[0])-1)] #matches[0][0] #
	#rStr = processResponse(getResponse(inCmd), replacements)
	responseForm = topSubstance[4][randint(0,len(topSubstance[4])-1)]
	rStr = processResponse(responseForm, [replacements])
	
	say(rStr, more=False, speak=setting("SPEAK"))



	# now modify mood accordingly
	ingestionTime = time.time()

	#print "appending: ", topSubstance



	GLOB['INGESTED'].append([topSubstance, ingestionTime, "SUBSTANCE"])


	#print "BEFORE UPDATE"
	#print GLOB['MOOD']

	GLOB['MOOD']=updateMood(GLOB['MOOD'], weight=[0]*GLOB['MOODDIM'])

	#print "AFTER SUBSTANCE ADD"
	#print GLOB['MOOD']

	return [topSubstance[0][0], True]
Example #6
0
def changeSettings(inCmd, inStr, matches=[[],[]]):
	from determineFunction import refineMatches, findCMD


	if len(matches[0]) != 2:
		return ["", False]

	topSetting = ""
	topSettingType = type(True)
	topScore = 0
	for i in range(len(GLOB['SETTINGS'])):
		
		score = wordSim(GLOB['SETTINGS'][i][0].replace('_',' '), matches[0][0], basic=True)
		
		if score > topScore:
			topScore = score
			topSetting = GLOB['SETTINGS'][i][0]
			topSettingType = type(GLOB['SETTINGS'][i][1])


	
	if setting('DEBUG'):
		print "CHANGE SETTINGS\n\ttopSetting:", topSetting, "score:", topScore
		print "\tqueryStr:", matches[0][0]

	if topScore < 0.9:
		return ["", False]


	newSetting = matches[0][1]
	if isinstance(True, topSettingType):

		# its a boolean setting
		if wordSim(matches[0][1], "True", basic=True) >= wordSim(matches[0][1], "False", basic=True):
			newSetting = True
		else:
			newSetting = False

	elif isinstance(1.0, topSettingType) or isinstance(1, topSettingType):
	
		# its a number
		valMatches = re.findall("[-+]?\d+[\.]?\d*", inStr)
		if len(valMatches) != 1:
			say(getResponse(findCMD("rephrase")), more=False, speak=setting("SPEAK"), moodUpdate=True)
			return ["", False]
		else:
			newSetting = float(valMatches[0])
	#else:
		# must be a string?



	#print "changing:", topSetting
	#print "to:", newSetting

	try:
		updateSettings(topSetting, newSetting)
	except:
		say(getResponse(findCMD("rephrase")), more=False, speak=setting("SPEAK"), moodUpdate=True)
		pass
		return ["", False]

	return [topSetting+'-'+'_'.join(('%s'%newSetting).split()), True]
Example #7
0
def reminders(inCmd, inStr, matches=[[], []]):
    from determineFunction import refineMatches, findCMD
    from Fermi import substituteBiographicMemory
    from timeParsing import getTimeVec

    #print "HERE"

    matches = refineMatches(inCmd, inStr)

    matches = substituteBiographicMemory(matches,
                                         queryType='what is',
                                         append=True,
                                         maxContextSub=5)

    inStr = inStr.lower()

    if len(matches[1]) == 0:
        matches[1].append("add")  # default mode

    #print "MATCHES:", matches

    mode = ""

    if "add" in matches[1]:
        mode = "add"
    elif "list" in matches[1]:
        mode = "list"
    elif "check" in matches[1] or "check off" in matches[1]:
        mode = "check"
    elif "uncheck" in matches[1]:
        mode = "uncheck"
    elif "delete" in matches[1] or "remove" in matches[1]:
        mode = "delete"
    elif "purge" in inStr:
        mode = "purge"
    elif len(matches[0]) > 0:
        mode = "add"
    else:
        say(getResponse(findCMD("rephrase")),
            more=False,
            speak=setting("SPEAK"),
            moodUpdate=True)
        return False

    #print "MODE:", mode

    REMINDERS = load(DATA_DIR + "reminders.txt", LPC=1)
    REMINDERS = [s[0] for s in REMINDERS]

    #print REMINDERS

    #return True

    updateReminders = False

    if mode == "add":
        # see if you need to ask for the reminder to add
        #if newStr.split() == [] or k.cleanWord(newStr)=='':
        if len(matches[0]) == 0:

            #say("What reminder would you like to add?", more=True, speak=setting("SPEAK"), moodUpdate=True)

            newStr = questionBox("What reminder would you like to add?")

            #newStr = raw_input("")

            if newStr == "xx":
                return True
            else:
                matches[0].append(newStr)

        # look for a time tag
        if "@+" in matches[0][0]:
            matches[0].append(matches[0][0][matches[0][0].index("@+") + 2:])
            matches[0][0] = matches[0][0][:matches[0][0].index("@+")]
            matches[0][0] = matches[0][0].strip()
            matches[0][1] = matches[0][1].strip()

        TD = []
        if len(matches[0]) == 1:
            # see if it has a time tag
            timeNow = getTimeVec("now")
            if "@-" in matches[0][0]:  # prevent any time tags
                TD = timeNow
                matches[0][0] = matches[0][0].replace("@-", "").strip()
            else:
                TD = getTimeVec(matches[0][0])
            timeVec = [
                TD["year"], TD["month"], TD["day"], TD["hour"], TD["minute"],
                TD["second"]
            ]
        else:
            # time tag said after @
            #print "TIME TAG:", matches[0][1]
            timeNow = getTimeVec("now")
            TD = getTimeVec(matches[0][1])
            timeVec = [
                TD["year"], TD["month"], TD["day"], TD["hour"], TD["minute"],
                TD["second"]
            ]

        rStr = processResponse(getResponse(inCmd), ["Adding", matches[0][0]])
        say(rStr, more=False, speak=setting("SPEAK"))

        if abs(secondsDiff(timeNow, TD)) >= 10:
            rStr = "I will remind you " + timeDiff(TD) + "."
            say(rStr, more=False, speak=setting("SPEAK"))
        else:
            timeVec = []

        # message, time tag, been reminded
        REMINDERS.append((matches[0][0], timeVec, False))
        updateReminders = True

    if mode == "check":
        # see if you need to ask for the reminder to check off
        if len(matches[0]) == 0:
            #say("What reminder would you like to check off?", more=True, speak=setting("SPEAK"), moodUpdate=True)
            #newStr = raw_input("")
            newStr = questionBox("What reminder would you like to check off?")
            if newStr == "xx":
                return True
            else:
                matches[0].append(newStr)

        maxMatch = 0  # calculate nearest reminder
        topLine = 0  # save index of line to delete

        for i in range(len(REMINDERS)):
            matchScore = wordSim(REMINDERS[i][0], matches[0][0])
            if matchScore >= maxMatch:
                maxMatch = matchScore
                topLine = i

        rStr = processResponse(
            "Are you sure you would like to check off: #0#?",
            [REMINDERS[topLine][0]])
        #say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
        #YN=raw_input("")
        #if getYesNo(YN):
        YN = yesNoBox(rStr)
        if YN:
            # remove reminders
            REMINDERS[topLine] = (REMINDERS[topLine][0], REMINDERS[i][1], True)
            say("Note checked off!",
                more=False,
                speak=setting("SPEAK"),
                moodUpdate=True)
            updateReminders = True

    if mode == "uncheck":
        # see if you need to ask for the reminder to check off
        if len(matches[0]) == 0:
            #say("What reminder would you like to uncheck?", more=True, speak=setting("SPEAK"), moodUpdate=True)
            #newStr = raw_input("")
            newStr = questionBox("What reminder would you like to uncheck?")
            if newStr == "xx":
                return True
            else:
                matches[0].append(newStr)

        maxMatch = 0  # calculate nearest reminder
        topLine = 0  # save index of line to delete

        for i in range(len(REMINDERS)):
            matchScore = wordSim(REMINDERS[i][0], matches[0][0])
            if matchScore >= maxMatch:
                maxMatch = matchScore
                topLine = i

        rStr = processResponse("Are you sure you would like to uncheck: #0#?",
                               [REMINDERS[topLine][0]])
        #say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
        #YN=raw_input("")
        #if getYesNo(YN):
        YN = yesNoBox(rStr)
        if YN:
            # remove reminders
            REMINDERS[topLine] = (REMINDERS[topLine][0], REMINDERS[i][1],
                                  False)
            say("Note unchecked.",
                more=False,
                speak=setting("SPEAK"),
                moodUpdate=True)
            updateReminders = True

    if mode == "list":
        histCatStr = ""
        for item in REMINDERS:
            checkedStr = ""
            countDownStr = ""
            if item[2]:
                checkedStr = "[" + u'\u2713' + "]"
            elif item[1] != []:
                checkedStr = "[*]"
                countDownStr = timeDiff(toDict(item[1]), short=True)
            else:
                checkedStr = "[ ]"
            #print "\t"+checkedStr+'%10s'%(countDownStr)+" | "+item[0]

            #tkHistCat(checkedStr+'%10s'%(countDownStr)+" | "+item[0]+'\n')
            histCatStr += checkedStr + '%10s' % (
                countDownStr) + " | " + item[0] + '\n'

        if histCatStr != "":
            tkHistCat(histCatStr)

        if len(REMINDERS) == 0:
            say("No reminders currently saved.",
                more=False,
                speak=setting("SPEAK"),
                moodUpdate=True)

        return True

    if mode == "delete":
        #if newStr.split() == [] or k.cleanWord(newStr)=='':
        if len(matches[0]) == 0:
            #say("What reminder would you like to delete?", more=True, speak=setting("SPEAK"), moodUpdate=True)
            #newStr = raw_input("")
            newStr = questionBox("What reminder would you like to delete?")
            if newStr == "xx":
                return True
            else:
                matches[0].append(newStr)

        maxMatch = 0  # calculate nearest reminder
        topLine = 0  # save index of line to delete

        for i in range(len(REMINDERS)):
            matchScore = wordSim(REMINDERS[i][0], matches[0][0])
            if matchScore >= maxMatch:
                maxMatch = matchScore
                topLine = i

        rStr = processResponse("Are you sure you would like to delete: #0#?",
                               [REMINDERS[topLine][0]])
        #say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
        #YN=raw_input("")
        #if getYesNo(YN):
        YN = yesNoBox(rStr)
        if YN:
            # remove reminders
            REMINDERS = REMINDERS[:topLine] + REMINDERS[topLine + 1:]
            say("Note deleted.",
                more=False,
                speak=setting("SPEAK"),
                moodUpdate=True)
            updateReminders = True

    if mode == "purge":

        rStr = "Are you sure you would like to delete all checked notes?"
        #say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
        #YN=raw_input("")
        #if getYesNo(YN):
        YN = yesNoBox(rStr)
        if YN:
            # remove reminders

            REMINDERS = [item for item in REMINDERS if item[2] == False]

            say("Checked notes deleted.",
                more=False,
                speak=setting("SPEAK"),
                moodUpdate=True)
            updateReminders = True

    # want to overwrite ingestions file

    if updateReminders:
        f = open(DATA_DIR + 'reminders.txt', 'w')
        for item in REMINDERS:
            userStr = k.cleanWord(item[0], cleanType=1)
            f.write("\'%s\', %s, %s\n" % (userStr, item[1], item[2]))
        f.close()

    #checkReminders()

    return True
Example #8
0
def suggestCommand(inCmd=[],
                   inStr="",
                   perform=False,
                   fromAuto=False,
                   matches=[[], []]):
    CMDHIST = GLOB['CMDHIST']

    if not perform:
        perform = wordSim(inStr, "do what you want") >= 0.85

    cmdList, nameList = generateCmdList()

    if len(cmdList) == 0:
        if not fromAuto:
            say("I'm not sure what to do.",
                more=False,
                moodUpdate=True,
                speak=setting("SPEAK"))
        return True

    topCmd, topDelta, topUserCmd = longTermSatisfactionMaximization(
        cmdList, nameList)

    # only do something autonomously if the need has enough weight
    #   and you are not too lazy

    if not perform:

        rStr = processResponse(getResponse(inCmd), [topCmd])

        #print "top cmd: ", topUserCmd
        rStr += ' (' + '%s' % k.sf(topDelta, 2) + ')'
        say(rStr, more=False, moodUpdate=True, speak=setting("SPEAK"))

    else:
        # say same thing as user when he issued command
        #print "top cmd: ", topUserCmd
        # only do thing if outcome is expected to be positive
        offLimits = [
            "suggestCommand", "none", "wrongCmd", "goodbye", "reminders"
        ]  # not allowed to do these
        if topDelta >= setting('LAZINESS') and topCmd not in offLimits:
            #print "performing: ", topUserCmd
            toSay = '*' + topUserCmd + '*'
            say(toSay,
                more=False,
                moodUpdate=True,
                fromAuto=False,
                describeFace=True,
                speak=False,
                location="top")

            if fromAuto:

                # AI manually calls determineFunction
                retVal, cmd = determineFunction(topUserCmd)
                if retVal == "new prompt":
                    newInput(findCMD("newInput"))
            else:
                # suggestion was called by determineFunction
                return [topUserCmd, True]

        else:
            if not fromAuto:
                retStr = "I'm okay."
                say(retStr,
                    more=False,
                    moodUpdate=True,
                    speak=setting("SPEAK"))

    return True
Example #9
0
def changeSettings(inCmd, inStr, matches=[[], []]):
    from determineFunction import refineMatches, findCMD

    if len(matches[0]) != 2:
        return ["", False]

    topSetting = ""
    topSettingType = type(True)
    topScore = 0
    for i in range(len(GLOB['SETTINGS'])):

        score = wordSim(GLOB['SETTINGS'][i][0].replace('_', ' '),
                        matches[0][0],
                        basic=True)

        if score > topScore:
            topScore = score
            topSetting = GLOB['SETTINGS'][i][0]
            topSettingType = type(GLOB['SETTINGS'][i][1])

    if setting('DEBUG'):
        print "CHANGE SETTINGS\n\ttopSetting:", topSetting, "score:", topScore
        print "\tqueryStr:", matches[0][0]

    if topScore < 0.9:
        return ["", False]

    newSetting = matches[0][1]
    if isinstance(True, topSettingType):

        # its a boolean setting
        if wordSim(matches[0][1], "True", basic=True) >= wordSim(
                matches[0][1], "False", basic=True):
            newSetting = True
        else:
            newSetting = False

    elif isinstance(1.0, topSettingType) or isinstance(1, topSettingType):

        # its a number
        valMatches = re.findall("[-+]?\d+[\.]?\d*", inStr)
        if len(valMatches) != 1:
            say(getResponse(findCMD("rephrase")),
                more=False,
                speak=setting("SPEAK"),
                moodUpdate=True)
            return ["", False]
        else:
            newSetting = float(valMatches[0])
    #else:
    # must be a string?

    #print "changing:", topSetting
    #print "to:", newSetting

    try:
        updateSettings(topSetting, newSetting)
    except:
        say(getResponse(findCMD("rephrase")),
            more=False,
            speak=setting("SPEAK"),
            moodUpdate=True)
        pass
        return ["", False]

    return [topSetting + '-' + '_'.join(('%s' % newSetting).split()), True]
Example #10
0
def reminders(inCmd, inStr, matches=[[],[]]):
	from determineFunction import refineMatches, findCMD
	from Fermi import substituteBiographicMemory
	from timeParsing import getTimeVec

	#print "HERE"

	matches = refineMatches(inCmd, inStr)

	matches = substituteBiographicMemory(matches, queryType='what is', append=True, maxContextSub=5)

	inStr = inStr.lower()


	if len(matches[1]) == 0:
		matches[1].append("add") # default mode

	#print "MATCHES:", matches

		
	mode=""
	
	if "add" in matches[1]:
		mode="add"
	elif "list" in matches[1]:
		mode="list"
	elif "check" in matches[1] or "check off" in matches[1]:
		mode="check"
	elif "uncheck" in matches[1]:
		mode="uncheck"
	elif "delete" in matches[1] or "remove" in matches[1]:
		mode="delete"
	elif "purge" in inStr:
		mode="purge"
	elif len(matches[0]) > 0:
		mode = "add"
	else:
		say(getResponse(findCMD("rephrase")), more=False, speak=setting("SPEAK"), moodUpdate=True)
		return False

	#print "MODE:", mode
	
	

	REMINDERS=load(DATA_DIR+"reminders.txt", LPC=1)
	REMINDERS=[s[0] for s in REMINDERS]

	#print REMINDERS

	#return True

	updateReminders = False
	
	
	if mode=="add":
		# see if you need to ask for the reminder to add
		#if newStr.split() == [] or k.cleanWord(newStr)=='':
		if len(matches[0]) == 0:
			

			#say("What reminder would you like to add?", more=True, speak=setting("SPEAK"), moodUpdate=True)

			newStr=questionBox("What reminder would you like to add?")
			
			#newStr = raw_input("")
			


			if newStr == "xx":
				return True
			else:
				matches[0].append(newStr)

		# look for a time tag
		if "@+" in matches[0][0]:
			matches[0].append(matches[0][0][matches[0][0].index("@+")+2:])
			matches[0][0] = matches[0][0][:matches[0][0].index("@+")]
			matches[0][0] = matches[0][0].strip()
			matches[0][1] = matches[0][1].strip()

		TD=[]
		if len(matches[0]) == 1:
			# see if it has a time tag
			timeNow = getTimeVec("now")
			if "@-" in matches[0][0]: # prevent any time tags
				TD = timeNow
				matches[0][0] = matches[0][0].replace("@-", "").strip()
			else:
				TD = getTimeVec(matches[0][0])
			timeVec=[TD["year"], TD["month"],TD["day"],TD["hour"],TD["minute"],TD["second"]]
		else:
			# time tag said after @
			#print "TIME TAG:", matches[0][1]
			timeNow = getTimeVec("now")
			TD = getTimeVec(matches[0][1])
			timeVec=[TD["year"], TD["month"],TD["day"],TD["hour"],TD["minute"],TD["second"]]

		rStr = processResponse(getResponse(inCmd), ["Adding", matches[0][0]])
		say(rStr, more=False, speak=setting("SPEAK"))

		if abs(secondsDiff(timeNow, TD)) >= 10:
			rStr = "I will remind you "+timeDiff(TD)+"."
			say(rStr, more=False, speak=setting("SPEAK"))
		else:
			timeVec = []

		# message, time tag, been reminded
		REMINDERS.append((matches[0][0], timeVec, False))
		updateReminders = True

	if mode=="check":
		# see if you need to ask for the reminder to check off
		if len(matches[0]) == 0:
			#say("What reminder would you like to check off?", more=True, speak=setting("SPEAK"), moodUpdate=True)
			#newStr = raw_input("")
			newStr=questionBox("What reminder would you like to check off?")
			if newStr == "xx":
				return True
			else:
				matches[0].append(newStr)

		maxMatch=0 # calculate nearest reminder
		topLine=0 # save index of line to delete

		for i in range(len(REMINDERS)):
			matchScore = wordSim(REMINDERS[i][0], matches[0][0])
			if matchScore >= maxMatch:
				maxMatch = matchScore
				topLine=i

		rStr=processResponse("Are you sure you would like to check off: #0#?", [REMINDERS[topLine][0]])
		#say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
		#YN=raw_input("")
		#if getYesNo(YN):
		YN = yesNoBox(rStr)
		if YN:
			# remove reminders
			REMINDERS[topLine] = (REMINDERS[topLine][0], REMINDERS[i][1], True)
			say("Note checked off!", more=False, speak=setting("SPEAK"), moodUpdate=True)
			updateReminders = True

	if mode=="uncheck":
		# see if you need to ask for the reminder to check off
		if len(matches[0]) == 0:
			#say("What reminder would you like to uncheck?", more=True, speak=setting("SPEAK"), moodUpdate=True)
			#newStr = raw_input("")
			newStr=questionBox("What reminder would you like to uncheck?")
			if newStr == "xx":
				return True
			else:
				matches[0].append(newStr)

		maxMatch=0 # calculate nearest reminder
		topLine=0 # save index of line to delete

		for i in range(len(REMINDERS)):
			matchScore = wordSim(REMINDERS[i][0], matches[0][0])
			if matchScore >= maxMatch:
				maxMatch = matchScore
				topLine=i

		rStr=processResponse("Are you sure you would like to uncheck: #0#?", [REMINDERS[topLine][0]])
		#say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
		#YN=raw_input("")
		#if getYesNo(YN):
		YN = yesNoBox(rStr)
		if YN:
			# remove reminders
			REMINDERS[topLine] = (REMINDERS[topLine][0], REMINDERS[i][1], False)
			say("Note unchecked.", more=False, speak=setting("SPEAK"), moodUpdate=True)
			updateReminders = True


	if mode == "list":
		histCatStr=""
		for item in REMINDERS:
			checkedStr=""
			countDownStr=""
			if item[2]:
				checkedStr = "["+u'\u2713'+"]"
			elif item[1] != []:
				checkedStr = "[*]"
				countDownStr = timeDiff(toDict(item[1]), short=True)
			else:
				checkedStr = "[ ]"
			#print "\t"+checkedStr+'%10s'%(countDownStr)+" | "+item[0]
			
			#tkHistCat(checkedStr+'%10s'%(countDownStr)+" | "+item[0]+'\n')
			histCatStr += checkedStr+'%10s'%(countDownStr)+" | "+item[0]+'\n'

		if histCatStr != "":
			tkHistCat(histCatStr)
	
		if len(REMINDERS) == 0:
			say("No reminders currently saved.", more=False, speak=setting("SPEAK"), moodUpdate=True)
		
		return True


	if mode == "delete":
		#if newStr.split() == [] or k.cleanWord(newStr)=='':
		if len(matches[0]) == 0:
			#say("What reminder would you like to delete?", more=True, speak=setting("SPEAK"), moodUpdate=True)
			#newStr = raw_input("")
			newStr=questionBox("What reminder would you like to delete?")
			if newStr == "xx":
				return True
			else:
				matches[0].append(newStr)

		maxMatch=0 # calculate nearest reminder
		topLine=0 # save index of line to delete

		for i in range(len(REMINDERS)):
			matchScore = wordSim(REMINDERS[i][0], matches[0][0])
			if matchScore >= maxMatch:
				maxMatch = matchScore
				topLine=i

		rStr=processResponse("Are you sure you would like to delete: #0#?", [REMINDERS[topLine][0]])
		#say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
		#YN=raw_input("")
		#if getYesNo(YN):
		YN = yesNoBox(rStr)
		if YN:
			# remove reminders
			REMINDERS = REMINDERS[:topLine]+REMINDERS[topLine+1:]
			say("Note deleted.", more=False, speak=setting("SPEAK"), moodUpdate=True)
			updateReminders = True

	if mode == "purge":

		rStr="Are you sure you would like to delete all checked notes?"
		#say(rStr, more=True, speak=setting("SPEAK"), moodUpdate=True)
		#YN=raw_input("")
		#if getYesNo(YN):
		YN = yesNoBox(rStr)
		if YN:
			# remove reminders

			REMINDERS = [item for item in REMINDERS if item[2] == False]
			

			say("Checked notes deleted.", more=False, speak=setting("SPEAK"), moodUpdate=True)
			updateReminders = True	


	
	# want to overwrite ingestions file

	if updateReminders:
		f = open(DATA_DIR+'reminders.txt', 'w')
		for item in REMINDERS:
			userStr =  k.cleanWord(item[0], cleanType=1)
			f.write("\'%s\', %s, %s\n" % (userStr, item[1], item[2]))
		f.close()

	#checkReminders()

	return True