Exemplo n.º 1
0
def createStory():
    content = request.get_json(silent=True)

    story = Story()
    story.storyName = content.get("storyName")
    story.intentName = content.get("intentName")
    story.speechResponse = content.get("speechResponse")

    if content.get("apiTrigger") is True:
        story.apiTrigger = True
        apiDetails = ApiDetails()
        isJson = content.get("apiDetails").get("isJson")
        apiDetails.isJson = isJson
        if isJson:
            apiDetails.jsonData = content.get("apiDetails").get("jsonData")

        apiDetails.url = content.get("apiDetails").get("url")
        apiDetails.requestType = content.get("apiDetails").get("requestType")
        story.apiDetails = apiDetails
    else:
        story.apiTrigger = False

    if content.get("parameters"):
        for param in content.get("parameters"):
            parameter = Parameter()
            update_document(parameter,param)
            story.parameters.append(parameter)
    try:
        story.save()
    except Exception as e:
        return buildResponse.buildJson({"error": str(e)})
    return buildResponse.sentOk()
Exemplo n.º 2
0
def createBot():

    print("In create Bot")
    content = request.get_json(silent=True)
    print(content)
    bot = Bot()
    story = Story()
    bot.botName = content.get("botName")
    bot.botDescription = content.get("botDescription")
    bot.userId = session.__getattribute__("userid")

    print("userID", bot.userId)
    print("Bot Name", bot.botName)
    print("Bot Desc", bot.botDescription)

    try:
        bot.save()
        # botid= Bot.objects.get(botName=bot.botName)
        print("ID", bot.id)
        #   print("IDddd",ObjectId(bot._id)
        story.botId = bot.id
        story.storyName = 'init_conversation' + str(bot.id)
        story.intentName = 'init_conversation'
        story.speechResponse = 'Hi!!! This is ' + bot.botName + ' bot, your virtual assisstant. You can configure me as you need. For more options look at menu in right'
        story.apiTrigger = False
        story.save()

    except Exception as e:
        print({"error", str(e)})
        return "botNotcreated"
    return "BotCreated"
 def predict(self, sentence):
     predicted = sentenceClassifer.predict(sentence, self.PATH)
     if not predicted:
         return  Story.objects(
             intentName=app.config["DEFAULT_FALLBACK_INTENT_NAME"]).first().id
     else:
         return predicted["class"]
Exemplo n.º 4
0
def readStories():
    print("BotId session in /read1", session.__getattribute__('botid'))
    bid = session.__getattribute__('botid')
    print("JSON", request.get_json(silent=True))
    stories = Story.objects(botId=ObjectId(bid))
    print("Stories json", stories.to_json)
    return buildResponse.sentJson(stories.to_json())
Exemplo n.º 5
0
 def predict(self, sentence):
     predicted = sentenceClassifer.predict(sentence, self.PATH)
     if not predicted:
         return Story.objects(
             intentName=app.config["DEFAULT_FALLBACK_INTENT_NAME"]).first(
             ).id
     else:
         return predicted["class"]
Exemplo n.º 6
0
def readStories():
        if (session.__getattribute__('loginstat') == 'login'):
    
            print("BotId session in /read1",session.__getattribute__('botid'))
            bid=session.__getattribute__('botid')
            print("JSON",request.get_json(silent=True))
            stories = Story.objects(botId=ObjectId(bid))
            print("Stories json",stories.to_json)
            return buildResponse.sentJson(stories.to_json())
        else:
            return render_template('index.html')
Exemplo n.º 7
0
def readStories():
  botId=None
  if g.botId:
    botId=g.botId
  elif request.args.get('botId'):
    botId=request.args.get('botId')
  
  if botId:
      stories = Story.objects(bot = botId)
  else:
      stories = Story.objects
      #stories = [a.to_json() for a in stories if not a.bot]
  return buildResponse.sentJson(stories.to_json())
Exemplo n.º 8
0
def createStory():
    content = request.get_json(silent=True)

    story = Story()
    story.storyName = content.get("storyName")
    story.intentName = content.get("intentName")
    story.speechResponse = content.get("speechResponse")

    if content.get("parameters"):
        for param in content.get("parameters"):
            parameter = Parameter()
            update_document(parameter,param)
            story.parameters.append(parameter)
    try:
        story.save()
    except Exception as e:
        return {"error": e}
    return buildResponse.sentOk()
