PatrickML commited on
Commit
e8ab71b
1 Parent(s): 78ee705

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -8
app.py CHANGED
@@ -1,11 +1,161 @@
1
- from transformers import pipeline
2
- import gradio as gr
3
 
4
- pipe = pipeline(model="PatrickML/whisper_small")
5
- def transcribe(audio):
6
- text = pipe(audio)["text"]
7
- return text
8
 
9
- mic = gr.Audio(source="microphone", type="filepath", label="Speak here...")
10
- iface = gr.Interface(transcribe,mic,"text").launch()
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from transformers import pipeline
2
+ # import gradio as gr
3
 
4
+ # pipe = pipeline(model="PatrickML/whisper_small")
5
+ # def transcribe(audio):
6
+ # text = pipe(audio)["text"]
7
+ # return text
8
 
9
+ # mic = gr.Audio(source="microphone", type="filepath", label="Speak here...")
10
+ # iface = gr.Interface(transcribe,mic,"text").launch()
11
 
12
+ import torch
13
+
14
+ import gradio as gr
15
+ import yt_dlp as youtube_dl
16
+ from transformers import pipeline
17
+ from transformers.pipelines.audio_utils import ffmpeg_read
18
+
19
+ import tempfile
20
+ import os
21
+
22
+ MODEL_NAME = "PatrickML/whisper_small"
23
+ BATCH_SIZE = 8
24
+ FILE_LIMIT_MB = 1000
25
+ YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
26
+
27
+ device = 0 if torch.cuda.is_available() else "cpu"
28
+
29
+ pipe = pipeline(
30
+ task="automatic-speech-recognition",
31
+ model=MODEL_NAME,
32
+ chunk_length_s=30,
33
+ device=device,
34
+ )
35
+
36
+
37
+ def transcribe(inputs, task):
38
+ if inputs is None:
39
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
40
+
41
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
42
+ return text
43
+
44
+
45
+ def _return_yt_html_embed(yt_url):
46
+ video_id = yt_url.split("?v=")[-1]
47
+ HTML_str = (
48
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
49
+ " </center>"
50
+ )
51
+ return HTML_str
52
+
53
+ def download_yt_audio(yt_url, filename):
54
+ info_loader = youtube_dl.YoutubeDL()
55
+
56
+ try:
57
+ info = info_loader.extract_info(yt_url, download=False)
58
+ except youtube_dl.utils.DownloadError as err:
59
+ raise gr.Error(str(err))
60
+
61
+ file_length = info["duration_string"]
62
+ file_h_m_s = file_length.split(":")
63
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
64
+
65
+ if len(file_h_m_s) == 1:
66
+ file_h_m_s.insert(0, 0)
67
+ if len(file_h_m_s) == 2:
68
+ file_h_m_s.insert(0, 0)
69
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
70
+
71
+ if file_length_s > YT_LENGTH_LIMIT_S:
72
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
73
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
74
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
75
+
76
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
77
+
78
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
79
+ try:
80
+ ydl.download([yt_url])
81
+ except youtube_dl.utils.ExtractorError as err:
82
+ raise gr.Error(str(err))
83
+
84
+
85
+ def yt_transcribe(yt_url, task, max_filesize=75.0):
86
+ html_embed_str = _return_yt_html_embed(yt_url)
87
+
88
+ with tempfile.TemporaryDirectory() as tmpdirname:
89
+ filepath = os.path.join(tmpdirname, "video.mp4")
90
+ download_yt_audio(yt_url, filepath)
91
+ with open(filepath, "rb") as f:
92
+ inputs = f.read()
93
+
94
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
95
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
96
+
97
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
98
+
99
+ return html_embed_str, text
100
+
101
+
102
+ demo = gr.Blocks()
103
+
104
+ mf_transcribe = gr.Interface(
105
+ fn=transcribe,
106
+ inputs=[
107
+ gr.inputs.Audio(source="microphone", type="filepath", optional=True),
108
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
109
+ ],
110
+ outputs="text",
111
+ layout="horizontal",
112
+ theme="huggingface",
113
+ title="Whisper Large V3: Transcribe Audio",
114
+ description=(
115
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
116
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
117
+ " of arbitrary length."
118
+ ),
119
+ allow_flagging="never",
120
+ )
121
+
122
+ file_transcribe = gr.Interface(
123
+ fn=transcribe,
124
+ inputs=[
125
+ gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
126
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
127
+ ],
128
+ outputs="text",
129
+ layout="horizontal",
130
+ theme="huggingface",
131
+ title="Whisper Large V3: Transcribe Audio",
132
+ description=(
133
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
134
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
135
+ " of arbitrary length."
136
+ ),
137
+ allow_flagging="never",
138
+ )
139
+
140
+ yt_transcribe = gr.Interface(
141
+ fn=yt_transcribe,
142
+ inputs=[
143
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
144
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe")
145
+ ],
146
+ outputs=["html", "text"],
147
+ layout="horizontal",
148
+ theme="huggingface",
149
+ title="Whisper Large V3: Transcribe YouTube",
150
+ description=(
151
+ "Transcribe long-form YouTube videos with the click of a button! Demo uses the checkpoint"
152
+ f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of"
153
+ " arbitrary length."
154
+ ),
155
+ allow_flagging="never",
156
+ )
157
+
158
+ with demo:
159
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
160
+
161
+ demo.launch(enable_queue=True)