Rezuwan commited on
Commit
d211629
·
verified ·
1 Parent(s): 90dc294

Upload 4 files

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. app.py +77 -0
  3. requirements.txt +8 -0
  4. screenshot.jpg +3 -0
  5. share_btn.py +180 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ screenshot.jpg filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import librosa
4
+ import torch
5
+ import numpy as np
6
+
7
+ MODEL_NAME = 'Rezuwan/regional_asr_weights'
8
+ #device = 0 if torch.cuda.is_available() else "cpu"
9
+ BATCH_SIZE = 8
10
+ FILE_LIMIT_MB = 1000
11
+
12
+ transcriber = pipeline(
13
+ task="automatic-speech-recognition",
14
+ model=MODEL_NAME,
15
+ chunk_length_s=30,
16
+ #device=device,
17
+ )
18
+
19
+ # Function to preprocess the audio and transcribe it
20
+ def transcribe_audio(audio_path):
21
+ if audio_path is None:
22
+ return "No audio provided."
23
+
24
+ try:
25
+ # If audio is a tuple, it is from the microphone (Gradio input type)
26
+ if isinstance(audio, tuple):
27
+ sample_rate, audio_data = audio_path # Unpack the tuple (sample rate, numpy array)
28
+ else:
29
+ # If audio is a file, it will be a file path (for file uploads)
30
+ audio_data, sample_rate = librosa.load(audio_path, sr=16000) # Load the audio file using librosa
31
+
32
+
33
+
34
+ # Convert to mono-channel if necessary (if the audio is stereo)
35
+ audio_data = librosa.to_mono(audio_data) if audio_data.ndim > 1 else audio_data
36
+ audio_data = audio_data.astype(np.float32)
37
+ audio_data /= np.max(np.abs(audio_data))
38
+ result = transcriber(audio_data)
39
+ return result["text"]
40
+
41
+
42
+ except Exception as e:
43
+ return f"Error: {str(e)}"
44
+
45
+ # Create the Gradio interface for both file upload and microphone input
46
+ iface = gr.Interface(
47
+ fn=transcribe_audio,
48
+ inputs=gr.Audio(type="filepath", label="Upload or Record Audio", interactive=True), # 'filepath' ensures file uploads provide a path for librosa to load
49
+ outputs="text",
50
+ title="Bengali Speech-to-Text with Regional Dialects",
51
+ description=(
52
+ f"""
53
+ Model Card: [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files of arbitrary length. [Do leave a like (❤️) on the model card and this space]
54
+
55
+ Instructions:
56
+
57
+ 1. Click on 'Record' option in the left 'Upload or Record Audio' section and record the audio.
58
+ 2. When done recording, click on 'Stop' button and give it some time until some waveform shows up in the 'Upload or Record Audio' section (Same goes when uploading pre-recorded audio files) and then click the 'Submit' button.
59
+ 3. Wait for the audio clip to be processed (This could take a while 😅. Still needs work on the inference time) and then transcription of the audio will appear on the right 'output' section.
60
+ 4. If want to submit a trimmed version of the input, select the trimmed audio snippet and then click 'Trim' and then wait a bit until wavform
61
+ shows up in the input section of the interface and then click 'Submit'.
62
+
63
+
64
+
65
+ Note:
66
+
67
+ 1. Since the corpus used to fine-tune this model was really small, The orthography might still not be upto the mark but it gets the work done but still needs work and manual validation.
68
+
69
+ 2.With proper data and a larger version of the corpus, I guess I'll be able to increase it's transcription performance of the Bengali speech with regional dialects.
70
+
71
+ ![](screenshot.jpg)
72
+ """
73
+ ),
74
+ allow_flagging="never",
75
+ )
76
+
77
+ iface.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ git+httpsgithub.comhuggingfacetransformers
2
+ gradio
3
+ numpy
4
+ torchaudio
5
+ torch
6
+ yt-dlp
7
+ librosa
8
+ soundfile
screenshot.jpg ADDED

