spark-nlp 5.0.2__py2.py3-none-any.whl → 5.1.1__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,250 @@
1
+ # Copyright 2017-2022 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
+ """Contains classes concerning WhisperForCTC."""
16
+
17
+ from sparknlp.common import *
18
+
19
+
20
+ class WhisperForCTC(AnnotatorModel,
21
+ HasBatchedAnnotateAudio,
22
+ HasAudioFeatureProperties,
23
+ HasEngine, HasGeneratorProperties):
24
+ """Whisper Model with a language modeling head on top for Connectionist Temporal Classification
25
+ (CTC).
26
+
27
+ Whisper is an automatic speech recognition (ASR) system trained on 680,000 hours of
28
+ multilingual and multitask supervised data collected from the web. It transcribe in multiple
29
+ languages, as well as translate from those languages into English.
30
+
31
+ The audio needs to be provided pre-processed an array of floats.
32
+
33
+ Note that at the moment, this annotator only supports greedy search.
34
+
35
+ For multilingual models, the language and the task (transcribe or translate) can be set with
36
+ ``setLanguage`` and ``setTask``.
37
+
38
+ Pretrained models can be loaded with ``pretrained`` of the companion object:
39
+
40
+ .. code-block:: python
41
+
42
+ speechToText = WhisperForCTC.pretrained() \\
43
+ .setInputCols(["audio_assembler"]) \\
44
+ .setOutputCol("text")
45
+
46
+
47
+ The default model is ``"asr_whisper_tiny_opt"``, if no name is provided.
48
+
49
+ For available pretrained models please see the `Models Hub <https://sparknlp.org/models>`__.
50
+
51
+ To see which models are compatible and how to import them see
52
+ https://github.com/JohnSnowLabs/spark-nlp/discussions/5669 and to see more extended
53
+ examples, see
54
+ `WhisperForCTCTestSpec <https://github.com/JohnSnowLabs/spark-nlp/blob/master/src/test/scala/com/johnsnowlabs/nlp/annotators/audio/WhisperForCTCTest.scala>`__.
55
+
56
+ **References:**
57
+
58
+ `Robust Speech Recognition via Large-Scale Weak Supervision <https://arxiv.org/abs/2212.04356>`__
59
+
60
+ **Paper Abstract:**
61
+
62
+ *We study the capabilities of speech processing systems trained simply to predict large
63
+ amounts of transcripts of audio on the internet. When scaled to 680,000 hours of multilingual
64
+ and multitask supervision, the resulting models generalize well to standard benchmarks and are
65
+ often competitive with prior fully supervised results but in a zero- shot transfer setting
66
+ without the need for any fine- tuning. When compared to humans, the models approach their
67
+ accuracy and robustness. We are releasing models and inference code to serve as a foundation
68
+ for further work on robust speech processing.*
69
+
70
+ ====================== ======================
71
+ Input Annotation types Output Annotation type
72
+ ====================== ======================
73
+ ``AUDIO`` ``DOCUMENT``
74
+ ====================== ======================
75
+
76
+ Parameters
77
+ ----------
78
+ task
79
+ The formatted task for the audio. Either `<|translate|>` or `<|transcribe|>`.
80
+ language
81
+ The language for the audio, formatted to e.g. `<|en|>`. Check the model description for
82
+ supported languages.
83
+ isMultilingual
84
+ Whether the model is multilingual
85
+ minOutputLength
86
+ Minimum length of the sequence to be generated
87
+ maxOutputLength
88
+ Maximum length of output text
89
+ doSample
90
+ Whether or not to use sampling; use greedy decoding otherwise
91
+ temperature
92
+ The value used to module the next token probabilities
93
+ topK
94
+ The number of highest probability vocabulary tokens to keep for top-k-filtering
95
+ topP
96
+ If set to float < 1, only the most probable tokens with probabilities that add up to ``top_p`` or higher are
97
+ kept for generation
98
+ repetitionPenalty
99
+ The parameter for repetition penalty. 1.0 means no penalty.
100
+ See `this paper <https://arxiv.org/pdf/1909.05858.pdf>`__ for more details
101
+ noRepeatNgramSize
102
+ If set to int > 0, all ngrams of that size can only occur once
103
+ beamSize
104
+ The Number of beams for beam search
105
+
106
+ Examples
107
+ --------
108
+ >>> import sparknlp
109
+ >>> from sparknlp.base import *
110
+ >>> from sparknlp.annotator import *
111
+ >>> from pyspark.ml import Pipeline
112
+ >>> audioAssembler = AudioAssembler() \\
113
+ ... .setInputCol("audio_content") \\
114
+ ... .setOutputCol("audio_assembler")
115
+ >>> speechToText = WhisperForCTC.pretrained() \\
116
+ ... .setInputCols(["audio_assembler"]) \\
117
+ ... .setOutputCol("text")
118
+ >>> pipeline = Pipeline().setStages([audioAssembler, speechToText])
119
+ >>> processedAudioFloats = spark.createDataFrame([[rawFloats]]).toDF("audio_content")
120
+ >>> result = pipeline.fit(processedAudioFloats).transform(processedAudioFloats)
121
+ >>> result.select("text.result").show(truncate = False)
122
+ +------------------------------------------------------------------------------------------+
123
+ |result |
124
+ +------------------------------------------------------------------------------------------+
125
+ |[ Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.]|
126
+ +------------------------------------------------------------------------------------------+
127
+ """
128
+ name = "WhisperForCTC"
129
+
130
+ inputAnnotatorTypes = [AnnotatorType.AUDIO]
131
+
132
+ outputAnnotatorType = AnnotatorType.DOCUMENT
133
+
134
+ configProtoBytes = Param(Params._dummy(),
135
+ "configProtoBytes",
136
+ "ConfigProto from tensorflow, serialized into byte array. Get with "
137
+ "config_proto.SerializeToString()",
138
+ TypeConverters.toListInt)
139
+
140
+ language = Param(Params._dummy(), "language", "Optional parameter to set the language for the transcription.",
141
+ typeConverter=TypeConverters.toString)
142
+
143
+ isMultilingual = Param(Params._dummy(), "isMultilingual", "Whether the model is multilingual.",
144
+ typeConverter=TypeConverters.toBoolean)
145
+
146
+ def setConfigProtoBytes(self, b):
147
+ """Sets configProto from tensorflow, serialized into byte array.
148
+
149
+ Parameters
150
+ ----------
151
+ b : List[int]
152
+ ConfigProto from tensorflow, serialized into byte array
153
+ """
154
+ return self._set(configProtoBytes=b)
155
+
156
+ def getLanguage(self):
157
+ """Gets the langauge for the transcription."""
158
+ return self.getOrDefault(self.language)
159
+
160
+ def getIsMultilingual(self):
161
+ """Gets whether the model is multilingual."""
162
+ return self.getOrDefault(self.isMultilingual)
163
+
164
+ def setLanguage(self, value):
165
+ """Sets the language for the audio, formatted to e.g. `<|en|>`. Check the model description for
166
+ supported languages.
167
+
168
+ Parameters
169
+ ----------
170
+ value : String
171
+ Formatted language code
172
+ """
173
+ return self._call_java("setLanguage", value)
174
+
175
+ def setTask(self, value):
176
+ """Sets the formatted task for the audio. Either `<|translate|>` or `<|transcribe|>`.
177
+
178
+ Only multilingual models can do translation.
179
+
180
+ Parameters
181
+ ----------
182
+ value : String
183
+ Formatted task
184
+ """
185
+ return self._call_java("setTask", value)
186
+
187
+ @keyword_only
188
+ def __init__(self, classname="com.johnsnowlabs.nlp.annotators.audio.WhisperForCTC",
189
+ java_model=None):
190
+ super(WhisperForCTC, self).__init__(
191
+ classname=classname,
192
+ java_model=java_model
193
+ )
194
+ self._setDefault(
195
+ minOutputLength=0,
196
+ maxOutputLength=448,
197
+ doSample=False,
198
+ temperature=1.0,
199
+ topK=1,
200
+ topP=1.0,
201
+ repetitionPenalty=1.0,
202
+ noRepeatNgramSize=0,
203
+ batchSize=2,
204
+ beamSize=1,
205
+ nReturnSequences=1,
206
+ isMultilingual=True,
207
+ )
208
+
209
+ @staticmethod
210
+ def loadSavedModel(folder, spark_session):
211
+ """Loads a locally saved model.
212
+
213
+ Parameters
214
+ ----------
215
+ folder : str
216
+ Folder of the saved model
217
+ spark_session : pyspark.sql.SparkSession
218
+ The current SparkSession
219
+
220
+ Returns
221
+ -------
222
+ WhisperForCTC
223
+ The restored model
224
+ """
225
+ from sparknlp.internal import _WhisperForCTC
226
+ jModel = _WhisperForCTC(folder, spark_session._jsparkSession)._java_obj
227
+ return WhisperForCTC(java_model=jModel)
228
+
229
+ @staticmethod
230
+ def pretrained(name="asr_whisper_tiny_opt", lang="xx", remote_loc=None):
231
+ """Downloads and loads a pretrained model.
232
+
233
+ Parameters
234
+ ----------
235
+ name : str, optional
236
+ Name of the pretrained model, by default
237
+ "asr_hubert_large_ls960"
238
+ lang : str, optional
239
+ Language of the pretrained model, by default "en"
240
+ remote_loc : str, optional
241
+ Optional remote address of the resource, by default None. Will use
242
+ Spark NLPs repositories otherwise.
243
+
244
+ Returns
245
+ -------
246
+ WhisperForCTC
247
+ The restored model
248
+ """
249
+ from sparknlp.pretrained import ResourceDownloader
250
+ return ResourceDownloader.downloadModel(WhisperForCTC, name, lang, remote_loc)
@@ -45,5 +45,6 @@ from sparknlp.annotator.classifier_dl.camembert_for_sequence_classification impo
45
45
  from sparknlp.annotator.classifier_dl.camembert_for_question_answering import *