Exemplo n.º 9
0
    if "'" in username:
        username = username.split("'")[0]
    u = User("{}{}".format(username.strip(), random.randint(0, 2000)), "email{}@example.com".format(i), "password", datetime.datetime.now())
    db.session.add(u)
    db.session.commit()
print("done")

u = User.query.all()
paragraphs = json.loads(open("var/lorem.json", "r").read())
print("Creating stories")
for i in range(1, 1000):
    number_of_paragraphs = random.randint(1, 20)
    story_content = ""
    for x in range(0, number_of_paragraphs):
        story_content += "{}\n\n".format(random.choice(paragraphs))
    s = Story(1, "Story {}".format(i), story_content, datetime.datetime.now())
    s.user_id = random.randint(1, len(u))
    db.session.add(s)
    db.session.commit()
print("done")

print("Creating comments ")
s = Story.query.all()
for i in range(1, 10000):
    c = Comment(1, 1, random.choice(paragraphs), datetime.datetime.now())
    c.user_id = random.randint(1, len(u))
    c.story_id = random.randint(1, len(s))
    db.session.add(c)
    db.session.commit()
print("done")
Exemplo n.º 10
0
import nltk
import os

#creating directory for storing chat logs
if not os.path.exists("logs"):
    os.makedirs("logs")

try:
    from app.stories.models import Story, LabeledSentences

    # Setting up default intents
    newStory = Story()
    newStory.storyName = 'Default Fallback intent'
    newStory.intentName = 'fallback'
    newStory.speechResponse = "Sorry. I'm having trouble understanding you."
    newStory.apiTrigger = False
    newLabeledSentence = LabeledSentences()
    newLabeledSentence.data = [['', 'VB', 'O']]
    newStory.labeledSentences.append(newLabeledSentence)
    newStory.save()

    newStory = Story()
    newStory.storyName = 'cancel'
    newStory.intentName = 'cancel'
    newStory.speechResponse = "Ok. Canceled."
    newStory.apiTrigger = False
    newLabeledSentence = LabeledSentences()
    newLabeledSentence.data = [['cancel', 'VB', 'O'], ['close', 'VB', 'O']]
    newStory.labeledSentences.append(newLabeledSentence)
    newStory.save()
Exemplo n.º 11
0
def api():
    print("Inside /api/.v1")
    requestJson = request.get_json(silent=True)
    resultJson = requestJson
    print("Test.....", requestJson)
    print("Bot Iddddddddddddddddddddddddddddddd",requestJson.get("botId"))
    if requestJson:


        context = {}
        context["context"] = requestJson["context"]

        if app.config["DEFAULT_WELCOME_INTENT_NAME"] in requestJson.get(
                "input"):
            print("--------------insideif------------------")
            story = Story.objects(
                intentName=app.config["DEFAULT_WELCOME_INTENT_NAME"]).first()
            print("Story" , story)
            resultJson["complete"] = True
