• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JohnSnowLabs / spark-nlp / 4413868535

pending completion
4413868535

push

github

GitHub
SPARKNLP-746: Handle empty validation sets (#13615)

8597 of 12936 relevant lines covered (66.46%)

0.66 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/main/scala/com/johnsnowlabs/nlp/annotators/audio/Wav2Vec2ForCTC.scala
1
/*
2
 * Copyright 2017-2022 John Snow Labs
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *    http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package com.johnsnowlabs.nlp.annotators.audio
18

19
import com.johnsnowlabs.ml.ai.Wav2Vec2
20
import com.johnsnowlabs.ml.tensorflow.{
21
  ReadTensorflowModel,
22
  TensorflowWrapper,
23
  WriteTensorflowModel
24
}
25
import com.johnsnowlabs.ml.util.LoadExternalModel.{
26
  loadJsonStringAsset,
27
  modelSanityCheck,
28
  notSupportedEngineError
29
}
30
import com.johnsnowlabs.ml.util.ModelEngine
31
import com.johnsnowlabs.nlp.AnnotatorType.{AUDIO, DOCUMENT}
32
import com.johnsnowlabs.nlp._
33
import com.johnsnowlabs.nlp.annotators.audio.feature_extractor.Preprocessor
34
import com.johnsnowlabs.nlp.serialization.MapFeature
35
import org.apache.spark.broadcast.Broadcast
36
import org.apache.spark.ml.param.IntArrayParam
37
import org.apache.spark.ml.util.Identifiable
38
import org.apache.spark.sql.SparkSession
39
import org.json4s._
40
import org.json4s.jackson.JsonMethods._
41

42
/** Wav2Vec2 Model with a language modeling head on top for Connectionist Temporal Classification
43
  * (CTC). Wav2Vec2 was proposed in wav2vec 2.0: A Framework for Self-Supervised Learning of
44
  * Speech Representations by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
45
  *
46
  * The annotator takes audio files and transcribes it as text. The audio needs to be provided
47
  * pre-processed an array of floats.
48
  *
49
  * Note that this annotator is currently not supported on Apple Silicon processors such as the
50
  * M1/M2 (Apple Silicon). This is due to the processor not supporting instructions for XLA.
51
  *
52
  * Pretrained models can be loaded with `pretrained` of the companion object:
53
  * {{{
54
  * val speechToText = Wav2Vec2ForCTC.pretrained()
55
  *   .setInputCols("audio_assembler")
56
  *   .setOutputCol("text")
57
  * }}}
58
  * The default model is `"asr_wav2vec2_base_960h"`, if no name is provided.
59
  *
60
  * For available pretrained models please see the
61
  * [[https://nlp.johnsnowlabs.com/models Models Hub]].
62
  *
63
  * To see which models are compatible and how to import them see
64
  * [[https://github.com/JohnSnowLabs/spark-nlp/discussions/5669]] and to see more extended
65
  * examples, see
66
  * [[https://github.com/JohnSnowLabs/spark-nlp/blob/master/src/test/scala/com/johnsnowlabs/nlp/annotators/audio/Wav2Vec2ForCTCTestSpec.scala Wav2Vec2ForCTCTestSpec]].
67
  *
68
  * ==Example==
69
  * {{{
70
  * import spark.implicits._
71
  * import com.johnsnowlabs.nlp.base._
72
  * import com.johnsnowlabs.nlp.annotators._
73
  * import com.johnsnowlabs.nlp.annotators.audio.Wav2Vec2ForCTC
74
  * import org.apache.spark.ml.Pipeline
75
  *
76
  * val audioAssembler: AudioAssembler = new AudioAssembler()
77
  *   .setInputCol("audio_content")
78
  *   .setOutputCol("audio_assembler")
79
  *
80
  * val speechToText: Wav2Vec2ForCTC = Wav2Vec2ForCTC
81
  *   .pretrained()
82
  *   .setInputCols("audio_assembler")
83
  *   .setOutputCol("text")
84
  *
85
  * val pipeline: Pipeline = new Pipeline().setStages(Array(audioAssembler, speechToText))
86
  *
87
  * val bufferedSource =
88
  *   scala.io.Source.fromFile("src/test/resources/audio/csv/audio_floats.csv")
89
  *
90
  * val rawFloats = bufferedSource
91
  *   .getLines()
92
  *   .map(_.split(",").head.trim.toFloat)
93
  *   .toArray
94
  * bufferedSource.close
95
  *
96
  * val processedAudioFloats = Seq(rawFloats).toDF("audio_content")
97
  *
98
  * val result = pipeline.fit(processedAudioFloats).transform(processedAudioFloats)
99
  * result.select("text.result").show(truncate = false)
100
  * +------------------------------------------------------------------------------------------+
101
  * |result                                                                                    |
102
  * +------------------------------------------------------------------------------------------+
103
  * |[MISTER QUILTER IS THE APOSTLE OF THE MIDLE CLASES AND WE ARE GLAD TO WELCOME HIS GOSPEL ]|
104
  * +------------------------------------------------------------------------------------------+
105
  * }}}
106
  * @param uid
107
  *   required uid for storing annotator to disk
108
  * @groupname anno Annotator types
109
  * @groupdesc anno
110
  *   Required input and expected output annotator types
111
  * @groupname Ungrouped Members
112
  * @groupname param Parameters
113
  * @groupname setParam Parameter setters
114
  * @groupname getParam Parameter getters
115
  * @groupname Ungrouped Members
116
  * @groupprio param  1
117
  * @groupprio anno  2
118
  * @groupprio Ungrouped 3
119
  * @groupprio setParam  4
120
  * @groupprio getParam  5
121
  * @groupdesc param
122
  *   A list of (hyper-)parameter keys this annotator can take. Users can set and get the
123
  *   parameter values through setters and getters, respectively.
124
  */
125
class Wav2Vec2ForCTC(override val uid: String)
126
    extends AnnotatorModel[Wav2Vec2ForCTC]
127
    with HasBatchedAnnotateAudio[Wav2Vec2ForCTC]
128
    with HasAudioFeatureProperties
129
    with WriteTensorflowModel
130
    with HasEngine {
131

132
  /** Annotator reference id. Used to identify elements in metadata or to refer to this annotator
133
    * type
134
    */
135
  def this() = this(Identifiable.randomUID("Wav2Vec2ForCTC"))
×
136

137
  /** Output annotator type : DOCUMENT
138
    *
139
    * @group anno
140
    */
141
  override val outputAnnotatorType: AnnotatorType = DOCUMENT
×
142

143
  /** Input annotator type : AUDIO
144
    *
145
    * @group anno
146
    */
147
  override val inputAnnotatorTypes: Array[AnnotatorType] = Array(AUDIO)
×
148

149
  /** ConfigProto from tensorflow, serialized into byte array. Get with
150
    * config_proto.SerializeToString()
151
    *
152
    * @group param
153
    */
154
  val configProtoBytes = new IntArrayParam(
×
155
    this,
156
    "configProtoBytes",
×
157
    "ConfigProto from tensorflow, serialized into byte array. Get with config_proto.SerializeToString()")
×
158

159
  /** ConfigProto from tensorflow, serialized into byte array. Get with
160
    * config_proto.SerializeToString()
161
    *
162
    * @group setParam
163
    */
164
  def setConfigProtoBytes(bytes: Array[Int]): Wav2Vec2ForCTC.this.type =
165
    set(this.configProtoBytes, bytes)
×
166

167
  /** ConfigProto from tensorflow, serialized into byte array. Get with
168
    * config_proto.SerializeToString()
169
    *
170
    * @group getParam
171
    */
172
  def getConfigProtoBytes: Option[Array[Byte]] =
173
    get(this.configProtoBytes).map(_.map(_.toByte))
×
174

175
  /** Vocabulary used to encode the words to ids
176
    *
177
    * @group param
178
    */
179
  val vocabulary: MapFeature[String, BigInt] = new MapFeature(this, "vocabulary")
×
180

181
  /** @group setParam */
182
  def setVocabulary(value: Map[String, BigInt]): this.type = set(vocabulary, value)
×
183

184
  /** It contains TF model signatures for the laded saved model
185
    *
186
    * @group param
187
    */
188
  val signatures = new MapFeature[String, String](model = this, name = "signatures")
×
189

190
  /** @group setParam */
191
  def setSignatures(value: Map[String, String]): this.type = {
192
    if (get(signatures).isEmpty)
×
193
      set(signatures, value)
×
194
    this
195
  }
196

197
  /** @group getParam */
198
  def getSignatures: Option[Map[String, String]] = get(this.signatures)
×
199

200
  private var _model: Option[Broadcast[Wav2Vec2]] = None
×
201

202
  /** @group getParam */
203
  def getModelIfNotSet: Wav2Vec2 = _model.get.value
×
204

205
  /** @group setParam */
206
  def setModelIfNotSet(spark: SparkSession, tensorflow: TensorflowWrapper): this.type = {
207
    if (_model.isEmpty) {
×
208

209
      _model = Some(
×
210
        spark.sparkContext.broadcast(
×
211
          new Wav2Vec2(
×
212
            tensorflow,
213
            configProtoBytes = getConfigProtoBytes,
×
214
            vocabs = $$(vocabulary),
×
215
            signatures = getSignatures)))
×
216
    }
217
    this
218
  }
219

220
  setDefault(batchSize -> 4)
×
221

222
  /** Takes a document and annotations and produces new annotations of this annotator's annotation
223
    * type
224
    *
225
    * @param batchedAnnotations
226
    *   Annotations that correspond to inputAnnotationCols generated by previous annotators if any
227
    * @return
228
    *   any number of annotations processed for every input annotation. Not necessary one to one
229
    *   relationship
230
    */
231
  override def batchAnnotate(
232
      batchedAnnotations: Seq[Array[AnnotationAudio]]): Seq[Seq[Annotation]] = {
233

234
    // Zip annotations to the row it belongs to
235
    val audiosWithRow = batchedAnnotations.zipWithIndex
×
236
      .flatMap { case (annotations, i) => annotations.map(x => (x, i)) }
×
237

238
    val noneEmptyAudios = audiosWithRow.map(_._1).filter(_.result.nonEmpty).toArray
×
239

240
    val allAnnotations =
241
      if (noneEmptyAudios.nonEmpty) {
×
242
        getModelIfNotSet.predict(
×
243
          audios = noneEmptyAudios,
244
          batchSize = $(batchSize),
×
245
          preprocessor = Preprocessor(
×
246
            do_normalize = getDoNormalize,
×
247
            return_attention_mask = getReturnAttentionMask,
×
248
            padding_side = getPaddingSide,
×
249
            padding_value = getPaddingValue,
×
250
            feature_size = getFeatureSize,
×
251
            sampling_rate = getSamplingRate))
×
252
      } else {
253
        Seq.empty[Annotation]
×
254
      }
255

256
    // Group resulting annotations by rows. If there are not sentences in a given row, return empty sequence
257
    batchedAnnotations.indices.map(rowIndex => {
×
258
      val rowAnnotations = allAnnotations
259
        // zip each annotation with its corresponding row index
260
        .zip(audiosWithRow)
×
261
        // select the sentences belonging to the current row
262
        .filter(_._2._2 == rowIndex)
×
263
        // leave the annotation only
264
        .map(_._1)
×
265

266
      if (rowAnnotations.nonEmpty)
×
267
        rowAnnotations
×
268
      else
269
        Seq.empty[Annotation]
×
270
    })
271

272
  }
273

274
  override def onWrite(path: String, spark: SparkSession): Unit = {
275
    super.onWrite(path, spark)
×
276
    writeTensorflowModelV2(
×
277
      path,
278
      spark,
279
      getModelIfNotSet.tensorflowWrapper,
×
280
      "_wav_ctc",
×
281
      Wav2Vec2ForCTC.tfFile,
×
282
      configProtoBytes = getConfigProtoBytes)
×
283
  }
284

285
}
286

287
trait ReadablePretrainedWav2Vec2ForAudioModel
288
    extends ParamsAndFeaturesReadable[Wav2Vec2ForCTC]
289
    with HasPretrained[Wav2Vec2ForCTC] {
290
  override val defaultModelName: Some[String] = Some("asr_wav2vec2_base_960h")
×
291

292
  /** Java compliant-overrides */
293
  override def pretrained(): Wav2Vec2ForCTC = super.pretrained()
×
294

295
  override def pretrained(name: String): Wav2Vec2ForCTC = super.pretrained(name)
×
296

297
  override def pretrained(name: String, lang: String): Wav2Vec2ForCTC =
298
    super.pretrained(name, lang)
×
299

300
  override def pretrained(name: String, lang: String, remoteLoc: String): Wav2Vec2ForCTC =
301
    super.pretrained(name, lang, remoteLoc)
×
302
}
303

304
trait ReadWav2Vec2ForAudioDLModel extends ReadTensorflowModel {
305
  this: ParamsAndFeaturesReadable[Wav2Vec2ForCTC] =>
306

307
  override val tfFile: String = "wav_ctc_tensorflow"
×
308

309
  def readModel(instance: Wav2Vec2ForCTC, path: String, spark: SparkSession): Unit = {
310

311
    val tf = readTensorflowModel(path, spark, "_wav_ctc_tf", initAllTables = false)
×
312
    instance.setModelIfNotSet(spark, tf)
×
313
  }
314

315
  addReader(readModel)
×
316

317
  def loadSavedModel(modelPath: String, spark: SparkSession): Wav2Vec2ForCTC = {
318

319
    val (localModelPath, detectedEngine) = modelSanityCheck(modelPath)
×
320

321
    val vocabJsonContent = loadJsonStringAsset(localModelPath, "vocab.json")
×
322
    val vocabJsonMap =
323
      parse(vocabJsonContent, useBigIntForLong = true).values
×
324
        .asInstanceOf[Map[String, BigInt]]
×
325

326
    val preprocessorConfigJsonContent =
327
      loadJsonStringAsset(localModelPath, "preprocessor_config.json")
×
328
    val preprocessorConfig =
329
      Preprocessor.loadPreprocessorConfig(preprocessorConfigJsonContent)
×
330

331
    /*Universal parameters for all engines*/
332
    val annotatorModel = new Wav2Vec2ForCTC()
333
      .setVocabulary(vocabJsonMap)
334
      .setDoNormalize(preprocessorConfig.do_normalize)
×
335
      .setFeatureSize(preprocessorConfig.feature_size)
×
336
      .setPaddingSide(preprocessorConfig.padding_side)
×
337
      .setPaddingValue(preprocessorConfig.padding_value)
×
338
      .setReturnAttentionMask(preprocessorConfig.return_attention_mask)
×
339
      .setSamplingRate(preprocessorConfig.sampling_rate)
×
340

341
    annotatorModel.set(annotatorModel.engine, detectedEngine)
×
342

343
    detectedEngine match {
344
      case ModelEngine.tensorflow =>
345
        val (wrapper, signatures) =
×
346
          TensorflowWrapper.read(localModelPath, zipped = false, useBundle = true)
347

348
        val _signatures = signatures match {
349
          case Some(s) => s
350
          case None => throw new Exception("Cannot load signature definitions from model!")
×
351
        }
352

353
        /** the order of setSignatures is important if we use getSignatures inside
354
          * setModelIfNotSet
355
          */
356
        annotatorModel
357
          .setSignatures(_signatures)
358
          .setModelIfNotSet(spark, wrapper)
×
359

360
      case _ =>
361
        throw new Exception(notSupportedEngineError)
×
362
    }
363

364
    annotatorModel
365
  }
366
}
367

368
/** This is the companion object of [[Wav2Vec2ForCTC]]. Please refer to that class for the
369
  * documentation.
370
  */
371
object Wav2Vec2ForCTC
372
    extends ReadablePretrainedWav2Vec2ForAudioModel
373
    with ReadWav2Vec2ForAudioDLModel
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc