Rules¶
Rule engine: combine keyword matches into higher-level conditions.
__all__
module-attribute
¶
__all__ = ['AllOf', 'AnyOf', 'AtLeast', 'CategoryRule', 'Document', 'EngineResult', 'KeywordRule', 'NamedRule', 'Near', 'Not', 'Rule', 'RuleEngine', 'RuleResult', 'RuleSyntaxError', 'SameParagraph', 'SameSentence', 'TagRule', 'all_of', 'any_of', 'at_least', 'before', 'category', 'kw', 'near', 'none_of', 'not_', 'parse_rule', 'same_paragraph', 'same_sentence', 'tag']
AnyOf ¶
AnyOf(*rules: Rule | str, min_count: int = 1)
Bases: Rule
At least min_count of the child rules match (default 1 = OR).
With min_count > 1 only children satisfied by different matches count (see the module
docs). Occurrences: for OR the number of distinct matches of the match-counting children plus
the counts of the others; for min_count > 1 the min_count-th largest count among the
distinct children.
CategoryRule ¶
CategoryRule(name: str)
Document ¶
Document(text: str, matches: Iterable[Match], *, aliases: Mapping[str, str] | None = None)
A text plus its matches, with lazily computed token / sentence / paragraph positions.
Sub-rule results are cached per document (see :meth:evaluate), so a sub-rule shared by
several rules of a :class:~keylex.rules.RuleEngine is evaluated once per text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text the matches were found in. |
required |
matches
|
Iterable[Match]
|
The keyword matches. |
required |
aliases
|
Mapping[str, str] | None
|
Optional |
None
|
restrict ¶
A view of this document that only contains matches (positions are shared).
evaluate ¶
evaluate(rule: Rule) -> RuleResult
Evaluate rule on this document, reusing the result of structurally equal rules.
keyword_matches ¶
keyword_matches(name: str) -> list[Match]
Matches of the keyword name (case-insensitive; aliases resolved).
word_index ¶
word_index(char_pos: int) -> int
Index of the word token containing / preceding char_pos.
unit_count ¶
unit_count(unit: str) -> int
Number of sentences (unit="sentence") or paragraphs in the text.
KeywordRule ¶
KeywordRule(name: str)
Near ¶
Bases: Rule
Two rules match within within words of each other (ordered: a before b).
With ordered=True (BEFORE) the a match must end before the b match starts (no
overlap). Matches with identical spans never pair up. Occurrences: the number of disjoint
qualifying pairs, formed greedily left to right (each match takes part in at most one pair).
Not ¶
Not(rule: Rule | str)
Bases: Rule
Negation. Never contributes matches.
At the top level (or inside AND / OR) it means "nowhere in the text". As an operand of
:class:SameSentence / :class:SameParagraph it means "not in that sentence / paragraph".
It is rejected as an operand of NEAR, BEFORE and ATLEAST.
Rule ¶
Bases: ABC
Base class. Combine rules with & (and), | (or), ~ (not).
Subclasses implement :meth:evaluate and :meth:to_dsl. Composite rules should evaluate
their children with doc.evaluate(child) so results are cached per document.
evaluate
abstractmethod
¶
evaluate(doc: Document) -> RuleResult
Evaluate the rule on doc. Call doc.evaluate(rule) instead to use the cache.
to_dsl
abstractmethod
¶
to_dsl() -> str
Serialise to the rule language accepted by :func:parse_rule.
keyword_names ¶
keyword_names() -> set[str]
Keyword names referenced by this rule (auto-added by :class:RuleEngine).
test ¶
test(text: str, matcher: BaseMatcher) -> RuleResult
Convenience: run matcher.find(text) and evaluate this rule.
RuleResult
dataclass
¶
RuleResult(rule: Rule, matched: bool, matches: tuple[Match, ...] = (), children: tuple[RuleResult, ...] = (), detail: str = '', count: int | None = None)
Outcome of evaluating a rule; truthy when the rule matched.
count is the number of occurrences of the rule (see the module docs); when a custom rule
leaves it unset, :attr:occurrences falls back to the number of distinct matched spans.
occurrences
property
¶
occurrences: int
How many times the rule occurs (what ATLEAST counts); 0 when it did not match.
keywords
property
¶
keywords: list[str]
Unique names of the keywords behind :attr:matches, in order of appearance.
explain ¶
explain(indent: int = 0, *, full_label: bool = True) -> str
Human-readable tree showing why the rule did or didn't match.
The top node shows the whole rule; nested nodes show a short label (operator plus a truncated form) so the output grows linearly with the size of the rule.
SameParagraph ¶
SameParagraph(*rules: Rule | str)
Bases: _SameUnit
All rules match inside one paragraph (blocks separated by blank lines).
SameSentence ¶
SameSentence(*rules: Rule | str)
Bases: _SameUnit
All rules match inside one sentence (NOT x operands: x is not in that sentence).
TagRule ¶
TagRule(name: str)
RuleSyntaxError ¶
RuleSyntaxError(message: str, source: str, pos: int, rule_name: str | None = None, filename: str | None = None)
Bases: ValueError
Raised for malformed rule strings; the message points at the offending position.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
The bare error message (without position / pointer). |
|
source |
The rule string. |
|
pos |
Character offset of the problem in |
|
rule_name |
Name of the rule being loaded, when known (prefixed to the message). |
|
filename |
The rules file the rule came from, when known (prefixed to the message). |
with_rule_name ¶
with_rule_name(name: str) -> RuleSyntaxError
A copy of this error whose message names the rule it came from.
with_filename ¶
with_filename(filename: str) -> RuleSyntaxError
A copy of this error whose message names the file it came from.
EngineResult
dataclass
¶
EngineResult(text: str, matches: list[Match], results: dict[str, RuleResult], rules: dict[str, NamedRule])
Result of :meth:RuleEngine.evaluate.
"name" in result tells whether a rule fired; result["name"] is its :class:RuleResult.
Attributes:
| Name | Type | Description |
|---|---|---|
text |
str
|
The evaluated text. |
matches |
list[Match]
|
All keyword matches found in the text. |
results |
dict[str, RuleResult]
|
|
rules |
dict[str, NamedRule]
|
The engine's rules at evaluation time. |
top
property
¶
top: str | None
The highest-weight rule that matched (handy for single-label classification).
explain ¶
explain() -> str
ASCII tree per rule (top node: the whole rule; nested nodes: short labels).
to_dict ¶
to_dict() -> dict[str, Any]
JSON-compatible summary: fired rules, score, and per-rule details with their matches.
NamedRule
dataclass
¶
NamedRule(name: str, rule: Rule, weight: float = 1.0, description: str = '', source: str = '')
A rule registered in a :class:RuleEngine with its name, weight and description.
to_dict ¶
to_dict() -> dict[str, Any]
{"rule": <rule string>, "weight": ..., "description": ...} (defaults omitted).
RuleEngine ¶
RuleEngine(keywords: KeywordsInput | None = None, rules: Mapping[str, Rule | str | Mapping[str, Any]] | None = None, **matcher_options: Any)
Evaluate a set of named, weighted rules against texts.
Keywords referenced by rules but missing from keywords are added automatically as plain
keywords, so the quickest start is just::
engine = RuleEngine(rules={
"finance": 'bank AND NOT NEAR(bank, river, 5)',
"ai": 'ANY("machine learning", "neural network", AI)',
})
engine.evaluate(text).fired
A rule name that is not a keyword name but a synonym / acronym / variant of exactly one
keyword (e.g. ML for "machine learning") refers to that keyword. If several keywords
share the term, a warning is issued and the term is matched as a keyword of its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keywords
|
KeywordsInput | None
|
Keyword definitions (synonyms, acronyms, categories, ...). Optional. |
None
|
rules
|
Mapping[str, Rule | str | Mapping[str, Any]] | None
|
|
None
|
**matcher_options
|
Any
|
Passed to :class: |
{}
|
rules
property
¶
rules: dict[str, NamedRule]
{name: NamedRule} (a copy; change rules with :meth:add_rule / :meth:remove_rule).
matcher
property
¶
matcher: KeywordMatcher
The underlying matcher (user keywords + keywords referenced by rules).
add_rule ¶
add_rule(name: str, rule: Rule | str, weight: float = 1.0, description: str = '') -> RuleEngine
Add (or replace) a named rule. Returns self for chaining.
Raises:
| Type | Description |
|---|---|
RuleSyntaxError
|
the rule string is malformed (the message names the rule). |
ValueError
|
empty name or non-finite weight. |
remove_rule ¶
remove_rule(name: str) -> None
Remove the rule called name. Raises KeyError if there is none.
evaluate ¶
evaluate(text: str) -> EngineResult
Match text once and evaluate every rule (shared sub-rules are evaluated once).
evaluate_many ¶
evaluate_many(texts: Iterable[str]) -> Iterator[EngineResult]
Lazily :meth:evaluate each text.
validate ¶
validate() -> list[str]
Static checks of the rule set; returns human-readable messages (empty list = clean).
The messages of :meth:diagnostics, errors and warnings alike.
diagnostics ¶
diagnostics() -> list[tuple[str, str]]
Static checks of the rule set as (level, message) pairs.
"error" (the rule set is broken): no rules at all, CATEGORY / TAG names that no
keyword has, ANY(n, ...) with fewer than n operands, non-finite weights.
"warning" (informational; keylex rules --check passes unless --strict): rules
naming keywords that are not in the keyword list (only when a keyword list was given; they
are added automatically, which is the intended use without one), names that are a term of
several keywords, and a lower-case and / or between bare words (rock and roll
means rock AND roll).
to_dict ¶
to_dict() -> dict[str, Any]
{"rules": ..., "keywords": ..., "options": ...}, readable by :meth:from_dict.
Only JSON-serialisable matcher options are kept (a callable stemmer is dropped).
from_dict
classmethod
¶
from_dict(data: Mapping[str, Any] | None, **matcher_options: Any) -> RuleEngine
Inverse of :meth:to_dict: {"keywords": [...], "rules": {...}, "options": {...}}.
Raises:
| Type | Description |
|---|---|
ValueError
|
a malformed structure (the message says what is wrong). |
load
classmethod
¶
load(path: str | Path, **matcher_options: Any) -> RuleEngine
Load a JSON (or YAML, with PyYAML) rules file (UTF-8; a byte-order mark is ignored).
Raises:
| Type | Description |
|---|---|
OSError
|
the file cannot be read. |
ValueError
|
malformed content (the message names the file); rule syntax errors are
:class: |
ImportError
|
a YAML file but PyYAML is not installed. |
save ¶
save(path: str | Path) -> None
Write :meth:to_dict as JSON; atomic, so a failure never truncates an existing file.
all_of ¶
All of rules match (AND). DSL: ALL(a, b, ...) or a AND b. Strings are keyword names.
any_of ¶
At least min_count of rules match (default 1: OR). DSL: ANY(n, a, b, ...).
With min_count > 1 operands must be satisfied by different matches, so
any_of("ML", "machine learning", min_count=2) does not fire on a single "ML".
Strings are keyword names.
at_least ¶
rule occurs at least n times. DSL: ATLEAST(n, rule).
See the module docs for what counts as an occurrence of each kind of rule.
before ¶
a occurs before b with at most within words in between. DSL: BEFORE(a, b, within).
category ¶
category(name: str) -> CategoryRule
Any keyword of category name occurs (case-insensitive). DSL: CATEGORY(name).
near ¶
a and b occur with at most within words between them. DSL: NEAR(a, b, within).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Rule | str
|
A rule or keyword name. |
required |
b
|
Rule | str
|
A rule or keyword name. |
required |
within
|
int
|
Maximum number of words between the two matches. |
5
|
ordered
|
bool
|
Require |
False
|
none_of ¶
None of rules occurs anywhere in the text. DSL: NONE(a, b, ...).
same_paragraph ¶
same_paragraph(*rules: Rule | str) -> SameParagraph
All rules match inside one paragraph (blocks separated by blank lines). DSL: PARAGRAPH(a, b, ...).
same_sentence ¶
same_sentence(*rules: Rule | str) -> SameSentence
All rules match inside one sentence. DSL: SENTENCE(a, b, ...).
A not_(x) operand means x is absent from that sentence.