46
46
  from sparknlp.annotator.classifier_dl.bert_for_zero_shot_classification import *
47
47
  from sparknlp.annotator.classifier_dl.distil_bert_for_zero_shot_classification import *
48
- from sparknlp.annotator.classifier_dl.roberta_bert_for_zero_shot_classification import *
49
- from sparknlp.annotator.classifier_dl.xlm_roberta_for_zero_shot_classification import *
48
+ from sparknlp.annotator.classifier_dl.roberta_for_zero_shot_classification import *
49
+ from sparknlp.annotator.classifier_dl.xlm_roberta_for_zero_shot_classification import *
50
+ from sparknlp.annotator.classifier_dl.bart_for_zero_shot_classification import *
@@ -0,0 +1,225 @@
1
+ # Copyright 2017-2023 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
+ """Contains classes for BartForZeroShotClassification."""
15
+
16
+ from sparknlp.common import *
17
+
18
+
19
+ class BartForZeroShotClassification(AnnotatorModel,
20
+ HasCaseSensitiveProperties,
21
+ HasBatchedAnnotate,
22
+ HasClassifierActivationProperties,
23
+ HasCandidateLabelsProperties,
24
+ HasEngine):
25
+ """BartForZeroShotClassification using a `ModelForSequenceClassification` trained on NLI (natural language
26
+ inference) tasks. Equivalent of `BartForSequenceClassification` models, but these models don't require a hardcoded
27
+ number of potential classes, they can be chosen at runtime. It usually means it's slower but it is much more
28
+ flexible.
29
+
30
+ Note that the model will loop through all provided labels. So the more labels you have, the
31
+ longer this process will take.
32
+
33
+ Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis
34
+ pair and passed to the pretrained model.
35
+
36
+ Pretrained models can be loaded with :meth:`.pretrained` of the companion
37
+ object:
38
+
39
+ >>> sequenceClassifier = BartForZeroShotClassification.pretrained() \\
40
+ ... .setInputCols(["token", "document"]) \\
41
+ ... .setOutputCol("label")
42
+
43
+ The default model is ``"bart_large_zero_shot_classifier_mnli"``, if no name is
44
+ provided.
45
+
46
+ For available pretrained models please see the `Models Hub
47
+ <https://sparknlp.orgtask=Text+Classification>`__.
48
+
49
+ To see which models are compatible and how to import them see
50
+ `Import Transformers into Spark NLP 🚀
51
+ <https://github.com/JohnSnowLabs/spark-nlp/discussions/5669>`_.
52
+
53
+ ====================== ======================
54
+ Input Annotation types Output Annotation type
55
+ ====================== ======================
56
+ ``DOCUMENT, TOKEN`` ``CATEGORY``
57
+ ====================== ======================
58
+
59
+ Parameters
60
+ ----------
61
+ batchSize
62
+ Batch size. Large values allows faster processing but requires more
63
+ memory, by default 8
64
+ caseSensitive
65
+ Whether to ignore case in tokens for embeddings matching, by default
66
+ True
67
+ configProtoBytes
68
+ ConfigProto from tensorflow, serialized into byte array.
69
+ maxSentenceLength
70
+ Max sentence length to process, by default 128
71
+ coalesceSentences
72
+ Instead of 1 class per sentence (if inputCols is `sentence`) output 1
73
+ class per document by averaging probabilities in all sentences, by
74
+ default False
75
+ activation
76
+ Whether to calculate logits via Softmax or Sigmoid, by default
77
+ `"softmax"`.
78
+
79
+ Examples
80
+ --------
81
+ >>> import sparknlp
82
+ >>> from sparknlp.base import *
83
+ >>> from sparknlp.annotator import *
84
+ >>> from pyspark.ml import Pipeline
85
+ >>> documentAssembler = DocumentAssembler() \\
86
+ ... .setInputCol("text") \\
87
+ ... .setOutputCol("document")
88
+ >>> tokenizer = Tokenizer() \\
89
+ ... .setInputCols(["document"]) \\
90
+ ... .setOutputCol("token")
91
+ >>> sequenceClassifier = BartForZeroShotClassification.pretrained() \\
92
+ ... .setInputCols(["token", "document"]) \\
93
+ ... .setOutputCol("label") \\
94
+ ... .setCaseSensitive(True)
95
+ >>> pipeline = Pipeline().setStages([
96
+ ... documentAssembler,
97
+ ... tokenizer,
98
+ ... sequenceClassifier
99
+ ... ])
100
+ >>> data = spark.createDataFrame([["I loved this movie when I was a child.", "It was pretty boring."]]).toDF("text")
101
+ >>> result = pipeline.fit(data).transform(data)
102
+ >>> result.select("label.result").show(truncate=False)
103
+ +------+
104
+ |result|
105
+ +------+
106
+ |[pos] |
107
+ |[neg] |
108
+ +------+
109
+ """
110
+ name = "BartForZeroShotClassification"
111
+
112
+ inputAnnotatorTypes = [AnnotatorType.DOCUMENT, AnnotatorType.TOKEN]
113
+
114
+ outputAnnotatorType = AnnotatorType.CATEGORY
115
+
116
+ maxSentenceLength = Param(Params._dummy(),
117
+ "maxSentenceLength",
118
+ "Max sentence length to process",
119
+ typeConverter=TypeConverters.toInt)
120
+
121
+ configProtoBytes = Param(Params._dummy(),
122
+ "configProtoBytes",
123
+ "ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()",
124
+ TypeConverters.toListInt)
125
+
126
+ coalesceSentences = Param(Params._dummy(), "coalesceSentences",
127
+ "Instead of 1 class per sentence (if inputCols is '''sentence''') output 1 class per document by averaging probabilities in all sentences.",
128
+ TypeConverters.toBoolean)
129
+
130
+ def getClasses(self):
131
+ """
132
+ Returns labels used to train this model
133
+ """
134
+ return self._call_java("getClasses")
135
+
136
+ def setConfigProtoBytes(self, b):
137
+ """Sets configProto from tensorflow, serialized into byte array.
138
+
139
+ Parameters
140
+ ----------
141
+ b : List[int]
142
+ ConfigProto from tensorflow, serialized into byte array
143
+ """
144
+ return self._set(configProtoBytes=b)
145
+
146
+ def setMaxSentenceLength(self, value):
147
+ """Sets max sentence length to process, by default 128.
148
+
149
+ Parameters
150
+ ----------
151
+ value : int
152
+ Max sentence length to process
153
+ """
154
+ return self._set(maxSentenceLength=value)
155
+
156
+ def setCoalesceSentences(self, value):
157
+ """Instead of 1 class per sentence (if inputCols is '''sentence''') output 1 class per document by averaging
158
+ probabilities in all sentences. Due to max sequence length limit in almost all transformer models such as Bart
159
+ (512 tokens), this parameter helps to feed all the sentences into the model and averaging all the probabilities
160
+ for the entire document instead of probabilities per sentence. (Default: true)
161
+
162
+ Parameters
163
+ ----------
164
+ value : bool
165
+ If the output of all sentences will be averaged to one output
166
+ """
167
+ return self._set(coalesceSentences=value)
168
+
169
+ @keyword_only
170
+ def __init__(self, classname="com.johnsnowlabs.nlp.annotators.classifier.dl.BartForZeroShotClassification",
171
+ java_model=None):
172
+ super(BartForZeroShotClassification, self).__init__(
173
+ classname=classname,
174
+ java_model=java_model
175
+ )
176
+ self._setDefault(
177
+ batchSize=8,
178
+ maxSentenceLength=128,
179
+ caseSensitive=True,
180
+ coalesceSentences=False,
181
+ activation="softmax"
182
+ )
183
+
184
+ @staticmethod
185
+ def loadSavedModel(folder, spark_session):
186
+ """Loads a locally saved model.
187
+
188
+ Parameters
189
+ ----------
190
+ folder : str
191
+ Folder of the saved model
192
+ spark_session : pyspark.sql.SparkSession
193
+ The current SparkSession
194
+
195
+ Returns
196
+ -------
197
+ BartForZeroShotClassification
198
+ The restored model
199
+ """
200
+ from sparknlp.internal import _BartForZeroShotClassification
201
+ jModel = _BartForZeroShotClassification(folder, spark_session._jsparkSession)._java_obj
202
+ return BartForZeroShotClassification(java_model=jModel)
203
+
204
+ @staticmethod
205
+ def pretrained(name="bart_large_zero_shot_classifier_mnli", lang="en", remote_loc=None):
206
+ """Downloads and loads a pretrained model.
207
+
208
+ Parameters
209
+ ----------
210
+ name : str, optional
211
+ Name of the pretrained model, by default
212
+ "bart_large_zero_shot_classifier_mnli"
213
+ lang : str, optional
214
+ Language of the pretrained model, by default "en"
215
+ remote_loc : str, optional
216
+ Optional remote address of the resource, by default None. Will use
217
+ Spark NLPs repositories otherwise.
218
+
219
+ Returns
220
+ -------
221
+ BartForZeroShotClassification
222
+ The restored model
223
+ """
224
+ from sparknlp.pretrained import ResourceDownloader
225
+ return ResourceDownloader.downloadModel(BartForZeroShotClassification, name, lang, remote_loc)