sparknlp_jsl.annotator.parser.structured_json_converter#

Contains classes for the StructuredJsonConverter.

Module Contents#

Classes#

StructuredJsonConverter

StructuredJsonConverter is a transformer that converts the output of the pipeline into a structured JSON format.

class StructuredJsonConverter#

Bases: sparknlp.internal.AnnotatorTransformer

StructuredJsonConverter is a transformer that converts the output of the pipeline into a structured JSON format. The output can be a string or a struct, depending on the value of the outputAsStr parameter.

The schema of the input columns is defined by the converterSchema parameter, which outlines the structure of input columns. The schema includes fields for the document identifier, document text, entities, assertions, resolutions, relations, summaries, deidentifications, and classifications. The transformer includes parameters for setting the schema, returning entities in relations, removing spark-nlp annotation columns, and outputting the result as a string or a structured JSON. The transformer checks the input columns and document identifier column and ensures that the input columns are compatible with the transformer.

PipelineParser` class can be used to extract the schema from a pipeline.

Examples

>>> import sparknlp
>>> from sparknlp.pretrained import PretrainedPipeline
>>> from sparknlp_jsl.pipeline_tracer import PipelineTracer
>>> text = "In the bone- marrow (BM) aspiration, blasts accounted for 88.1% of ANCs, which were positive for CD9 and CD10 on flow cytometry."
>>> df = spark.createDataFrame([[text]]).toDF("text")
>>> bio_pipe = PretrainedPipeline("explain_clinical_doc_biomarker", "en", "clinical/models")
>>> pipeline_tracer = PipelineTracer(bio_pipe)
>>> columns = pipeline_tracer.createParserDictionary()
>>> converter = StructuredJsonConverter()\
...            .setOutputCol("json")\
...            .setConverterSchema(columns)
>>> base_df = bio_pipe.transform(df)
>>> json_df = converter.transform(base_df)
>>> json_df.select("json").show(truncate=False)
result::
|{"json":{"document_identifier":"ccf25343-e01c-42f6-932d-297e731fc3bf",
"document_text":["In the bone- marrow (BM) aspiration, blasts accounted for 88.1% of ANCs, which were positive for CD9 and CD10 on flow cytometry."],
"entities":[{"begin":"84","chunk":"positive","ner_source":"ner_oncology_chunk","end":"91","ner_label":"Biomarker_Result","chunk_id":"bc15add6","sentence":"0","ner_confidence":"0.9672"},{"begin":"97","chunk":"CD9","ner_source":"ner_oncology_chunk","end":"99","ner_label":"Biomarker","chunk_id":"b473fd80","sentence":"0","ner_confidence":"0.992"},{"begin":"105","chunk":"CD10","ner_source":"ner_oncology_chunk","end":"108","ner_label":"Biomarker","chunk_id":"0252d08a","sentence":"0","ner_confidence":"0.9987"}],
"assertions":[],
"resolutions":[],
"relations":[{"relation":"is_finding_of","direction":"both","confidence":"0.99814475","chunk2":"CD9","chunk2_id":"b473fd80","chunk1":"positive","chunk1_id":"bc15add6"},{"relation":"is_finding_of","direction":"both","confidence":"0.9996313","chunk2":"CD10","chunk2_id":"0252d08a","chunk1":"positive","chunk1_id":"bc15add6"}],
"summaries":[],
"deidentifications":[],
"classifications":[{"classification":"1","sentence":"In the bone- marrow (BM) aspiration, blasts accounted for 88.1% of ANCs, which were positive for CD9 and CD10 on flow cytometry.","sentence_id":"0"}]}
}|

Notes

document_identifier field is empty or not found in the input schema, a random UUID will be generated. If the document_identifier field is found in the input schema and It is not the column name, the value of the document_identifier field will be used. If the document_identifier field is found in the input schema and It is the column name, the column must be of type StringType.

cleanAnnotations#
getter_attrs = []#
name = 'StructuredJsonConverter'#
outputAnnotatorType = None#
outputAsStr#
outputCol#
returnRelationEntities#
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

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.

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.

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.

setCleanAnnotations(value)#

Sets whether to remove annotation columns, by default False.

Parameters:

value (bool) – Whether to remove annotation columns

setConverterSchema(value: dict)#

Sets the schema for converting the output of the pipeline into a structured JSON format.

Fields in the schema:

- `document_identifier`: The identifier of the document. This column must be of type `StringType`.
- `document_text`: The text of the document, typically created by the `DocumentAssembler` annotator.
- `entities`: Chunk columns generated by various annotators, such as the `ChunkMergeModel` annotator.
- `assertions`: Assertion columns produced by annotators like the `AssertionDLModel` annotator.
- `resolutions`: The schema for resolutions. See `ResolutionSchema` for details.
- `relations`: Relation columns created by annotators such as the `RelationExtractionModel` annotator.
- `summaries`: Summary columns generated by annotators like the `MedicalSummarizer` annotator.
- `deidentifications`: The schema for deidentifications.
- `classifications`: The schema for classifications.

Example

>>> from sparknlp.pretrained import PretrainedPipeline
>>> from sparknlp_jsl.pipeline_tracer import PipelineTracer
>>> bio_pipe = PretrainedPipeline("explain_clinical_doc_biomarker", "en", "clinical/models")
>>> pipeline_tracer = PipelineTracer(bio_pipe)
>>> columns = pipeline_tracer.createParserDictionary()
>>> converter = StructuredJsonConverter()\
...            .setOutputCol("json")\
...            .setConverterSchema(columns)
Parameters:

value (dict) – The schema for converting the output of the pipeline into a structured JSON format.

setConverterSchemaAsStr(value: str)#

Sets the schema for converting the output of the pipeline into a structured JSON format.

Fields in the schema:

- `document_identifier`: The identifier of the document. This column must be of type `StringType`.
- `document_text`: The text of the document, typically created by the `DocumentAssembler` annotator.
- `entities`: Chunk columns generated by various annotators, such as the `ChunkMergeModel` annotator.
- `assertions`: Assertion columns produced by annotators like the `AssertionDLModel` annotator.
- `resolutions`: The schema for resolutions. See `ResolutionSchema` for details.
- `relations`: Relation columns created by annotators such as the `RelationExtractionModel` annotator.
- `summaries`: Summary columns generated by annotators like the `MedicalSummarizer` annotator.
- `deidentifications`: The schema for deidentifications.
- `classifications`: The schema for classifications.
Parameters:

value (str) – The schema for converting the output of the pipeline into a structured JSON format.

setOutputAsStr(value)#

Sets whether to output the result as a string or as a structured json, by default True.

When set to True, the output column will be a string:

|-- column_name: string (nullable = true)

When set to False, the output column will be a struct with the following schema:

|-- column_name: struct (nullable = true)
      |-- document_identifier: string (nullable = true)
      |-- document_text: array (nullable = true)
      |    |-- element: string (containsNull = true)
      |-- entities: array (nullable = true)
      |    |-- element: map (containsNull = true)
      |        |-- key: string
      |        |-- value: string (valueContainsNull = true)
      |-- assertions: array (nullable = true)
      |    |-- element: map (containsNull = true)
      |        |-- key: string
      |        |-- value: string (valueContainsNull = true)
      |-- resolutions: array (nullable = true)
      |    |-- element: map (containsNull = true)
      |        |-- key: string
      |        |-- value: string (valueContainsNull = true)
      |-- relations: array (nullable = true)
      |    |-- element: map (containsNull = true)
      |        |-- key: string
      |        |-- value: string (valueContainsNull = true)
      |-- summaries: array (nullable = true)
      |    |-- element: string (containsNull = true)
      |-- deidentifications: array (nullable = true)
      |    |-- element: map (containsNull = true)
      |        |-- key: string
      |        |-- value: string (valueContainsNull = true)
      |-- classifications: array (nullable = true)
      |    |-- element: map (containsNull = true)
      |        |-- key: string
      |        |-- value: string (valueContainsNull = true)

Use this parameter to control the format of the output based on your specific requirements.

Parameters:

value (bool) – Whether to output the result as a string or as a structured json.

setOutputCol(value)#

Sets output column name.

Parameters:

value (str) – Name of the Output Column

setParamValue(paramName)#

Sets the value of a parameter.

Parameters:

paramName (str) – Name of the parameter

setParams()#
setReturnRelationEntities(value)#

Sets whether to return the entities in the relations or not, by default False.

Parameters:

value (bool) – Whether to return the entities in the relations or not

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.