File size: 11,531 Bytes
09b2769
 
8414736
09b2769
 
 
 
 
8414736
09b2769
d521dce
234fe59
d521dce
 
09b2769
 
 
 
 
 
 
 
 
 
 
 
 
 
8414736
 
234fe59
 
09b2769
 
234fe59
09b2769
 
 
 
 
 
 
 
 
 
 
d521dce
 
09b2769
 
234fe59
 
 
 
09b2769
234fe59
 
 
 
 
09b2769
234fe59
 
 
09b2769
 
 
234fe59
d521dce
8414736
 
09b2769
d521dce
 
09b2769
234fe59
09b2769
 
234fe59
 
09b2769
 
 
 
d521dce
 
09b2769
 
 
 
 
 
 
 
 
 
d521dce
 
 
09b2769
 
 
 
 
d521dce
 
234fe59
 
d521dce
 
09b2769
d521dce
09b2769
 
 
 
 
 
234fe59
09b2769
234fe59
 
 
 
09b2769
 
d521dce
234fe59
d521dce
234fe59
 
 
d521dce
234fe59
 
 
 
 
 
d521dce
09b2769
234fe59
 
 
 
09b2769
 
d521dce
 
 
 
234fe59
 
09b2769
 
234fe59
 
8414736
09b2769
 
 
234fe59
 
09b2769
 
 
 
 
 
 
 
 
 
 
234fe59
09b2769
d521dce
09b2769
d521dce
09b2769
 
 
 
 
 
d521dce
09b2769
 
8414736
 
09b2769
 
234fe59
 
09b2769
234fe59
d521dce
09b2769
 
234fe59
 
09b2769
 
234fe59
 
8414736
 
 
 
 
 
 
 
 
09b2769
 
 
 
 
 
 
 
 
d521dce
8414736
 
8cfce12
 
 
 
 
09b2769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8414736
 
09b2769
 
 
 
 
 
8414736
 
 
 
 
 
 
 
 
8cfce12
 
 
 
 
 
 
 
09b2769
8414736
 
 
 
 
09b2769
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
from transformers import WhisperProcessor, WhisperForConditionalGeneration
from transformers import Speech2TextForConditionalGeneration, Speech2TextProcessor
from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
import plotly.graph_objs as go
from datasets import load_dataset
from datasets import Audio
import evaluate
import librosa
import torch
import numpy as np
import pandas as pd
import time

N_SAMPLES = 30

wer_metric = evaluate.load("wer")

