Views
No views yet
pip install transformers1
2from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer1model = Wav2Vec2ForCTC.from_pretrained("Konstantin-Bogdanoski/wav2vec2-macedonian-base")
2tokenizer = Wav2Vec2Tokenizer.from_pretrained("Konstantin-Bogdanoski/wav2vec2-macedonian-base")1file_path = "path/to/audio.wav"
2input_audio = tokenizer(file_path, return_tensors="pt").input_values
3transcription = model(input_audio).logits.argmax(-1)1transcription_text = tokenizer.decode(transcription[0])
2print("Transcription:", transcription_text)1## Read audio from *user*
2
3audio, sr = get_audio() # This function needs to be implemented to read audio from the microphone
4
5print(audio)
6print(sr)
7
8================================================================================================
9
10### Changing the sampling rate to correspond to the processor's sample rate
11
12import numpy as np
13from scipy.io import wavfile
14from scipy import interpolate
15
16================================================================================================
17
18NEW_SAMPLERATE = 22050
19
20old_samplerate = sr
21old_audio = audio
22
23if sr != NEW_SAMPLERATE:
24 duration = old_audio.shape[0] / old_samplerate
25
26 time_old = np.linspace(0, duration, old_audio.shape[0])
27 time_new = np.linspace(0, duration, int(old_audio.shape[0] * NEW_SAMPLERATE / old_samplerate))
28
29 interpolator = interpolate.interp1d(time_old, old_audio.T)
30 new_audio = interpolator(time_new).T
31
32 new_audio = wavfile.write("out.wav", NEW_SAMPLERATE, np.round(new_audio).astype(old_audio.dtype))
33
34================================================================================================
35
36import soundfile
37import torch
38
39batch = {}
40
41speech_array, sampling_rate = soundfile.read("out.wav")
42
43# speech_array, sampling_rate = soundfile.read("out.wav")
44
45batch["speech"] = speech_array
46batch["sampling_rate"] = sampling_rate
47batch["target_text"] = ""
48batch["input_values"] = torch.from_numpy(np.asarray(processor(speech_array, sampling_rate=22050).input_values)).to("cuda")
49
50with processor.as_target_processor():
51 batch["labels"] = processor("").input_ids
52
53================================================================================================
54
55batch['input_values'][0]
56
57================================================================================================
58
59batch["sampling_rate"]
60
61================================================================================================get_audio() is a function we used in Google Colab to read audio from the user's microphone. The following code does that (Note: this code can only be used in Google Colab, you need to apply changes to use it in a local environment):1"""
2JS Script and python code which read audio from user
3"""
4from IPython.display import HTML, Audio
5from google.colab.output import eval_js
6from base64 import b64decode
7import numpy as np
8from scipy.io.wavfile import read as wav_read
9import io
10import ffmpeg
11
12AUDIO_HTML = """
13<script>
14var my_div = document.createElement("DIV");
15var my_p = document.createElement("P");
16var my_btn = document.createElement("BUTTON");
17var t = document.createTextNode("Press to start recording");
18
19my_btn.appendChild(t);
20//my_p.appendChild(my_btn);
21my_div.appendChild(my_btn);
22document.body.appendChild(my_div);
23
24var base64data = 0;
25var reader;
26var recorder, gumStream;
27var recordButton = my_btn;
28
29var handleSuccess = function(stream) {
30 gumStream = stream;
31 var options = {
32 //bitsPerSecond: 8000, //chrome seems to ignore, always 48k
33 mimeType : 'audio/webm;codecs=opus'
34 //mimeType : 'audio/webm;codecs=pcm'
35 };
36 //recorder = new MediaRecorder(stream, options);
37 recorder = new MediaRecorder(stream);
38 recorder.ondataavailable = function(e) {
39 var url = URL.createObjectURL(e.data);
40 var preview = document.createElement('audio');
41 preview.controls = true;
42 preview.src = url;
43 document.body.appendChild(preview);
44
45 reader = new FileReader();
46 reader.readAsDataURL(e.data);
47 reader.onloadend = function() {
48 base64data = reader.result;
49 //console.log("Inside FileReader:" + base64data);
50 }
51 };
52 recorder.start();
53 };
54
55recordButton.innerText = "Recording... press to stop";
56
57navigator.mediaDevices.getUserMedia({audio: true}).then(handleSuccess);
58
59
60function toggleRecording() {
61 if (recorder && recorder.state == "recording") {
62 recorder.stop();
63 gumStream.getAudioTracks()[0].stop();
64 recordButton.innerText = "Saving the recording... pls wait!"
65 }
66}
67
68// https://stackoverflow.com/a/951057
69function sleep(ms) {
70 return new Promise(resolve => setTimeout(resolve, ms));
71}
72
73var data = new Promise(resolve=>{
74//recordButton.addEventListener("click", toggleRecording);
75recordButton.onclick = ()=>{
76toggleRecording()
77
78sleep(2000).then(() => {
79 // wait 2000ms for the data to be available...
80 // ideally this should use something like await...
81 //console.log("Inside data:" + base64data)
82 resolve(base64data.toString())
83
84});
85
86}
87});
88
89</script>
90"""
91
92def get_audio():
93 display(HTML(AUDIO_HTML))
94 data = eval_js("data")
95 binary = b64decode(data.split(',')[1])
96
97 process = (ffmpeg
98 .input('pipe:0')
99 .output('pipe:1', format='wav')
100 .run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True, quiet=True, overwrite_output=True)
101 )
102 output, err = process.communicate(input=binary)
103
104 riff_chunk_size = len(output) - 8
105 # Break up the chunk size into four bytes, held in b.
106 q = riff_chunk_size
107 b = []
108 for i in range(4):
109 q, r = divmod(q, 256)
110 b.append(r)
111
112 # Replace bytes 4:8 in proc.stdout with the actual size of the RIFF chunk.
113 riff = output[:4] + bytes(b) + output[8:]
114
115 sr, audio = wav_read(io.BytesIO(riff))
116
117 return audio, sr@InProceedings{10.1007/978-3-031-39059-3_17,
author="Bogdanoski, Konstantin
and Mishev, Kostadin
and Simjanoska, Monika
and Trajanov, Dimitar",
editor="Conte, Donatello
and Fred, Ana
and Gusikhin, Oleg
and Sansone, Carlo",
title="Exploring ASR Models in Low-Resource Languages: Use-Case the Macedonian Language",
booktitle="Deep Learning Theory and Applications",
year="2023",
publisher="Springer Nature Switzerland",
address="Cham",
pages="254--268",
abstract="We explore the use of Wav2Vec 2.0, NeMo, and ESPNet models trained on a dataset in Macedonian language for the development of Automatic Speech Recognition (ASR) models for low-resource languages. The study aims to evaluate the performance of recent state-of-the-art models for speech recognition in low-resource languages, such as Macedonian, where there are limited resources available for training or fine-tuning. The paper presents a methodology used for data collection and preprocessing, as well as the details of the three architectures used in the study. The study evaluates the performance of each model using WER and CER metrics and provides a comparative analysis of the results. The findings of the research showed that Wav2Vec 2.0 outperformed the other models for the Macedonian language with a WER of 0.21, and CER of 0.09, however, NeMo and ESPNet models are still good candidates for creating ASR tools for low-resource languages such as Macedonian. The research presented provides insights into the effectiveness of different models for ASR in low-resource languages and highlights the potentials for using these models to develop ASR tools for other languages in the future. These findings have significant implications for the development of ASR tools for other low-resource languages in the future, and can potentially improve accessibility to speech recognition technology for individuals and communities who speak these languages.",
isbn="978-3-031-39059-3"
}