sparknlp_jsl.annotator.seq2seq.text2sql#

Module Contents#

Classes#

Text2SQL

MedicalTextGenerator is a GPT based model for text generation.

class Text2SQL(classname='com.johnsnowlabs.nlp.annotators.seq2seq.Text2SQL', java_model=None)#

Bases: sparknlp_jsl.annotator.seq2seq.medical_text_generator.MedicalTextGenerator

MedicalTextGenerator is a GPT based model for text generation.

Input Annotation types

Output Annotation type

DOCUMENT, DOCUMENT

CHUNK

Parameters:
  • maxNewTokens – Maximum number of of new tokens to generate, by default 30

  • maxContextLength – Maximum length of context text

  • configProtoBytes – ConfigProto from tensorflow, serialized into byte array.

  • doSample – Whether or not to use sampling; use greedy decoding otherwise, by default False

  • topK – The number of highest probability vocabulary tokens to consider, by default 1

  • noRepeatNgramSize – The number of tokens that can’t be repeated in the same order. Useful for preventing loops. The default is 0.

  • ignoreTokenIds – A list of token ids which are ignored in the decoder’s output, by default []

  • randomSeed (int) – Random seed. Set to positive integer to get reproducible results, by default None.

  • customPrompt – Custom prompt template. The only available variable is {DOCUMENT} and it is populated with the contents of the input document

Examples

>>> data = spark.createDataFrame([["Covid 18 is "]]).toDF("prompt")
>>> document_assembler = DocumentAssembler()    ...   .setInputCol("prompt")    ...   .setOutputCol("document_prompt")
...
>>> med_text_generator = sparknlp_jsl.annotators.qa.MedicalTextGenerator    ...   .pretrained()    ...   .setInputCols(["document_prompt"])    ...   .setMaxNewTokens(100)    ...   .setOutputCol("answer")    >>> pipeline = Pipeline(stages=[document_assembler, med_text_generator])
>>> pipeline    ...   .fit(data)    ...   .select("answer.result")    ...   .show(truncate=False)
+-------+
|result |
+-------+
|[Convid 19 is a pandemic that has affected millions of people worldwide.]  |
+-------+
batchSize#
configProtoBytes#
customPrompt#
doSample#
getter_attrs = []#
ignoreTokenIds#
inputAnnotatorTypes#
inputCols#
lazyAnnotator#
maxContextLength#
maxNewTokens#
maxTextLength#
mlFrameworkType#
modelType#
name = 'Text2SQL'#
noRepeatNgramSize#
optionalInputAnnotatorTypes = []#
outputAnnotatorType#
outputCol#
skipLPInputColsValidation = True#
stopAtEos#
tableLimit#
topK#
uid#
useCache#
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

getAdditionalTokens()#

Get additional tokens

Returns:

dict[int, str]

getBatchSize()#

Gets current batch size.

Returns:

Current batch size

Return type:

int

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

getPostProcessingSubstitutions()#

Get post processing substitution strings

getSchema()#

Get SQL schema

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).

static loadSavedModel(folder, spark_session, model_type)#

Loads a locally saved model.

Parameters:
  • folder (str) – Folder of the saved model

  • spark_session (pyspark.sql.SparkSession) – The current SparkSession

  • model_type (str) – The type of the model

Returns:

The restored model

Return type:

Text2SQL

static pretrained(name='text2sql_mimicsql', lang='en', remote_loc='clinical/models')#

Downloads and loads a pretrained model.

Parameters:
  • name (str, optional) – Name of the pretrained model, by default “text2sql_mimicsql”

  • lang (str, optional) – Language of the pretrained model, by default “en”

  • remote_loc (str, optional) – Optional remote address of the resource, by default None. Will use Spark NLPs repositories otherwise.

Returns:

The restored model

Return type:

MedicalSummarizer

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.

setAdditionalTokens(additionalTokens)#

Set additional tokens

Parameters:

value (dict[int, str]) – additional tokens

setBatchSize(v)#

Sets batch size.

Parameters:

v (int) – Batch size

setConfigProtoBytes(b)#

Sets configProto from tensorflow, serialized into byte array.

Parameters:

b (List[int]) – ConfigProto from tensorflow, serialized into byte array

setCustomPrompt(value)#

Sets the custom prompt template. The only available variable is {DOCUMENT}, which is populated with the contents of the input document

Parameters:

value (str) – prompt template

setDoSample(value)#

Sets whether or not to use sampling, use greedy decoding otherwise.

Parameters:

value (bool) – Whether or not to use sampling; use greedy decoding otherwise

setForceInputTypeValidation(etfm)#
setIgnoreTokenIds(value)#

A list of token ids which are ignored in the decoder’s output.

Parameters:

value (List[int]) – The words to be filtered out

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

setMaxContextLength(value)#

Sets maximum length of output text.

Parameters:

value (int) – Maximum length of output text

setMaxNewTokens(value)#

Sets the maximum number of new tokens to be generated

Parameters:

value (int) – the maximum number of new tokens to be generated

setMaxTextLength(value)#

Set max text length to process

Parameters:

value (int) – max text length

setNoRepeatNgramSize(value)#

Sets size of n-grams that can only occur once.

If set to int > 0, all ngrams of that size can only occur once.

Parameters:

value (int) – N-gram size can only occur once

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()#
setPostProcessingSubstitutions(substitutions)#

Set post processing substitution strings

Parameters:

substitutions (dict[str, str]) – substitution strings

setRandomSeed(seed)#

Sets random seed.

Parameters:

seed (int) – Random seed

setSchema(schema)#

Set SQL schema

Parameters:

schema (dict[str, list[str]]) – SQL schema, a dictionary mapping table names to list of columns, e.g {“users”: [“id”, “name”, “age”]}

setStopAtEos(b)#

Stop text generation when the end-of-sentence token is encountered.

Parameters:

b (bool) – whether to stop at end-of-sentence token or not

setTableLimit(value)#

Sets the maximum number of tables allowed for this model

Parameters:

value (int) –

setTopK(value)#

Sets the number of highest probability vocabulary tokens to consider

Parameters:

value (int) – Number of highest probability vocabulary tokens to consider

setUseCache(value)#

Cache internal state of the model to improve performance

Parameters:

value (bool) – Whether or not to use cache

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.