jtlonsako commited on
Commit
c506d75
1 Parent(s): 394d8c1

Converted to blocks format to allow for tabs (new microphone tab)

Browse files
Files changed (1) hide show
  1. app.py +156 -119
app.py CHANGED
@@ -64,127 +64,164 @@ def format_time(seconds):
64
 
65
  #Convert Video/Audio into 16K wav file
66
  def preprocessAudio(audioFile):
67
- os.system(f"ffmpeg -y -i {audioFile.name} -ar 16000 ./audioToConvert.wav")
 
 
 
68
 
69
  #Transcribe!!!
70
- def Transcribe(file, batch_size):
71
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
72
- start_time = time.time()
73
- model.load_adapter("amh")
74
- processor.tokenizer.set_target_lang("amh")
75
-
76
- preprocessAudio(file)
77
- block_size = 30
78
-
79
- transcripts = []
80
- speech_segments = []
81
-
82
- stream = librosa.stream(
83
- "./audioToConvert.wav",
84
- block_length=block_size,
85
- frame_length=16000,
86
- hop_length=16000
87
- )
88
-
89
- model.to(device)
90
- print(f"Model loaded to {device}: Entering transcription phase")
91
-
92
- #Code for timestamping
93
- encoding_start = 0
94
- encoding_end = 0
95
- sbv_file = open("subtitle.sbv", "w")
96
- transcription_file = open("transcription.txt", "w")
97
-
98
- # Create an empty list to hold batches
99
- batch = []
100
-
101
- for speech_segment in stream:
102
- if len(speech_segment.shape) > 1:
103
- speech_segment = speech_segment[:,0] + speech_segment[:,1]
104
-
105
- # Add the current speech segment to the batch
106
- batch.append(speech_segment)
107
-
108
- # If the batch is full, process it
109
- if len(batch) == batch_size:
110
- # Concatenate all segments in the batch along the time axis
111
- input_values = processor(batch, sampling_rate=16_000, return_tensors="pt", padding=True)
112
- input_values = input_values.to(device)
113
- with torch.no_grad():
114
- logits = model(**input_values).logits
115
- if len(logits.shape) == 1:
116
- logits = logits.unsqueeze(0)
117
- beam_search_result = beam_search_decoder(logits.to("cpu"))
118
-
119
- # Transcribe each segment in the batch
120
- for i in range(batch_size):
121
- transcription = " ".join(beam_search_result[i][0].words).strip()
122
- transcripts.append(transcription)
123
-
124
- encoding_end = encoding_start + block_size
125
- formatted_start = format_time(encoding_start)
126
- formatted_end = format_time(encoding_end)
127
- sbv_file.write(f"{formatted_start},{formatted_end}\n")
128
- sbv_file.write(f"{transcription}\n\n")
129
-
130
- encoding_start = encoding_end
131
-
132
- # Freeing up memory
133
- del input_values
134
- del logits
135
- del transcription
136
- torch.cuda.empty_cache()
137
- gc.collect()
138
-
139
- # Clear the batch
140
- batch = []
141
-
142
- if batch:
143
- # Concatenate all segments in the batch along the time axis
144
- input_values = processor(batch, sampling_rate=16_000, return_tensors="pt", padding=True)
145
- input_values = input_values.to(device)
146
- with torch.no_grad():
147
- logits = model(**input_values).logits
148
- if len(logits.shape) == 1:
149
- logits = logits.unsqueeze(0)
150
- beam_search_result = beam_search_decoder(logits.to("cpu"))
151
-
152
- # Transcribe each segment in the batch
153
- for i in range(len(batch)):
154
- transcription = " ".join(beam_search_result[i][0].words).strip()
155
- print(transcription)
156
- transcripts.append(transcription)
157
-
158
- encoding_end = encoding_start + block_size
159
- formatted_start = format_time(encoding_start)
160
- formatted_end = format_time(encoding_end)
161
- sbv_file.write(f"{formatted_start},{formatted_end}\n")
162
- sbv_file.write(f"{transcription}\n\n")
163
-
164
- encoding_start = encoding_end
165
-
166
- # Freeing up memory
167
- del input_values
168
- del logits
169
- del transcription
170
- torch.cuda.empty_cache()
171
- gc.collect()
172
-
173
- # Join all transcripts into a single transcript
174
- transcript = ' '.join(transcripts)
175
- transcription_file.write(f"{transcript}")
176
- sbv_file.close()
177
- transcription_file.close()
178
-
179
- end_time = time.time()
180
- print(f"The script ran for {end_time - start_time} seconds.")
181
- return(["./subtitle.sbv", "./transcription.txt"])
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
- demo = gr.Interface(fn=Transcribe, inputs=[gr.File(label="Upload an audio file of Amharic content"), gr.Slider(0, 25, value=4, step=1, label="batch size", info="Approximately .5GB per batch")],
184
- outputs=gr.File(label="Download .sbv transcription", file_count="multiple"),
185
- title="Amharic Audio Transcription",
186
- description="This application uses Meta MMS and an Amharic kenLM model to transcribe Amharic Audio files of arbitrary length into .sbv and .txt files. Upload an Amharic audio file and get your transcription! \n(Note: Transcription quality is quite low, you should review and edit transcriptions before making them publicly available)"
187
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
  demo.launch()
190
-
 
64
 
65
  #Convert Video/Audio into 16K wav file
66
  def preprocessAudio(audioFile):
67
+ if isinstance(audioFile, str): # If audioFile is a string (filepath)
68
+ os.system(f"ffmpeg -y -i {audioFile} -ar 16000 ./audioToConvert.wav")
69
+ else: # If audioFile is an object with a name attribute
70
+ os.system(f"ffmpeg -y -i {audioFile.name} -ar 16000 ./audioToConvert.wav")
71
 
72
  #Transcribe!!!
73
+ def Transcribe(file):
74
+ try:
75
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
76
+ start_time = time.time()
77
+ model.load_adapter("amh")
78
+ processor.tokenizer.set_target_lang("amh")
79
+
80
+ preprocessAudio(file)
81
+ block_size = 30
82
+ batch_size = 1
83
+
84
+ transcripts = []
85
+ speech_segments = []
86
+
87
+ stream = librosa.stream(
88
+ "./audioToConvert.wav",
89
+ block_length=block_size,
90
+ frame_length=16000,
91
+ hop_length=16000
92
+ )
93
+
94
+ model.to(device)
95
+ print(f"Model loaded to {device}: Entering transcription phase")
96
+
97
+ #Code for timestamping
98
+ encoding_start = 0
99
+ encoding_end = 0
100
+ sbv_file = open("subtitle.sbv", "w")
101
+ transcription_file = open("transcription.txt", "w")
102
+
103
+ # Create an empty list to hold batches
104
+ batch = []
105
+
106
+ for speech_segment in stream:
107
+ if len(speech_segment.shape) > 1:
108
+ speech_segment = speech_segment[:,0] + speech_segment[:,1]
109
+
110
+ # Add the current speech segment to the batch
111
+ batch.append(speech_segment)
112
+
113
+ # If the batch is full, process it
114
+ if len(batch) == batch_size:
115
+ # Concatenate all segments in the batch along the time axis
116
+ input_values = processor(batch, sampling_rate=16_000, return_tensors="pt", padding=True)
117
+ input_values = input_values.to(device)
118
+ with torch.no_grad():
119
+ logits = model(**input_values).logits
120
+ if len(logits.shape) == 1:
121
+ logits = logits.unsqueeze(0)
122
+ beam_search_result = beam_search_decoder(logits.to("cpu"))
123
+
124
+ # Transcribe each segment in the batch
125
+ for i in range(batch_size):
126
+ transcription = " ".join(beam_search_result[i][0].words).strip()
127
+ transcripts.append(transcription)
128
+
129
+ encoding_end = encoding_start + block_size
130
+ formatted_start = format_time(encoding_start)
131
+ formatted_end = format_time(encoding_end)
132
+ sbv_file.write(f"{formatted_start},{formatted_end}\n")
133
+ sbv_file.write(f"{transcription}\n\n")
134
+
135
+ encoding_start = encoding_end
136
+
137
+ # Freeing up memory
138
+ del input_values
139
+ del logits
140
+ del transcription
141
+ torch.cuda.empty_cache()
142
+ gc.collect()
143
+
144
+ # Clear the batch
145
+ batch = []
146
+
147
+ if batch:
148
+ # Concatenate all segments in the batch along the time axis
149
+ input_values = processor(batch, sampling_rate=16_000, return_tensors="pt", padding=True)
150
+ input_values = input_values.to(device)
151
+ with torch.no_grad():
152
+ logits = model(**input_values).logits
153
+ if len(logits.shape) == 1:
154
+ logits = logits.unsqueeze(0)
155
+ beam_search_result = beam_search_decoder(logits.to("cpu"))
156
+
157
+ # Transcribe each segment in the batch
158
+ for i in range(len(batch)):
159
+ transcription = " ".join(beam_search_result[i][0].words).strip()
160
+ print(transcription)
161
+ transcripts.append(transcription)
162
+
163
+ encoding_end = encoding_start + block_size
164
+ formatted_start = format_time(encoding_start)
165
+ formatted_end = format_time(encoding_end)
166
+ sbv_file.write(f"{formatted_start},{formatted_end}\n")
167
+ sbv_file.write(f"{transcription}\n\n")
168
+
169
+ encoding_start = encoding_end
170
+
171
+ # Freeing up memory
172
+ del input_values
173
+ del logits
174
+ del transcription
175
+ torch.cuda.empty_cache()
176
+ gc.collect()
177
+
178
+ # Join all transcripts into a single transcript
179
+ transcript = ' '.join(transcripts)
180
+ transcription_file.write(f"{transcript}")
181
+ sbv_file.close()
182
+ transcription_file.close()
183
+
184
+ end_time = time.time()
185
+ print(f"The script ran for {end_time - start_time} seconds.")
186
+ return(["./subtitle.sbv", "./transcription.txt"])
187
+ except Exception as e:
188
+ error_log = open("error_log.txt", "w")
189
+ error_log.write(f"Exception occurred: {e}")
190
+ error_log.close()
191
+
192
+ demo = gr.Blocks()
193
+
194
+ with demo:
195
+ gr.Markdown(
196
+ """
197
+ <div align="center">
198
 
199
+ # Amharic Audio Transcription
200
+
201
+ This application uses Meta MMS and an Amharic kenLM model to transcribe Amharic Audio files of arbitrary length into .sbv and .txt files. Upload an Amharic audio file and get your transcription!
202
+
203
+ ### (Note: Transcription quality is quite low, you should review and edit transcriptions before making them publicly available)
204
+ </div>
205
+ """)
206
+ with gr.Tabs():
207
+ with gr.TabItem("From File"):
208
+ with gr.Row():
209
+ file_input = gr.File(label="Upload an audio file of Amharic Content")
210
+ file_output = gr.Files(label="Download output files")
211
+ file_button = gr.Button("Submit")
212
+ with gr.TabItem("From Microphone"):
213
+ with gr.Row():
214
+ microphone_input = gr.Audio(type="filepath", source="microphone")
215
+ microphone_output = gr.Files(label="Download output files")
216
+ microphone_button = gr.Button("Submit")
217
+
218
+ file_button.click(Transcribe, inputs=file_input, outputs=file_output)
219
+ microphone_button.click(Transcribe, inputs=microphone_input, outputs=microphone_output)
220
+
221
+ # demo = gr.Interface(fn=Transcribe, inputs=[gr.File(label="Upload an audio file of Amharic content"), gr.Slider(0, 25, value=4, step=1, label="batch size", info="Approximately .5GB per batch")],
222
+ # outputs=gr.File(label="Download .sbv transcription", file_count="multiple"),
223
+ # title="Amharic Audio Transcription",
224
+ # description="This application uses Meta MMS and an Amharic kenLM model to transcribe Amharic Audio files of arbitrary length into .sbv and .txt files. Upload an Amharic audio file and get your transcription! \n(Note: Transcription quality is quite low, you should review and edit transcriptions before making them publicly available)"
225
+ # )
226
 
227
  demo.launch()