#            resultJson["intent"]["name"] = story.storyName
            resultJson["intent"]["storyId"] = str(story.id)
            resultJson["input"] = requestJson.get("input")
            template = Template(
                story.speechResponse,
                undefined=SilentUndefined)
            resultJson["speechResponse"] = template.render(**context)

            logger.info(requestJson.get("input"), extra=resultJson)
            return buildResponse.buildJson(resultJson)
        print("OutSide if")

        intentClassifier = IntentClassifier()
        try:
            storyId = intentClassifier.predict(requestJson.get("input"))
            print("Story Id",storyId)
        except AttributeError:
            resultJson["speechResponse"]="Question not available"
            return buildResponse.buildJson(resultJson)
        story = Story.objects.get(id=ObjectId(storyId))

        if story.parameters:
            print("Inside story.params")
            parameters = story.parameters
        else:
            print("No paramters")
            parameters = []

        if ((requestJson.get("complete") is None) or (
                requestJson.get("complete") is True)):
            print("Check whether complete is none or true")
            resultJson["intent"] = {
                "name": story.intentName,
                "storyId": str(story.id)
            }
            print(resultJson["intent"])

            if parameters:
                print("Check whether parametrs are present are not")
                extractedParameters = sequenceLabeler.predict(
                    storyId, requestJson.get("input"))
                print("Extracted parameters",extractedParameters)
                missingParameters = []
                resultJson["missingParameters"] = []
                resultJson["extractedParameters"] = {}
                resultJson["parameters"] = []
                for parameter in parameters:
                    print("If parameters are present")
                    resultJson["parameters"].append({
                        "name": parameter.name,
                        "type": parameter.type,
                        "required": parameter.required
                    })
                    print("Result JSON...",resultJson)

                    if parameter.required:
                        print("Check whether parameter is required are not")
                        if parameter.name not in extractedParameters.keys():
                            print("Check whether paramter name is present in extracted paramters")
                            resultJson["missingParameters"].append(
                                parameter.name)
                            missingParameters.append(parameter)
                            print("Result JSON2",resultJson)

                resultJson["extractedParameters"] = extractedParameters
                print("F Result json",resultJson)

                if missingParameters:
                    print("Check whether missing parameters is present or not")
                    resultJson["complete"] = False
                    currentNode = missingParameters[0]
                    resultJson["currentNode"] = currentNode["name"]
                    resultJson["speechResponse"] = currentNode["prompt"]
                    print("Inside missingparameters if ",resultJson)
                else:
                    resultJson["complete"] = True
                    context["parameters"] = extractedParameters
            else:
                resultJson["complete"] = True

        elif (requestJson.get("complete") is False):
            if "cancel" not in story.intentName:
                storyId = requestJson["intent"]["storyId"]
                story = Story.objects.get(id=ObjectId(storyId))
                resultJson["extractedParameters"][requestJson.get(
                    "currentNode")] = requestJson.get("input")

                resultJson["missingParameters"].remove(
                    requestJson.get("currentNode"))

                if len(resultJson["missingParameters"]) == 0:
                    resultJson["complete"] = True
                    context = {}
                    context["parameters"] = resultJson["extractedParameters"]
                    context["context"] = requestJson["context"]
                else:
                    missingParameter = resultJson["missingParameters"][0]
                    resultJson["complete"] = False
                    currentNode = [
                        node for node in story.parameters if missingParameter in node.name][0]
                    resultJson["currentNode"] = currentNode.name
                    resultJson["speechResponse"] = currentNode.prompt
            else:
                resultJson["currentNode"] = None
                resultJson["missingParameters"] = []
                resultJson["parameters"] = {}
                resultJson["intent"] = {}
                resultJson["complete"] = True

        if resultJson["complete"]: 
            if story.apiTrigger:
                isJson = False
                isHeader=False
                parameters = resultJson["extractedParameters"]

                urlTemplate = Template(story.apiDetails.url, undefined=SilentUndefined)
                renderedUrl = urlTemplate.render(**context)
                if story.apiDetails.isJson and story.apiDetails.isHeader:
                    isJson = True
                    isHeader= True
                    requestTemplate = Template(story.apiDetails.jsonData,story.apiDetails.headerData, undefined=SilentUndefined)
                    parameters = requestTemplate.render(**context)
                elif story.apiDetails.isJson:
                    isJson = True
                    requestTemplate = Template(story.apiDetails.jsonData,
                                               undefined=SilentUndefined)
                    parameters = requestTemplate.render(**context)
                elif story.apiDetails.isHeader:
                    isHeader = True
                    requestTemplate = Template(story.apiDetails.headerData,
                                               undefined=SilentUndefined)
                    parameters = requestTemplate.render(**context)
                try:
                    result = callApi(renderedUrl,
                                     story.apiDetails.requestType,
                                     parameters,story.apiDetails.headerData,isJson,isHeader)
                except Exception as e:
                    print(e)
                    resultJson["speechResponse"] = "Service is not available. "
                else:
                    print(result)
                    context["result"] = result
                    template = Template(story.speechResponse, undefined=SilentUndefined)
                    resultJson["speechResponse"] = template.render(**context)
            else:
                context["result"] = {}
                template = Template(story.speechResponse, undefined=SilentUndefined)
                resultJson["speechResponse"] = template.render(**context)
        logger.info(requestJson.get("input"), extra=resultJson)
        return buildResponse.buildJson(resultJson)
    else:
        return abort(400)
