ovieyra21 commited on
Commit
b51dfa4
1 Parent(s): 3e9badc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -182
app.py CHANGED
@@ -1,21 +1,10 @@
1
  import torch
2
  import gradio as gr
3
- import yt_dlp as youtube_dl
4
- import numpy as np
5
- from datasets import Dataset, Audio
6
- from scipy.io import wavfile
7
  from transformers import pipeline
8
- from transformers.pipelines.audio_utils import ffmpeg_read
9
- import tempfile
10
- import os
11
- import time
12
- import demucs.api
13
 
14
- MODEL_NAME = "openai/whisper-large-v3" # "patrickvonplaten/wav2vec2-large-960h-lv60-self-4-gram" #
15
- DEMUCS_MODEL_NAME = "htdemucs_ft"
16
  BATCH_SIZE = 8
17
- FILE_LIMIT_MB = 1000
18
- YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
19
 
20
  device = 0 if torch.cuda.is_available() else "cpu"
21
 
@@ -26,181 +15,30 @@ pipe = pipeline(
26
  device=device,
27
  )
28
 
29
- separator = demucs.api.Separator(model=DEMUCS_MODEL_NAME, )
30
-
31
- def separate_vocal(path):
32
- origin, separated = separator.separate_audio_file(path)
33
- demucs.api.save_audio(separated["vocals"], path, samplerate=separator.samplerate)
34
- return path
35
-
36
- def transcribe(inputs_path, task, use_demucs, dataset_name, oauth_token: gr.OAuthToken | None, progress=gr.Progress()):
37
  if inputs_path is None:
38
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
39
- if dataset_name is None:
40
- raise gr.Error("No dataset name submitted! Please submit a dataset name. Should be in the format : <user>/<dataset_name> or <org>/<dataset_name>. Also accepts <dataset_name>, which will default to the namespace of the logged-in user.")
41
-
42
- if oauth_token is None:
43
- gr.Warning("Make sure to click and login before using this demo.")
44
- return [["transcripts will appear here"]], ""
45
-
46
- total_step = 4
47
- current_step = 0
48
 
49
- current_step += 1
50
- progress((current_step, total_step), desc="Transcribe using Whisper.")
51
-
52
  sampling_rate, inputs = wavfile.read(inputs_path)
