def deleteStory(storyId):
  story = Story.objects.filter(id=ObjectId(storyId))
  if g.botId:
      story=story.filter(bot=g.botId)
      botId=g.botId
  else:
      botId='default'
  story.get().delete()
  try:
      intentClassifier = IntentClassifier()
      intentClassifier.setBotId(g.botId)
      intentClassifier.train()
  except BaseException:
      pass

  try:
      os.remove("{}/{},{}.model".format(app.config["MODELS_DIR"],botId, storyId))
  except OSError:
      pass
  return buildResponse.sentOk()
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()
        intentClassifier.setBotId(g.botId)
        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)
def buildModel(storyId):
    sequenceLabeler.train(storyId)
    intentClassifier = IntentClassifier()
    intentClassifier.setBotId(g.botId)
    intentClassifier.train()
    return buildResponse.sentOk()
Example #4
0
import nltk
import os

# 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:
    print("Training models..")
    from app.core.intentClassifier import IntentClassifier
    intentClassifier = IntentClassifier()
    intentClassifier.setBotId('default')
    intentClassifier.train()
    print("Training models finished..")
except Exception as e:
    e = str(e)
    if e == "NO_DATA":
        e = "load Data first into mongodb. Reffer Readme."
    print("Could not train models..skipping.. (reason: {})".format(e))