def run(data_subset:str, model_1:str, model_2:str, own_audio, own_transcription:str):

    if data_subset is None:
        raise ValueError("No Dataset selected")
    if model_1 is None:
        raise ValueError("No Model 1 selected")
    if model_2 is None:
        raise ValueError("No Model 2 selected")

    if data_subset == "Common Voice":
        dataset, text_column = load_Common_Voice()
    elif data_subset == "Librispeech ASR clean":
        dataset, text_column = load_Librispeech_ASR_clean()
    elif data_subset == "Librispeech ASR other":
        dataset, text_column = load_Librispeech_ASR_other()
    elif data_subset == "OWN Recoding/Sample":
        sr, audio = own_audio
        audio = audio.astype(np.float32)
        print("AUDIO: ", type(audio), audio)
        audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)
    else:
        # if data_subset is None then still load load_Common_Voice
        dataset, text_column = load_Common_Voice()
    print("Dataset Loaded")
    
    model1, processor1 = load_model(model_1)
    model2, processor2 = load_model(model_2)
    print("Models Loaded")



    if data_subset == "OWN Recoding/Sample":
        sample = {"audio":{"array":audio,"sampling_rate":16000}}
        inference_times1 = []
        inference_times2 = []

        time_start = time.time()
        transcription1 = model_compute(model1, processor1, sample, model_1)
        time_stop = time.time()
        duration = time_stop - time_start
        inference_times1.append(duration)

        time_start = time.time()
        transcription2 = model_compute(model2, processor2, sample, model_2)
        time_stop = time.time()
        duration = time_stop - time_start
        inference_times2.append(duration)

        transcriptions1 = [transcription1]
        transcriptions2 = [transcription2]
        references = [own_transcription.lower()]
        
        wer1 = round(N_SAMPLES * compute_wer(references, transcriptions1), 2)
        wer2 = round(N_SAMPLES * compute_wer(references, transcriptions2), 2)

        results_md = f"""
        #### {model_1} 
        - WER Score: {wer1}
        - Avg. Inference Duration: {round(sum(inference_times1)/len(inference_times1), 4)}s
           
        #### {model_2} 
        - WER Score: {wer2}
        - Avg. Inference Duration: {round(sum(inference_times2)/len(inference_times2), 4)}s"""

        # Create the bar plot
        fig = go.Figure(
            data=[
                go.Bar(x=[f"{model_1}"], y=[wer1], showlegend=False),
                go.Bar(x=[f"{model_2}"], y=[wer2], showlegend=False),
            ]
        )
        # Update the layout for better visualization
        fig.update_layout(
            title="Comparison of Two Models",
            xaxis_title="Models",
            yaxis_title="Value",
            barmode="group",
        )

        df = pd.DataFrame({"references":references, "transcriptions 1":transcriptions1,"WER 1":[wer1],"transcriptions 2":transcriptions2,"WER 2":[wer2]})

        yield results_md, fig, df

    else:
        references = []
        transcriptions1 = []
        transcriptions2 = []
        WER1s = []
        WER2s = []
        inference_times1 = []
        inference_times2 = []


        counter = 0
        for i, sample in enumerate(dataset, start=1):
            print(counter)
            counter += 1

            references.append(sample[text_column])

            if model_1 == model_2:
                time_start = time.time()
                transcription = model_compute(model1, processor1, sample, model_1)
                time_stop = time.time()
                duration = time_stop - time_start
                inference_times1.append(duration)
                inference_times2.append(duration)               
                transcriptions1.append(transcription)
                transcriptions2.append(transcription)
            else:
                time_start = time.time()
                transcription1 = model_compute(model1, processor1, sample, model_1)
                time_stop = time.time()
                duration = time_stop - time_start
                inference_times1.append(duration)
                transcriptions1.append(transcription1)

                time_start = time.time()                
                transcription2 = model_compute(model2, processor2, sample, model_2)
                time_stop = time.time()
                duration = time_stop - time_start
                inference_times2.append(duration) 
                transcriptions2.append(transcription2)

            WER1s.append(round(compute_wer([sample[text_column]], [transcription1]),4))
            WER2s.append(round(compute_wer([sample[text_column]], [transcription2]),4))
            wer1 = round(sum(WER1s)/len(WER1s), 4)
            wer2 = round(sum(WER2s)/len(WER2s), 4)


            results_md = f"""
            {i}/{len(dataset)}-{'#'*i}{'_'*(N_SAMPLES-i)}
            
            #### {model_1} 
            - WER Score: {wer1}
            - Avg. Inference Duration: {round(sum(inference_times1)/len(inference_times1), 4)}s
            
            #### {model_2} 
            - WER Score: {wer2}
            - Avg. Inference Duration: {round(sum(inference_times2)/len(inference_times2), 4)}s"""
            
            # Create the bar plot
            fig = go.Figure(
                data=[
                    go.Bar(x=[f"{model_1}"], y=[wer1], showlegend=False),
                    go.Bar(x=[f"{model_2}"], y=[wer2], showlegend=False),
                ]
            )

            # Update the layout for better visualization
            fig.update_layout(
                title="Comparison of Two Models",
                xaxis_title="Models",
                yaxis_title="Value",
                barmode="group",
            )

            df = pd.DataFrame({"references":references, f"{model_1}":transcriptions1,"WER 1":WER1s,f"{model_2}":transcriptions2,"WER 2":WER2s})

            yield results_md, fig, df

    


