chiyo123 commited on
Commit
b3bafb9
β€’
1 Parent(s): 80fe091

Create whisper-small-bemba.py

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