nirajandhakal commited on
Commit
1723f0f
·
verified ·
1 Parent(s): 3fd7fa0

Update app.py

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