Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,35 +1,41 @@
|
|
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 = "openai/whisper-large-v3"
|
12 |
-
BATCH_SIZE = 8
|
13 |
-
FILE_LIMIT_MB = 100000
|
14 |
-
YT_LENGTH_LIMIT_S = 360000 # limit to 1 hour YouTube files
|
15 |
|
|
|
16 |
device = 0 if torch.cuda.is_available() else "cpu"
|
17 |
-
|
18 |
pipe = pipeline(
|
19 |
task="automatic-speech-recognition",
|
20 |
model=MODEL_NAME,
|
21 |
-
chunk_length_s=
|
22 |
device=device,
|
23 |
)
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
def _return_yt_html_embed(yt_url):
|
35 |
video_id = yt_url.split("?v=")[-1]
|
@@ -39,145 +45,97 @@ def _return_yt_html_embed(yt_url):
|
|
39 |
)
|
40 |
return HTML_str
|
41 |
|
42 |
-
def download_yt_audio(yt_url, filename):
|
43 |
-
info_loader = youtube_dl.YoutubeDL()
|
44 |
-
|
45 |
-
try:
|
46 |
-
info = info_loader.extract_info(yt_url, download=False)
|
47 |
-
except youtube_dl.utils.DownloadError as err:
|
48 |
-
raise gr.Error(str(err))
|
49 |
-
|
50 |
-
file_length = info["duration_string"]
|
51 |
-
file_h_m_s = file_length.split(":")
|
52 |
-
file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
|
53 |
-
|
54 |
-
if len(file_h_m_s) == 1:
|
55 |
-
file_h_m_s.insert(0, 0)
|
56 |
-
if len(file_h_m_s) == 2:
|
57 |
-
file_h_m_s.insert(0, 0)
|
58 |
-
file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
|
59 |
-
|
60 |
-
if file_length_s > YT_LENGTH_LIMIT_S:
|
61 |
-
yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
|
62 |
-
file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
|
63 |
-
raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
|
64 |
-
|
65 |
-
ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
|
66 |
-
|
67 |
-
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
68 |
-
try:
|
69 |
-
ydl.download([yt_url])
|
70 |
-
except youtube_dl.utils.ExtractorError as err:
|
71 |
-
raise gr.Error(str(err))
|
72 |
-
|
73 |
-
|
74 |
def yt_transcribe(yt_url, task):
|
|
|
|
|
|
|
|
|
75 |
html_embed_str = _return_yt_html_embed(yt_url)
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
text = pipe(inputs,return_timestamps=True)
|
88 |
-
# text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"language":"zh"}, return_timestamps=True)
|
89 |
-
# text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
|
90 |
-
# text = pipe("audio.mp3",return_timestamps=True)
|
91 |
-
#trans to SRT
|
92 |
-
text= convert_to_srt(text)
|
93 |
return html_embed_str, text
|
94 |
|
95 |
-
|
96 |
-
# SRT prepare
|
97 |
# Assuming srt format is a sequence of subtitles with index, time range and text
|
98 |
def convert_to_srt(input):
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
|
113 |
# Helper function to format time
|
114 |
def format_time(seconds):
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
|
124 |
demo = gr.Blocks()
|
125 |
-
|
126 |
mf_transcribe = gr.Interface(
|
127 |
fn=transcribe,
|
128 |
inputs=[
|
129 |
gr.inputs.Audio(source="microphone", type="filepath", optional=True),
|
|
|
130 |
gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
|
131 |
],
|
132 |
outputs="text",
|
133 |
layout="horizontal",
|
134 |
theme="huggingface",
|
135 |
-
title="
|
136 |
-
description=(
|
137 |
-
"Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the OpenAI Whisper"
|
138 |
-
f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
|
139 |
-
" of arbitrary length."
|
140 |
-
),
|
141 |
-
allow_flagging="never",
|
142 |
-
)
|
143 |
-
|
144 |
-
file_transcribe = gr.Interface(
|
145 |
-
fn=transcribe,
|
146 |
-
inputs=[
|
147 |
-
gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
|
148 |
-
gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
|
149 |
-
],
|
150 |
-
outputs="text",
|
151 |
-
layout="horizontal",
|
152 |
-
theme="huggingface",
|
153 |
-
title="Whisper Large V3: Transcribe Audio",
|
154 |
description=(
|
155 |
-
"
|
156 |
-
f"
|
157 |
-
"
|
158 |
),
|
159 |
allow_flagging="never",
|
160 |
)
|
161 |
-
|
162 |
yt_transcribe = gr.Interface(
|
163 |
fn=yt_transcribe,
|
164 |
inputs=[
|
165 |
-
gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
|
166 |
-
gr.inputs.Radio(["
|
167 |
],
|
168 |
outputs=["html", "text"],
|
169 |
layout="horizontal",
|
170 |
theme="huggingface",
|
171 |
-
title="
|
172 |
description=(
|
173 |
-
"
|
174 |
-
f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME})
|
175 |
-
"
|
176 |
),
|
177 |
allow_flagging="never",
|
178 |
)
|
179 |
|
180 |
-
|
181 |
-
|
|
|
|
|
|
|
|
|
|
|
182 |
|
|
|
|
|
|
|
|
|
183 |
demo.launch(enable_queue=True)
|
|
|
1 |
import torch
|
2 |
+
# from PIL import Image
|
3 |
import gradio as gr
|
4 |
+
import yt_dlp as youtube_dl # 用 yt_dlp 代替 pytube
|
5 |
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
MODEL_NAME = "openai/whisper-large-v2"
|
8 |
device = 0 if torch.cuda.is_available() else "cpu"
|
|
|
9 |
pipe = pipeline(
|
10 |
task="automatic-speech-recognition",
|
11 |
model=MODEL_NAME,
|
12 |
+
chunk_length_s=30,
|
13 |
device=device,
|
14 |
)
|
15 |
|
16 |
+
all_special_ids = pipe.tokenizer.all_special_ids
|
17 |
+
transcribe_token_id = all_special_ids[-5]
|
18 |
+
translate_token_id = all_special_ids[-6]
|
19 |
+
|
20 |
+
def transcribe(microphone, file_upload, task):
|
21 |
+
warn_output = ""
|
22 |
+
if (microphone is not None) and (file_upload is not None):
|
23 |
+
warn_output = (
|
24 |
+
"警告:您已经上传了一个音频文件并使用了麦克录制。 "
|
25 |
+
"录制文件将被使用上传的音频将被丢弃。[^1^][1] \n"
|
26 |
+
)
|
27 |
+
elif (microphone is None) and (file_upload is None):
|
28 |
+
return "错误: 您必须使用麦克风录制或上传音频文件"
|
29 |
+
|
30 |
+
file = microphone if microphone is not None else file_upload
|
31 |
+
pipe.model.config.forced_decoder_ids = [
|
32 |
+
[2, transcribe_token_id if task == "transcribe" else translate_token_id]
|
33 |
+
]
|
34 |
+
# text = pipe(file, return_timestamps=True)["text"]
|
35 |
+
text = pipe(file, return_timestamps=True)
|
36 |
+
# trans to SRT
|
37 |
+
text = convert_to_srt(text)
|
38 |
+
return warn_output + text
|
39 |
|
40 |
def _return_yt_html_embed(yt_url):
|
41 |
video_id = yt_url.split("?v=")[-1]
|
|
|
45 |
)
|
46 |
return HTML_str
|
47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
def yt_transcribe(yt_url, task):
|
49 |
+
# yt = pt.YouTube(yt_url) # 用 yt_dlp 代替 pytube
|
50 |
+
ydl = youtube_dl.YoutubeDL({"format": "bestaudio"}) # 创建 yt_dlp 对象
|
51 |
+
info = ydl.extract_info(yt_url, download=False) # 提取视频信息
|
52 |
+
audio_url = info["formats"][0]["url"] # 获取音频链接
|
53 |
html_embed_str = _return_yt_html_embed(yt_url)
|
54 |
+
# stream = yt.streams.filter(only_audio=True)[0]
|
55 |
+
# stream.download(filename="audio.mp3")
|
56 |
+
ydl.download([audio_url]) # 下载音频文件
|
57 |
+
pipe.model.config.forced_decoder_ids = [
|
58 |
+
[2, transcribe_token_id if task == "transcribe" else translate_token_id]
|
59 |
+
]
|
60 |
+
text = pipe("audio.mp3", return_timestamps=True)
|
61 |
+
# text = pipe("audio.mp3", return_timestamps=True)["text"]
|
62 |
+
# trans to SRT
|
63 |
+
text = convert_to_srt(text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
return html_embed_str, text
|
65 |
|
|
|
|
|
66 |
# Assuming srt format is a sequence of subtitles with index, time range and text
|
67 |
def convert_to_srt(input):
|
68 |
+
output = ""
|
69 |
+
index = 1
|
70 |
+
for chunk in input["chunks"]:
|
71 |
+
start, end = chunk["timestamp"]
|
72 |
+
text = chunk["text"]
|
73 |
+
if end is None:
|
74 |
+
end = "None"
|
75 |
+
# Convert seconds to hours:minutes:seconds,milliseconds format
|
76 |
+
start = format_time(start)
|
77 |
+
end = format_time(end)
|
78 |
+
output += f"{index}\n{start} --> {end}\n{text}\n\n"
|
79 |
+
index += 1
|
80 |
+
return output
|
81 |
|
82 |
# Helper function to format time
|
83 |
def format_time(seconds):
|
84 |
+
if seconds == "None":
|
85 |
+
return seconds
|
86 |
+
hours = int(seconds // 3600)
|
87 |
+
minutes = int((seconds % 3600) // 60)
|
88 |
+
seconds = int(seconds % 60)
|
89 |
+
milliseconds = int((seconds % 1) * 1000)
|
90 |
+
return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
|
|
|
91 |
|
92 |
demo = gr.Blocks()
|
|
|
93 |
mf_transcribe = gr.Interface(
|
94 |
fn=transcribe,
|
95 |
inputs=[
|
96 |
gr.inputs.Audio(source="microphone", type="filepath", optional=True),
|
97 |
+
gr.inputs.Audio(source="upload", type="filepath", optional=True),
|
98 |
gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
|
99 |
],
|
100 |
outputs="text",
|
101 |
layout="horizontal",
|
102 |
theme="huggingface",
|
103 |
+
title="Audio-to-Text-SRT 自动生成字幕",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
description=(
|
105 |
+
"直接在网页录音或上传音频文件,加入Youtube连接,轻松转换为文字和字幕格式! 本演示采用"
|
106 |
+
f" 模型 [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) 和 🤗 Transformers 转换任意长度的"[^2^][2]
|
107 |
+
"音视频文件!使用GPU转换效率会大幅提高,大约每小时 $0.6 约相当于人民币 5 元。 如果您有较长内容,需要更快的转换速度,请私信作者微信 1259388,并备注“语音转文字”。[^3^][3] "
|
108 |
),
|
109 |
allow_flagging="never",
|
110 |
)
|
|
|
111 |
yt_transcribe = gr.Interface(
|
112 |
fn=yt_transcribe,
|
113 |
inputs=[
|
114 |
+
gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),[^4^][4]
|
115 |
+
gr.inputs.Radio(["转译", "翻译"], label="Task", default="transcribe")
|
116 |
],
|
117 |
outputs=["html", "text"],
|
118 |
layout="horizontal",
|
119 |
theme="huggingface",
|
120 |
+
title="Audio-to-Text-SRT 自动生成字幕",
|
121 |
description=(
|
122 |
+
"直接在网页录音或上传音频文件,加入Youtube连接,轻松转换为文字和字幕格式! 本演示采用"
|
123 |
+
f" 模型 [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) 和 🤗 Transformers 转换任意长度的"[^2^][2]
|
124 |
+
"音视频文件!使用GPU转换效率会大幅提高,大约每小时 $0.6 约相当于人民币 5 元。 如果您有较长内容,需要更快的转换速度,请私信作者微信 1259388,并备注“语音转文字”。[^3^][3] "
|
125 |
),
|
126 |
allow_flagging="never",
|
127 |
)
|
128 |
|
129 |
+
# # Load the images
|
130 |
+
# image1 = Image("wechatqrcode.jpg")
|
131 |
+
# image2 = Image("paypalqrcode.png")
|
132 |
+
|
133 |
+
# # Define a function that returns the images and captions
|
134 |
+
# def display_images():
|
135 |
+
# return image1, "WeChat Pay", image2, "PayPal"
|
136 |
|
137 |
+
with demo:
|
138 |
+
gr.TabbedInterface([mf_transcribe, yt_transcribe], ["转译音频成文字", "YouTube转字幕"])
|
139 |
+
# Create a gradio interface with no inputs and four outputs
|
140 |
+
# gr.Interface(display_images, [], [gr.outputs.Image(), gr.outputs.Textbox(), gr.outputs.Image(), gr.outputs.Textbox()], layout="horizontal").launch()
|
141 |
demo.launch(enable_queue=True)
|