def get_inventory(room_ID_0, username) -> str: #items == list of tuples items_db = database.get_all_user_items(username) if items_db is None: return "Your Inventory is empty" item_str = "Your inventory contains: <br><ul>" #index = 0 size = len(items_db) l.log_time("items_number: " + str(size)) # logging for i in items_db: item_name, room_ID_1 = i item_str = item_str + "<li>" + item_name + "</li>" # if index == 0: # item_str = item_str + item_name # elif index < size-1: # item_str = item_str + ", " + item_name # elif index == size-1: # item_str = item_str + " and " + item_name # else: # item_str = item_str + " ERROR!!! " + item_name # index += 1 item_str = item_str + "</ul>" return item_str
def checkSimilarity(word1: str, word2: str) -> int: l.log_time('pre-checkSimilarity') #logging if not word1.isalpha() or not word2.isalpha(): raise ValueError("words should only have alpha chars") synsofword1 = getSynonyms(word1, getWordtype(word1)) synsofword2 = getSynonyms(word2, getWordtype(word2)) l.log_time('post-checkSimilarity') #logging return len(set(synsofword1).intersection(synsofword2))
def classifyIntent(msg: str, choices: list) -> int: if not all(isinstance(choice, str) for choice in choices): raise TypeError("intent choices must be a list of strings") answer = process.extractOne(msg, choices, scorer=fuzz.partial_ratio) l.log_time('classify-Intent') #logging """ try: response = m1.classifiers.classify(model_id='cl_bEWrgUGS', data=[msg]).body[0].get("classifications")[0] except PlanQueryLimitError as e: print(e.error_code, e.detail) except MonkeyLearnException: raise Exception("Something went wrong with Monkey Learn") answer = [response.get("tag_name"), response.get("confidence")] if not isinstance(answer[0], str) or not isinstance(answer, list) or not isinstance(answer[1], float): raise TypeError("MonkeyLearn error created wrong types in the answer") """ return keyToNumber(answer[0], choices) if answer[1] >= 75 else keyToNumber( checkSynonyms(msg, choices), choices)
def checkSynonyms(msg: str, choices: list) -> str: if len(re.findall(r'[^\s!,.?":;0-9]+', msg)) > 10: return "i don't know" start = time.time() l.log_time('check') #logging listofwords = filterMessage(msg).split() l.log_time('filter') #logging typeofwords = list( map(lambda x: getWordtype(x, ' '.join(listofwords)), listofwords)) l.log_time('typeofwords') #logging wordsandtype = list(zip(listofwords, typeofwords)) #msgwordsynonyms = list(map(lambda x: getSynonyms(x[0],x[1]) , wordsandtype)) #new l.log_time('wordsandtype') #logging listofchoices = list(map(lambda x: filterMessage(x).split(), choices)) l.log_time('listofchoices') #logging results = [] l.log_time('pre-loop') #logging for intent in listofchoices: if not time.time() < start + 10: return "i don't know" results.append(0) for body in intent: #synsofbody = getSynonyms(body, getWordtype(body)) #new wordratings = [0] for tup in wordsandtype: #for tup, synsofword in zip(wordsandtype, msgwordsynonyms): #new if tup[1] == getWordtype(body): wordratings.append(checkSimilarity(body, tup[0])) #wordratings.append(len(set(synsofbody).intersection(synsofword))) results[len(results) - 1] += max(wordratings) l.log_time('post-loop') #logging return ["i dont know", choices[results.index(max(results))]][max(results) > 0]
def answerHandler(inputjson, username): l.log_start() # logging obj = json.loads(inputjson) # When the mode is phone and player inputs exit phone if str(obj['mode']) == 'phone' and classifyMessage( str(obj['message'].lower()), {"exit": ["exit", "leave", "shut down", "close"]}) == "exit": answer = ('You stop looking at the bad quality of your phone.', getRoomName(getRoomId(str(obj['room']))), 'game') # When the mode is phone elif str(obj['mode']) == 'phone': answer = [ handleAnswer(str(obj['message'].lower()), username, int(obj['level']), getRoomId(str(obj['room']))), getRoomName(getRoomId(str(obj['room']))), 'phone' ] # When the mode is gps and player inputs exit gps elif str(obj['mode']) == 'gps' and classifyMessage( str(obj['message'].lower()), {"exit": ["exit", "leave", "shut down", "close"]}) == "exit": answer = ('Your gps device is now turned off', getRoomName(getRoomId(str(obj['room']))), 'game') # When the mode is gps elif str(obj['mode']) == 'gps': cur_room_id = getRoomId(str(obj['room'])) gpsTriple = handleGPS(str(obj['message'].lower()), username, int(obj['level']), getRoomId(str(obj['room']))) if cur_room_id == gpsTriple[1]: answer = [gpsTriple[0], getRoomName(gpsTriple[1]), gpsTriple[2]] else: answer = [ gpsTriple[0] + "<br>" + get_gpt2_intro(getRoomIntroduction(gpsTriple[1]), username), getRoomName(gpsTriple[1]), gpsTriple[2] ] # When the mode is riddle elif str(obj['mode']) == 'riddle': answer = checkAnswer(str(obj['message'].lower()), getRoomId(str(obj['room'])), username) answer[1] = getRoomName(answer[1]) # When mode is game else: #l.log_time('remove_tables') #database.remove_unused_tables() answer = findAnswer(username, str(obj['message'].lower()), getRoomId(str(obj['room']))) if writeMessagetoTrainingData(str(obj['message'])): print("added message to training data") else: print("added nothing to training data") #text to spreech if it is turned on in the setting @author Max Petendra if json.loads(database.get_settings_by_username(username))['readMessages']: audio.playSound(formatHTMLText(answer[0])[0:200]) # json wird wieder zusammen gepackt l.log_time('end') # logging l.log_end() # logging #Check if a differnt sender is given if len(answer) <= 3: newSender = "bot" else: newSender = answer[3] database.update_user_room(username, getRoomId(answer[1])) #regular return statment return json.dumps({ "level": 1, "sender": newSender, "room": answer[1], "items": [], "mode": answer[2], "message": answer[0] })