sparknlp_jsl.annotator.context.contextual_entity_ruler#

Module Contents#

Classes#

ContextualEntityRuler

ContextualEntityRuler is an annotator that updates chunks based on contextual rules.

class ContextualEntityRuler(classname='com.johnsnowlabs.nlp.annotators.context.ContextualEntityRuler', java_model=None)#

Bases: sparknlp_jsl.common.AnnotatorModelInternal, sparknlp_jsl.annotator.handle_exception_params.HandleExceptionParams

ContextualEntityRuler is an annotator that updates chunks based on contextual rules. These rules are defined in the form of dictionaries and can include prefixes, suffixes, and the context within a specified scope window around the chunk.

This annotator modifies detected chunks by replacing their entity labels or content based on matching patterns and rules. It is particularly useful for refining entity recognition results in domain-specific text processing.

Input Annotation types

Output Annotation type

DOCUMENT, TOKEN, CHUNK

CHUNK

Parameters:
  • caseSensitive (bool) – Whether to perform case-sensitive matching. Default is False.

  • allowPunctuationInBetween (bool) – Whether to allow punctuation between prefix/suffix patterns and the entity. Default is True.

  • dropEmptyChunks (bool) – If True, removes chunks with empty content after applying rules. Default is False.

  • rules (list[dict]) – The contextual rules as a list of dictionaries. Each rule includes: - entity (str): The target entity to match. - scopeWindow (list[int]): A list specifying the range [before, after] tokens or chars to consider. - scopeWindowLevel (str): Specifies whether the window applies to tokens or characters. Options: “token”, “char”. - prefixPatterns (list[str]): Patterns to match before the entity. - suffixPatterns (list[str]): Patterns to match after the entity. - prefixRegexes (list[str]): Regular expressions to match before the entity. - suffixRegexes (list[str]): Regular expressions to match after the entity. - replaceEntity (str): Replacement value for the matched entity. - mode (str): The mode of the rule. Options: “include”, “exclude”.

Examples

>>> from sparknlp.base import DocumentAssembler
>>> from sparknlp_jsl.annotator import ContextualEntityRuler
>>> from sparknlp.annotator import SentenceDetector, Tokenizer, WordEmbeddingsModel, MedicalNerModel, NerConverterInternal
>>> from pyspark.ml import Pipeline
>>> documentAssembler = DocumentAssembler() \
...     .setInputCol("text") \
...     .setOutputCol("document")
>>> sentenceDetector = SentenceDetector() \
...     .setInputCols(["document"]) \
...     .setOutputCol("sentences")
>>> tokenizer = Tokenizer() \
...     .setInputCols(["sentences"]) \
...     .setOutputCol("tokens")
>>> embeddings = WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models") \
...     .setInputCols(["sentences", "tokens"]) \
...     .setOutputCol("embeddings")
>>> medicalNerModel = MedicalNerModel.pretrained("ner_deid_generic_augmented", "en", "clinical/models") \
...     .setInputCols(["sentences", "tokens", "embeddings"]) \
...     .setOutputCol("ner")
>>> nerConverter = NerConverterInternal() \
...     .setInputCols(["sentences", "tokens", "ner"]) \
...     .setOutputCol("ner_chunks")
>>> rules = [
...     {
...         "entity": "AGE",
...         "scopeWindow": [2, 2],
...         "scopeWindowLevel": "token",
...         "prefixPatterns": ["is"],
...         "suffixPatterns": ["years"],
...         "replaceEntity": "REPLACED_AGE"
...     }
... ]
>>> contextualEntityRuler = ContextualEntityRuler() \
...     .setInputCols(["sentences", "tokens", "ner_chunks"]) \
...     .setOutputCol("updated_chunks") \
...     .setRules(rules) \
...     .setCaseSensitive(False) \
...     .setAllowPunctuationInBetween(True)
>>> pipeline = Pipeline().setStages([
...     documentAssembler,
...     sentenceDetector,
...     tokenizer,
...     embeddings,
...     medicalNerModel,
...     nerConverter,
...     contextualEntityRuler
... ])
>>> data = spark.createDataFrame([
...     ("California is 36 years old. The Grand Canyon in Arizona is 37 years.",)
... ], ["text"])
>>> model = pipeline.fit(data).transform(data)
>>> model.selectExpr("explode(updated_chunks) as chunk").show(truncate=False)
allowPunctuationInBetween#
caseSensitive#
doExceptionHandling#
dropEmptyChunks#
getter_attrs = []#
inputAnnotatorTypes#
inputCols#
lazyAnnotator#
mergeOverlapping#
name = 'ContextualEntityRuler'#
optionalInputAnnotatorTypes = []#
outputAnnotatorType = 'chunk'#
outputCol#
skipLPInputColsValidation = True#
uid = ''#
clear(param: pyspark.ml.param.Param) None#

