jtlonsako commited on
Commit
18680df
1 Parent(s): 43541ee

Updated to use Meta's language model

Browse files
Files changed (1) hide show
  1. app.py +109 -42
app.py CHANGED
@@ -2,18 +2,65 @@ import soundfile as sf
2
  import datetime
3
  from pyctcdecode import BeamSearchDecoderCTC
4
  import torch
 
5
  import os
6
  import time
7
  import gc
8
  import gradio as gr
9
  import librosa
10
- from transformers import Wav2Vec2ForCTC, Wav2Vec2ProcessorWithLM, AutoModelForSeq2SeqLM, AutoTokenizer
 
 
11
  from numba import cuda
12
 
13
  # load pretrained model
14
  model = Wav2Vec2ForCTC.from_pretrained("facebook/mms-1b-all")
15
- processor = Wav2Vec2ProcessorWithLM.from_pretrained("jlonsako/mms-1b-all-AmhLM")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  #Define Functions
19
 
@@ -31,11 +78,11 @@ def Transcribe(file):
31
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
32
  start_time = time.time()
33
  model.load_adapter("amh")
34
- model.half()
35
 
36
  preprocessAudio(file)
37
  block_size = 30
38
- batch_size = 22 # or whatever number you choose
39
 
40
  transcripts = []
41
  speech_segments = []
@@ -48,71 +95,91 @@ def Transcribe(file):
48
  )
49
 
50
  model.to(device)
51
- print("Model loaded to gpu: Entering transcription phase")
52
 
53
  #Code for timestamping
54
  encoding_start = 0
55
  encoding_end = 0
56
  sbv_file = open("subtitle.sbv", "w")
57
 
58
- for speech_segment in stream:
 
 
 
 
 
 
59
  if len(speech_segment.shape) > 1:
60
  speech_segment = speech_segment[:,0] + speech_segment[:,1]
61
- speech_segments.append(speech_segment)
62
 
63
- if len(speech_segments) == batch_size:
64
- input_values = processor(speech_segments, sampling_rate=16_000, return_tensors="pt", padding=True).input_values.to(device)
65
- input_values = input_values.half()
 
 
 
 
 
66
  with torch.no_grad():
67
- logits = model(input_values).logits
68
  if len(logits.shape) == 1:
69
  logits = logits.unsqueeze(0)
70
- #predicted_ids = torch.argmax(logits, dim=-1)
71
- transcriptions = processor.batch_decode(logits.cpu().numpy()).text
72
- transcripts.extend(transcriptions)
 
 
 
 
73
 
74
- # Write to the .sbv file
75
- for i, transcription in enumerate(transcriptions):
76
- encoding_start = encoding_end # Maintain the 'encoding_start' across batches
77
  encoding_end = encoding_start + block_size
78
  formatted_start = format_time(encoding_start)
79
  formatted_end = format_time(encoding_end)
80
  sbv_file.write(f"{formatted_start},{formatted_end}\n")
81
  sbv_file.write(f"{transcription}\n\n")
82
 
83
- # Clear the batch
84
- speech_segments = []
85
 
86
  # Freeing up memory
87
  del input_values
88
  del logits
89
- del transcriptions
90
  torch.cuda.empty_cache()
91
  gc.collect()
92
 
93
- if speech_segments:
94
- input_values = processor(speech_segments, sampling_rate=16_000, return_tensors="pt", padding=True).input_values.to(device)
95
- input_values = input_values.half()
96
- with torch.no_grad():
97
- logits = model(input_values).logits
98
- transcriptions = processor.batch_decode(logits.cpu().numpy()).text
99
- transcripts.extend(transcriptions)
100
-
101
- for i in range(len(speech_segments)):
102
- encoding_end = encoding_start + block_size
103
- formatted_start = format_time(encoding_start)
104
- formatted_end = format_time(encoding_end)
105
- sbv_file.write(f"{formatted_start},{formatted_end}\n")
106
- sbv_file.write(f"{transcriptions[i]}\n\n")
107
- encoding_start = encoding_end
108
-
109
- # Freeing up memory
110
- del input_values
111
- del logits
112
- del transcriptions
113
- torch.cuda.empty_cache()
114
- gc.collect()
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
  # Join all transcripts into a single transcript
118
  transcript = ' '.join(transcripts)
 
2
  import datetime
3
  from pyctcdecode import BeamSearchDecoderCTC
4
  import torch
5
+ import json
6
  import os
7
  import time
8
  import gc
9
  import gradio as gr
10
  import librosa
11
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2ProcessorWithLM, AutoModelForSeq2SeqLM, AutoTokenizer, AutoProcessor
12
+ from huggingface_hub import hf_hub_download
13
+ from torchaudio.models.decoder import ctc_decoder
14
  from numba import cuda
15
 
16
  # load pretrained model
17
  model = Wav2Vec2ForCTC.from_pretrained("facebook/mms-1b-all")
