Files changed (5) hide show
  1. README.md +1 -1
  2. app.py +78 -76
  3. requirements.txt +1 -0
  4. sample_diarization_japanese.mp3 +0 -0
  5. share_btn.py +203 -0
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🔥
4
  colorFrom: yellow
5
  colorTo: blue
6
  sdk: gradio
7
- sdk_version: 4.39.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
 
4
  colorFrom: yellow
5
  colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 3.38.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
app.py CHANGED
@@ -1,108 +1,110 @@
1
- import os
2
- from math import floor
3
- from typing import Optional
4
-
5
- import numpy as np
6
- import spaces
7
  import torch
 
8
  import gradio as gr
 
9
  from transformers import pipeline
10
  from transformers.pipelines.audio_utils import ffmpeg_read
11
 
 
 
12
 
13
- # configuration
14
- MODEL_NAME = "kotoba-tech/kotoba-whisper-v2.0"
15
- BATCH_SIZE = 16
16
- CHUNK_LENGTH_S = 15
17
- EXAMPLE = "./sample_diarization_japanese.mp3"
18
-
19
- # device setting
20
- if torch.cuda.is_available():
21
- torch_dtype = torch.bfloat16
22
- device = "cuda"
23
- model_kwargs = {'attn_implementation': 'sdpa'}
24
- else:
25
- torch_dtype = torch.float32
26
- device = "cpu"
27
- model_kwargs = {}
28
 
29
- # define the pipeline
30
  pipe = pipeline(
 
31
  model=MODEL_NAME,
32
- chunk_length_s=CHUNK_LENGTH_S,
33
- batch_size=BATCH_SIZE,
34
- torch_dtype=torch_dtype,
35
  device=device,
36
- model_kwargs=model_kwargs,
37
- trust_remote_code=True
38
  )
39
 
40
 
41
- def format_time(start: Optional[float], end: Optional[float]):
42
-
43
- def _format_time(seconds: Optional[float]):
44
- if seconds is None:
45
- return "complete "
46
- minutes = floor(seconds / 60)
47
- hours = floor(seconds / 3600)
48
- seconds = seconds - hours * 3600 - minutes * 60
49
- m_seconds = floor(round(seconds - floor(seconds), 3) * 10 ** 3)
50
- seconds = floor(seconds)
51
- return f'{hours:02}:{minutes:02}:{seconds:02}.{m_seconds:03}'
52
 
53
- return f"[{_format_time(start)}-> {_format_time(end)}]:"
54
 
 
 
 
55
 
56
- @spaces.GPU
57
- def get_prediction(inputs, prompt: Optional[str]):
58
- generate_kwargs = {"language": "ja", "task": "transcribe"}
59
- if prompt:
60
- generate_kwargs['prompt_ids'] = pipe.tokenizer.get_prompt_ids(prompt, return_tensors='pt').to(device)
61
- prediction = pipe(inputs, return_timestamps=True, generate_kwargs=generate_kwargs)
62
- text = "".join([c['text'] for c in prediction['chunks']])
63
- text_timestamped = "\n".join([f"{format_time(*c['timestamp'])} {c['text']}" for c in prediction['chunks']])
64
- return text, text_timestamped
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
 
67
- def transcribe(inputs: str, prompt):
68
- if inputs is None:
69
- raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
70
- with open(inputs, "rb") as f:
71
- inputs = f.read()
 
 
72
  inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
73
- array_pad = np.zeros(int(pipe.feature_extractor.sampling_rate * 0.5))
74
- inputs = np.concatenate([array_pad, inputs, array_pad])
75
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
76
- return get_prediction(inputs, prompt)
 
77
 
78
 
79
  demo = gr.Blocks()
80
- description = (f"Transcribe long-form microphone or audio inputs with the click of a button! Demo uses Kotoba-Whisper "
81
- f"checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio"
82
- f" files of arbitrary length.")
83
- title = f"Transcribe Audio with {os.path.basename(MODEL_NAME)}"
84
  mf_transcribe = gr.Interface(
85
  fn=transcribe,
86
- inputs=[
87
- gr.Audio(sources="microphone", type="filepath"),
88
- gr.Textbox(lines=1, placeholder="Prompt"),
89
- ],
90
- outputs=["text", "text"],
91
- title=title,
92
- description=description,
93
  allow_flagging="never",
94
  )
 
95
  file_transcribe = gr.Interface(
96
  fn=transcribe,
97
- inputs=[
98
- gr.Audio(sources="upload", type="filepath", label="Audio file"),
99
- gr.Textbox(lines=1, placeholder="Prompt"),
100
- ],
101
- outputs=["text", "text"],
102
- title=title,
103
- description=description,
104
  allow_flagging="never",
105
  )
 
 
 
 
 
 
 
 
 
 
 