Clears a param from the param map if it has been explicitly set.

copy(extra: pyspark.ml._typing.ParamMap | None = None) JP#

Creates a copy of this instance with the same uid and some extra params. This implementation first calls Params.copy and then make a copy of the companion Java pipeline component with extra params. So both the Python wrapper and the Java pipeline component get copied.

Parameters:

extra (dict, optional) – Extra parameters to copy to the new instance

Returns:

Copy of this instance

Return type:

JavaParams

explainParam(param: str | Param) str#

Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.

explainParams() str#

Returns the documentation of all params with their optionally default values and user-supplied values.

extractParamMap(extra: pyspark.ml._typing.ParamMap | None = None) pyspark.ml._typing.ParamMap#

Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.

Parameters:

extra (dict, optional) – extra param values

Returns:

merged param map

Return type:

dict

getInputCols()#

Gets current column names of input annotations.

getLazyAnnotator()#

Gets whether Annotator should be evaluated lazily in a RecursivePipeline.

getOrDefault(param: str) Any#
getOrDefault(param: Param[T]) T

Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set.

getOutputCol()#

Gets output column name of annotations.

getParam(paramName: str) Param#

Gets a param by its name.

getParamValue(paramName)#

Gets the value of a parameter.

Parameters:

paramName (str) – Name of the parameter

hasDefault(param: str | Param[Any]) bool#

Checks whether a param has a default value.

hasParam(paramName: str) bool#

Tests whether this instance contains a param with a given (string) name.

inputColsValidation(value)#
isDefined(param: str | Param[Any]) bool#

Checks whether a param is explicitly set by user or has a default value.

isSet(param: str | Param[Any]) bool#

Checks whether a param is explicitly set by user.

classmethod load(path: str) RL#

Reads an ML instance from the input path, a shortcut of read().load(path).

classmethod read()#

Returns an MLReader instance for this class.

save(path: str) None#

Save this ML instance to the given path, a shortcut of ‘write().save(path)’.

set(param: Param, value: Any) None#

Sets a parameter in the embedded param map.

setAllowPunctuationInBetween(value: bool)#

Sets whether punctuation is allowed between prefix/suffix patterns and the entity.

If True, punctuation (e.g., commas, periods) can exist between patterns and entities without breaking the match. If False, punctuation will prevent a match.

Parameters:

value (bool) – Whether to allow punctuation between matched patterns and entities.

setCaseSensitive(value: bool)#

Sets the caseSensitive parameter to use case sensitive when matching words.

Parameters:

value (bool) – Whether to use case sensitive when matching words.

setDoExceptionHandling(value: bool)#

If True, exceptions are handled. If exception causing data is passed to the model, a error annotation is emitted which has the exception message. Processing continues with the next one. This comes with a performance penalty.

Parameters:

value (bool) – If True, exceptions are handled.

setDropEmptyEntities(value: bool)#

Sets the dropEmptyEntities parameter to remove chunks with empty content after applying rules.

Parameters:

value (bool) – Whether to remove chunks with empty content after applying rules.

setForceInputTypeValidation(etfm)#
setInputCols(*value)#

Sets column names of input annotations.

Parameters:

*value (List[str]) – Input columns for the annotator

setLazyAnnotator(value)#

Sets whether Annotator should be evaluated lazily in a RecursivePipeline.

Parameters:

value (bool) – Whether Annotator should be evaluated lazily in a RecursivePipeline

setMergeOverlapping(value)#

Sets whether to merge overlapping chunks. Default is false

Parameters:

value (boolean) – whether to merge overlapping chunks. Default is false

setOutputCol(value)#

Sets output column name of annotations.