Exemplo n.º 12
0
def createStory():
    content = request.get_json(silent=True)

    story = Story()
    story.storyName = content.get("storyName")
    story.intentName = content.get("intentName")
    story.speechResponse = content.get("speechResponse")
    story.botId = content.get("botId")

    if content.get("apiTrigger") is True:
        story.apiTrigger = True
        apiDetails = ApiDetails()
        isJson = content.get("apiDetails").get("isJson")
        isHeader = content.get("apiDetails").get("isHeader")
        print("Is header", isHeader)
        apiDetails.isJson = isJson
        apiDetails.isHeader = isHeader
        if isJson:
            apiDetails.jsonData = content.get("apiDetails").get("jsonData")
        if isHeader:
            print("Is header data",
                  content.get("apiDetails").get("headerData"))
            apiDetails.headerData = content.get("apiDetails").get("headerData")

        apiDetails.url = content.get("apiDetails").get("url")
        apiDetails.requestType = content.get("apiDetails").get("requestType")
        story.apiDetails = apiDetails
    else:
        story.apiTrigger = False

    if content.get("parameters"):
        for param in content.get("parameters"):
            parameter = Parameter()
            update_document(parameter, param)
            story.parameters.append(parameter)

    story.save()
    print("Story Saved")
    return buildResponse.sentOk()
