Staticaliza commited on
Commit
08e100b
·
verified ·
1 Parent(s): a318b56

Create app.py

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