• 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/HubertForCTC.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.tensorflow.{ReadTensorflowModel, TensorflowWrapper}
20
import com.johnsnowlabs.ml.util.LoadExternalModel.{
21
  loadJsonStringAsset,
22
  modelSanityCheck,
23
  notSupportedEngineError
24
}
25
import com.johnsnowlabs.ml.util.ModelEngine
26
import com.johnsnowlabs.nlp._
27
import com.johnsnowlabs.nlp.annotators.audio.feature_extractor.Preprocessor
28
import org.apache.spark.ml.util.Identifiable
29
import org.apache.spark.sql.SparkSession
30
import org.json4s._
31
import org.json4s.jackson.JsonMethods._
32

33
/** Hubert Model with a language modeling head on top for Connectionist Temporal Classification
34
  * (CTC). Hubert was proposed in HuBERT: Self-Supervised Speech Representation Learning by Masked
35
  * Prediction of Hidden Units by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal
36
  * Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
37
  *
38
  * The annotator takes audio files and transcribes it as text. The audio needs to be provided
39
  * pre-processed an array of floats.
40
  *
41
  * Note that this annotator is currently not supported on Apple Silicon processors such as the
42
  * M1/M2 (Apple Silicon). This is due to the processor not supporting instructions for XLA.
43
  *
44
  * Pretrained models can be loaded with `pretrained` of the companion object:
45
  * {{{
46
  * val speechToText = HubertForCTC.pretrained()
47
  *   .setInputCols("audio_assembler")
48
  *   .setOutputCol("text")
49
  * }}}
50
  * The default model is `"asr_hubert_large_ls960"`, if no name is provided.
51
  *
52
  * For available pretrained models please see the
53
  * [[https://nlp.johnsnowlabs.com/models Models Hub]].
54
  *
55
  * To see which models are compatible and how to import them see
56
  * [[https://github.com/JohnSnowLabs/spark-nlp/discussions/5669]] and to see more extended
57
  * examples, see
58
  * [[https://github.com/JohnSnowLabs/spark-nlp/blob/master/src/test/scala/com/johnsnowlabs/nlp/annotators/audio/HubertForCTCTestSpec.scala HubertForCTCTestSpec]].
59
  *
60
  * '''References:'''
61
  *
62
  * [[https://arxiv.org/abs/2106.07447 HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units]]
63
  *
64
  * '''Paper Abstract:'''
65
  *
66
  * ''Self-supervised approaches for speech representation learning are challenged by three unique
67
  * problems: (1) there are multiple sound units in each input utterance, (2) there is no lexicon
68
  * of input sound units during the pre-training phase, and (3) sound units have variable lengths
69
  * with no explicit segmentation. To deal with these three problems, we propose the Hidden-Unit
70
  * BERT (HuBERT) approach for self-supervised speech representation learning, which utilizes an
71
  * offline clustering step to provide aligned target labels for a BERT-like prediction loss. A
72
  * key ingredient of our approach is applying the prediction loss over the masked regions only,
73
  * which forces the model to learn a combined acoustic and language model over the continuous
74
  * inputs. HuBERT relies primarily on the consistency of the unsupervised clustering step rather
75
  * than the intrinsic quality of the assigned cluster labels. Starting with a simple k-means
76
  * teacher of 100 clusters, and using two iterations of clustering, the HuBERT model either
77
  * matches or improves upon the state-of-the-art wav2vec 2.0 performance on the Librispeech
78
  * (960h) and Libri-light (60,000h) benchmarks with 10min, 1h, 10h, 100h, and 960h fine-tuning
79
  * subsets. Using a 1B parameter model, HuBERT shows up to 19% and 13% relative WER reduction on
80
  * the more challenging dev-other and test-other evaluation subsets.''
81
  *
82
  * ==Example==
83
  * {{{
84
  * import spark.implicits._
85
  * import com.johnsnowlabs.nlp.base._
86
  * import com.johnsnowlabs.nlp.annotators._
87
  * import com.johnsnowlabs.nlp.annotators.audio.HubertForCTC
88
  * import org.apache.spark.ml.Pipeline
89
  *
90
  * val audioAssembler: AudioAssembler = new AudioAssembler()
91
  *   .setInputCol("audio_content")
92
  *   .setOutputCol("audio_assembler")
93
  *
94
  * val speechToText: HubertForCTC = HubertForCTC
95
  *   .pretrained()
96
  *   .setInputCols("audio_assembler")
97
  *   .setOutputCol("text")
98
  *
99
  * val pipeline: Pipeline = new Pipeline().setStages(Array(audioAssembler, speechToText))
100
  *
101
  * val bufferedSource =
102
  *   scala.io.Source.fromFile("src/test/resources/audio/csv/audio_floats.csv")
103
  *
104
  * val rawFloats = bufferedSource
105
  *   .getLines()
106
  *   .map(_.split(",").head.trim.toFloat)
107
  *   .toArray
108
  * bufferedSource.close
109
  *
110
  * val processedAudioFloats = Seq(rawFloats).toDF("audio_content")
111
  *
112
  * val result = pipeline.fit(processedAudioFloats).transform(processedAudioFloats)
113
  * result.select("text.result").show(truncate = false)
114
  * +------------------------------------------------------------------------------------------+
115
  * |result                                                                                    |
116
  * +------------------------------------------------------------------------------------------+
117
  * |[MISTER QUILTER IS THE APOSTLE OF THE MIDLE CLASES AND WE ARE GLAD TO WELCOME HIS GOSPEL ]|
118
  * +------------------------------------------------------------------------------------------+
119
  * }}}
120
  *
121
  * @param uid
122
  *   required uid for storing annotator to disk
123
  * @groupname anno Annotator types
124
  * @groupdesc anno
125
  *   Required input and expected output annotator types
126
  * @groupname Ungrouped Members
127
  * @groupname param Parameters
128
  * @groupname setParam Parameter setters
129
  * @groupname getParam Parameter getters
130
  * @groupname Ungrouped Members
131
  * @groupprio param  1
132
  * @groupprio anno  2
133
  * @groupprio Ungrouped 3
134
  * @groupprio setParam  4
135
  * @groupprio getParam  5
136
  * @groupdesc param
137
  *   A list of (hyper-)parameter keys this annotator can take. Users can set and get the
138
  *   parameter values through setters and getters, respectively.
139
  */