18
+ processor = AutoProcessor.from_pretrained("facebook/mms-1b-all")
19
+
20
+ lm_decoding_config = {}
21
+ lm_decoding_configfile = hf_hub_download(
22
+ repo_id="facebook/mms-cclms",
23
+ filename="decoding_config.json",
24
+ subfolder="mms-1b-all",
25
+ )
26
+
27
+ with open(lm_decoding_configfile) as f:
28
+ lm_decoding_config = json.loads(f.read())
29
+
30
+ # allow language model decoding for "eng"
31
+
32
+ decoding_config = lm_decoding_config["amh"]
33
+
34
+ lm_file = hf_hub_download(
35
+ repo_id="facebook/mms-cclms",
36
+ filename=decoding_config["lmfile"].rsplit("/", 1)[1],
37
+ subfolder=decoding_config["lmfile"].rsplit("/", 1)[0],
38
+ )
39
+ token_file = hf_hub_download(
40
+ repo_id="facebook/mms-cclms",
41
+ filename=decoding_config["tokensfile"].rsplit("/", 1)[1],
42
+ subfolder=decoding_config["tokensfile"].rsplit("/", 1)[0],
43
+ )
44
+ lexicon_file = None
45
+ if decoding_config["lexiconfile"] is not None:
46
+ lexicon_file = hf_hub_download(
47
+ repo_id="facebook/mms-cclms",
48
+ filename=decoding_config["lexiconfile"].rsplit("/", 1)[1],
49
+ subfolder=decoding_config["lexiconfile"].rsplit("/", 1)[0],
50
+ )
51
 
52
+ beam_search_decoder = ctc_decoder(
53
+ lexicon="./vocab_correct_cleaned.txt",
54
+ tokens=token_file,
55
+ lm=lm_file,
56
+ nbest=1,
57
+ beam_size=500,
58
+ beam_size_token=50,
59
+ lm_weight=float(decoding_config["lmweight"]),
60
+ word_score=float(decoding_config["wordscore"]),
61
+ sil_score=float(decoding_config["silweight"]),
62
+ blank_token="<s>",
63
+ )
64
 
65
  #Define Functions
66
 
 
78
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
79
  start_time = time.time()
80
  model.load_adapter("amh")
81
+ processor.tokenizer.set_target_lang("amh")
82
 
83
  preprocessAudio(file)
84
  block_size = 30
85
+ batch_size = 8 # or whatever number you choose
86
 
87
  transcripts = []
88
  speech_segments = []
 
95
  )
96
 
97
  model.to(device)
98
+ print(f"Model loaded to {device}: Entering transcription phase")
99
 
100
  #Code for timestamping
101
  encoding_start = 0
102
  encoding_end = 0
103
  sbv_file = open("subtitle.sbv", "w")
104
 
105
+ # Define batch size
106
+ batch_size = 11
107
+
108
+ # Create an empty list to hold batches
109
+ batch = []
110
+
111
+ for speech_segment in stream:
112
  if len(speech_segment.shape) > 1:
113
  speech_segment = speech_segment[:,0] + speech_segment[:,1]
 
114
 
115
+ # Add the current speech segment to the batch
116
+ batch.append(speech_segment)
117
+
118
+ # If the batch is full, process it
119
+ if len(batch) == batch_size:
120
+ # Concatenate all segments in the batch along the time axis
121
+ input_values = processor(batch, sampling_rate=16_000, return_tensors="pt")
122
+ input_values = input_values.to(device)
123
  with torch.no_grad():
124
+ logits = model(**input_values).logits
125
  if len(logits.shape) == 1:
126
  logits = logits.unsqueeze(0)
127
+ beam_search_result = beam_search_decoder(logits.to("cpu"))
128
+
129
+ # Transcribe each segment in the batch
130
+ for i in range(batch_size):
131
+ transcription = " ".join(beam_search_result[i][0].words).strip()
132
+ print(transcription)
133
+ transcripts.append(transcription)
134
 
 
 
 
135
  encoding_end = encoding_start + block_size
136
  formatted_start = format_time(encoding_start)
137
  formatted_end = format_time(encoding_end)
138
  sbv_file.write(f"{formatted_start},{formatted_end}\n")
139
  sbv_file.write(f"{transcription}\n\n")
140
 
141
+ encoding_start = encoding_end
 
142
 
143
  # Freeing up memory
144
  del input_values
145
  del logits
146
+ del transcription
147
  torch.cuda.empty_cache()
148
  gc.collect()
149
 
150
+ # Clear the batch
151
+ batch = []
152
+
153
+ if batch:
154
+ # Concatenate all segments in the batch along the time axis
155
+ input_values = processor(batch, sampling_rate=16_000, return_tensors="pt")
156
+ input_values = input_values.to(device)
157
+ with torch.no_grad():
158
+ logits = model(**input_values).logits
159
+ if len(logits.shape) == 1:
160
+ logits = logits.unsqueeze(0)
161
+ beam_search_result = beam_search_decoder(logits.to("cpu"))
162
+
163
+ # Transcribe each segment in the batch
164
+ for i in range(batch_size):
165
+ transcription = " ".join(beam_search_result[i][0].words).strip()
166
+ print(transcription)
167
+ transcripts.append(transcription)
 
 
 
 
168
 
169
+ encoding_end = encoding_start + block_size
170
+ formatted_start = format_time(encoding_start)
171
+ formatted_end = format_time(encoding_end)
172
+ sbv_file.write(f"{formatted_start},{formatted_end}\n")
173
+ sbv_file.write(f"{transcription}\n\n")
174
+
175
+ encoding_start = encoding_end
176
+
177
+ # Freeing up memory
178
+ del input_values
179
+ del logits
180
+ del transcription
181
+ torch.cuda.empty_cache()
182
+ gc.collect()
183
 
184
  # Join all transcripts into a single transcript
185
  transcript = ' '.join(transcripts)