53
-
54
  out = pipe(inputs_path, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
55
-
56
  text = out["text"]
57
 
58
- current_step += 1
59
- progress((current_step, total_step), desc="Merge chunks.")
60
- chunks = naive_postprocess_whisper_chunks(out["chunks"], inputs, sampling_rate)
61
-
62
- current_step += 1
63
- progress((current_step, total_step), desc="Create dataset.")
64
-
65
- transcripts = []
66
- audios = []
67
- with tempfile.TemporaryDirectory() as tmpdirname:
68
- for i, chunk in enumerate(progress.tqdm(chunks, desc="Creating dataset (and clean audio if asked for)")):
69
- arr = chunk["audio"]
70
- path = os.path.join(tmpdirname, f"{i}.wav")
71
- wavfile.write(path, sampling_rate, arr)
72
-
73
- if use_demucs == "separate-audio":
74
- print(f"Separating vocals #{i}")
75
- path = separate_vocal(path)
76
-
77
- audios.append(path)
78
- transcripts.append(chunk["text"])
79
-
80
- dataset = Dataset.from_dict({"audio": audios, "text": transcripts}).cast_column("audio", Audio())
81
-
82
- current_step += 1
83
- progress((current_step, total_step), desc="Push dataset.")
84
- dataset.push_to_hub(dataset_name, token=oauth_token.token if oauth_token else oauth_token)
85
-
86
- return [[transcript] for transcript in transcripts], text
87
-
88
- def _return_yt_html_embed(yt_url):
89
- video_id = yt_url.split("?v=")[-1]
90
- HTML_str = (
91
- f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
92
- " </center>"
93
  )
94
- return HTML_str
95
-
96
- def download_yt_audio(yt_url, filename):
97
- info_loader = youtube_dl.YoutubeDL()
98
-
99
- try:
100
- info = info_loader.extract_info(yt_url, download=False)
101
- except youtube_dl.utils.DownloadError as err:
102
- raise gr.Error(str(err))
103
-
104
- file_length = info["duration_string"]
105
- file_h_m_s = file_length.split(":")
106
- file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
107
-
108
- if len(file_h_m_s) == 1:
109
- file_h_m_s.insert(0, 0)
110
- if len(file_h_m_s) == 2:
111
- file_h_m_s.insert(0, 0)
112
- file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
113
-
114
- if file_length_s > YT_LENGTH_LIMIT_S:
115
- yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
116
- file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
117
- raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
118
-
119
- ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
120
-
121
- with youtube_dl.YoutubeDL(ydl_opts) as ydl:
122
- try:
123
- ydl.download([yt_url])
124
- except youtube_dl.utils.ExtractorError as err:
125
- raise gr.Error(str(err))
126
-
127
- def yt_transcribe(yt_url, task, use_demucs, dataset_name, oauth_token: gr.OAuthToken | None, max_filesize=75.0, dataset_sampling_rate=24000, progress=gr.Progress()):
128
- if yt_url is None:
129
- raise gr.Error("No youtube link submitted! Please put a working link.")
130
- if dataset_name is None:
131
- raise gr.Error("No dataset name submitted! Please submit a dataset name. Should be in the format : <user>/<dataset_name> or <org>/<dataset_name>. Also accepts <dataset_name>, which will default to the namespace of the logged-in user.")
132
-
133
- total_step = 5
134
- current_step = 0
135
-
136
- html_embed_str = _return_yt_html_embed(yt_url)
137
-
138
- if oauth_token is None:
139
- gr.Warning("Make sure to click and login before using this demo.")
140
- return html_embed_str, [["transcripts will appear here"]], ""
141
-
142
- current_step += 1
143
- progress((current_step, total_step), desc="Load video.")
144
-
145
- with tempfile.TemporaryDirectory() as tmpdirname:
146
- filepath = os.path.join(tmpdirname, "video.mp4")
147
-
148
- download_yt_audio(yt_url, filepath)
149
- with open(filepath, "rb") as f:
150
- inputs_path = f.read()
151
-
152
- inputs = ffmpeg_read(inputs_path, pipe.feature_extractor.sampling_rate)
153
- inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
154
-
155
- current_step += 1
156
- progress((current_step, total_step), desc="Transcribe using Whisper.")
157
- out = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
158
-
159
- text = out["text"]
160
-
161
- inputs = ffmpeg_read(inputs_path, dataset_sampling_rate)
162
-
163
- current_step += 1
164
- progress((current_step, total_step), desc="Merge chunks.")
165
- chunks = naive_postprocess_whisper_chunks(out["chunks"], inputs, dataset_sampling_rate)
166
-
167
- current_step += 1
168
- progress((current_step, total_step), desc="Create dataset.")
169
-
170
- transcripts = []
171
- audios = []
172
- with tempfile.TemporaryDirectory() as tmpdirname:
173
- for i, chunk in enumerate(progress.tqdm(chunks, desc="Creating dataset (and clean audio if asked for).")):
174
- arr = chunk["audio"]
175
- path = os.path.join(tmpdirname, f"{i}.wav")
176
- wavfile.write(path, dataset_sampling_rate, arr)
177
-
178
- if use_demucs == "separate-audio":
179
- print(f"Separating vocals #{i}")
180
- path = separate_vocal(path)
181
-
182
- audios.append(path)
183
- transcripts.append(chunk["text"])
184
-
185
- dataset = Dataset.from_dict({"audio": audios, "text": transcripts}).cast_column("audio", Audio())
186
-
187
- current_step += 1
188
- progress((current_step, total_step), desc="Push dataset.")
189
- dataset.push_to_hub(dataset_name, token=oauth_token.token if oauth_token else oauth_token)
190
-
191
- return html_embed_str, [[transcript] for transcript in transcripts], text
192
 
193
- def naive_postprocess_whisper_chunks(chunks, audio_array, sampling_rate, stop_chars=".!:;?", min_duration=5):
194
- min_duration = int(min_duration * sampling_rate)
195
- new_chunks = []
196
- while chunks:
197
- current_chunk = chunks.pop(0)
198
- begin, end = current_chunk["timestamp"]
199
- begin, end = int(begin * sampling_rate), int(end * sampling_rate)
200
- current_dur = end - begin
201
- text = current_chunk["text"]
202
- chunk_to_concat = [audio_array[begin:end]]
203
- while chunks and (text[-1] not in stop_chars or (current_dur < min_duration)):
204
- ch = chunks.pop(0)
205
- begin, end = ch["timestamp"]
206
- begin, end = int(begin * sampling_rate), int(end * sampling_rate)
 
1
  import torch
2
  import gradio as gr
 
 
 
 
3
  from transformers import pipeline
4
+ from scipy.io import wavfile
 
 
 
 
5
 
6
+ MODEL_NAME = "openai/whisper-large-v3"
 
7
  BATCH_SIZE = 8
 
 
8
 
9
  device = 0 if torch.cuda.is_available() else "cpu"
10
 
 
15
  device=device,
16
  )
17
 
18
+ def transcribe_simple(inputs_path, task):
 
 
 
 
 
 
 
19
  if inputs_path is None:
20
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
 
 
 
 
 
 
 
 
 
21
 
 
 
 
22
  sampling_rate, inputs = wavfile.read(inputs_path)
 
23
  out = pipe(inputs_path, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)
 
24
  text = out["text"]
25
 
26
+ return [[transcript] for transcript in text.split(".") if transcript], text
27
+
28
+ with gr.Blocks() as demo:
29
+ with gr.Row():
30
+ with gr.Column():
31
+ audio_input = gr.Audio(source="upload", type="filepath", label="Upload Audio")
32
+ task_input = gr.Dropdown(choices=["transcribe", "translate"], value="transcribe", label="Task")
33
+ submit_button = gr.Button("Transcribe")
34
+ with gr.Column():
35
+ output_text = gr.Dataframe(label="Transcripts")
36
+ output_full_text = gr.Textbox(label="Full Text")
37
+
38
+ submit_button.click(
39
+ transcribe_simple,
40
+ inputs=[audio_input, task_input],
41
+ outputs=[output_text, output_full_text],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ demo.launch()