140
class HubertForCTC(override val uid: String) extends Wav2Vec2ForCTC(uid) {
141

142
  /** Annotator reference id. Used to identify elements in metadata or to refer to this annotator
143
    * type
144
    */
145
  def this() = this(Identifiable.randomUID("HubertForCTC"))
×
146

147
  override def onWrite(path: String, spark: SparkSession): Unit = {
148
    super.onWrite(path, spark)
×
149
    writeTensorflowModelV2(
×
150
      path,
151
      spark,
152
      getModelIfNotSet.tensorflowWrapper,
×
153
      "_hubert_ctc",
×
154
      HubertForCTC.tfFile,
×
155
      configProtoBytes = getConfigProtoBytes)
×
156
  }
157

158
}
159

160
trait ReadablePretrainedHubertForAudioModel
161
    extends ParamsAndFeaturesReadable[HubertForCTC]
162
    with HasPretrained[HubertForCTC] {
163
  override val defaultModelName: Some[String] = Some("asr_hubert_large_ls960")
×
164

165
  /** Java compliant-overrides */
166
  override def pretrained(): HubertForCTC = super.pretrained()
×
167

168
  override def pretrained(name: String): HubertForCTC = super.pretrained(name)
×
169

170
  override def pretrained(name: String, lang: String): HubertForCTC =
171
    super.pretrained(name, lang)
×
172

173
  override def pretrained(name: String, lang: String, remoteLoc: String): HubertForCTC =
174
    super.pretrained(name, lang, remoteLoc)
×
175
}
176

177
trait ReadHubertForAudioDLModel extends ReadTensorflowModel {
178
  this: ParamsAndFeaturesReadable[HubertForCTC] =>
179

180
  override val tfFile: String = "hubert_ctc_tensorflow"
×
181

182
  def readTensorflow(instance: HubertForCTC, path: String, spark: SparkSession): Unit = {
183

184
    val tf = readTensorflowModel(path, spark, "_hubert_ctc_tf", initAllTables = false)
×
185
    instance.setModelIfNotSet(spark, tf)
×
186
  }
187

188
  addReader(readTensorflow)
×
189

190
  def loadSavedModel(modelPath: String, spark: SparkSession): HubertForCTC = {
191

192
    val (localModelPath, detectedEngine) = modelSanityCheck(modelPath)
×
193

194
    val vocabJsonContent = loadJsonStringAsset(localModelPath, "vocab.json")
×
195
    val vocabJsonMap =
196
      parse(vocabJsonContent, useBigIntForLong = true).values
×
197
        .asInstanceOf[Map[String, BigInt]]
×
198

199
    val preprocessorConfigJsonContent =
200
      loadJsonStringAsset(localModelPath, "preprocessor_config.json")
×
201
    val preprocessorConfig =
202
      Preprocessor.loadPreprocessorConfig(preprocessorConfigJsonContent)
×
203

204
    /*Universal parameters for all engines*/
205
    val annotatorModel = new HubertForCTC()
206
      .setVocabulary(vocabJsonMap)
207
      .setDoNormalize(preprocessorConfig.do_normalize)
×
208
      .setFeatureSize(preprocessorConfig.feature_size)
×
209
      .setPaddingSide(preprocessorConfig.padding_side)
×
210
      .setPaddingValue(preprocessorConfig.padding_value)
×
211
      .setReturnAttentionMask(preprocessorConfig.return_attention_mask)
×
212
      .setSamplingRate(preprocessorConfig.sampling_rate)
×
213

214
    annotatorModel.set(annotatorModel.engine, detectedEngine)
×
215

216
    detectedEngine match {
217
      case ModelEngine.tensorflow =>
218
        val (wrapper, signatures) =
×
219
          TensorflowWrapper.read(localModelPath, zipped = false, useBundle = true)
220

221
        val _signatures = signatures match {
222
          case Some(s) => s
223
          case None => throw new Exception("Cannot load signature definitions from model!")
×
224
        }
225

226
        /** the order of setSignatures is important if we use getSignatures inside
227
          * setModelIfNotSet
228
          */
229
        annotatorModel
230
          .setSignatures(_signatures)
231
          .setModelIfNotSet(spark, wrapper)
×
232

233
      case _ =>
234
        throw new Exception(notSupportedEngineError)
×
235
    }
236

237
    annotatorModel
238
  }
239
}
240

241
/** This is the companion object of [[HubertForCTC]]. Please refer to that class for the
242
  * documentation.
243
  */
244
object HubertForCTC extends ReadablePretrainedHubertForAudioModel with ReadHubertForAudioDLModel
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