Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,39 @@ 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 Software
set defaultAction=>CreateSpecificEntity()
Python:::Software.PROGRAM:
"""
# or rules_file="software.rules"
nlp.compile_rules("software.bin", rules=rules, save_rules="software.rules",
entity_types=["Software.PROGRAM"])

# Later, possibly in another process
nlp.add_rules("software.bin", entity_types=["Software.PROGRAM"])
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. There, its path is relative to a resources
directory (e.g. the `user_resources_path` of `Lima`).

## Python bindings API documentation

The Lima python API documentation is [part of the LIMA documentation](https://aymara.github.io/lima/reference/python-api/),
Expand Down
280 changes: 240 additions & 40 deletions aymara/lima.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1621,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])
Expand Down Expand Up @@ -1778,6 +1779,241 @@ 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"\"Software.PROGRAM\"), 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
# 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}")
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 Software",
"set defaultAction=>CreateSpecificEntity()",
"Python::$PROPN:Software.PROGRAM:",
"Lima::$PROPN:Software.PROGRAM:",
]) + "\\n"
nlp.compile_rules("software.bin", rules=rules,
save_rules="software.rules",
entity_types=["Software.PROGRAM"])
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. ["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
: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=["Software.PROGRAM"],
rules="using groups Software\\n"
"set defaultAction=>CreateSpecificEntity()\\n"
"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", "Software.PROGRAM")]

: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
Expand Down Expand Up @@ -1896,8 +2132,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):
Expand Down Expand Up @@ -1958,37 +2192,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):
Expand All @@ -1998,12 +2202,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

Expand Down
Loading
Loading