def add_synonyms(agent_name): if request.get_data(): request_data = json.loads((request.get_data()).decode()) AgentsService.get_instance().add_agent_synonyms(request_data["agent_name"], request_data["data"]) return response_template(200, "Synonyms successfully added for agent {0}".format(agent_name)) else: return response_template(400, "A body is mandatory inside the request")
def handle_text(self, text, agent_name, user_id): from agents_service import AgentsService from context_service import ContextService from responses_service import ResponsesService nlu_data = {} nlu_data["intent"] = {} nlu_data["text"] = text intent_from_db = AgentsService.get_instance().get_intent_by_text(text, agent_name) if intent_from_db is not None: intent = intent_from_db["data"]["intent"] nlu_data["intent"]["name"] = intent nlu_data["intent"]["confidence"] = 1 if (intent_from_db["data"].get("entities") is not None): nlu_data["entities"] = intent_from_db["data"].get("entities") else: if self.interpreter is None: intent = "UNKNOWN" nlu_data["intent"]["name"] = "UNKNOWN" nlu_data["intent"]["confidence"] = 1 else: nlu_data = self.interpreter.parse(text) confidence = float(nlu_data.get("intent").get("confidence")) intent = nlu_data.get("intent").get("name") if AgentsService.get_instance().is_fallback(agent_name, confidence): intent = "FALLBACK" nlu_data["intent"]["name"] = intent nlu_data["intent"]["confidence"] = 1 nlu_data["response"] = ResponsesService.get_instance().get_response(agent_name, intent) if (user_id is not None): nlu_data["context"] = ContextService.get_instance().get_user_context_key_value(agent_name, user_id).get("context") if (nlu_data.get("entities") is not None): for entity in nlu_data["entities"]: ContextService.get_instance().remove_user_context(agent_name, user_id, entity.get("entity")) ContextService.get_instance().insert_user_context(agent_name, user_id, entity.get("entity"), entity.get("value")) return nlu_data
def __enter__(self): all_agents = AgentsService.get_instance().get_all_agents() trained_agents = [] for agent in all_agents: bot = agent.get("name") try : if (agent.get("last_modified") > agent.get("last_train")): logger.info("Start training Agent: {0}".format(bot)) AgentsService.get_instance().train_agent(bot) trained_agents.append(bot) except Exception as e: logger.error("Exception when training agent {0}. {1}".format(bot, e), exc_info=True) logger.info("Trained Agents: {0}".format(trained_agents))
def get_agent_inputs(agent_name): min_confidence = request.args.get("minConfidence", default = 0, type = float) max_confidence = request.args.get("maxConfidence", default = 1, type = float) page_number = request.args.get("pageNumber", default = 1, type = int) page_size = request.args.get("pageSize", default = 20, type = int) agent_inputs = AgentsService.get_instance().get_agent_inputs(agent_name, max_confidence, min_confidence, page_number, page_size) return jsonify(agent_inputs)
def __enter__(self): self.start = datetime.now() all_trained_agents = list( AgentsService.get_instance().get_trained_agents()) logger.info("Agents found for Loading: {0}".format(all_trained_agents)) for agent in all_trained_agents: try: logger.info("Start loading Agent: {0}".format( agent.get("name"))) AgentsService.get_instance().load_agent( agent.get("name"), agent.get("last_version")) except Exception as e: logger.error( "Exception when loading agent {0} with version {1} inside Cron Loader. {2}" .format(agent.get("name"), agent.get("last_version"), e), exc_info=True) remove_file_or_dir(modelName)
def set_specific_model(agent_name): if request.get_data(): request_data = json.loads((request.get_data()).decode()) if AgentsService.get_instance().load_agent(agent_name = agent_name, model_name = request_data.get("modelName")): return("Model " + request_data.get("modelName") + " loaded for bot " + agent_name) else: return("Can't load model " + request_data.get("modelName") + "for bot " + agent_name) else: return response_template(400, "A body is mandatory inside the request")
def get_agent_file(agent_name): directory_name = os.environ.get("MODELS_PATH") + "export/" file_name = agent_name + ".json" file_path = directory_name + file_name remove_file_or_dir(file_path) dic = AgentsService.get_instance().create_agent_file(agent_name) create_folder(directory_name) with open(file_path, "w+") as f: json.dump(dic,f) return(send_from_directory(directory = directory_name, filename = "./" + file_name, as_attachment = True))
def parse(agent_name): """Parse a text to get nlu response with intent/entities assosciated""" if request.get_data(): text_query = (json.loads((request.get_data()).decode())).get("text") intent_query = (json.loads((request.get_data()).decode())).get("intent") user_id = (json.loads((request.get_data()).decode())).get("user_id") bot = ((AgentsService.get_instance().get_bots()).get(agent_name)) if bot is not None: if text_query: nlu_response = bot.handle_text(text_query, agent_name, user_id) if (request.args.get("test") is None or request.args.get("test").lower() != "true"): AgentsService.get_instance().store_user_input(agent_name, dict(nlu_response), user_id) elif intent_query: nlu_response = bot.handle_intent(intent_query, agent_name) else: return response_template(400, "A text field or an intent field are mandatory") return jsonify(nlu_response) else: return response_template(404, "Agent {0} not found".format(agent_name)) else: return response_template(400, "A body is mandatory inside the request")
def before_request_callback(): if (request.view_args is not None): agent_name = request.view_args.get("agent_name") path = request.path method = request.method if agent_name is not None and (method != "PUT" or path != "/nlu/agents/" + agent_name): """Return 404 in case of non existing agent associated to agent_name used in path except creation case""" if not AgentsService.get_instance().agent_exist(agent_name): return response_template( 404, "Agent {0} not found".format(agent_name))
def create_agent(): agent_name = "" if request.files: """Create agent from file in the case of file uploading""" file_key = list(request.files)[0] data = json.loads(request.files[file_key].read().decode()) agent_name = data.get("name") if agent_name is None or agent_name == "": return response_template(400, "Agent name field is mandatory") elif AgentsService.get_instance().agent_exist(agent_name): return response_template(400, "Already existing agent with name {0}".format(agent_name)) elif data.get("config") is None: return response_template(400, "Should Contains config field inside file data") AgentsService.get_instance().create_agent(agent_name, 0, data.get("config"), data.get("rasa_nlu_data"), data.get("fallback"), data.get("responses"), data.get("current_version")) elif request.get_data(): """Create agent with data passed directly inside query""" request_data = json.loads((request.get_data()).decode()) agent_name = request_data.get("name") if agent_name is None or agent_name == "": return response_template(400, "Agent name field is mandatory") elif AgentsService.get_instance().agent_exist(agent_name): return response_template(400, "Already existing agent with name {0}".format(agent_name)) elif request_data.get("config") is None: return response_template(400, "Should Contains config field inside body request") AgentsService.get_instance().create_agent(agent_name, 0, request_data.get("config"), request_data.get("rasa_nlu_data"), request_data.get("fallback"), request_data.get("responses"), request_data.get("current_version")) else: return response_template(400, "Shoulds Contains a valid body or file of new Agent") return response_template(201, "Agent {0} successfully created".format(agent_name))
def delete_agent(agent_name): AgentsService.get_instance().delete_agent(agent_name) return response_template(200, "Agent {0} successfully deleted".format(agent_name))
def get_agent(agent_name): agent = AgentsService.get_instance().get_agent(agent_name) return jsonify(agent)
def get_all_agents(): agents = AgentsService.get_instance().get_agents() return jsonify(agents)
def delete_input(agent_name, id): AgentsService.get_instance().delete_agent_user_input(agent_name, id) return response_template(200, "User Input was successfully deleted for agent {0}".format(agent_name))
from flask_jwt_extended import JWTManager jwt = JWTManager(current_app) current_app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY") from flask_cors import CORS CORS(current_app) routes = Blueprint("routes", __name__) from .agent import * from .training_data import * from .response import * from .user import * from .context import * from agents_service import AgentsService AgentsService.get_instance().starting_load_agents() from user_service import UserService exist_user = UserService.get_instance().exist_user() if not exist_user: UserService.get_instance().add_new_user(os.environ.get("ADMIN_LOGIN"), "Admin", "Admin", os.environ.get("ADMIN_PWD")) @current_app.route("/", methods=["GET"]) def index(): return "Boticot API !" @current_app.route("/healthcheck", methods=["GET"])