Parameters:

value (str) – Name of output column

setParamValue(paramName)#

Sets the value of a parameter.

Parameters:

paramName (str) – Name of the parameter

setParams()#
setRules(value: list)#

Sets the rules parameter to update chunks based on contextual rules. The rules parameter is a list of dictionaries. A dictionary should contain the following keys:

  • entity: The target entity field for update.

  • scopeWindow: A list of two integers [before, after], specifying how many tokens/chars before and after the target to consider.

  • scopeWindowLevel: Determines whether the scopeWindow is applied at the token or chunk level. Options: token, char.

  • prefixPatterns: A list of prefix patterns to add the target chunk.

  • suffixPatterns: A list of suffix patterns to add the target chunk.

  • prefixRegexes: A list of prefix regexes to add the target chunk.

  • suffixRegexes: A list of suffix regexes to add the target chunk.

  • replaceEntity: The entity to replace the target entity.

  • mode: The mode of the rule. Options: include, exclude.

Notes:#

  • entity, scopeWindow, and scopeWindowLevel are required for “include” mode. Other keys are optional.

  • scopeWindowLevel defines whether the window is applied at the token or char level.

  • scopeWindow is defined as [before, after], representing how many chars or tokens to check around the target entity. Scope can be calculated looking at tokens or chars.Decision of char or token can be defined by scopeWindowLevel.

Example:#

>>> rules = [
 ...     {
 ...         "entity": "AGE",
 ...         "scopeWindow": [2, 2],
 ...         "scopeWindowLevel": "token",
 ...         "prefixPatterns": ["is"],
 ...         "suffixPatterns": ["years"],
 ...         "replaceEntity": "REPLACED_AGE"
 ...     }
 ... ]
param value:

The rules parameter to filter the chunks based on contextual rules.

type value:

list[dict]

setRulesAsStr(value: str)#

Sets the rules parameter to update chunks based on contextual rules. The rules parameter is a list of dictionaries. A dictionary should contain the following keys:

  • entity: The target entity field for update.

  • scopeWindow: A list of two integers [before, after], specifying how many tokens/chars before and after the target to consider.

  • scopeWindowLevel: Determines whether the scopeWindow is applied at the token or chunk level. Options: token, char.

  • prefixPatterns: A list of prefix patterns to add the target chunk.

  • suffixPatterns: A list of suffix patterns to add the target chunk.

  • prefixRegexes: A list of prefix regexes to add the target chunk.

  • suffixRegexes: A list of suffix regexes to add the target chunk.

  • replaceEntity: The entity to replace the target entity.

Notes:#

  • entity, scopeWindow, and scopeWindowLevel are required. Other keys are optional.

  • scopeWindowLevel defines whether the window is applied at the token or char level.

  • scopeWindow is defined as [before, after], representing how many chars or tokens to check around the target entity.

    Scope can be calculated looking at tokens or chars. Decision of char or token can be defined by scopeWindowLevel.

>>> contextual_entity_filterer = ContextualEntityFilterer() \
...     .setRules( \
...         [{ \
...             "entity": "LOCATION", \
...             "scopeWindow": [2, 2], \
...             "whiteListEntities": ["AGE", "DATE"], \
...             "blackListEntities": ["ID", "NAME"], \
...             "scopeWindowLevel": "token", \
...             "blackListWords": ["known", "in"], \
...         }, \
...         { \
...             "entity": "DATE", \
...             "scopeWindow": [2, 2], \
...             "whiteListEntities": ["AGE", "DATE"], \
...             "blackListEntities": ["ID", "NAME"], \
...             "scopeWindowLevel": "chunk", \
...             "confidenceThreshold": 0.5 \
...         }] \
...     )
transform(dataset: pyspark.sql.dataframe.DataFrame, params: pyspark.ml._typing.ParamMap | None = None) pyspark.sql.dataframe.DataFrame#

Transforms the input dataset with optional parameters.

New in version 1.3.0.

Parameters:
  • dataset (pyspark.sql.DataFrame) – input dataset

  • params (dict, optional) – an optional param map that overrides embedded params.

Returns:

transformed dataset

Return type:

pyspark.sql.DataFrame

write() JavaMLWriter#

Returns an MLWriter instance for this ML instance.