Exemplo n.º 13
0
def fileupload(botId):
    print("Bot Id in file upload", session.__getattribute__('botid'))
    if request.method == 'POST':
        # check if the post request has the file part
        print(request.files)
        if 'file' not in request.files:
            print('No file part')
            return redirect(request.url)
        file = request.files['file']
        print("File Details", file)
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            print('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            print("File Name", filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print("File saved to folder")
            #return redirect(url_for('stories_blueprint.fileupload', filename=filename))
            csvfile = open(UPLOAD_FOLDER + '/' + filename,
                           'r',
                           encoding='utf-8',
                           errors='ignore')
            reader = csv.DictReader(csvfile)
            #print(reader)
            header = [
                "storyName", "intentName", "apiTrigger", "speechResponse",
                "labeledSentences", "parameters"
            ]

            parameter1 = []

            ls = LabeledSentences()

            for each in reader:
                row = {}
                labelSent = []
                ls = LabeledSentences()
                for field in header:
                    #print("Field",field)
                    list2 = []
                    if field == "labeledSentences":
                        #print("Inside labeled send")
                        #print("Row[fiel}",each[field])
                        cleanSentences = html2text.html2text(each[field])
                        #print("After clean Sentences")
                        #labelSen.data=posTagAndLabel(cleanSentences)
                        data = nlp.posTagAndLabel(cleanSentences)
                        print("Type of data", type(data))
                        ls.data = data
                        #print("Result ", labelSent)
                        #print("Type", type(labelSent))
                    row[field] = each[field]
                    #print("row field",row[field])

                list2.append(ls)
                csvStories = Story(storyName=row['storyName'],
                                   intentName=row['intentName'],
                                   apiTrigger=False,
                                   speechResponse=row['speechResponse'],
                                   parameters=parameter1,
                                   labeledSentences=list2,
                                   botId=botId)
                csvStories.save()
                print(row['storyName'], "Story Saved in DB")

            for story in Story.objects():
                try:
                    #               print("Object Id",ObjectId(story.id))
                    sequenceLabeler.train(ObjectId(story.id))
                    print("Build Successfull")
                    print(ObjectId(story.id))
                except:
                    print("In sequence labeller excpetion")

            IntentClassifier().train()

            #return redirect(url_for('stories_blueprint.fileupload', filename=filename))
    return ''
Exemplo n.º 14
0
def api():
    requestJson = request.get_json(silent=True)
    resultJson = requestJson

    if requestJson:

        context = {}
        context["context"] = requestJson["context"]

        if app.config["DEFAULT_WELCOME_INTENT_NAME"] in requestJson.get("input"):
            story=Story.objects(
                intentName=app.config["DEFAULT_WELCOME_INTENT_NAME"]).first()
            resultJson["complete"] = True
            resultJson["intent"]["name"] = story.storyName
            resultJson["intent"]["storyId"] = str(story.id)
            resultJson["input"] = requestJson.get("input")
            template = Template(story.speechResponse, undefined=SilentUndefined)
            resultJson["speechResponse"] = template.render(**context)

            logger.info(requestJson.get("input"), extra=resultJson)
            return buildResponse.buildJson(resultJson)

        intentClassifier = IntentClassifier()
        storyId = intentClassifier.predict(requestJson.get("input"))
        story = Story.objects.get(id=ObjectId(storyId))


        if story.parameters:
            parameters = story.parameters
        else:
            parameters = []

        if ((requestJson.get("complete") is None) or (requestJson.get("complete") is True)):
            resultJson["intent"] = {
                "name": story.intentName,
                "storyId": str(story.id)
            }

            if parameters:
                extractedParameters = sequenceLabeler.predict(storyId,
                                                              requestJson.get("input")
                                                              )
                missingParameters = []
                resultJson["missingParameters"] = []
                resultJson["extractedParameters"] = {}
                resultJson["parameters"] = []
                for parameter in parameters:
                    resultJson["parameters"].append({
                        "name": parameter.name,
                        "required": parameter.required
                    })

                    if parameter.required:
                        if parameter.name not in extractedParameters.keys():
                            resultJson["missingParameters"].append(parameter.name)
                            missingParameters.append(parameter)

                resultJson["extractedParameters"] = extractedParameters

                if missingParameters:
                    resultJson["complete"] = False
                    currentNode = missingParameters[0]
                    resultJson["currentNode"] = currentNode["name"]
                    resultJson["speechResponse"] = currentNode["prompt"]
                else:
                    resultJson["complete"] = True

                    context["parameters"] = extractedParameters


                    try:
                        if story.apiTrigger:
                            isJson = False
                            parameters = extractedParameters

                            urlTemplate = Template(story.apiDetails.url, undefined=SilentUndefined)
                            renderedUrl = urlTemplate.render(**context)
                            if story.apiDetails.isJson:
                                isJson = True
                                requestTemplate = Template(story.apiDetails.jsonData, undefined=SilentUndefined)
                                parameters = requestTemplate.render(**context)

                            result = callApi(renderedUrl,
                                             story.apiDetails.requestType,
                                             parameters,isJson)

                        else:
                            result = {}

                        context["result"] = result
                        resultTemplate = Template(story.speechResponse, undefined=SilentUndefined)
                        resultJson["speechResponse"] = resultTemplate.render(**context)
                    except Exception as e:
                        print(e)
                        resultJson["speechResponse"] = "Service is not available."
            else:
                resultJson["complete"] = True
                resultTemplate = Template(story.speechResponse, undefined=SilentUndefined)
                resultJson["speechResponse"] = resultTemplate.render(**context)


        elif (requestJson.get("complete") is False):
            if "cancel" not in story.intentName:
                storyId = requestJson["intent"]["storyId"]
                story = Story.objects.get(id=ObjectId(storyId))
                resultJson["extractedParameters"][requestJson.get("currentNode")] = requestJson.get("input")

                resultJson["missingParameters"].remove(requestJson.get("currentNode"))

                if len(resultJson["missingParameters"]) == 0:
                    resultJson["complete"] = True
                    context = {}
                    context["parameters"] = resultJson["extractedParameters"]
                    context["context"] = requestJson["context"]
                    try:
                        if story.apiTrigger:
                            isJson = False
                            parameters = resultJson["extractedParameters"]

                            urlTemplate = Template(story.apiDetails.url, undefined=SilentUndefined)
                            renderedUrl = urlTemplate.render(**context)
                            if story.apiDetails.isJson:
                                isJson = True
                                requestTemplate = Template(story.apiDetails.jsonData, undefined=SilentUndefined)
                                parameters = requestTemplate.render(**context)

                            result = callApi(renderedUrl,
                                             story.apiDetails.requestType,
                                             parameters,isJson)
                            print(result)
                        else:
                            result = {}
                        context["result"] = result

                        template = Template(story.speechResponse, undefined=SilentUndefined)
                        resultJson["speechResponse"] = template.render(**context)
                    except Exception as e:
                        print(e)
                        resultJson["speechResponse"] = "Service is not available. "
                else:
                    missingParameter = resultJson["missingParameters"][0]
                    resultJson["complete"] = False
                    currentNode = [node for node in story.parameters if missingParameter in node.name][0]
                    resultJson["currentNode"] = currentNode.name
                    resultJson["speechResponse"] = currentNode.prompt
            else:
                resultJson["currentNode"] = None
                resultJson["missingParameters"] = []
                resultJson["parameters"] = {}
                resultJson["intent"] = {}
                resultJson["complete"] = True
                template = Template(story.speechResponse, undefined=SilentUndefined)
                resultJson["speechResponse"] = template.render(**context)
        logger.info(requestJson.get("input"), extra=resultJson)
        return buildResponse.buildJson(resultJson)
    else:
        return abort(400)
Exemplo n.º 15
0
    u = User("{}{}".format(username.strip(), random.randint(0, 2000)),
             "email{}@example.com".format(i), "password",
             datetime.datetime.now())
    db.session.add(u)
    db.session.commit()
print("done")

u = User.query.all()
paragraphs = json.loads(open("var/lorem.json", "r").read())
print("Creating stories")
for i in range(1, 1000):
    number_of_paragraphs = random.randint(1, 20)
    story_content = ""
    for x in range(0, number_of_paragraphs):
        story_content += "{}\n\n".format(random.choice(paragraphs))
    s = Story(1, "Story {}".format(i), story_content, datetime.datetime.now())
    s.user_id = random.randint(1, len(u))
    db.session.add(s)
    db.session.commit()
print("done")

print("Creating comments ")
s = Story.query.all()
for i in range(1, 10000):
    c = Comment(1, 1, random.choice(paragraphs), datetime.datetime.now())
    c.user_id = random.randint(1, len(u))
    c.story_id = random.randint(1, len(s))
    db.session.add(c)
    db.session.commit()
print("done")
Exemplo n.º 16
0
# Downloading necessary NLTK datasets
nltk.download("stopwords")
nltk.download("wordnet")
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')

#creating directory for storing chat logs
if not os.path.exists("logs"):
    os.makedirs("logs")

try:
    from app.stories.models import Story, LabeledSentences

    # Setting up default intents
    newStory = Story()
    newStory.storyName = 'Default Fallback intent'
    newStory.intentName = 'fallback'
    newStory.speechResponse = "Sorry. I'm having trouble understanding you."
    newStory.apiTrigger = False
    newLabeledSentence = LabeledSentences()
    newLabeledSentence.data = [['', 'VB', 'O']]
    newStory.labeledSentences.append(newLabeledSentence)
    newStory.save()

    newStory = Story()
    newStory.storyName = 'cancel'
    newStory.intentName = 'cancel'
    newStory.speechResponse = "Ok. Canceled."
    newStory.apiTrigger = False
    newLabeledSentence = LabeledSentences()
Exemplo n.º 17
0
def api():
    requestJson = request.get_json(silent=True)
    resultJson = requestJson

    if requestJson:

        context = {}
        context["context"] = requestJson["context"]

        if app.config["DEFAULT_WELCOME_INTENT_NAME"] in requestJson.get(
                "input"):
            story = Story.objects(
                intentName=app.config["DEFAULT_WELCOME_INTENT_NAME"]).first()
            resultJson["complete"] = True
            resultJson["intent"]["name"] = story.storyName
            resultJson["intent"]["storyId"] = str(story.id)
            resultJson["input"] = requestJson.get("input")
            template = Template(story.speechResponse,
                                undefined=SilentUndefined)
            resultJson["speechResponse"] = template.render(**context)

            logger.info(requestJson.get("input"), extra=resultJson)
            return buildResponse.buildJson(resultJson)

        intentClassifier = IntentClassifier()
        storyId = intentClassifier.predict(requestJson.get("input"))
        story = Story.objects.get(id=ObjectId(storyId))

        if story.parameters:
            parameters = story.parameters
        else:
            parameters = []

        if ((requestJson.get("complete") is None)
                or (requestJson.get("complete") is True)):
            resultJson["intent"] = {
                "name": story.intentName,
                "storyId": str(story.id)
            }

            if parameters:
                extractedParameters = sequenceLabeler.predict(
                    storyId, requestJson.get("input"))
                missingParameters = []
                resultJson["missingParameters"] = []
                resultJson["extractedParameters"] = {}
                resultJson["parameters"] = []
                for parameter in parameters:
                    resultJson["parameters"].append({
                        "name":
                        parameter.name,
                        "type":
                        parameter.type,
                        "required":
                        parameter.required
                    })

                    if parameter.required:
                        if parameter.name not in extractedParameters.keys():
                            resultJson["missingParameters"].append(
                                parameter.name)
                            missingParameters.append(parameter)

                resultJson["extractedParameters"] = extractedParameters

                if missingParameters:
                    resultJson["complete"] = False
                    currentNode = missingParameters[0]
                    resultJson["currentNode"] = currentNode["name"]
                    resultJson["speechResponse"] = currentNode["prompt"]
                else:
                    resultJson["complete"] = True
                    context["parameters"] = extractedParameters
            else:
                resultJson["complete"] = True

        elif (requestJson.get("complete") is False):
            if "cancel" not in story.intentName:
                storyId = requestJson["intent"]["storyId"]
                story = Story.objects.get(id=ObjectId(storyId))
                resultJson["extractedParameters"][requestJson.get(
                    "currentNode")] = requestJson.get("input")

                resultJson["missingParameters"].remove(
                    requestJson.get("currentNode"))

                if len(resultJson["missingParameters"]) == 0:
                    resultJson["complete"] = True
                    context = {}
                    context["parameters"] = resultJson["extractedParameters"]
                    context["context"] = requestJson["context"]
                else:
                    missingParameter = resultJson["missingParameters"][0]
                    resultJson["complete"] = False
                    currentNode = [
                        node for node in story.parameters
                        if missingParameter in node.name
                    ][0]
                    resultJson["currentNode"] = currentNode.name
                    resultJson["speechResponse"] = currentNode.prompt
            else:
                resultJson["currentNode"] = None
                resultJson["missingParameters"] = []
                resultJson["parameters"] = {}
                resultJson["intent"] = {}
                resultJson["complete"] = True

        if resultJson["complete"]:
            if story.apiTrigger:
                isJson = False
                parameters = resultJson["extractedParameters"]

                urlTemplate = Template(story.apiDetails.url,
                                       undefined=SilentUndefined)
                renderedUrl = urlTemplate.render(**context)
                if story.apiDetails.isJson:
                    isJson = True
                    requestTemplate = Template(story.apiDetails.jsonData,
                                               undefined=SilentUndefined)
                    parameters = requestTemplate.render(**context)

                try:
                    result = callApi(renderedUrl, story.apiDetails.requestType,
                                     parameters, isJson)
                except Exception as e:
                    print(e)
                    resultJson["speechResponse"] = "Service is not available. "
                else:
                    print(result)
                    context["result"] = result
                    template = Template(story.speechResponse,
                                        undefined=SilentUndefined)
                    resultJson["speechResponse"] = template.render(**context)
            else:
                context["result"] = {}
                template = Template(story.speechResponse,
                                    undefined=SilentUndefined)
                resultJson["speechResponse"] = template.render(**context)
        logger.info(requestJson.get("input"), extra=resultJson)
        return buildResponse.buildJson(resultJson)
    else:
        return abort(400)
Exemplo n.º 18
0
# # russian setup
# # nltk.download("stopwords")
# # nltk.download("wordnet")
# # rename folder 'averaged_perceptron_tagger_ru' to 'averaged_perceptron_tagger'
# nltk.download('averaged_perceptron_tagger_ru')
# nltk.download('punkt')

# creating directory for storing chat logs
if not os.path.exists("logs"):
    os.makedirs("logs")

try:
    from app.stories.models import Story, LabeledSentences

    Story.drop_collection()

    # Setting up default intents
    newStory = Story()
    newStory.storyName = 'Default Fallback intent'
    newStory.intentName = 'fallback'
    newStory.speechResponse = "Что-т пошло не так :("
    newStory.apiTrigger = False
    newLabeledSentence = LabeledSentences()
    newLabeledSentence.data = [['', 'VB', 'O']]
    newStory.labeledSentences.append(newLabeledSentence)
    newStory.save()

    # newStory = Story()
    # newStory.storyName = 'cancel'
    # newStory.intentName = 'cancel'