nithinraok commited on
Commit
b6c2bc0
1 Parent(s): 759ef4d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import subprocess
3
+ import torch
4
+ import gradio as gr
5
+ import yt_dlp
6
+ import pandas as pd
7
+ from nemo.collections.asr.models import ASRModel
8
+ from nemo_align import align_tdt_to_ctc_timestamps
9
+ import os
10
+
11
+
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+
14
+ def process_audio(input_file, output_file):
15
+ command = [
16
+ 'sox', input_file,
17
+ output_file,
18
+ 'channels', '1',
19
+ 'rate', '16000'
20
+ ]
21
+ try:
22
+ subprocess.run(command, check=True)
23
+ return output_file
24
+ except:
25
+ raise gr.Error("Failed to convert audio to single channel and sampling rate to 16000")
26
+
27
+ def get_dataframe_segments(segments):
28
+ df = pd.DataFrame(columns=['start_time', 'end_time', 'text'])
29
+ if len(segments) == 0:
30
+ df.loc[0] = 0, 0, ''
31
+ return df
32
+
33
+ for segment in segments:
34
+ text, start_time, end_time = segment
35
+ if len(text)>0:
36
+ df.loc[len(df)] = round(start_time, 2), round(end_time, 2), text
37
+
38
+ return df
39
+
40
+
41
+ def get_video_info(url):
42
+ ydl_opts = {
43
+ 'quiet': True,
44
+ 'skip-download': True,
45
+ }
46
+
47
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
48
+ try:
49
+ info = ydl.extract_info(url, download=False)
50
+ except:
51
+ raise gr.Error("Failed to extract video info from Youtube")
52
+ return info
53
+
54
+ def download_audio(url):
55
+ ydl_opts = {
56
+ 'format': 'bestaudio/best,channels:1',
57
+ 'quiet': True,
58
+ 'outtmpl': 'audio_file',
59
+ 'postprocessors': [{
60
+ 'key': 'FFmpegExtractAudio',
61
+ 'preferredcodec': 'flac',
62
+ 'preferredquality': '192',
63
+ }],
64
+ }
65
+
66
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
67
+ try:
68
+ ydl.download([url])
69
+ except yt_dlp.utils.DownloadError as err:
70
+ raise gr.Error(str(err))
71
+
72
+ return process_audio('audio_file.flac', 'processed_file.flac')
73
+
74
+
75
+ def get_audio_from_youtube(url):
76
+ info = get_video_info(url)
77
+ duration = info.get('duration', 0) # Duration in seconds
78
+ video_id = info.get('id',None)
79
+
80
+ html = f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
81
+
82
+ if duration > 2*60*60: # 2 hrs change later based on GPU
83
+ return gr.Error(str("For GPU {}, single pass maximum audio can be 2hrs"))
84
+ else:
85
+ return download_audio(url), html
86
+
87
+
88
+ def get_transcripts(audio_path, model):
89
+ with torch.cuda.amp.autocast(enabled=True, dtype=torch.bfloat16):
90
+ with torch.inference_mode():
91
+ text = model.transcribe(audio=[audio_path], )
92
+ return text
93
+
94
+ def pick_asr_model():
95
+ model = 'nvidia/parakeet-tdt_ctc-1.1b'
96
+ asr_model = ASRModel.from_pretrained(model).to(device)
97
+ asr_model.eval()
98
+ return asr_model
99
+
100
+ asr_model = pick_asr_model()
101
+
102
+ def run_nemo_models(url, microphone, audio_path):
103
+ html = None
104
+ if url is None or len(url)<2:
105
+ path1 = microphone if microphone else audio_path
106
+ else:
107
+ gr.Info("Downloading and processing audio from Youtube")
108
+ path1, html = get_audio_from_youtube(url)
109
+
110
+ gr.Info("Running NeMo Model")
111
+ text = get_transcripts(path1, asr_model)
112
+
113
+ segments = align_tdt_to_ctc_timestamps(text, asr_model, path1)
114
+
115
+ df = get_dataframe_segments(segments)
116
+
117
+ return df, html
118
+
119
+ def clear_youtube_link():
120
+ # Remove .flac files in current directory
121
+ file_list = os.listdir()
122
+ for file in file_list:
123
+ if file.endswith(".flac"):
124
+ os.remove(file)
125
+
126
+ return None
127
+
128
+
129
+ # def run_speaker_diarization()
130
+
131
+ with gr.Blocks(
132
+ title="NeMo Parakeet Model",
133
+ css="""
134
+ textarea { font-size: 18px;}
135
+ #model_output_text_box span {
136
+ font-size: 18px;
137
+ font-weight: bold;
138
+ }
139
+ """,
140
+ theme=gr.themes.Default(text_size=gr.themes.sizes.text_lg) # make text slightly bigger (default is text_md )
141
+ ) as demo:
142
+ gr.HTML("<h1 style='text-align: center'>Transcription with timestamps using Parakeet TDT-CTC</h1>")
143
+ gr.Markdown('''
144
+ Choose between different sources of audio (Microphone, Audio File, Youtube Video) to transcribe along with timestamps.
145
+
146
+ Parakeet models with limited attention are quite fast due to their limited attention mechanism. The current model with 1.1B parameters can transcribe very long audios upto 11 hrs on A6000 GPU in a single pass.
147
+
148
+ Model used: [nvidia/parakeet-tdt_ctc-1.1b](https://huggingface.co/nvidia/parakeet-tdt_ctc-1.1b).
149
+ ''')
150
+ # This block is for reading audio from MIC
151
+ with gr.Tab('Audio from Youtube'):
152
+ with gr.Row():
153
+ yt_link = gr.Textbox(value=None, label='Enter Youtube Link', type='text')
154
+ yt_render = gr.HTML()
155
+
156
+ with gr.Tab('Audio From File'):
157
+ file_input = gr.Audio(sources='upload', label='Upload Audio', type='filepath')
158
+
159
+ with gr.Tab('Audio From Microphone'):
160
+ mic_input = gr.Audio(sources='microphone', label='Record Audio', type='filepath')
161
+
162
+
163
+ # b1 = gr.Button("Get Transcription with Punctuation and Capitalization")
164
+
165
+ gr.Markdown('''Speech Recognition''')
166
+
167
+ # text_output = gr.Textbox(label='Transcription', type='text')
168
+
169
+ b2 = gr.Button("Get timestamps with text")
170
+
171
+ time_stamp = gr.DataFrame(wrap=True, label='Speech Recognition with TimeStamps',
172
+ row_count=(1, "dynamic"), headers=['start_time', 'end_time', 'text'])
173
+
174
+ # b1.click(run_nemo_models, inputs=[file_input, mic_input, yt_link], outputs=[text_output, yt_render])
175
+
176
+ b2.click(run_nemo_models, inputs=[yt_link, file_input, mic_input], outputs=[time_stamp, yt_render]).then(
177
+ clear_youtube_link, None, yt_link, queue=False) #here clean up passing None to audio.
178
+
179
+ demo.queue(True)
180
+ demo.launch(share=True, debug=True)
181
+