2017-11-19 12 views
1

데이터를 전송하는 데 rasa nlu를 사용하고 있습니다. 코드를 수행하면 파일 데모 rasa.json에 존재하는 데이터를 양성하는 데 사용되어야한다 http://nlu.rasa.ai/python.html의 문서에 따라파이썬에서 라사 nlu에서 json 객체를 직접 전달하는 방법

from rasa_nlu.converters import load_data 
from rasa_nlu.config import RasaNLUConfig 
from rasa_nlu.model import Trainer 

training_data = load_data('data/examples/rasa/demo-rasa.json') 
trainer = Trainer(RasaNLUConfig("sample_configs/config_spacy.json")) 
trainer.train(training_data) 
model_directory = trainer.persist('./projects/default/') 

하지만 그 대신 우리가 어떻게 교육을위한 JSON 객체에서 데이터를 읽고 있습니다.

+0

관심있는 모든 사람들에게이 질문에 대한 답변이 계속됩니다. https://stackoverflow.com/questions/47313046/how-to-create-training-data-for-rasa-nlu-through-program-nodejs/47313236 –

답변

1

당신이 load_data의 구현을 보면, 그것은 두 단계를 수행

  1. 파일 형식
  2. 부하 적절한 적재 방법

을 사용하여 파일을 추측

을 가장 간단한 해결책은 될 것이다 json 객체를 파일 또는 StringIO 객체에 작성합니다.

또는 특정 로딩 기능 (예 : load_rasa_data)을 선택하고 해당 파일을 별도로 읽을 수 있습니다. 이 예제의 경우 전체 함수를 가져 와서 data = _read_json_from_file(filename) 줄을 제거 할 수 있습니다.

나는 현재 이미로드 된 json 객체를 읽을 방법이 없다는 것에 다소 놀랐다. 이 기능을이 기능에 적용하기로 결정한 경우 해당 기능에 대한 요청을 작성하는 것이 좋습니다.

+0

응답 해 주셔서 감사합니다. 결론적으로 우리는 json 객체를 직접 전달할 수 없습니까? 파일을 만드는 것은 내가하고 싶지 않은 것이다. 아마도 StringIO를 사용하는 옵션을 살펴볼 것입니다. –

+0

소스 코드를 보면서 : 예, 간단한 방법이 없습니다. GitHub에서 개발자가 알 수 있도록 문제를 열면 대안 솔루션을 제공 할 수 있습니다. –

1

JSON 개체를 파일에서 읽는 대신 요청 본문에서 가져 오는 플라스크 응용 프로그램을 만들었습니다.

이 코드는 엔터티에 spaCy를 사용하고 의도를 인식하기 위해 sklearn-crfsuite를 사용하여 기존 LUIS json을 변환합니다.

from flask import Flask, jsonify, request 
from flask_cors import CORS 
import json, os, msvcrt, psutil, subprocess, datetime 

app = Flask(__name__) 

CORS(app) 

