Повторная инициализация конвейера Stanford CoreNLP для соответствия изменениям файла RegexNER - PullRequest
0 голосов
/ 26 марта 2019

Я разрабатываю приложение, в котором отправляю новые правила в файл RegexNER через конечную точку REST HTTP PATCH.

[Route("RegexNER")]
[HttpPatch]
public IHttpActionResult UpdateRegexNERFile([FromBody] List<RegexNERUpdateDTO> UpdateEntries)
{
    if (UpdateEntries == null)
        return Content(HttpStatusCode.BadRequest, new { message = "Cannot update Regex NER for invalid requests!" });

    string regexNERFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "Models", "regexner_custom.txt");
    string regexFileContents = File.ReadAllText(regexNERFilePath);

    List<string> newEntryList = new List<string>();

    foreach (RegexNERUpdateDTO entry in UpdateEntries)
    {
        foreach (string entityEntry in entry.Entries)
        {
            string newEntry = $"{entityEntry}\t{entry.Entity}";

            if (regexFileContents.IndexOf(newEntry, StringComparison.OrdinalIgnoreCase) == -1)
                newEntryList.Add(newEntry);
        }
    }

    // Remove read only file access
    FileInfo myFile = new FileInfo(regexNERFilePath)
    {
        IsReadOnly = false
    };

    File.AppendAllText(regexNERFilePath, Environment.NewLine + string.Join(Environment.NewLine, newEntryList));
    NLPInitializer.InitializeCoreNLP();
    return Ok();
}

Это код для инициализации конвейера CoreNLP:

public static class NLPInitializer
{
    public static StanfordCoreNLP Pipeline { get; set; }

    /// <summary>
    /// This method is called only once (at startup) to initialize the StanfordCoreNLP pipeline object
    /// </summary>
    public static void InitializeCoreNLP()
    {
        // Path to the folder with models extracted from `stanford-corenlp-3.8.0-models.jar`
        string jarRoot = ConfigurationManager.AppSettings["CoreNLPModelPath"];
        string modelsDirectory = Path.Combine(jarRoot, "edu", "stanford", "nlp", "models");

        // SUTime configuration
        string sutimeRules = Path.Combine(modelsDirectory, "sutime", "defs.sutime.txt") + "," +
                          // Path.Combine(modelsDirectory, "sutime", "english.holidays.sutime.txt") + "," +
                          Path.Combine(modelsDirectory, "sutime", "english.sutime.txt");
        try
        {
            Properties props = new Properties();
            //props.setProperty("ner.model", Path.Combine(modelsDirectory + "ner", "english.muc.7class.distsim.crf.ser.gz"));
            string regexNerFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "Models", "regexner_custom.txt");
            props.setProperty("regexner.mapping", regexNerFilePath);
            props.setProperty("regexner.ignorecase", "true");
            props.setProperty("coref.algorithm", "neural");
            //props.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner,parse,depparse,mention,coref,sentiment,regexner,relation,natlog,openie");
            props.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner,parse,depparse,coref,sentiment,regexner,relation,natlog,openie");
            //props.setProperty("ner.useSUTime", "0");
            props.setProperty("sutime.rules", sutimeRules);
            props.setProperty("sutime.binders", "0");
            props.setProperty("openie.resolve_coref", "false");

            string curDir = Environment.CurrentDirectory;
            Directory.SetCurrentDirectory(jarRoot);
            Pipeline = new StanfordCoreNLP(props);
            Pipeline.addAnnotator(new TimeAnnotator("sutime", props));
            Directory.SetCurrentDirectory(curDir);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

Но проблема в этой строке NLPInitializer.InitializeCoreNLP();

Я хочу повторно инициализировать конвейер Stanford CoreNLP так, чтобы он брал последние изменения, внесенные в файл RegexNER, и находил объект на основеобновленные правила.

Но конвейер не инициализируется повторно, я не знаю почему.

Одна вещь, на которую следует обратить внимание, - это когда я перезагружаю IIS илиперезапустите приложение из inetmgr, после чего CoreNLP подберет последние изменения, внесенные в файл RegexNER.

Но перезапуск сервера IIS невозможен для каждого запроса HTTP PATCH, есть ли альтернатива этой проблеме.

Я использую CoreNLP v3.9.1 английскую модель и CoreNLP 3.9.1 C # Nuget .

...