BoburAmirov commited on
Commit
19d6a92
1 Parent(s): 537c31f

Add application file

Browse files
Files changed (5) hide show
  1. packages.txt +1 -0
  2. .gitattributes +1 -1
  3. .gitignore +1 -0
  4. app.py +184 -0
  5. requirements.txt +3 -0
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
.gitattributes CHANGED
@@ -32,4 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .idea
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import time
4
+
5
+ import gradio as gr
6
+ import yt_dlp as youtube_dl
7
+ from transformers import pipeline
8
+ from transformers.pipelines.audio_utils import ffmpeg_read
9
+
10
+ import tempfile
11
+ import os
12
+
13
+ MODEL_NAME = "openai/whisper-large-v3"
14
+ BATCH_SIZE = 8
15
+ FILE_LIMIT_MB = 1000
16
+ YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
17
+
18
+ device = 0 if torch.cuda.is_available() else "cpu"
19
+
20
+ pipe = pipeline(
21
+ task="automatic-speech-recognition",
22
+ model=MODEL_NAME,
23
+ chunk_length_s=30,
24
+ device=device,
25
+ )
26
+
27
+
28
+ def chunks_to_srt(chunks):
29
+ srt_format = ""
30
+ for i, chunk in enumerate(chunks, 1):
31
+ start_time, end_time = chunk['timestamp']
32
+ start_time_hms = "{:02}:{:02}:{:02},{:03}".format(int(start_time // 3600), int((start_time % 3600) // 60),
33
+ int(start_time % 60), int((start_time % 1) * 1000))
34
+ end_time_hms = "{:02}:{:02}:{:02},{:03}".format(int(end_time // 3600), int((end_time % 3600) // 60),
35
+ int(end_time % 60), int((end_time % 1) * 1000))
36
+ srt_format += f"{i}\n{start_time_hms} --> {end_time_hms}\n{chunk['text']}\n\n"
37
+ return srt_format
38
+
39
+
40
+ def transcribe(inputs, task, return_timestamps, language):
41
+ if inputs is None:
42
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
43
+
44
+ # Map the language names to their corresponding codes
45
+ language_codes = {"English": "en", "Uzbek": "uz"}
46
+ language_code = language_codes.get(language, "en") # Default to "en" if the language is not found
47
+ result = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task, "language": f"<|{language_code}|>"},
48
+ return_timestamps=return_timestamps)
49
+
50
+ if return_timestamps:
51
+ return chunks_to_srt(result['chunks'])
52
+ else:
53
+ return result['text']
54
+
55
+
56
+ def _return_yt_html_embed(yt_url):
57
+ video_id = yt_url.split("?v=")[-1]
58
+ HTML_str = (
59
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
60
+ " </center>"
61
+ )
62
+ return HTML_str
63
+
64
+
65
+ def download_yt_audio(yt_url, filename):
66
+ info_loader = youtube_dl.YoutubeDL()
67
+
68
+ try:
69
+ info = info_loader.extract_info(yt_url, download=False)
70
+ except youtube_dl.utils.DownloadError as err:
71
+ raise gr.Error(str(err))
72
+
73
+ file_length = info["duration_string"]
74
+ file_h_m_s = file_length.split(":")
75
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
76
+
77
+ if len(file_h_m_s) == 1:
78
+ file_h_m_s.insert(0, 0)
79
+ if len(file_h_m_s) == 2:
80
+ file_h_m_s.insert(0, 0)
81
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
82
+
83
+ if file_length_s > YT_LENGTH_LIMIT_S:
84
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
85
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
86
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
87
+
88
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
89
+
90
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
91
+ try:
92
+ ydl.download([yt_url])
93
+ except youtube_dl.utils.ExtractorError as err:
94
+ raise gr.Error(str(err))
95
+
96
+
97
+ def yt_transcribe(yt_url, task, return_timestamps, language, max_filesize=75.0):
98
+ html_embed_str = _return_yt_html_embed(yt_url)
99
+
100
+ with tempfile.TemporaryDirectory() as tmpdirname:
101
+ filepath = os.path.join(tmpdirname, "video.mp4")
102
+ download_yt_audio(yt_url, filepath)
103
+ with open(filepath, "rb") as f:
104
+ inputs = f.read()
105
+
106
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
107
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
108
+
109
+ # Map the language names to their corresponding codes
110
+ language_codes = {"English": "en", "Uzbek": "uz"}
111
+ language_code = language_codes.get(language, "en") # Default to "en" if the language is not found
112
+
113
+ result = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task, "language": f"<|{language_code}|>"},
114
+ return_timestamps=return_timestamps)
115
+
116
+ if return_timestamps:
117
+ return html_embed_str, chunks_to_srt(result['chunks'])
118
+ else:
119
+ return html_embed_str, result['text']
120
+
121
+
122
+ demo = gr.Blocks()
123
+
124
+ mf_transcribe = gr.Interface(
125
+ fn=transcribe,
126
+ inputs=[
127
+ gr.inputs.Audio(source="microphone", type="filepath", optional=True),
128
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
129
+ gr.inputs.Checkbox(label="Return timestamps"),
130
+ gr.inputs.Dropdown(choices=["English", "Uzbek"], label="Language"),
131
+ ],
132
+ outputs="text",
133
+ layout="horizontal",
134
+ theme="huggingface",
135
+ title="Whisper Large V3: Transcribe Audio",
136
+ description=(
137
+ "\n\n"
138
+ "<center>⭐️Brought to you by <a href='https://note.com/sangmin/n/n9813f2064a6a'>Chiomirai School</a>⭐️</center>"
139
+ ),
140
+ allow_flagging="never",
141
+ )
142
+
143
+ file_transcribe = gr.Interface(
144
+ fn=transcribe,
145
+ inputs=[
146
+ gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
147
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
148
+ gr.inputs.Checkbox(label="Return timestamps"),
149
+ gr.inputs.Dropdown(choices=["English", "Uzbek"], label="Language"),
150
+ ],
151
+ outputs="text",
152
+ layout="horizontal",
153
+ theme="huggingface",
154
+ title="Whisper Large V3: Transcribe Audio File",
155
+ description=(
156
+ "\n\n"
157
+ "<center>⭐️Brought to you by <a href='https://note.com/sangmin/n/n9813f2064a6a'>Chiomirai School</a>⭐️</center>"
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(["transcribe", "translate"], label="Task", default="transcribe"),
167
+ gr.inputs.Checkbox(label="Return timestamps"),
168
+ gr.inputs.Dropdown(choices=["English", "Uzbek"], label="Language"),
169
+ ],
170
+ outputs=["html", "text"],
171
+ layout="horizontal",
172
+ theme="huggingface",
173
+ title="Whisper Large V3: Transcribe YouTube",
174
+ description=(
175
+ "\n\n"
176
+ "<center>⭐️Brought to you by <a href='https://note.com/sangmin/n/n9813f2064a6a'>Chiomirai School</a>⭐️</center>"
177
+ ),
178
+ allow_flagging="never",
179
+ )
180
+
181
+ with demo:
182
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
183
+
184
+ demo.launch(enable_queue=True)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ git+https://github.com/huggingface/transformers
2
+ torch
3
+ yt-dlp