spark-nlp 5.5.0rc1__py2.py3-none-any.whl → 5.5.2__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of spark-nlp might be problematic. Click here for more details.

@@ -0,0 +1,161 @@
1
+ # Copyright 2017-2024 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from sparknlp.common import *
16
+
17
+ class BertForMultipleChoice(AnnotatorModel,
18
+ HasCaseSensitiveProperties,
19
+ HasBatchedAnnotate,
20
+ HasEngine,
21
+ HasMaxSentenceLengthLimit):
22
+ """BertForMultipleChoice can load BERT Models with a multiple choice classification head on top
23
+ (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks.
24
+
25
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
26
+ object:
27
+
28
+ >>> spanClassifier = BertForMultipleChoice.pretrained() \\
29
+ ... .setInputCols(["document_question", "document_context"]) \\
30
+ ... .setOutputCol("answer")
31
+
32
+ The default model is ``"bert_base_uncased_multiple_choice"``, if no name is
33
+ provided.
34
+
35
+ For available pretrained models please see the `Models Hub
36
+ <https://sparknlp.org/models?task=Multiple+Choice>`__.
37
+
38
+ To see which models are compatible and how to import them see
39
+ `Import Transformers into Spark NLP 🚀
40
+ <https://github.com/JohnSnowLabs/spark-nlp/discussions/5669>`_.
41
+
42
+ ====================== ======================
43
+ Input Annotation types Output Annotation type
44
+ ====================== ======================
45
+ ``DOCUMENT, DOCUMENT`` ``CHUNK``
46
+ ====================== ======================
47
+
48
+ Parameters
49
+ ----------
50
+ batchSize
51
+ Batch size. Large values allows faster processing but requires more
52
+ memory, by default 8
53
+ caseSensitive
54
+ Whether to ignore case in tokens for embeddings matching, by default
55
+ False
56
+ maxSentenceLength
57
+ Max sentence length to process, by default 512
58
+
59
+ Examples
60
+ --------
61
+ >>> import sparknlp
62
+ >>> from sparknlp.base import *
63
+ >>> from sparknlp.annotator import *
64
+ >>> from pyspark.ml import Pipeline
65
+ >>> documentAssembler = MultiDocumentAssembler() \\
66
+ ... .setInputCols(["question", "context"]) \\
67
+ ... .setOutputCols(["document_question", "document_context"])
68
+ >>> questionAnswering = BertForMultipleChoice.pretrained() \\
69
+ ... .setInputCols(["document_question", "document_context"]) \\
70
+ ... .setOutputCol("answer") \\
71
+ ... .setCaseSensitive(False)
72
+ >>> pipeline = Pipeline().setStages([
73
+ ... documentAssembler,
74
+ ... questionAnswering
75
+ ... ])
76
+ >>> data = spark.createDataFrame([["The Eiffel Tower is located in which country??", "Germany, France, Italy"]]).toDF("question", "context")
77
+ >>> result = pipeline.fit(data).transform(data)
78
+ >>> result.select("answer.result").show(truncate=False)
79
+ +--------------------+
80
+ |result |
81
+ +--------------------+
82
+ |[France] |
83
+ +--------------------+
84
+ """
85
+ name = "BertForMultipleChoice"
86
+
87
+ inputAnnotatorTypes = [AnnotatorType.DOCUMENT, AnnotatorType.DOCUMENT]
88
+
89
+ outputAnnotatorType = AnnotatorType.CHUNK
90
+
91
+ choicesDelimiter = Param(Params._dummy(),
92
+ "choicesDelimiter",
93
+ "Delimiter character use to split the choices",
94
+ TypeConverters.toString)
95
+
96
+ def setChoicesDelimiter(self, value):
97
+ """Sets delimiter character use to split the choices
98
+
99
+ Parameters
100
+ ----------
101
+ value : string
102
+ Delimiter character use to split the choices
103
+ """
104
+ return self._set(caseSensitive=value)
105
+
106
+ @keyword_only
107
+ def __init__(self, classname="com.johnsnowlabs.nlp.annotators.classifier.dl.BertForMultipleChoice",
108
+ java_model=None):
109
+ super(BertForMultipleChoice, self).__init__(
110
+ classname=classname,
111
+ java_model=java_model
112
+ )
113
+ self._setDefault(
114
+ batchSize=4,
115
+ maxSentenceLength=512,
116
+ caseSensitive=False,
117
+ choicesDelimiter = ","
118
+ )
119
+
120
+ @staticmethod
121
+ def loadSavedModel(folder, spark_session):
122
+ """Loads a locally saved model.
123
+
124
+ Parameters
125
+ ----------
126
+ folder : str
127
+ Folder of the saved model
128
+ spark_session : pyspark.sql.SparkSession
129
+ The current SparkSession
130
+
131
+ Returns
132
+ -------
133
+ BertForQuestionAnswering
134
+ The restored model
135
+ """
136
+ from sparknlp.internal import _BertMultipleChoiceLoader
137
+ jModel = _BertMultipleChoiceLoader(folder, spark_session._jsparkSession)._java_obj
138
+ return BertForMultipleChoice(java_model=jModel)
139
+
140
+ @staticmethod
141
+ def pretrained(name="bert_base_uncased_multiple_choice", lang="en", remote_loc=None):
142
+ """Downloads and loads a pretrained model.
143
+
144
+ Parameters
145
+ ----------
146
+ name : str, optional
147
+ Name of the pretrained model, by default
148
+ "bert_base_uncased_multiple_choice"
149
+ lang : str, optional
150
+ Language of the pretrained model, by default "en"
151
+ remote_loc : str, optional
152
+ Optional remote address of the resource, by default None. Will use
153
+ Spark NLPs repositories otherwise.
154
+
155
+ Returns
156
+ -------
157
+ BertForQuestionAnswering
158
+ The restored model
159
+ """
160
+ from sparknlp.pretrained import ResourceDownloader
161
+ return ResourceDownloader.downloadModel(BertForMultipleChoice, name, lang, remote_loc)
@@ -16,3 +16,4 @@ from sparknlp.annotator.cv.swin_for_image_classification import *
16
16
  from sparknlp.annotator.cv.convnext_for_image_classification import *