# DATASET LOADERS
def load_Common_Voice():
    dataset = load_dataset("mozilla-foundation/common_voice_11_0", "en", revision="streaming", split="test", streaming=True, token=True, trust_remote_code=True)
    text_column = "sentence"
    dataset = dataset.take(N_SAMPLES)
    dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
    dataset = list(dataset)
    for sample in dataset:
        sample["text"] = sample["text"].lower()
    return dataset, text_column

def load_Librispeech_ASR_clean():
    dataset = load_dataset("librispeech_asr", "clean", split="test", streaming=True, token=True, trust_remote_code=True)
    print(next(iter(dataset)))
    text_column = "text"
    dataset = dataset.take(N_SAMPLES)
    dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
    dataset = list(dataset)
    for sample in dataset:
        sample["text"] = sample["text"].lower()
    return dataset, text_column

def load_Librispeech_ASR_other():
    dataset = load_dataset("librispeech_asr", "other", split="test", streaming=True, token=True, trust_remote_code=True)
    print(next(iter(dataset)))
    text_column = "text"
    dataset = dataset.take(N_SAMPLES)
    dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
    dataset = list(dataset)
    for sample in dataset:
        sample["text"] = sample["text"].lower()
    return dataset, text_column



# MODEL LOADERS
def load_model(model_id:str):
    if model_id == "openai/whisper-tiny.en":
        model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
        processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
    elif model_id == "facebook/s2t-medium-librispeech-asr":
        model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-medium-librispeech-asr")
        processor = Speech2TextProcessor.from_pretrained("facebook/s2t-medium-librispeech-asr")
    elif model_id == "facebook/wav2vec2-base-960h":
        processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")
        model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
    elif model_id == "openai/whisper-large-v2":
        processor = WhisperProcessor.from_pretrained("openai/whisper-large-v2")
        model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v2")
        model.config.forced_decoder_ids = None
    else:
        model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
        processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
    
    return model, processor


# MODEL INFERENCE
def model_compute(model, processor, sample, model_id):

    if model_id == "openai/whisper-tiny.en":
        sample = sample["audio"]
        input_features = processor(sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt").input_features
        predicted_ids = model.generate(input_features)
        transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
        transcription = processor.tokenizer.normalize(transcription[0])
        return transcription
    elif model_id == "facebook/s2t-medium-librispeech-asr":
        sample = sample["audio"]
        features = processor(sample["array"], sampling_rate=16000, padding=True, return_tensors="pt")
        input_features = features.input_features
        attention_mask = features.attention_mask
        gen_tokens = model.generate(input_features=input_features, attention_mask=attention_mask)
        transcription= processor.batch_decode(gen_tokens, skip_special_tokens=True)
        return transcription[0]
    elif model_id == "facebook/wav2vec2-base-960h":
        sample = sample["audio"]
        input_values = processor(sample["array"], sampling_rate=16000, return_tensors="pt", padding="longest").input_values  # Batch size 1
        logits = model(input_values).logits
        predicted_ids = torch.argmax(logits, dim=-1)
        transcription = processor.batch_decode(predicted_ids)
        return transcription[0].lower()
    elif model_id == "openai/whisper-large-v2":
        sample = sample["audio"]
        input_features = processor(sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt").input_features 
        predicted_ids = model.generate(input_features)
        transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
        transcription = processor.tokenizer.normalize(transcription[0])
        print("TRANSCRIPTION Whisper Large v2: ", transcription)
        return transcription
    else:
        sample = sample["audio"]
        input_features = processor(sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt").input_features
        predicted_ids = model.generate(input_features)
        transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
        return transcription[0]

# UTILS
def compute_wer(references, predictions):
    wer = wer_metric.compute(references=references, predictions=predictions)
    return wer