Sharfraz commited on
Commit
5f0ba81
β€’
1 Parent(s): 96d5c7e

Upload 6 files

Browse files
Files changed (6) hide show
  1. README.md +6 -6
  2. app.py +149 -1
  3. gitattributes +31 -0
  4. packages.txt +1 -0
  5. requirements.txt +3 -0
  6. share_btn.py +203 -0
README.md CHANGED
@@ -1,10 +1,10 @@
1
  ---
2
- title: Openai Whisper Large V3
3
- emoji: πŸš€
4
- colorFrom: yellow
5
- colorTo: green
6
- sdk: streamlit
7
- sdk_version: 1.40.1
8
  app_file: app.py
9
  pinned: false
10
  ---
 
1
  ---
2
+ title: Whisper
3
+ emoji: πŸ“‰
4
+ colorFrom: pink
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 3.38.0
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py CHANGED
@@ -1,3 +1,151 @@
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- gr.load("models/openai/whisper-large-v3").launch()
 
1
+ import torch
2
+
3
  import gradio as gr
4
+ import yt_dlp as youtube_dl
5
+ from transformers import pipeline
6
+ from transformers.pipelines.audio_utils import ffmpeg_read
7
+
8
+ import tempfile
9
+ import os
10
+
11
+ MODEL_NAME = "openai/whisper-large-v3"
12
+ BATCH_SIZE = 8
13
+ FILE_LIMIT_MB = 1000
14
+ YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
15
+
16
+ device = 0 if torch.cuda.is_available() else "cpu"
17
+
18
+ pipe = pipeline(
19
+ task="automatic-speech-recognition",
20
+ model=MODEL_NAME,
21
+ chunk_length_s=30,
22
+ device=device,
23
+ )
24
+
25
+
26
+ def transcribe(inputs, task):
27
+ if inputs is None:
28
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
29
+
30
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
31
+ return text
32
+
33
+
34
+ def _return_yt_html_embed(yt_url):
35
+ video_id = yt_url.split("?v=")[-1]
36
+ HTML_str = (
37
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
38
+ " </center>"
39
+ )
40
+ return HTML_str
41
+
42
+ def download_yt_audio(yt_url, filename):
43
+ info_loader = youtube_dl.YoutubeDL()
44
+
45
+ try:
46
+ info = info_loader.extract_info(yt_url, download=False)
47
+ except youtube_dl.utils.DownloadError as err:
48
+ raise gr.Error(str(err))
49
+
50
+ file_length = info["duration_string"]
51
+ file_h_m_s = file_length.split(":")
52
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
53
+
54
+ if len(file_h_m_s) == 1:
55
+ file_h_m_s.insert(0, 0)
56
+ if len(file_h_m_s) == 2:
57
+ file_h_m_s.insert(0, 0)
58
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
59
+
60
+ if file_length_s > YT_LENGTH_LIMIT_S:
61
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
62
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
63
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
64
+
65
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
66
+
67
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
68
+ try:
69
+ ydl.download([yt_url])
70
+ except youtube_dl.utils.ExtractorError as err:
71
+ raise gr.Error(str(err))
72
+
73
+
74
+ def yt_transcribe(yt_url, task, max_filesize=75.0):
75
+ html_embed_str = _return_yt_html_embed(yt_url)
76
+
77
+ with tempfile.TemporaryDirectory() as tmpdirname:
78
+ filepath = os.path.join(tmpdirname, "video.mp4")
79
+ download_yt_audio(yt_url, filepath)
80
+ with open(filepath, "rb") as f:
81
+ inputs = f.read()
82
+
83
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
84
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
85
+
86
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
87
+
88
+ return html_embed_str, text
89
+
90
+
91
+ demo = gr.Blocks()
92
+
93
+ mf_transcribe = gr.Interface(
94
+ fn=transcribe,
95
+ inputs=[
96
+ gr.inputs.Audio(source="microphone", type="filepath", optional=True),
97
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
98
+ ],
99
+ outputs="text",
100
+ layout="horizontal",
101
+ theme="huggingface",
102
+ title="Whisper Large V3: Transcribe Audio",
103
+ description=(
104
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the OpenAI Whisper"
105
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and πŸ€— Transformers to transcribe audio files"
106
+ " of arbitrary length."
107
+ ),
108
+ allow_flagging="never",
109
+ )
110
+
111
+ file_transcribe = gr.Interface(
112
+ fn=transcribe,
113
+ inputs=[
114
+ gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
115
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
116
+ ],
117
+ outputs="text",
118
+ layout="horizontal",
119
+ theme="huggingface",
120
+ title="Whisper Large V3: Transcribe Audio",
121
+ description=(
122
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the OpenAI Whisper"
123
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and πŸ€— Transformers to transcribe audio files"
124
+ " of arbitrary length."
125
+ ),
126
+ allow_flagging="never",
127
+ )
128
+
129
+ yt_transcribe = gr.Interface(
130
+ fn=yt_transcribe,
131
+ inputs=[
132
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
133
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe")
134
+ ],
135
+ outputs=["html", "text"],
136
+ layout="horizontal",
137
+ theme="huggingface",
138
+ title="Whisper Large V3: Transcribe YouTube",
139
+ description=(
140
+ "Transcribe long-form YouTube videos with the click of a button! Demo uses the OpenAI Whisper checkpoint"
141
+ f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and πŸ€— Transformers to transcribe video files of"
142
+ " arbitrary length."
143
+ ),
144
+ allow_flagging="never",
145
+ )
146
+
147
+ with demo:
148
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
149
+
150
+ demo.launch(enable_queue=True)
151
 
 
gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zst filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ git+https://github.com/huggingface/transformers
2
+ torch
3
+ yt-dlp
share_btn.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
26
+ function audioResample(buffer, sampleRate){
27
+ const offlineCtx = new OfflineAudioContext(2, (buffer.length / buffer.sampleRate) * sampleRate, sampleRate);
28
+ const source = offlineCtx.createBufferSource();
29
+ source.buffer = buffer;
30
+ source.connect(offlineCtx.destination);
31
+ source.start();
32
+ return offlineCtx.startRendering();
33
+ };
34
+
35
+ function audioReduceChannels(buffer, targetChannelOpt){
36
+ if(targetChannelOpt === 'both' || buffer.numberOfChannels < 2) return buffer;
37
+ const outBuffer = new AudioBuffer({
38
+ sampleRate: buffer.sampleRate,
39
+ length: buffer.length,
40
+ numberOfChannels: 1
41
+ });
42
+
43
+ const data = [buffer.getChannelData(0), buffer.getChannelData(1)];
44
+ const newData = new Float32Array(buffer.length);
45
+ for(let i = 0; i < buffer.length; ++i)
46
+ newData[i] =
47
+ targetChannelOpt === 'left'? data[0][i] :
48
+ targetChannelOpt === 'right'? data[1][i] :
49
+ (data[0][i] + data[1][i]) / 2 ;
50
+ outBuffer.copyToChannel(newData, 0);
51
+ return outBuffer;
52
+ };
53
+
54
+ function audioNormalize(buffer){
55
+ const data = Array.from(Array(buffer.numberOfChannels)).map((_, idx) => buffer.getChannelData(idx));
56
+ const maxAmplitude = Math.max(...data.map(chan => chan.reduce((acc, cur) => Math.max(acc, Math.abs(cur)), 0)));
57
+ if(maxAmplitude >= 1.0) return buffer;
58
+ const coeff = 1.0 / maxAmplitude;
59
+ data.forEach(chan => {
60
+ chan.forEach((v, idx) => chan[idx] = v*coeff);
61
+ buffer.copyToChannel(chan, 0);
62
+ });
63
+ return buffer;
64
+ };
65
+
66
+ async function processAudioFile(
67
+ audioBufferIn,
68
+ targetChannelOpt,
69
+ targetSampleRate
70
+ ) {
71
+ const resampled = await audioResample(audioBufferIn, targetSampleRate);
72
+ const reduced = audioReduceChannels(resampled, targetChannelOpt);
73
+ const normalized = audioNormalize(reduced);
74
+ return normalized;
75
+ }
76
+
77
+ function audioToRawWave(audioChannels, bytesPerSample, mixChannels=false) {
78
+ const bufferLength = audioChannels[0].length;
79
+ const numberOfChannels = audioChannels.length === 1 ? 1 : 2;
80
+ const reducedData = new Uint8Array(
81
+ bufferLength * numberOfChannels * bytesPerSample
82
+ );
83
+ for (let i = 0; i < bufferLength; ++i) {
84
+ for (
85
+ let channel = 0;
86
+ channel < (mixChannels ? 1 : numberOfChannels);
87
+ ++channel
88
+ ) {
89
+ const outputIndex = (i * numberOfChannels + channel) * bytesPerSample;
90
+ let sample;
91
+ if (!mixChannels) sample = audioChannels[channel][i];
92
+ else
93
+ sample =
94
+ audioChannels.reduce((prv, cur) => prv + cur[i], 0) /
95
+ numberOfChannels;
96
+ sample = sample > 1 ? 1 : sample < -1 ? -1 : sample; //check for clipping
97
+ //bit reduce and convert to Uint8
98
+ switch (bytesPerSample) {
99
+ case 2:
100
+ sample = sample * 32767;
101
+ reducedData[outputIndex] = sample;
102
+ reducedData[outputIndex + 1] = sample >> 8;
103
+ break;
104
+ case 1:
105
+ reducedData[outputIndex] = (sample + 1) * 127;
106
+ break;
107
+ default:
108
+ throw "Only 8, 16 bits per sample are supported";
109
+ }
110
+ }
111
+ }
112
+ return reducedData;
113
+ }
114
+
115
+ function makeWav(data, channels, sampleRate, bytesPerSample) {
116
+ const headerLength = 44;
117
+ var wav = new Uint8Array(headerLength + data.length);
118
+ var view = new DataView(wav.buffer);
119
+
120
+ view.setUint32(0, 1380533830, false); // RIFF identifier 'RIFF'
121
+ view.setUint32(4, 36 + data.length, true); // file length minus RIFF identifier length and file description length
122
+ view.setUint32(8, 1463899717, false); // RIFF type 'WAVE'
123
+ view.setUint32(12, 1718449184, false); // format chunk identifier 'fmt '
124
+ view.setUint32(16, 16, true); // format chunk length
125
+ view.setUint16(20, 1, true); // sample format (raw)
126
+ view.setUint16(22, channels, true); // channel count
127
+ view.setUint32(24, sampleRate, true); // sample rate
128
+ view.setUint32(28, sampleRate * bytesPerSample * channels, true); // byte rate (sample rate * block align)
129
+ view.setUint16(32, bytesPerSample * channels, true); // block align (channel count * bytes per sample)
130
+ view.setUint16(34, bytesPerSample * 8, true); // bits per sample
131
+ view.setUint32(36, 1684108385, false); // data chunk identifier 'data'
132
+ view.setUint32(40, data.length, true); // data chunk length
133
+
134
+ wav.set(data, headerLength);
135
+
136
+ return new Blob([wav.buffer], { type: "audio/wav" });
137
+ }
138
+
139
+ const gradioEl = document.querySelector('body > gradio-app');
140
+ const audioEl = gradioEl.querySelector('audio');
141
+ const resultTxt = gradioEl.querySelector('#result-textarea textarea').value;
142
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
143
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
144
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
145
+
146
+ if(!audioEl){
147
+ return;
148
+ };
149
+
150
+ shareBtnEl.style.pointerEvents = 'none';
151
+ shareIconEl.style.display = 'none';
152
+ loadingIconEl.style.removeProperty('display');
153
+
154
+ const res = await fetch(audioEl.src);
155
+ const blob = await res.blob();
156
+
157
+ const channelOpt = "both";
158
+ const sampleRate = 48000;
159
+ const bytesPerSample = 1; // or 2
160
+ const audioBufferIn = await new AudioContext().decodeAudioData(
161
+ await blob.arrayBuffer()
162
+ );
163
+ const audioBuffer = await processAudioFile(
164
+ audioBufferIn,
165
+ channelOpt,
166
+ sampleRate
167
+ );
168
+ const rawData = audioToRawWave(
169
+ channelOpt === "both"
170
+ ? [audioBuffer.getChannelData(0), audioBuffer.getChannelData(1)]
171
+ : [audioBuffer.getChannelData(0)],
172
+ bytesPerSample
173
+ );
174
+ const blobWav = makeWav(
175
+ rawData,
176
+ channelOpt === "both" ? 2 : 1,
177
+ sampleRate,
178
+ bytesPerSample
179
+ );
180
+
181
+ const fileName = `whisper-demo-input.wav`;
182
+ const audioFile = new File([blobWav], fileName, { type: 'audio/wav' });
183
+
184
+ const url = await uploadFile(audioFile);
185
+
186
+ const descriptionMd = `#### Input audio:
187
+ <audio controls src='${url}'></audio>
188
+
189
+ #### Transcription:
190
+
191
+ > ${resultTxt}`;
192
+
193
+ const params = new URLSearchParams({
194
+ description: descriptionMd,
195
+ });
196
+
197
+ const paramsStr = params.toString();
198
+ window.open(`https://huggingface.co/spaces/openai/whisper/discussions/new?${paramsStr}`, '_blank');
199
+
200
+ shareBtnEl.style.removeProperty('pointer-events');
201
+ shareIconEl.style.removeProperty('display');
202
+ loadingIconEl.style.display = 'none';
203
+ }"""