17
17
  from sparknlp.annotator.cv.vision_encoder_decoder_for_image_captioning import *
18
18
  from sparknlp.annotator.cv.clip_for_zero_shot_classification import *
19
+ from sparknlp.annotator.cv.blip_for_question_answering import *
@@ -0,0 +1,172 @@
1
+ # Copyright 2017-2024 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from sparknlp.common import *
16
+
17
+ class BLIPForQuestionAnswering(AnnotatorModel,
18
+ HasBatchedAnnotateImage,
19
+ HasImageFeatureProperties,
20
+ HasEngine,
21
+ HasCandidateLabelsProperties,
22
+ HasRescaleFactor):
23
+ """BLIPForQuestionAnswering can load BLIP models for visual question answering.
24
+ The model consists of a vision encoder, a text encoder as well as a text decoder.
25
+ The vision encoder will encode the input image, the text encoder will encode the input question together
26
+ with the encoding of the image, and the text decoder will output the answer to the question.
27
+
28
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
29
+ object:
30
+
31
+ >>> visualQAClassifier = BLIPForQuestionAnswering.pretrained() \\
32
+ ... .setInputCols(["image_assembler"]) \\
33
+ ... .setOutputCol("answer")
34
+
35
+ The default model is ``"blip_vqa_base"``, if no name is
36
+ provided.
37
+
38
+ For available pretrained models please see the `Models Hub
39
+ <https://sparknlp.org/models?task=Question+Answering>`__.
40
+
41
+ To see which models are compatible and how to import them see
42
+ `Import Transformers into Spark NLP 🚀
43
+ <https://github.com/JohnSnowLabs/spark-nlp/discussions/5669>`_.
44
+
45
+ ====================== ======================
46
+ Input Annotation types Output Annotation type
47
+ ====================== ======================
48
+ ``IMAGE`` ``DOCUMENT``
49
+ ====================== ======================
50
+
51
+ Parameters
52
+ ----------
53
+ batchSize
54
+ Batch size. Large values allows faster processing but requires more
55
+ memory, by default 2
56
+ configProtoBytes
57
+ ConfigProto from tensorflow, serialized into byte array.
58
+ maxSentenceLength
59
+ Max sentence length to process, by default 50
60
+
61
+ Examples
62
+ --------
63
+ >>> import sparknlp
64
+ >>> from sparknlp.base import *
65
+ >>> from sparknlp.annotator import *
66
+ >>> from pyspark.ml import Pipeline
67
+ >>> image_df = SparkSessionForTest.spark.read.format("image").load(path=images_path)
68
+ >>> test_df = image_df.withColumn("text", lit("What's this picture about?"))
69
+ >>> imageAssembler = ImageAssembler() \\
70
+ ... .setInputCol("image") \\
71
+ ... .setOutputCol("image_assembler")
72
+ >>> visualQAClassifier = BLIPForQuestionAnswering.pretrained() \\
73
+ ... .setInputCols("image_assembler") \\
74
+ ... .setOutputCol("answer") \\
75
+ ... .setSize(384)
76
+ >>> pipeline = Pipeline().setStages([
77
+ ... imageAssembler,
78
+ ... visualQAClassifier
79
+ ... ])
80
+ >>> result = pipeline.fit(test_df).transform(test_df)
81
+ >>> result.select("image_assembler.origin", "answer.result").show(false)
82
+ +--------------------------------------+------+
83
+ |origin |result|
84
+ +--------------------------------------+------+
85
+ |[file:///content/images/cat_image.jpg]|[cats]|
86
+ +--------------------------------------+------+
87
+ """
88
+
89
+ name = "BLIPForQuestionAnswering"
90
+
91
+ inputAnnotatorTypes = [AnnotatorType.IMAGE]
92
+
93
+ outputAnnotatorType = AnnotatorType.DOCUMENT
94
+
95
+ configProtoBytes = Param(Params._dummy(),
96
+ "configProtoBytes",
97
+ "ConfigProto from tensorflow, serialized into byte array. Get with "
98
+ "config_proto.SerializeToString()",
99
+ TypeConverters.toListInt)
100
+
101
+ maxSentenceLength = Param(Params._dummy(),
102
+ "maxSentenceLength",
103
+ "Maximum sentence length that the annotator will process. Above this, the sentence is skipped",
104
+ typeConverter=TypeConverters.toInt)
105
+
106
+ def setMaxSentenceSize(self, value):
107
+ """Sets Maximum sentence length that the annotator will process, by
108
+ default 50.
109
+
110
+ Parameters
111
+ ----------
112
+ value : int
113
+ Maximum sentence length that the annotator will process
114
+ """
115
+ return self._set(maxSentenceLength=value)
116
+
117
+
118
+ @keyword_only
119
+ def __init__(self, classname="com.johnsnowlabs.nlp.annotators.cv.BLIPForQuestionAnswering",
120
+ java_model=None):
121
+ super(BLIPForQuestionAnswering, self).__init__(
122
+ classname=classname,
123
+ java_model=java_model
124
+ )
125
+ self._setDefault(
126
+ batchSize=2,
127
+ size=384,
128
+ maxSentenceLength=50
129
+ )
130
+
131
+ @staticmethod
132
+ def loadSavedModel(folder, spark_session):
133
+ """Loads a locally saved model.
134
+
135
+ Parameters
136
+ ----------
137
+ folder : str
138
+ Folder of the saved model
139
+ spark_session : pyspark.sql.SparkSession
140
+ The current SparkSession
141
+
142
+ Returns
143
+ -------
144
+ CLIPForZeroShotClassification
145
+ The restored model
146
+ """
147
+ from sparknlp.internal import _BLIPForQuestionAnswering
148
+ jModel = _BLIPForQuestionAnswering(folder, spark_session._jsparkSession)._java_obj
149
+ return BLIPForQuestionAnswering(java_model=jModel)
150
+
151
+ @staticmethod
152
+ def pretrained(name="blip_vqa_base", lang="en", remote_loc=None):
153
+ """Downloads and loads a pretrained model.
154
+
155
+ Parameters
156
+ ----------
157
+ name : str, optional
158
+ Name of the pretrained model, by default
159
+ "blip_vqa_tf"
160
+ lang : str, optional
161
+ Language of the pretrained model, by default "en"
162
+ remote_loc : str, optional
163
+ Optional remote address of the resource, by default None. Will use
164
+ Spark NLPs repositories otherwise.
165
+
166
+ Returns
167
+ -------
168
+ CLIPForZeroShotClassification
169
+ The restored model
170
+ """
171
+ from sparknlp.pretrained import ResourceDownloader
172
+ return ResourceDownloader.downloadModel(BLIPForQuestionAnswering, name, lang, remote_loc)
@@ -40,3 +40,4 @@ from sparknlp.annotator.embeddings.uae_embeddings import *
40
40
  from sparknlp.annotator.embeddings.mxbai_embeddings import *
41
41
  from sparknlp.annotator.embeddings.snowflake_embeddings import *
42
42
  from sparknlp.annotator.embeddings.nomic_embeddings import *
43
+ from sparknlp.annotator.embeddings.auto_gguf_embeddings import *