Git LFS Details

  • SHA256: 096f3549eb06950bd9166c971be38ba5fc147de857175203d8dd7739a867ea0b
  • Pointer size: 131 Bytes
  • Size of remote file: 158 kB
share_btn.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
+
11
+ share_js = """async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': 'audio/wav',
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file, /// <- File inherits from Blob
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+ function audioResample(buffer, sampleRate){
26
+ const offlineCtx = new OfflineAudioContext(2, (buffer.length / buffer.sampleRate) * sampleRate, sampleRate);
27
+ const source = offlineCtx.createBufferSource();
28
+ source.buffer = buffer;
29
+ source.connect(offlineCtx.destination);
30
+ source.start();
31
+ return offlineCtx.startRendering();
32
+ };
33
+ function audioReduceChannels(buffer, targetChannelOpt){
34
+ if(targetChannelOpt === 'both' || buffer.numberOfChannels < 2) return buffer;
35
+ const outBuffer = new AudioBuffer({
36
+ sampleRate: buffer.sampleRate,
37
+ length: buffer.length,
38
+ numberOfChannels: 1
39
+ });
40
+ const data = [buffer.getChannelData(0), buffer.getChannelData(1)];
41
+ const newData = new Float32Array(buffer.length);
42
+ for(let i = 0; i < buffer.length; ++i)
43
+ newData[i] =
44
+ targetChannelOpt === 'left'? data[0][i] :
45
+ targetChannelOpt === 'right'? data[1][i] :
46
+ (data[0][i] + data[1][i]) / 2 ;
47
+ outBuffer.copyToChannel(newData, 0);
48
+ return outBuffer;
49
+ };
50
+ function audioNormalize(buffer){
51
+ const data = Array.from(Array(buffer.numberOfChannels)).map((_, idx) => buffer.getChannelData(idx));
52
+ const maxAmplitude = Math.max(...data.map(chan => chan.reduce((acc, cur) => Math.max(acc, Math.abs(cur)), 0)));
53
+ if(maxAmplitude >= 1.0) return buffer;
54
+ const coeff = 1.0 / maxAmplitude;
55
+ data.forEach(chan => {
56
+ chan.forEach((v, idx) => chan[idx] = v*coeff);
57
+ buffer.copyToChannel(chan, 0);
58
+ });
59
+ return buffer;
60
+ };
61
+ async function processAudioFile(
62
+ audioBufferIn,
63
+ targetChannelOpt,
64
+ targetSampleRate
65
+ ) {
66
+ const resampled = await audioResample(audioBufferIn, targetSampleRate);
67
+ const reduced = audioReduceChannels(resampled, targetChannelOpt);
68
+ const normalized = audioNormalize(reduced);
69
+ return normalized;
70
+ }
71
+ function audioToRawWave(audioChannels, bytesPerSample, mixChannels=false) {
72
+ const bufferLength = audioChannels[0].length;
73
+ const numberOfChannels = audioChannels.length === 1 ? 1 : 2;
74
+ const reducedData = new Uint8Array(
75
+ bufferLength * numberOfChannels * bytesPerSample
76
+ );
77
+ for (let i = 0; i < bufferLength; ++i) {
78
+ for (
79
+ let channel = 0;
80
+ channel < (mixChannels ? 1 : numberOfChannels);
81
+ ++channel
82
+ ) {
83
+ const outputIndex = (i * numberOfChannels + channel) * bytesPerSample;
84
+ let sample;
85
+ if (!mixChannels) sample = audioChannels[channel][i];
86
+ else
87
+ sample =
88
+ audioChannels.reduce((prv, cur) => prv + cur[i], 0) /
89
+ numberOfChannels;
90
+ sample = sample > 1 ? 1 : sample < -1 ? -1 : sample; //check for clipping
91
+ //bit reduce and convert to Uint8
92
+ switch (bytesPerSample) {
93
+ case 2:
94
+ sample = sample * 32767;
95
+ reducedData[outputIndex] = sample;
96
+ reducedData[outputIndex + 1] = sample >> 8;
97
+ break;
98
+ case 1:
99
+ reducedData[outputIndex] = (sample + 1) * 127;
100
+ break;
101
+ default:
102
+ throw "Only 8, 16 bits per sample are supported";
103
+ }
104
+ }
105
+ }
106
+ return reducedData;
107
+ }
108
+ function makeWav(data, channels, sampleRate, bytesPerSample) {
109
+ const headerLength = 44;
110
+ var wav = new Uint8Array(headerLength + data.length);
111
+ var view = new DataView(wav.buffer);
112
+ view.setUint32(0, 1380533830, false); // RIFF identifier 'RIFF'
113
+ view.setUint32(4, 36 + data.length, true); // file length minus RIFF identifier length and file description length
114
+ view.setUint32(8, 1463899717, false); // RIFF type 'WAVE'
115
+ view.setUint32(12, 1718449184, false); // format chunk identifier 'fmt '
116
+ view.setUint32(16, 16, true); // format chunk length
117
+ view.setUint16(20, 1, true); // sample format (raw)
118
+ view.setUint16(22, channels, true); // channel count
119
+ view.setUint32(24, sampleRate, true); // sample rate
120
+ view.setUint32(28, sampleRate * bytesPerSample * channels, true); // byte rate (sample rate * block align)
121
+ view.setUint16(32, bytesPerSample * channels, true); // block align (channel count * bytes per sample)
122
+ view.setUint16(34, bytesPerSample * 8, true); // bits per sample
123
+ view.setUint32(36, 1684108385, false); // data chunk identifier 'data'
124
+ view.setUint32(40, data.length, true); // data chunk length
125
+ wav.set(data, headerLength);
126
+ return new Blob([wav.buffer], { type: "audio/wav" });
127
+ }
128
+ const gradioEl = document.querySelector('body > gradio-app');
129
+ const audioEl = gradioEl.querySelector('audio');
130
+ const resultTxt = gradioEl.querySelector('#result-textarea textarea').value;
131
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
132
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
133
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
134
+ if(!audioEl){
135
+ return;
136
+ };
137
+ shareBtnEl.style.pointerEvents = 'none';
138
+ shareIconEl.style.display = 'none';
139
+ loadingIconEl.style.removeProperty('display');
140
+ const res = await fetch(audioEl.src);
141
+ const blob = await res.blob();
142
+ const channelOpt = "both";
143
+ const sampleRate = 48000;
144
+ const bytesPerSample = 1; // or 2
145
+ const audioBufferIn = await new AudioContext().decodeAudioData(
146
+ await blob.arrayBuffer()
147
+ );
148
+ const audioBuffer = await processAudioFile(
149
+ audioBufferIn,
150
+ channelOpt,
151
+ sampleRate
152
+ );
153
+ const rawData = audioToRawWave(
154
+ channelOpt === "both"
155
+ ? [audioBuffer.getChannelData(0), audioBuffer.getChannelData(1)]
156
+ : [audioBuffer.getChannelData(0)],
157
+ bytesPerSample
158
+ );
159
+ const blobWav = makeWav(
160
+ rawData,
161
+ channelOpt === "both" ? 2 : 1,
162
+ sampleRate,
163
+ bytesPerSample
164
+ );
165
+ const fileName = `whisper-demo-input.wav`;
166
+ const audioFile = new File([blobWav], fileName, { type: 'audio/wav' });
167
+ const url = await uploadFile(audioFile);
168
+ const descriptionMd = `#### Input audio:
169
+ <audio controls src='${url}'></audio>
170
+ #### Transcription:
171
+ > ${resultTxt}`;
172
+ const params = new URLSearchParams({
173
+ description: descriptionMd,
174
+ });
175
+ const paramsStr = params.toString();
176
+ window.open(`https://huggingface.co/spaces/openai/whisper/discussions/new?${paramsStr}`, '_blank');
177
+ shareBtnEl.style.removeProperty('pointer-events');
178
+ shareIconEl.style.removeProperty('display');
179
+ loadingIconEl.style.display = 'none';
180
+ }"""