From f8b5d9af975ff52d9c569559328fc8270d0d5e35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20de=20Chalendar?= Date: Sun, 29 Nov 2026 00:05:20 +0100 Subject: [PATCH 1/4] Lima.compile_rules and add_rules: ModEx rules compiled and saved from Python (#12) LimaAnalyzer (C++): compileRules compiles a rules file and writes the recognizer (.bin) as compile-rules does, loadRecognizerRules reads one into a recognizer. Lima.compile_rules takes the rules as a string or a file and saves the .bin and optionally the rules; Lima.add_rules applies a .bin (or a text rules file) before the named entities rules. PhraseMatcher uses the shared pipeline and entity types helpers. Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 7 ++ README.md | 32 ++++++ aymara/lima.py | 268 +++++++++++++++++++++++++++++++++++++------- lima.cpp | 149 +++++++++++++++++++++++- lima.h | 16 +++ tests/test_rules.py | 132 ++++++++++++++++++++++ 6 files changed, 560 insertions(+), 44 deletions(-) create mode 100644 tests/test_rules.py diff --git a/CHANGES.md b/CHANGES.md index 1a5910c..8eec79d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -9,6 +9,13 @@ * `lima` command: writes CoNLL-U with the metadata comments (`to_conllu`) instead of `repr(doc)`, to the standard output or to `-o/--output`; with several input files, each one's name is its document id. +* `Lima.compile_rules(output, rules=... | rules_file=..., save_rules=None, + entity_types=())` (#12): compiles ModEx rules, given as a string or a file, + as LIMA's `compile-rules` does, and saves the compiled rules (`.bin`) and + optionally the rules themselves. `Lima.add_rules(rules_file, + entity_types=())`: the analyzer applies the rules of a `.bin` (or of a text + rules file) before its named entities rules. `LimaAnalyzer` (C++): + `compileRules` and `loadRecognizerRules`. ## 0.11.0 - 20261128 diff --git a/README.md b/README.md index f50855a..39ff743 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,38 @@ The differences with spaCy: speech (take the patterns in sentences, so that their words get the POS they have in the texts). +## Compiling ModEx rules + +`Lima.compile_rules` compiles ModEx rules, as LIMA's `compile-rules` tool +does. The rules can come from a string or a file. It saves the compiled rules +(a `.bin` file, for the given language) and, optionally, the rules +themselves. `Lima.add_rules` makes an analyzer apply a `.bin` file (or a text +rules file) before its named entities rules. The documents analyzed afterwards +contain the rules' entities in `doc.ents`: + +```python +import aymara.lima +nlp = aymara.lima.Lima("ud-eng") +rules = """set encoding=utf8 +using groups Product +set defaultAction=>CreateSpecificEntity() +Python:::Product.SOFTWARE: +""" +# or rules_file="software.rules" +nlp.compile_rules("software.bin", rules=rules, save_rules="software.rules", + entity_types=["Product.SOFTWARE"]) + +# Later, possibly in another process +nlp.add_rules("software.bin", entity_types=["Product.SOFTWARE"]) +print(nlp("Python analyzes texts.").ents) +``` + +`entity_types` declares the entity types that the LIMA configuration does not +know yet. The types of a group are declared all at once. When the rules come +from a string, their `include`s are searched for next to `save_rules`. The +`.bin` file can also be used as the `rules` of an `AutomatonRecognizer` +resource in a LIMA configuration. + ## Python bindings API documentation The Lima python API documentation is [part of the LIMA documentation](https://aymara.github.io/lima/reference/python-api/), diff --git a/aymara/lima.py b/aymara/lima.py index 31248ea..e2534dc 100644 --- a/aymara/lima.py +++ b/aymara/lima.py @@ -1497,7 +1497,8 @@ def __init__(self, self.pipes = pipes.split(",") self._user_config_path = user_config_path self._meta = meta - # The units of the pipelines added at runtime (by PhraseMatcher) + # The units of the pipelines added at runtime (by PhraseMatcher and + # add_rules) self._pipeline_units: Dict[str, List[str]] = {} def __call__(self, @@ -1778,6 +1779,231 @@ def add_pipeline_unit(self, pipeline: str, language: str, group: str): raise LimaInternalError(self.analyzer.errorMessage()) return result + # The units before which the recognizers added at runtime (PhraseMatcher, + # add_rules) are inserted in the pipeline + _BEFORE_UNITS = ("SpecificEntitiesModexAfterPos",) + # The number of recognizers added by add_rules (their resources are + # shared by the Lima instances of the process) + _rules_count = 0 + # The entity groups declared at runtime (shared by the Lima instances of + # the process): (media, group) -> its types + _entity_groups: Dict[Tuple[str, str], List[str]] = {} + + def _check(self, ok: bool, what: str): + """Raises the analyzer's error if ok is false.""" + if not ok or self.analyzer.error(): + raise LimaInternalError(f"{what}: {self.analyzer.errorMessage()}") + + def _add_recognizer(self, name: str) -> str: + """Adds to the analyzer an empty ModEx recognizer (resource + name + "Rules"), the unit applying it on the PosGraph, and a pipeline + made of the analyzer's one with this unit before the named entities + rules, which becomes the analyzer's default. Returns the name of the + recognizer.""" + analyzer, lang = self.analyzer, self.lang + base = self.pipes[0] if self.pipes else "deepud" + units = self._pipeline_units.get(base) or self._configured_units(base) + if not units: + raise LimaInternalError(f"{name}: the units of the pipeline " + f"'{base}' of {lang} are not found") + recognizer = f"{name}Rules" + unit = f"{name}Recognition" + position = next((k for k, u in enumerate(units) + if u in self._BEFORE_UNITS or u.endswith("Dumper")), + len(units)) + units = units[:position] + [unit] + units[position:] + pipeline_unit = f"{name}Pipeline" + pipeline = f"{base}-{name.lower()}" + self._check(analyzer.addResource(lang, json.dumps({ + "name": recognizer, "class": "AutomatonRecognizer", + "rules": ""})), f"{name} recognizer") + self._check(analyzer.addProcessUnit(lang, json.dumps({ + "name": unit, "class": "ApplyRecognizer", + "automaton": recognizer, "applyOnGraph": "PosGraph", + "useSentenceBounds": "no"})), f"{name} unit") + self._check(analyzer.addProcessUnit(lang, json.dumps({ + "name": pipeline_unit, "class": "ProcessUnitPipeline", + "processUnitSequence": units})), f"{name} pipeline unit") + self._check(analyzer.addPipeline(pipeline, lang, pipeline_unit), + f"{name} pipeline") + self._pipeline_units[pipeline] = units + if self.pipes: + self.pipes[0] = pipeline + else: + self.pipes.append(pipeline) + return recognizer + + def _declare_entity_types(self, entity_types: Iterable[str]): + """Declares the "Group.TYPE" entity types and, for each group, the + micro-categories (PROPN) of the token merging an entity in the + PosGraph. A group gets all its types at once: the first time it is + declared.""" + groups: Dict[str, List[str]] = {} + for entity_type in ([entity_types] if isinstance(entity_types, str) + else entity_types): + group, _, name = str(entity_type).partition(".") + if not re.fullmatch(r"[^\W\d]\w*", group) \ + or not re.fullmatch(r"\w+", name): + raise ValueError(f"An entity type is Group.TYPE (e.g. " + f"\"Product.SOFTWARE\"), not {entity_type!r}") + groups.setdefault(group, []) + if name not in groups[group]: + groups[group].append(name) + for group, names in groups.items(): + known = Lima._entity_groups.get((self.lang, group)) + if known is not None: + missing = [name for name in names if name not in known] + if missing: + raise ValueError( + f"The entity group {group} is declared with the types " + f"{', '.join(known)}: its types are declared at once, " + f"{', '.join(missing)} cannot be added") + continue + for name in names: + self._check(self.analyzer.addEntityType(group, name), + f"entity type {group}.{name}") + self._check(self.analyzer.addResource(self.lang, json.dumps({ + "name": f"{group}Micros", "class": "SpecificEntitiesMicros", + **{f"{group}.{name}": ["PROPN"] for name in names}})), + f"micro-categories of {group}") + Lima._entity_groups[(self.lang, group)] = names + + def compile_rules(self, + output: Union[str, os.PathLike], + *, + rules: Optional[str] = None, + rules_file: Union[str, os.PathLike, None] = None, + save_rules: Union[str, os.PathLike, None] = None, + entity_types: Iterable[str] = (), + lang: Optional[str] = None) -> pathlib.Path: + """Compiles ModEx rules, as LIMA's compile-rules tool, and saves the + compiled rules (and optionally the rules themselves) for later use: by + add_rules, or by a LIMA configuration (the "rules" of an + AutomatonRecognizer resource). + + The rules are given as a string (rules) or a file (rules_file, utf-8). + Their include and gazetteer files are searched for as given (relative + to the current directory), then next to the rules file (next to + save_rules for a string), then in the LIMA_RESOURCES directories. + + Example:: + + import pathlib + import aymara.lima + nlp = aymara.lima.Lima() + rules = "\\n".join([ + "set encoding=utf8", + "using groups Product", + "set defaultAction=>CreateSpecificEntity()", + "Python::$PROPN:Product.SOFTWARE:", + "Lima::$PROPN:Product.SOFTWARE:", + ]) + "\\n" + nlp.compile_rules("software.bin", rules=rules, + save_rules="software.rules", + entity_types=["Product.SOFTWARE"]) + assert pathlib.Path("software.bin").stat().st_size > 0 + assert pathlib.Path("software.rules").read_text() == rules + + :param output: the file of the compiled rules (by convention a .bin), for + the language lang only. It is replaced only if the compilation + succeeds + :param rules: the ModEx rules (text), instead of rules_file + :param rules_file: the file of the ModEx rules, instead of rules + :param save_rules: a file where the rules are saved (written before the + compilation, so that their includes are searched for next to it) + :param entity_types: the entity types of the rules that the analyzer + does not know yet, as "Group.TYPE" (e.g. ["Product.SOFTWARE"]); the + ones of the configuration (Location.CITY...) are known. A group gets + all its types at once. A compiled file declares its types itself + :param lang: the language of the rules (Default: the analyzer's one) + :return: the path of the compiled rules + :raise ValueError: if neither or both of rules and rules_file are given + :raise LimaInternalError: if the rules cannot be compiled (the error + gives the file and line) + """ + if (rules is None) == (rules_file is None): + raise ValueError("compile_rules needs either rules (a string) or " + "rules_file") + lang = _media(lang) if lang else self.lang + if lang not in self.langs: + raise ValueError(f"compile_rules: {lang} is not a language of the " + f"analyzer ({', '.join(self.langs)})") + if rules_file is not None: + rules_file = pathlib.Path(rules_file) + if not rules_file.is_file(): + raise FileNotFoundError(f"compile_rules: no rules file {rules_file}") + rules = rules_file.read_text(encoding="utf-8") + output = pathlib.Path(output) + self._declare_entity_types(entity_types) + if save_rules is not None: + save_rules = pathlib.Path(save_rules) + if rules_file is None or not (save_rules.exists() + and save_rules.samefile(rules_file)): + save_rules.write_text(rules, encoding="utf-8") + if rules_file is not None: + self._check(self.analyzer.compileRules( + lang, str(rules_file), str(output)), "compile_rules") + elif save_rules is not None: + self._check(self.analyzer.compileRules( + lang, str(save_rules), str(output)), "compile_rules") + else: + with tempfile.TemporaryDirectory(prefix="lima-rules-") as tmp: + source = pathlib.Path(tmp) / "rules.rules" + source.write_text(rules, encoding="utf-8") + self._check(self.analyzer.compileRules( + lang, str(source), str(output)), "compile_rules") + return output + + def add_rules(self, + rules_file: Union[str, os.PathLike], + *, + entity_types: Iterable[str] = ()): + """Makes the analyzer apply ModEx rules: compiled ones (a .bin file, of + compile_rules or LIMA's compile-rules) or text ones (any other file, + compiled here). They are applied after the dependency parsing and + before the named entities rules, by a new pipeline which becomes the + analyzer's default: the documents analyzed afterwards contain their + entities (in doc.ents, with the label "Group.TYPE"). + + Example:: + + import aymara.lima + nlp = aymara.lima.Lima() + nlp.compile_rules("software.bin", entity_types=["Product.SOFTWARE"], + rules="using groups Product\\n" + "set defaultAction=>CreateSpecificEntity()\\n" + "Python:::Product.SOFTWARE:\\n") + nlp.add_rules("software.bin", entity_types=["Product.SOFTWARE"]) + doc = nlp("Python analyzes texts.") + assert [(e.text, e.label_) for e in doc.ents] == [ + ("Python", "Product.SOFTWARE")] + + :param rules_file: the file of the rules: compiled if its extension is + .bin, text (utf-8) otherwise + :param entity_types: the entity types of the rules that the analyzer + does not know yet, as in compile_rules: needed, even for a compiled + file, to create the entities in the analysis graph + :raise LimaInternalError: if the rules cannot be read or compiled + """ + rules_file = pathlib.Path(rules_file) + if not rules_file.is_file(): + raise FileNotFoundError(f"add_rules: no rules file {rules_file}") + self._declare_entity_types(entity_types) + Lima._rules_count += 1 + pipes = list(self.pipes) + recognizer = self._add_recognizer(f"LimaRules{Lima._rules_count}") + try: + if rules_file.suffix == ".bin": + self._check(self.analyzer.loadRecognizerRules( + self.lang, recognizer, str(rules_file)), "add_rules") + else: + self._check(self.analyzer.setRecognizerRules( + self.lang, recognizer, str(rules_file)), "add_rules") + except Exception: + # The analyzer keeps its pipeline + self.pipes[:] = pipes + raise + @staticmethod def export_system_conf(dir: pathlib.Path = None, lang: str = None) -> bool: """Export LIMA configuration files from the module system path to the given @@ -1896,8 +2122,6 @@ class PhraseMatcher: """ _ATTRS = ("ORTH", "LOWER", "LEMMA", "POS") - # The units before which the matcher is inserted in the pipeline - _BEFORE_UNITS = ("SpecificEntitiesModexAfterPos",) _count = 0 def __init__(self, nlp: "Lima", attr: str = "ORTH", validate: bool = False): @@ -1958,37 +2182,7 @@ def _install(self): applying it, and a pipeline made of the analyzer's one with this unit before the named entities rules, which becomes the analyzer's default.""" - analyzer, lang = self.nlp.analyzer, self.lang - base = self.nlp.pipes[0] if self.nlp.pipes else "deepud" - units = (self.nlp._pipeline_units.get(base) - or self.nlp._configured_units(base)) - if not units: - raise LimaInternalError(f"PhraseMatcher: the units of the pipeline " - f"'{base}' of {lang} are not found") - unit = f"{self._name}Recognition" - position = next((k for k, u in enumerate(units) - if u in self._BEFORE_UNITS or u.endswith("Dumper")), - len(units)) - units = units[:position] + [unit] + units[position:] - pipeline_unit = f"{self._name}Pipeline" - pipeline = f"{base}-{self._name.lower()}" - self._check(analyzer.addResource(lang, json.dumps({ - "name": self._recognizer, "class": "AutomatonRecognizer", - "rules": ""})), "recognizer") - self._check(analyzer.addProcessUnit(lang, json.dumps({ - "name": unit, "class": "ApplyRecognizer", - "automaton": self._recognizer, "applyOnGraph": "PosGraph", - "useSentenceBounds": "no"})), "unit") - self._check(analyzer.addProcessUnit(lang, json.dumps({ - "name": pipeline_unit, "class": "ProcessUnitPipeline", - "processUnitSequence": units})), "pipeline unit") - self._check(analyzer.addPipeline(pipeline, lang, pipeline_unit), - "pipeline") - self.nlp._pipeline_units[pipeline] = units - if self.nlp.pipes: - self.nlp.pipes[0] = pipeline - else: - self.nlp.pipes.append(pipeline) + self._recognizer = self.nlp._add_recognizer(self._name) self._installed = True def _declare(self, key): @@ -1998,12 +2192,8 @@ def _declare(self, key): return group = f"{self._name}_{len(self._labels)}" name = re.sub(r"\W", "_", str(key), flags=re.ASCII) or "MATCH" - self._check(self.nlp.analyzer.addEntityType(group, name), "entity type") label = f"{group}.{name}" - # The micro-category of the token merging the match in the PosGraph - self._check(self.nlp.analyzer.addResource(self.lang, json.dumps({ - "name": f"{group}Micros", "class": "SpecificEntitiesMicros", - label: ["PROPN"]})), "micro-categories") + self.nlp._declare_entity_types([label]) self._labels[key] = label self._keys[label] = key diff --git a/lima.cpp b/lima.cpp index 1ad627c..01ef28c 100644 --- a/lima.cpp +++ b/lima.cpp @@ -88,6 +88,7 @@ #include "linguisticProcessing/client/AnalysisHandlers/SimpleStreamHandler.h" #include "linguisticProcessing/client/AnalysisHandlers/LTRTextHandler.h" #include "linguisticProcessing/client/AnalysisHandlers/PipelineHandlers.h" +#include "linguisticProcessing/core/Automaton/automatonReaderWriter.h" #include "linguisticProcessing/core/Automaton/recognizer.h" #include "linguisticProcessing/core/Automaton/SpecificEntityAnnotation.h" #include "linguisticProcessing/tools/automatonCompiler/libautomatonCompiler/recognizerCompiler.h" @@ -211,6 +212,18 @@ class LimaAnalyzerPrivate bool setRecognizerRules(const std::string& media, const std::string& recognizer, const std::string& rulesFile); + bool compileRules(const std::string& media, + const std::string& rulesFile, + const std::string& binFile); + bool loadRecognizerRules(const std::string& media, + const std::string& recognizer, + const std::string& binFile); + + /** The recognizer resource of the media into which compileRules compiles + * (created when first needed), nullptr (error set) if it cannot be. */ + std::shared_ptr recognizer(const std::string& media, + const std::string& name, + const std::string& what); /** Runs f, an error (false, error and errorMessage set) if it throws */ bool guarded(const std::string& what, const std::function& f); @@ -316,6 +329,8 @@ class LimaAnalyzerPrivate /** The handlers named by the units added by addPipelineUnit (they are not * in the configuration), by media and pipeline */ std::map, std::set> addedUnitsHandlers; + /** The medias whose compileRules recognizer resource is declared */ + std::set rulesCompilers; /** The output of the handlers whose output is not used: discarded (a stream * without buffer, safe for all the handlers, unlike a null one) */ std::shared_ptr discardedOutput = std::make_shared(nullptr); @@ -1086,6 +1101,20 @@ bool LimaAnalyzer::setRecognizerRules(const std::string& media, return m_d->setRecognizerRules(media, recognizer, rulesFile); } +bool LimaAnalyzer::compileRules(const std::string& media, + const std::string& rulesFile, + const std::string& binFile) +{ + return m_d->compileRules(media, rulesFile, binFile); +} + +bool LimaAnalyzer::loadRecognizerRules(const std::string& media, + const std::string& recognizer, + const std::string& binFile) +{ + return m_d->loadRecognizerRules(media, recognizer, binFile); +} + bool LimaAnalyzerPrivate::guarded(const std::string& what, const std::function& f) { @@ -1215,13 +1244,9 @@ bool LimaAnalyzerPrivate::setRecognizerRules(const std::string& media, { return guarded("setRecognizerRules", [&]() { auto mediaid = MedData::single().getMediaId(media); - auto reco = std::dynamic_pointer_cast( - LinguisticResources::single().getResource(mediaid, recognizer)); + auto reco = this->recognizer(media, recognizer, "setRecognizerRules"); if (reco == nullptr) { - error = true; - errorMessage = "setRecognizerRules: no recognizer '" + recognizer - + "' for media " + media; return false; } // The rules are replaced in place: the units using the recognizer keep @@ -1234,6 +1259,120 @@ bool LimaAnalyzerPrivate::setRecognizerRules(const std::string& media, }); } +std::shared_ptr LimaAnalyzerPrivate::recognizer( + const std::string& media, const std::string& name, const std::string& what) +{ + auto mediaid = MedData::single().getMediaId(media); + auto reco = std::dynamic_pointer_cast( + LinguisticResources::single().getResource(mediaid, name)); + if (reco == nullptr) + { + error = true; + errorMessage = what + ": no recognizer '" + name + "' for media " + media; + } + return reco; +} + +bool LimaAnalyzerPrivate::compileRules(const std::string& media, + const std::string& rulesFile, + const std::string& binFile) +{ + // A recognizer resource of the media (initialized for it, as the one of + // compile-rules), only used to compile + static const std::string name = "AymaraRulesCompiler"; + if (rulesCompilers.find(media) == rulesCompilers.end()) + { + if (!addResource(media, "{\"name\": \"" + name + + "\", \"class\": \"AutomatonRecognizer\", \"rules\": \"\"}")) + { + return false; + } + rulesCompilers.insert(media); + } + return guarded("compileRules", [&]() { + auto mediaid = MedData::single().getMediaId(media); + auto reco = this->recognizer(media, name, "compileRules"); + if (reco == nullptr) + { + return false; + } + reco->clearRules(); + // Written next to binFile, then renamed: a failure leaves binFile as it + // was + auto tmpFile = binFile + ".tmp"; + try + { + Automaton::RecognizerCompiler::setRecognizerEncoding("utf8"); + Automaton::RecognizerCompiler compiler(rulesFile); + compiler.buildRecognizer(*reco, mediaid); + Automaton::AutomatonWriter writer; + writer.writeRecognizer(*reco, tmpFile, mediaid); + } + catch (...) + { + reco->clearRules(); + QFile::remove(QString::fromStdString(tmpFile)); + throw; + } + reco->clearRules(); + auto qbinFile = QString::fromStdString(binFile); + if ((QFile::exists(qbinFile) && !QFile::remove(qbinFile)) + || !QFile::rename(QString::fromStdString(tmpFile), qbinFile)) + { + QFile::remove(QString::fromStdString(tmpFile)); + error = true; + errorMessage = "compileRules: cannot write " + binFile; + return false; + } + return true; + }); +} + +bool LimaAnalyzerPrivate::loadRecognizerRules(const std::string& media, + const std::string& recognizer, + const std::string& binFile) +{ + return guarded("loadRecognizerRules", [&]() { + auto reco = this->recognizer(media, recognizer, "loadRecognizerRules"); + if (reco == nullptr) + { + return false; + } + auto mediaid = MedData::single().getMediaId(media); + { + // The rules of binFile are compiled for a media: this one + std::ifstream file(binFile, std::ios::in | std::ios::binary); + if (!file.good()) + { + error = true; + errorMessage = "loadRecognizerRules: cannot read " + binFile; + return false; + } + Automaton::AutomatonReader header; + if (header.readHeader(file) != mediaid) + { + error = true; + errorMessage = "loadRecognizerRules: " + binFile + + " is not compiled for media " + media; + return false; + } + } + // The rules are replaced in place (see setRecognizerRules) + reco->clearRules(); + try + { + Automaton::AutomatonReader reader; + reader.readRecognizer(binFile, *reco); + } + catch (...) + { + reco->clearRules(); + throw; + } + return true; + }); +} + QString LimaAnalyzerPrivate::getFeats(const LinguisticAnalysisStructure::MorphoSyntacticData& morphoData) { #ifdef DEBUG_LP diff --git a/lima.h b/lima.h index d4a0071..db39c97 100644 --- a/lima.h +++ b/lima.h @@ -128,6 +128,22 @@ class BINDINGS_API LimaAnalyzer const std::string& recognizer, const std::string& rulesFile); + /** Compiles the ModEx rules of the given file (text format, utf-8) for the + * media, as LIMA's compile-rules, and writes the compiled recognizer to + * binFile (the .bin of an AutomatonRecognizer resource). The entity types + * of the rules must be known (configuration or addEntityType). binFile is + * left untouched if the compilation fails. */ + bool compileRules(const std::string& media, + const std::string& rulesFile, + const std::string& binFile); + + /** Replaces the rules of the recognizer resource (class + * AutomatonRecognizer) of the media by the compiled rules of binFile (as + * written by compileRules or compile-rules, for this media). */ + bool loadRecognizerRules(const std::string& media, + const std::string& recognizer, + const std::string& binFile); + /** return true if an error occured */ bool error(); /** return the error message if an error occured and reset the error state */ diff --git a/tests/test_rules.py b/tests/test_rules.py new file mode 100644 index 0000000..9fdc49b --- /dev/null +++ b/tests/test_rules.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: 2026 CEA LIST +# +# SPDX-License-Identifier: MIT + +"""Lima.compile_rules and Lima.add_rules: ModEx rules compiled from Python, +saved and applied by the analyzer.""" + +import pytest + +import aymara.lima +from aymara.lima import LimaInternalError + +try: + from tests.test_aymara import lima +except ImportError: # pragma: no cover + from test_aymara import lima + + +def _rules(group: str, word: str) -> str: + """ModEx rules making word an entity group.WORD.""" + return (f"set encoding=utf8\n" + f"using groups {group}\n" + f"set defaultAction=>CreateSpecificEntity()\n" + f"{word}:::{group}.WORD:\n") + + +@pytest.fixture +def nlp(): + """Give the analyzer shared by the tests.""" + # add_rules makes the analyzer use a new pipeline: restored afterwards + pipes = list(lima.pipes) + yield lima + lima.pipes[:] = pipes + + +def _entities(nlp, text): + return [(e.text, e.label_) for e in nlp(text).ents] + + +def test_compile_string_saved(nlp, tmp_path): + rules = _rules("RulesString", "Python") + output = nlp.compile_rules(tmp_path / "string.bin", rules=rules, + save_rules=tmp_path / "string.rules", + entity_types=["RulesString.WORD"]) + assert output == tmp_path / "string.bin" + assert output.stat().st_size > 0 + assert (tmp_path / "string.rules").read_text(encoding="utf-8") == rules + nlp.add_rules(output, entity_types=["RulesString.WORD"]) + assert ("Python", "RulesString.WORD") in _entities(nlp, "Python analyzes texts.") + + +def test_compile_string_not_saved(nlp, tmp_path): + nlp.compile_rules(tmp_path / "nosave.bin", rules=_rules("RulesNoSave", "Python"), + entity_types=["RulesNoSave.WORD"]) + assert sorted(p.name for p in tmp_path.iterdir()) == ["nosave.bin"] + + +def test_compile_file(nlp, tmp_path): + rules = _rules("RulesFile", "Python") + source = tmp_path / "file.rules" + source.write_text(rules, encoding="utf-8") + nlp.compile_rules(tmp_path / "file.bin", rules_file=source, + save_rules=tmp_path / "copy.rules", + entity_types=["RulesFile.WORD"]) + assert (tmp_path / "file.bin").stat().st_size > 0 + assert (tmp_path / "copy.rules").read_text(encoding="utf-8") == rules + nlp.add_rules(tmp_path / "file.bin", entity_types=["RulesFile.WORD"]) + assert ("Python", "RulesFile.WORD") in _entities(nlp, "Python analyzes texts.") + + +def test_compile_include(nlp, tmp_path): + """The includes of a string are searched for next to save_rules.""" + included = tmp_path / "included.rules" + included.write_text(_rules("RulesInclude", "Python"), encoding="utf-8") + nlp.compile_rules(tmp_path / "include.bin", rules="include included.rules\n", + save_rules=tmp_path / "main.rules", + entity_types=["RulesInclude.WORD"]) + nlp.add_rules(tmp_path / "include.bin", entity_types=["RulesInclude.WORD"]) + assert ("Python", "RulesInclude.WORD") in _entities(nlp, "Python analyzes texts.") + + +def test_add_text_rules(nlp, tmp_path): + source = tmp_path / "text.rules" + source.write_text(_rules("RulesText", "Python"), encoding="utf-8") + nlp.add_rules(source, entity_types=["RulesText.WORD"]) + assert ("Python", "RulesText.WORD") in _entities(nlp, "Python analyzes texts.") + + +def test_compile_error_keeps_output(nlp, tmp_path): + output = tmp_path / "error.bin" + output.write_bytes(b"previous") + with pytest.raises(LimaInternalError): + nlp.compile_rules(output, rules="using groups RulesUnknownGroup\n" + "Python:::RulesUnknownGroup.WORD:\n") + assert output.read_bytes() == b"previous" + assert sorted(p.name for p in tmp_path.iterdir()) == ["error.bin"] + + +def test_add_rules_error_keeps_pipeline(nlp, tmp_path): + pipes = list(nlp.pipes) + bad = tmp_path / "bad.bin" + bad.write_bytes(b"not compiled rules") + with pytest.raises(LimaInternalError): + nlp.add_rules(bad) + assert nlp.pipes == pipes + + +def test_compile_rules_arguments(nlp, tmp_path): + with pytest.raises(ValueError): + nlp.compile_rules(tmp_path / "x.bin") + with pytest.raises(ValueError): + nlp.compile_rules(tmp_path / "x.bin", rules="", rules_file=tmp_path / "r") + with pytest.raises(FileNotFoundError): + nlp.compile_rules(tmp_path / "x.bin", rules_file=tmp_path / "missing.rules") + with pytest.raises(ValueError): + nlp.compile_rules(tmp_path / "x.bin", rules="", lang="ud-fra") + with pytest.raises(FileNotFoundError): + nlp.add_rules(tmp_path / "missing.bin") + + +def test_entity_types(nlp): + with pytest.raises(ValueError): + nlp._declare_entity_types(["NoType"]) + with pytest.raises(ValueError): + nlp._declare_entity_types(["1Group.TYPE"]) + nlp._declare_entity_types(["RulesTypes.A", "RulesTypes.B"]) + # Already declared: nothing to do + nlp._declare_entity_types(["RulesTypes.A"]) + assert aymara.lima.Lima._entity_groups[(nlp.lang, "RulesTypes")] == ["A", "B"] + # A group gets its types at once + with pytest.raises(ValueError): + nlp._declare_entity_types(["RulesTypes.C"]) From abcc883f2a68174aaf14847ad20c344a15a275df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20de=20Chalendar?= Date: Sun, 29 Nov 2026 00:18:21 +0100 Subject: [PATCH 2/4] compile_rules: a group of the configuration is a clear ValueError; examples on a new group Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++---- aymara/lima.py | 44 +++++++++++++++++++++++++++----------------- tests/test_rules.py | 8 ++++++++ 3 files changed, 39 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 39ff743..0500bc7 100644 --- a/README.md +++ b/README.md @@ -151,16 +151,16 @@ contain the rules' entities in `doc.ents`: import aymara.lima nlp = aymara.lima.Lima("ud-eng") rules = """set encoding=utf8 -using groups Product +using groups Software set defaultAction=>CreateSpecificEntity() -Python:::Product.SOFTWARE: +Python:::Software.PROGRAM: """ # or rules_file="software.rules" nlp.compile_rules("software.bin", rules=rules, save_rules="software.rules", - entity_types=["Product.SOFTWARE"]) + entity_types=["Software.PROGRAM"]) # Later, possibly in another process -nlp.add_rules("software.bin", entity_types=["Product.SOFTWARE"]) +nlp.add_rules("software.bin", entity_types=["Software.PROGRAM"]) print(nlp("Python analyzes texts.").ents) ``` diff --git a/aymara/lima.py b/aymara/lima.py index e2534dc..f02c73e 100644 --- a/aymara/lima.py +++ b/aymara/lima.py @@ -1845,7 +1845,7 @@ def _declare_entity_types(self, entity_types: Iterable[str]): if not re.fullmatch(r"[^\W\d]\w*", group) \ or not re.fullmatch(r"\w+", name): raise ValueError(f"An entity type is Group.TYPE (e.g. " - f"\"Product.SOFTWARE\"), not {entity_type!r}") + f"\"Software.PROGRAM\"), not {entity_type!r}") groups.setdefault(group, []) if name not in groups[group]: groups[group].append(name) @@ -1859,13 +1859,21 @@ def _declare_entity_types(self, entity_types: Iterable[str]): f"{', '.join(known)}: its types are declared at once, " f"{', '.join(missing)} cannot be added") continue + # First, as it fails for a group of the configuration (its + # micro-categories resource exists) + if not self.analyzer.addResource(self.lang, json.dumps({ + "name": f"{group}Micros", "class": "SpecificEntitiesMicros", + **{f"{group}.{name}": ["PROPN"] for name in names}})): + message = self.analyzer.errorMessage() + if "already exists" in message: + raise ValueError( + f"The entity group {group} is defined by the LIMA " + f"configuration: its types need no declaration, and " + f"new ones need another group") + raise LimaInternalError(f"micro-categories of {group}: {message}") for name in names: self._check(self.analyzer.addEntityType(group, name), f"entity type {group}.{name}") - self._check(self.analyzer.addResource(self.lang, json.dumps({ - "name": f"{group}Micros", "class": "SpecificEntitiesMicros", - **{f"{group}.{name}": ["PROPN"] for name in names}})), - f"micro-categories of {group}") Lima._entity_groups[(self.lang, group)] = names def compile_rules(self, @@ -1893,14 +1901,14 @@ def compile_rules(self, nlp = aymara.lima.Lima() rules = "\\n".join([ "set encoding=utf8", - "using groups Product", + "using groups Software", "set defaultAction=>CreateSpecificEntity()", - "Python::$PROPN:Product.SOFTWARE:", - "Lima::$PROPN:Product.SOFTWARE:", + "Python::$PROPN:Software.PROGRAM:", + "Lima::$PROPN:Software.PROGRAM:", ]) + "\\n" nlp.compile_rules("software.bin", rules=rules, save_rules="software.rules", - entity_types=["Product.SOFTWARE"]) + entity_types=["Software.PROGRAM"]) assert pathlib.Path("software.bin").stat().st_size > 0 assert pathlib.Path("software.rules").read_text() == rules @@ -1912,9 +1920,11 @@ def compile_rules(self, :param save_rules: a file where the rules are saved (written before the compilation, so that their includes are searched for next to it) :param entity_types: the entity types of the rules that the analyzer - does not know yet, as "Group.TYPE" (e.g. ["Product.SOFTWARE"]); the - ones of the configuration (Location.CITY...) are known. A group gets - all its types at once. A compiled file declares its types itself + does not know yet, as "Group.TYPE" (e.g. ["Software.PROGRAM"]); the + ones of the configuration (Location.CITY...) are known, and their + groups (Person, Location, Organization, Product...) get no new + types. A group gets all its types at once. A compiled file declares + its types itself :param lang: the language of the rules (Default: the analyzer's one) :return: the path of the compiled rules :raise ValueError: if neither or both of rules and rules_file are given @@ -1969,14 +1979,14 @@ def add_rules(self, import aymara.lima nlp = aymara.lima.Lima() - nlp.compile_rules("software.bin", entity_types=["Product.SOFTWARE"], - rules="using groups Product\\n" + nlp.compile_rules("software.bin", entity_types=["Software.PROGRAM"], + rules="using groups Software\\n" "set defaultAction=>CreateSpecificEntity()\\n" - "Python:::Product.SOFTWARE:\\n") - nlp.add_rules("software.bin", entity_types=["Product.SOFTWARE"]) + "Python:::Software.PROGRAM:\\n") + nlp.add_rules("software.bin", entity_types=["Software.PROGRAM"]) doc = nlp("Python analyzes texts.") assert [(e.text, e.label_) for e in doc.ents] == [ - ("Python", "Product.SOFTWARE")] + ("Python", "Software.PROGRAM")] :param rules_file: the file of the rules: compiled if its extension is .bin, text (utf-8) otherwise diff --git a/tests/test_rules.py b/tests/test_rules.py index 9fdc49b..88ac6d6 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -130,3 +130,11 @@ def test_entity_types(nlp): # A group gets its types at once with pytest.raises(ValueError): nlp._declare_entity_types(["RulesTypes.C"]) + + +def test_configured_group(nlp): + """The groups of the configuration (with their micro-categories) cannot be + declared.""" + with pytest.raises(ValueError, match="configuration"): + nlp._declare_entity_types(["Product.RULESNEW"]) + assert (nlp.lang, "Product") not in aymara.lima.Lima._entity_groups From 151b02c47ef34fce16505bf468c122aff62b5f73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20de=20Chalendar?= Date: Sun, 29 Nov 2026 00:20:25 +0100 Subject: [PATCH 3/4] compileRules: its recognizer resource is shared by the analyzers of the process Tests of a second analyzer and of a .bin used by another process. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 ++- aymara/lima.py | 2 +- lima.cpp | 19 +++++++++---------- tests/test_rules.py | 31 +++++++++++++++++++++++++++++++ 4 files changed, 43 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 0500bc7..010f19d 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,8 @@ print(nlp("Python analyzes texts.").ents) know yet. The types of a group are declared all at once. When the rules come from a string, their `include`s are searched for next to `save_rules`. The `.bin` file can also be used as the `rules` of an `AutomatonRecognizer` -resource in a LIMA configuration. +resource in a LIMA configuration. There, its path is relative to a resources +directory (e.g. the `user_resources_path` of `Lima`). ## Python bindings API documentation diff --git a/aymara/lima.py b/aymara/lima.py index f02c73e..ca7e0f3 100644 --- a/aymara/lima.py +++ b/aymara/lima.py @@ -1622,7 +1622,7 @@ def pipe_names(self) -> List[str]: LIMA configuration file, e.g. ["RnnTokenizer", "RnnTokensAnalyzer", "RnnDependencyParser", "SpecificEntitiesModexAfterPos", "conllDumper"]; empty if the file is not found. Units added by add_pipeline_unit are not - listed, the ones of the PhraseMatchers are.""" + listed, the ones of the PhraseMatchers and add_rules are.""" pipeline = self.pipes[0] if self.pipes else "deepud" if pipeline in self._pipeline_units: return list(self._pipeline_units[pipeline]) diff --git a/lima.cpp b/lima.cpp index 01ef28c..197c1a4 100644 --- a/lima.cpp +++ b/lima.cpp @@ -329,8 +329,6 @@ class LimaAnalyzerPrivate /** The handlers named by the units added by addPipelineUnit (they are not * in the configuration), by media and pipeline */ std::map, std::set> addedUnitsHandlers; - /** The medias whose compileRules recognizer resource is declared */ - std::set rulesCompilers; /** The output of the handlers whose output is not used: discarded (a stream * without buffer, safe for all the handlers, unlike a null one) */ std::shared_ptr discardedOutput = std::make_shared(nullptr); @@ -1280,17 +1278,18 @@ bool LimaAnalyzerPrivate::compileRules(const std::string& media, // A recognizer resource of the media (initialized for it, as the one of // compile-rules), only used to compile static const std::string name = "AymaraRulesCompiler"; - if (rulesCompilers.find(media) == rulesCompilers.end()) - { - if (!addResource(media, "{\"name\": \"" + name - + "\", \"class\": \"AutomatonRecognizer\", \"rules\": \"\"}")) + return guarded("compileRules", [&]() { + auto mediaid = MedData::single().getMediaId(media); + // Declared by the first analyzer of the process compiling for the media + // (the resources are shared by the analyzers) + const auto& module = + LinguisticResources::changeable().getModuleConfiguration(mediaid); + if (module.find(name) == module.end() + && !addResource(media, "{\"name\": \"" + name + + "\", \"class\": \"AutomatonRecognizer\", \"rules\": \"\"}")) { return false; } - rulesCompilers.insert(media); - } - return guarded("compileRules", [&]() { - auto mediaid = MedData::single().getMediaId(media); auto reco = this->recognizer(media, name, "compileRules"); if (reco == nullptr) { diff --git a/tests/test_rules.py b/tests/test_rules.py index 88ac6d6..06e18b8 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -138,3 +138,34 @@ def test_configured_group(nlp): with pytest.raises(ValueError, match="configuration"): nlp._declare_entity_types(["Product.RULESNEW"]) assert (nlp.lang, "Product") not in aymara.lima.Lima._entity_groups + + +def test_second_analyzer(nlp, tmp_path): + """The compiler's resource is shared by the analyzers of the process.""" + nlp.compile_rules(tmp_path / "first.bin", rules=_rules("RulesSecond", "Python"), + entity_types=["RulesSecond.WORD"]) + other = aymara.lima.Lima("ud-eng", pipes="") + other.compile_rules(tmp_path / "second.bin", + rules=_rules("RulesSecond", "Lima"), + entity_types=["RulesSecond.WORD"]) + assert (tmp_path / "second.bin").stat().st_size > 0 + + +def test_add_rules_other_process(nlp, tmp_path): + """A compiled file is used later by another process.""" + import subprocess + import sys + output = nlp.compile_rules(tmp_path / "later.bin", + rules=_rules("RulesLater", "Python"), + entity_types=["RulesLater.WORD"]) + script = ( + "import sys\n" + "import aymara.lima\n" + "nlp = aymara.lima.Lima('ud-eng', meta=dict(udlang=sys.argv[2]))\n" + "nlp.add_rules(sys.argv[1], entity_types=['RulesLater.WORD'])\n" + "print([(e.text, e.label_) for e in nlp('Python analyzes texts.').ents])\n") + result = subprocess.run( + [sys.executable, "-c", script, str(output), nlp._meta["udlang"]], + capture_output=True, text=True, timeout=600) + assert result.returncode == 0, result.stderr[-2000:] + assert "('Python', 'RulesLater.WORD')" in result.stdout From e5e8aa65d2189c5c10879303db6fb2b22464392f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20de=20Chalendar?= Date: Sun, 29 Nov 2026 00:26:02 +0100 Subject: [PATCH 4/4] test_rules: the second analyzer is a deepud one Co-Authored-By: Claude Opus 5.5 --- tests/test_rules.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_rules.py b/tests/test_rules.py index 06e18b8..155d534 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -144,7 +144,7 @@ def test_second_analyzer(nlp, tmp_path): """The compiler's resource is shared by the analyzers of the process.""" nlp.compile_rules(tmp_path / "first.bin", rules=_rules("RulesSecond", "Python"), entity_types=["RulesSecond.WORD"]) - other = aymara.lima.Lima("ud-eng", pipes="") + other = aymara.lima.Lima("ud-eng", meta=dict(nlp._meta)) other.compile_rules(tmp_path / "second.bin", rules=_rules("RulesSecond", "Lima"), entity_types=["RulesSecond.WORD"])