106
  with demo:
107
- gr.TabbedInterface([mf_transcribe, file_transcribe], ["Microphone", "Audio file"])
108
- demo.queue(api_open=False, default_concurrency_limit=40).launch(show_api=False, show_error=True)
 
 
 
 
 
 
 
 
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 = "kotoba-tech/kotoba-whisper-v1.0"
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
  pipe = pipeline(
18
+ task="automatic-speech-recognition",
19
  model=MODEL_NAME,
20
+ chunk_length_s=30,
 
 
21
  device=device,
 
 
22
  )
23
 
24
 
25
+ def transcribe(inputs):
26
+ if inputs is None:
27
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
28
+ return pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": "transcribe"}, return_timestamps=True)["text"]
 
 
 
 
 
 
 
29
 
 
30
 
31
+ def _return_yt_html_embed(yt_url):
32
+ video_id = yt_url.split("?v=")[-1]
33
+ return f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe> </center>'
34
 
35
+ def download_yt_audio(yt_url, filename):
36
+ info_loader = youtube_dl.YoutubeDL()
37
+ try:
38
+ info = info_loader.extract_info(yt_url, download=False)
39
+ except youtube_dl.utils.DownloadError as err:
40
+ raise gr.Error(str(err))
41
+ file_length = info["duration_string"]
42
+ file_h_m_s = file_length.split(":")
43
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
44
+ if len(file_h_m_s) == 1:
45
+ file_h_m_s.insert(0, 0)
46
+ if len(file_h_m_s) == 2:
47
+ file_h_m_s.insert(0, 0)
48
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
49
+ if file_length_s > YT_LENGTH_LIMIT_S:
50
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
51
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
52
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
53
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
54
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
55
+ try:
56
+ ydl.download([yt_url])
57
+ except youtube_dl.utils.ExtractorError as err:
58
+ raise gr.Error(str(err))
59
 
60
 
61
+ def yt_transcribe(yt_url, max_filesize=75.0):
62
+ html_embed_str = _return_yt_html_embed(yt_url)
63
+ with tempfile.TemporaryDirectory() as tmpdirname:
64
+ filepath = os.path.join(tmpdirname, "video.mp4")
65
+ download_yt_audio(yt_url, filepath)
66
+ with open(filepath, "rb") as f:
67
+ inputs = f.read()
68
  inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
 
 
69
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
70
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": "transcribe"}, return_timestamps=True)["text"]
71
+ return html_embed_str, text
72
 
73
 
74
  demo = gr.Blocks()
 
 
 
 
75
  mf_transcribe = gr.Interface(
76
  fn=transcribe,
77
+ inputs=[gr.inputs.Audio(source="microphone", type="filepath", optional=True)],
78
+ outputs="text",
79
+ layout="horizontal",
80
+ theme="huggingface",
81
+ title=f"Transcribe Audio with {os.path.basename(MODEL_NAME)}",
82
+ description=f"Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the Kotoba-Whisper checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files of arbitrary length.",
 
83
  allow_flagging="never",
84
  )
85
+
86
  file_transcribe = gr.Interface(
87
  fn=transcribe,
88
+ inputs=[gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file")],
89
+ outputs="text",
90
+ layout="horizontal",
91
+ theme="huggingface",
92
+ title=f"Transcribe Audio with {os.path.basename(MODEL_NAME)}",
93
+ description=f"Transcribe long-form microphone or audio inputs with the click of a button! Demo uses Kotoba-Whisper checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files of arbitrary length.",
 
94
  allow_flagging="never",
95
  )
96
+ yt_transcribe = gr.Interface(
97
+ fn=yt_transcribe,
98
+ inputs=[gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL")],
99
+ outputs=["html", "text"],
100
+ layout="horizontal",
101
+ theme="huggingface",
102
+ title=f"Transcribe YouTube with {os.path.basename(MODEL_NAME)}",
103
+ description=f"Transcribe long-form YouTube videos with the click of a button! Demo uses Kotoba-Whisper checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of arbitrary length.",
104
+ allow_flagging="never",
105
+ )
106
+
107
  with demo:
108
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
109
+
110
+ demo.launch(enable_queue=True)
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
  git+https://github.com/huggingface/transformers
2
  torch
 
 
1
  git+https://github.com/huggingface/transformers
2
  torch
3
+ yt-dlp
sample_diarization_japanese.mp3 DELETED
Binary file (780 kB)
 
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
+ }"""