Ejemplo n.º 1
0
def check_condition(items, cont, quantity):
    g = nltk.Assignment(folval.domain)
    m = nltk.Model(folval.domain, folval)
    # Checking if a field has all/any(some) items in it
    sent = quantity + ' ' + items + ' are_in ' + cont
    results = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
    if results[2]:
        return 'Yes.'
    else:
        return 'No.'
Ejemplo n.º 2
0
def check_for_car(input_arr):
    # check car locations
    input_arr = remove_spaces(input_arr)
    g = nltk.Assignment(fol_val.domain)
    m = nltk.Model(fol_val.domain, fol_val)
    sent = 'some ' + input_arr[1] + ' are_in ' + input_arr[2]
    answer = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
    if answer[2]:
        print("Your", input_arr[1], "is in", input_arr[2])
    else:
        print("Your", input_arr[1], "is not in", input_arr[2])
 def answer(self, sentence):
     words = sentence.split(" ")
     sanatized_sentence = " ".join(list(map(self.__sanatizeWord, words)))
     try:
         results = nltk.evaluate_sents([sanatized_sentence], self.grammar,
                                       self.model, self.assignment)
         (_, logical_expression, value) = results[0][0]
         (response, new_value) = self.__format_response(logical_expression)
         return (logical_expression, new_value, response)
     except:
         return ("", None, "")
Ejemplo n.º 4
0
 def is_all_cards_in_zone(self, location_input):
     g = nltk.Assignment(self.valuation.domain)
     m = nltk.Model(self.valuation.domain, self.valuation)
     location = self.translate_location(location_input)
     if location is None:
         print("That doesn't make sense :(")
         return
     sent = "all card are_in " + location
     results = nltk.evaluate_sents([sent], self.grammar_file, m, g)[0][0]
     if results[2] == True:
         print("Yes.")
     else:
         print("No.")
Ejemplo n.º 5
0
                     if ('',) in folval["be_in"]:
                         folval["be_in"].clear()
                 folval["be_in"].add((o, folval[recipe])) #insert location
                 print("Bot: Added!")
 elif cmd == 5: #Are there any x in y
     if folval.__contains__(params[1]) == False:
         print("Bot: Sorry but the ingredient does not exist")
     else:
         if params[2] not in recipeList:
             print("Bot: The recipe does not exist")
         else:
             g = nltk.Assignment(folval.domain)
             m = nltk.Model(folval.domain, folval)
             recipe = "recipe" + str(recipeList.index(params[2]))
             sent = 'some ' + params[1] + ' are_in ' + recipe
             results = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
             if results[2] == True:
                 print("Yes.")
             else:
                 print("No.")
 elif cmd == 6: # Are all x in y
     if folval.__contains__(params[1]) == False:
         print("Bot: Sorry but the ingredient does not exist")
     else:
         if params[2] not in recipeList:
             print("Bot: The recipe does not exist")
         else:
             g = nltk.Assignment(folval.domain)
             m = nltk.Model(folval.domain, folval)
             recipe = "recipe" + str(recipeList.index(params[2]))
             sent = 'all ' + params[1] + ' are_in ' + recipe
Ejemplo n.º 6
0
v = """
bertie=>b
olive=>o
cyril=>c
boy=>{b}
girl=>{o}
dog=>{c}
walk=>{o,c}
see=>{(b,o),(c,b),(o,c)}
"""
val = nltk.Valuation.fromstring(v)
grammar = nltk.Assignment(val.domain)
model = nltk.Model(val.domain, val)
sent = 'Cyril sees every boy'
grammar_file = 'grammars/book_grammars/simple-sem.fcfg'
results = nltk.evaluate_sents([sent], grammar_file, model, grammar)[0]
for (synrep, semrep, value) in results:
    print(synrep)
    print(semrep)
    print(value)

# 4.5 量词歧义(同一个句子的不同的量词表示,可以跳过)
# 在语义表示与句法分析紧密耦合的前提下,语义中量词的范围也反映了句法分析树中对应的NP的相对范围。
# Cooper存储:是由“核心”语义表示与绑定操作符链表组成的配对。
# S-检索:结合了绑定操作符与核心的操作。
# 建立一个“核心+存储表示”的组合
# nltk.sem.cooper_storage将存储形式的语义表示转换成标准逻辑形式
from nltk.sem import cooper_storage as cs