with app.app_context(): 
    with app.test_request_context(): 

     #region REST based RASA API 
     serverExecutablePID = 0  
     hasAPIStarted = False 
     configFileDirectory = "C:\\Code\\RasaAPI\\RASAResources\\config" 
     chitChatModel = "ChitChat" 
     assetsDirectory = "C:\\Code\\RasaAPI\\RASAResources" 

     def createSchema(SchemaPath, dataToBeWritten): 
      try: 
        #write LUIS or RASA JSON Schema in json file locking the file to avoid race condition using Python's Windows msvcrt binaries 
        with open(SchemaPath, "w") as SchemaCreationHandle: 
         msvcrt.locking(SchemaCreationHandle.fileno(), msvcrt.LK_LOCK, os.path.getsize(SchemaPath)) 
         json.dump(dataToBeWritten, SchemaCreationHandle, indent = 4, sort_keys=False) 
         SchemaCreationHandle.close() 

        #Check if written file actually exists on disk or not 
        doesFileExist = os.path.exists(SchemaPath)      
        return doesFileExist 

      except Exception as ex: 
       return str(ex.args) 


     def appendTimeStampToModel(ModelName): 
      return ModelName + '_{:%Y%m%d-%H%M%S}.json'.format(datetime.datetime.now()) 

     def appendTimeStampToConfigSpacy(ModelName): 
      return ModelName + '_config_spacy_{:%Y%m%d-%H%M%S}.json'.format(datetime.datetime.now()) 

     def createConfigSpacy(ModelName, DataPath, ConfigSpacyPath, TrainedModelsPath, LogDataPath): 
      try: 
        with open(ConfigSpacyPath, "w") as configSpacyFileHandle: 
         msvcrt.locking(configSpacyFileHandle.fileno(), msvcrt.LK_LOCK, os.path.getsize(ConfigSpacyPath)) 
         configDataToBeWritten = dict({ 
         "project": ModelName, 
         "data": DataPath, 
         "path": TrainedModelsPath, 
         "response_log": LogDataPath, 
         "log_level": "INFO", 
         "max_training_processes": 1, 
         "pipeline": "spacy_sklearn", 
         "language": "en", 
         "emulate": "luis", 
         "cors_origins": ["*"], 
         "aws_endpoint_url": None, 
         "token": None, 
         "num_threads": 2, 
         "port": 5000 
         }) 
         json.dump(configDataToBeWritten, configSpacyFileHandle, indent = 4, sort_keys=False) 

        return os.path.getsize(ConfigSpacyPath) > 0 

      except Exception as ex: 
       return str(ex.args) 

     def TrainRASA(configFilePath): 
      try: 
       trainingString = 'start /wait python -m rasa_nlu.train -c ' + '\"' + os.path.normpath(configFilePath) + '\"' 
       returnCode = subprocess.call(trainingString, shell = True) 
       return returnCode 

      except Exception as ex: 
       return str(ex.args) 

     def StartRASAServer(configFileDirectory, ModelName): 
      #region Server starting logic 
      try: 
       global hasAPIStarted 
       global serverExecutablePID 
       #1) for finding which is the most recent config_spacy 
       root, dirs, files = next(os.walk(os.path.normpath(configFileDirectory))) 

       configFiles = [configFile for configFile in files if ModelName in configFile] 
       configFiles.sort(key = str.lower, reverse = True) 
       mostRecentConfigSpacy = os.path.join(configFileDirectory, configFiles[0]) 

       serverStartingString = 'start /wait python -m rasa_nlu.server -c ' + '\"' + os.path.normpath(mostRecentConfigSpacy) + '\"' 

       serverProcess = subprocess.Popen(serverStartingString, shell = True) 
       serverExecutablePID = serverProcess.pid 

       pingReturnCode = 1 
       while(pingReturnCode): 
        pingReturnCode = os.system("netstat -na | findstr /i 5000") 
       if(pingReturnCode == 0): 
        hasAPIStarted = True 

       return pingReturnCode 

      except Exception as ex: 
       return jsonify({"message": "Failed because: " + str(ex.args) , "success": False}) 
      #endregion 

     def KillProcessWindow(hasAPIStarted, serverExecutablePID): 
      if(hasAPIStarted == True and serverExecutablePID != 0): 
       me = psutil.Process(serverExecutablePID) 
       for child in me.children(): 
        child.kill() 


     @app.route('/api/TrainRASA', methods = ['POST']) 
     def TrainRASAServer(): 
      try: 
       #get request body of POST request 
       postedJSONData = json.loads(request.data, strict = False) 

       if postedJSONData["data"] is not None: 
        print("Valid data") 
        #region JSON file building logic 
        modelName = postedJSONData["modelName"] 
        modelNameWithExtension = appendTimeStampToModel(modelName) 
        schemaPath = os.path.join(assetsDirectory, "data", modelNameWithExtension) 
        print(createSchema(schemaPath, postedJSONData["data"])) 
        #endregion 

        #region config file creation logic 
        configFilePath = os.path.join(assetsDirectory, "config", appendTimeStampToConfigSpacy(modelName)) 
        logsDirectory = os.path.join(assetsDirectory, "logs") 
        trainedModelDirectory = os.path.join(assetsDirectory, "models") 
        configFileCreated = createConfigSpacy(modelName, schemaPath, configFilePath, trainedModelDirectory, logsDirectory) 
        #endregion 

        if(configFileCreated == True): 
         #region Training RASA NLU with schema 
         TrainingReturnCode = TrainRASA(configFilePath) 
         #endregion 

         if(TrainingReturnCode == 0): 
          return jsonify({"message": "Successfully trained RASA NLU with modelname: " + modelName, "success": True}) 
          # KillProcessWindow(hasAPIStarted, serverExecutablePID) 
          # serverStartingReturnCode = StartRASAServer(configFileDirectory, modelName) 
          # #endregion 

          # if serverStartingReturnCode == 0:      
          #  return jsonify({"message": "Successfully started RASA server on port 5000", "success": True}) 

          # elif serverStartingReturnCode is None: 
          #  return jsonify({"message": "Could not start RASA server, request timed out", "success": False}) 

         else: 
          return jsonify({"message": "Soemthing wrong happened while training RASA NLU!", "success": False}) 

        else: 
         return jsonify({"message": "Could not create config file for RASA NLU", "success": False}) 

       #throw exception if request body is empty 
       return jsonify({"message": "Please enter some JSON, JSON seems to be empty", "success": False}) 

      except Exception as ex: 
       return jsonify({"Reason": "Failed because" + str(ex.args), "success": False}) 

     @app.route('/api/StopRASAServer', methods = ['GET']) 
     def StopRASAServer(): 
      try: 
       global serverExecutablePID 

       if(serverExecutablePID != 0 or serverExecutablePID != None): 
        me = psutil.Process(serverExecutablePID) 
        for child in me.children(): 
         child.kill() 
        return jsonify({"message": "Server stopped....", "success": True}) 
      except Exception as ex: 
       return jsonify({"message": "Something went wrong while shutting down the server because: " + str(ex.args), "success": True}) 

     if __name__ == "__main__": 
      StartRASAServer(configFileDirectory, chitChatModel) 
      app.run(debug=False, threaded = True, host='0.0.0.0', port = 5050)