sentence = 'every girl chases a dog'
trees = cs.parse_with_bindops(sentence,
Ejemplo n.º 7
0
"""

if mode == 1 or mode == 2:
    # Load model valuations
    val = nltk.Valuation.fromstring(v)

    # Initialize assignment g
    g = nltk.Assignment(val.domain)

    # Create model
    m = nltk.Model(val.domain, val)

    # Input sentence
    sent = inputAsString

    results = nltk.evaluate_sents([sent], grammar2, m, g)[0]

    for (syntree, semrep, value) in results:
        #print(semrep)
        #print(value)
        if value == True and mode == 1:
            print("I Know.")
            break
        elif value == False and mode == 1:
            print("I Don't think so.")
            break
        elif value == True and mode == 2:
            print("yes.")
            break
        elif value == False and mode == 2:
            print("No.")
Ejemplo n.º 8
0
def get_bot_response():
    while True:
        #get user input
        try:
            userInput = request.args.get('msg')
            userInput = str(userInput)
        except (KeyboardInterrupt, EOFError) as e:
            ans = "Bye!"
            return ans
            break
        #pre-process user input and determine response agent (if needed)
        responseAgent = 'query'
        #activate selected response agent
        if responseAgent == 'query':
            answer = kern.respond(userInput)
        #post-process the answer for commands
        if answer[0] == '#':
            params = answer[1:].split('$')
            cmd = int(params[0])
            if cmd == 0:
                ans = params[1]
                return ans
                break
            elif cmd == 1:
                wpage = wiki_wiki.page(params[1])
                if wpage.exists():
                    ans1 = wpage.summary[
                        0:300] + '...' + 'Learn more at ' + wpage.canonicalurl
                    return ans1
                else:
                    ans = "Sorry, I don't know what that is."
                    return ans
            elif cmd == 2:
                userInput = userInput.lower()
                return response(userInput)
            ######################################################
            # CFG phrases #
            ######################################################
            elif cmd == 4:  # I will buy x from y
                o = 'o' + str(objCounter)
                folval['o' + o] = o  #insert constant
                if len(folval[params[1]]) == 1:  #clean up if necessary
                    if ('', ) in folval[params[1]]:
                        folval[params[1]].clear()
                folval[params[1]].add((o, ))  #insert dog
                folval["be_in"].add((o, folval[params[2]]))  #insert location
                g = nltk.Assignment(folval.domain)
                m = nltk.Model(folval.domain, folval)
                sent = 'some ' + params[1] + ' are_in ' + params[2]
                results = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
                if results[2] == True:
                    ans = "There's some " + params[1] + " in " + params[2] + "."
                    return ans
                else:
                    ans = "No."
                    return ans
            elif cmd == 5:  #Are there any x in y
                g = nltk.Assignment(folval.domain)
                m = nltk.Model(folval.domain, folval)
                sent = 'some ' + params[1] + ' are_in ' + params[2]
                results = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
                if results[2] == True:
                    ans = "Yes. There are some " + params[1] + " in " + params[
                        2] + "."
                    return ans
                else:
                    ans = "No."
                    return ans
            elif cmd == 7:  # Which dogs are in ...
                g = nltk.Assignment(folval.domain)
                m = nltk.Model(folval.domain, folval)
                e = nltk.Expression.fromstring("be_in(x," + params[1] + ")")
                sat = m.satisfiers(e, "x", g)
                counter = 0
                ans = "The list of dogs available are: "
                if len(sat) == 0:
                    ans = "None."
                    return ans
                else:
                    #find satisfying objects in the valuation dictionary,
                    #and print their type names
                    sol = folval.values()
                    for so in sat:
                        for k, v in folval.items():
                            if counter == 5:
                                return ans
                                break
                            if len(v) > 0:
                                vl = list(v)
                                if len(vl[0]) == 1:
                                    for i in vl:
                                        if i[0] == so:
                                            if counter == 4:
                                                ans = ans + k + ". "
                                                counter = counter + 1
                                            else:
                                                ans = ans + k + ", "
                                                counter = counter + 1
                                                break

            elif cmd == 8:  # I will buy a x from y
                o = 'o' + str(objCounter)
                folval['o' + o] = o  #insert constant
                if len(folval[params[1]]) == 1:  #clean up if necessary
                    if ('', ) in folval[params[1]]:
                        folval[params[1]].clear()
                folval[params[1]].add((o, ))  #insert dog
                folval["be_in"].add((o, folval[params[2]]))  #insert location
                g = nltk.Assignment(folval.domain)
                m = nltk.Model(folval.domain, folval)
                sent = 'some ' + params[1] + ' is_in ' + params[2]
                results = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
                if results[2] == True:
                    ans = "Yes. You can buy your " + params[
                        1] + " from " + params[2]
                    return ans
                else:
                    ans = "No."
                    return ans
            elif cmd == 9:  #Did i buy my x from y
                g = nltk.Assignment(folval.domain)
                m = nltk.Model(folval.domain, folval)
                sent = 'some ' + params[1] + ' is_in ' + params[2]
                results = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
                if results[2] == True:
                    ans = "Yes. You said you bought the " + params[
                        1] + " from " + params[2]
                    return ans
                else:
                    ans = "No."
                    return ans
            elif cmd == 10:  #Did i buy x from y
                g = nltk.Assignment(folval.domain)
                m = nltk.Model(folval.domain, folval)
                sent = 'some ' + params[1] + ' are_in ' + params[2]
                results = nltk.evaluate_sents([sent], grammar_file, m, g)[0][0]
                if results[2] == True:
                    ans = "Yes. You bought your " + params[
                        1] + " from " + params[2]
                    return ans
                else:
                    ans = "No."
                    return ans

            elif cmd == 12:  # my x is named y
                o = 'o' + str(objCounter)
                if len(folval[params[1]]) == 1:  #clean up if necessary
                    if ('', ) in folval[params[1]]:
                        folval[params[1]].clear()
                #insert name of breed
                folval[params[1]].add((o, ))
                if len(folval["is_named"]) == 1:  #clean up if necessary
                    if ('', ) in folval["is_named"]:
                        folval["is_named"].clear()
                folval["is_named"].add((o, folval[params[2]]))  # name dog
                ans = params[2] + " seems like a nice dog."
                return ans

            ######################################################
            # Final submission implementation #
            ######################################################
            elif cmd == 19:
                # if they ask for which is the best food make the calc and send the response
                ans = dog_food_calc()
                return ans
            elif cmd == 99:
                # for everything else, send it to be predicted by the transformer network
                userInput = userInput.lower()
                return transformer_net_predict(userInput)

        else:
            return answer