Nick088 commited on
Commit
ad5c122
1 Parent(s): 06be303

Upload 4 files

Browse files
Files changed (4) hide show
  1. LICENSE.md +36 -0
  2. app.py +523 -0
  3. packages.txt +1 -0
  4. requirements.txt +2 -0
LICENSE.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nick088's Non-Commercial License (NNC)
2
+
3
+ ## 1. Definitions
4
+
5
+ - "Software" refers to the content present within this repository including code, text, graphics, sounds, images, and other files.
6
+ - "You" refers to the individual or entity that wishes to use the Software.
7
+ - "Nick088" refers to the original creator of the Software.
8
+ - "Fork" refers to the action of creating a personal copy of another user's repository.
9
+
10
+ ## 2. Grant of Rights
11
+
12
+ Subject to the terms of this license, Nick088 hereby grants You a worldwide, royalty-free, non-exclusive, perpetual license to use the Software for personal and non-commercial purposes. This includes the rights to use, copy, modify, merge, publish, and distribute the Software for non-commercial purposes.
13
+
14
+ ## 3. Redistribution
15
+
16
+ You may not distribute or sell the Software, or any derivative works based on the Software, unless you have been specifically granted permission by Nick088. Any permitted redistribution must also be under the terms of this license. Unauthorized distribution is strictly prohibited and will result in the termination of this license.
17
+
18
+ ## 4. Commercial Use
19
+
20
+ The use of the Software for commercial purposes, including any form of paid software support and , is strictly forbidden without the explicit written approval of Nick088. This applies to both profit-driven businesses and non-profit organizations that handle monetary transactions.
21
+
22
+ Nick088 may agree to a predetermined or subsequently decided percentage of the profits. Nick088 maintains an upper hand in all such negotiations and reserves any rights, including the right to terminate the contract at any time.
23
+
24
+ Any unauthorized commercial use is strictly prohibited and will result to an immediate termination of this license. In the event of a breach of these terms, Nick088 reserves the right to pursue legal remedies. This may result in litigation, and the offending party may be held liable for any damages incurred. Please be aware that non-compliance with these terms is a serious matter and could have significant legal consequences.
25
+
26
+ ## 5. Forking & Personal Use
27
+
28
+ You are free to fork and modify the Software for your own personal use. You may not distribute, or create derivative works from your modifications unless granted permission by Nick088. All modifications must also be under the terms of this license.
29
+
30
+ ## 6. Liability
31
+
32
+ Nick088 provides the Software "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall Nick088 be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software. You agree to use the Software at your own risk.
33
+
34
+ ## 7. Governing Law
35
+
36
+ This license is governed by the laws of the jurisdiction in which Nick088 resides. Any disputes related to this license will be resolved in the courts of that jurisdiction.
app.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import json
4
+ from datetime import timedelta
5
+ import tempfile
6
+ import re
7
+ import gradio as gr
8
+ import groq
9
+ from groq import Groq
10
+
11
+
12
+ # setup groq
13
+
14
+ client = Groq(api_key=os.environ.get("Groq_Api_Key"))
15
+
16
+ def handle_groq_error(e, model_name):
17
+ error_data = e.args[0]
18
+
19
+ if isinstance(error_data, str):
20
+ # Use regex to extract the JSON part of the string
21
+ json_match = re.search(r'(\{.*\})', error_data)
22
+ if json_match:
23
+ json_str = json_match.group(1)
24
+ # Ensure the JSON string is well-formed
25
+ json_str = json_str.replace("'", '"') # Replace single quotes with double quotes
26
+ error_data = json.loads(json_str)
27
+
28
+ if isinstance(e, groq.RateLimitError):
29
+ if isinstance(error_data, dict) and 'error' in error_data and 'message' in error_data['error']:
30
+ error_message = error_data['error']['message']
31
+ raise gr.Error(error_message)
32
+ else:
33
+ raise gr.Error(f"Error during Groq API call: {e}")
34
+
35
+
36
+ # language codes for subtitle maker
37
+
38
+ LANGUAGE_CODES = {
39
+ "English": "en",
40
+ "Chinese": "zh",
41
+ "German": "de",
42
+ "Spanish": "es",
43
+ "Russian": "ru",
44
+ "Korean": "ko",
45
+ "French": "fr",
46
+ "Japanese": "ja",
47
+ "Portuguese": "pt",
48
+ "Turkish": "tr",
49
+ "Polish": "pl",
50
+ "Catalan": "ca",
51
+ "Dutch": "nl",
52
+ "Arabic": "ar",
53
+ "Swedish": "sv",
54
+ "Italian": "it",
55
+ "Indonesian": "id",
56
+ "Hindi": "hi",
57
+ "Finnish": "fi",
58
+ "Vietnamese": "vi",
59
+ "Hebrew": "he",
60
+ "Ukrainian": "uk",
61
+ "Greek": "el",
62
+ "Malay": "ms",
63
+ "Czech": "cs",
64
+ "Romanian": "ro",
65
+ "Danish": "da",
66
+ "Hungarian": "hu",
67
+ "Tamil": "ta",
68
+ "Norwegian": "no",
69
+ "Thai": "th",
70
+ "Urdu": "ur",
71
+ "Croatian": "hr",
72
+ "Bulgarian": "bg",
73
+ "Lithuanian": "lt",
74
+ "Latin": "la",
75
+ "Māori": "mi",
76
+ "Malayalam": "ml",
77
+ "Welsh": "cy",
78
+ "Slovak": "sk",
79
+ "Telugu": "te",
80
+ "Persian": "fa",
81
+ "Latvian": "lv",
82
+ "Bengali": "bn",
83
+ "Serbian": "sr",
84
+ "Azerbaijani": "az",
85
+ "Slovenian": "sl",
86
+ "Kannada": "kn",
87
+ "Estonian": "et",
88
+ "Macedonian": "mk",
89
+ "Breton": "br",
90
+ "Basque": "eu",
91
+ "Icelandic": "is",
92
+ "Armenian": "hy",
93
+ "Nepali": "ne",
94
+ "Mongolian": "mn",
95
+ "Bosnian": "bs",
96
+ "Kazakh": "kk",
97
+ "Albanian": "sq",
98
+ "Swahili": "sw",
99
+ "Galician": "gl",
100
+ "Marathi": "mr",
101
+ "Panjabi": "pa",
102
+ "Sinhala": "si",
103
+ "Khmer": "km",
104
+ "Shona": "sn",
105
+ "Yoruba": "yo",
106
+ "Somali": "so",
107
+ "Afrikaans": "af",
108
+ "Occitan": "oc",
109
+ "Georgian": "ka",
110
+ "Belarusian": "be",
111
+ "Tajik": "tg",
112
+ "Sindhi": "sd",
113
+ "Gujarati": "gu",
114
+ "Amharic": "am",
115
+ "Yiddish": "yi",
116
+ "Lao": "lo",
117
+ "Uzbek": "uz",
118
+ "Faroese": "fo",
119
+ "Haitian": "ht",
120
+ "Pashto": "ps",
121
+ "Turkmen": "tk",
122
+ "Norwegian Nynorsk": "nn",
123
+ "Maltese": "mt",
124
+ "Sanskrit": "sa",
125
+ "Luxembourgish": "lb",
126
+ "Burmese": "my",
127
+ "Tibetan": "bo",
128
+ "Tagalog": "tl",
129
+ "Malagasy": "mg",
130
+ "Assamese": "as",
131
+ "Tatar": "tt",
132
+ "Hawaiian": "haw",
133
+ "Lingala": "ln",
134
+ "Hausa": "ha",
135
+ "Bashkir": "ba",
136
+ "jw": "jw",
137
+ "Sundanese": "su",
138
+ }
139
+
140
+
141
+ # helper functions
142
+
143
+ def split_audio(audio_file_path, chunk_size_mb):
144
+ chunk_size = chunk_size_mb * 1024 * 1024 # Convert MB to bytes
145
+ file_number = 1
146
+ chunks = []
147
+ with open(audio_file_path, 'rb') as f:
148
+ chunk = f.read(chunk_size)
149
+ while chunk:
150
+ chunk_name = f"{os.path.splitext(audio_file_path)[0]}_part{file_number:03}.mp3" # Pad file number for correct ordering
151
+ with open(chunk_name, 'wb') as chunk_file:
152
+ chunk_file.write(chunk)
153
+ chunks.append(chunk_name)
154
+ file_number += 1
155
+ chunk = f.read(chunk_size)
156
+ return chunks
157
+
158
+ def merge_audio(chunks, output_file_path):
159
+ with open("temp_list.txt", "w") as f:
160
+ for file in chunks:
161
+ f.write(f"file '{file}'\n")
162
+ try:
163
+ subprocess.run(
164
+ [
165
+ "ffmpeg",
166
+ "-f",
167
+ "concat",
168
+ "-safe", "0",
169
+ "-i",
170
+ "temp_list.txt",
171
+ "-c",
172
+ "copy",
173
+ "-y",
174
+ output_file_path
175
+ ],
176
+ check=True
177
+ )
178
+ os.remove("temp_list.txt")
179
+ for chunk in chunks:
180
+ os.remove(chunk)
181
+ except subprocess.CalledProcessError as e:
182
+ raise gr.Error(f"Error during audio merging: {e}")
183
+
184
+
185
+ # Checks file extension, size, and downsamples or splits if needed.
186
+
187
+ ALLOWED_FILE_EXTENSIONS = ["mp3", "mp4", "mpeg", "mpga", "m4a", "wav", "webm"]
188
+ MAX_FILE_SIZE_MB = 25
189
+ CHUNK_SIZE_MB = 25
190
+
191
+ def check_file(audio_file_path):
192
+ if not audio_file_path:
193
+ raise gr.Error("Please upload an audio/video file.")
194
+
195
+ file_size_mb = os.path.getsize(audio_file_path) / (1024 * 1024)
196
+ file_extension = audio_file_path.split(".")[-1].lower()
197
+
198
+ if file_extension not in ALLOWED_FILE_EXTENSIONS:
199
+ raise gr.Error(f"Invalid file type (.{file_extension}). Allowed types: {', '.join(ALLOWED_FILE_EXTENSIONS)}")
200
+
201
+ if file_size_mb > MAX_FILE_SIZE_MB:
202
+ gr.Warning(
203
+ f"File size too large ({file_size_mb:.2f} MB). Attempting to downsample to 16kHz MP3 128kbps. Maximum size allowed: {MAX_FILE_SIZE_MB} MB"
204
+ )
205
+
206
+ output_file_path = os.path.splitext(audio_file_path)[0] + "_downsampled.mp3"
207
+ try:
208
+ subprocess.run(
209
+ [
210
+ "ffmpeg",
211
+ "-i",
212
+ audio_file_path,
213
+ "-ar",
214
+ "16000",
215
+ "-ab",
216
+ "128k",
217
+ "-ac",
218
+ "1",
219
+ "-f",
220
+ "mp3",
221
+ "-y",
222
+ output_file_path,
223
+ ],
224
+ check=True
225
+ )
226
+
227
+ # Check size after downsampling
228
+ downsampled_size_mb = os.path.getsize(output_file_path) / (1024 * 1024)
229
+ if downsampled_size_mb > MAX_FILE_SIZE_MB:
230
+ gr.Warning(f"File still too large after downsampling ({downsampled_size_mb:.2f} MB). Splitting into {CHUNK_SIZE_MB} MB chunks.")
231
+ return split_audio(output_file_path, CHUNK_SIZE_MB), "split"
232
+
233
+ return output_file_path, None
234
+ except subprocess.CalledProcessError as e:
235
+ raise gr.Error(f"Error during downsampling: {e}")
236
+ return audio_file_path, None
237
+
238
+
239
+ # subtitle maker
240
+
241
+ def format_time(seconds):
242
+ hours = int(seconds // 3600)
243
+ minutes = int((seconds % 3600) // 60)
244
+ seconds = int(seconds % 60)
245
+ milliseconds = int((seconds % 1) * 1000)
246
+
247
+ return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
248
+
249
+ def json_to_srt(transcription_json):
250
+ srt_lines = []
251
+
252
+ for segment in transcription_json:
253
+ start_time = format_time(segment['start'])
254
+ end_time = format_time(segment['end'])
255
+ text = segment['text']
256
+
257
+ srt_line = f"{segment['id']+1}\n{start_time} --> {end_time}\n{text}\n"
258
+ srt_lines.append(srt_line)
259
+
260
+ return '\n'.join(srt_lines)
261
+
262
+
263
+ def generate_subtitles(audio_file_path, prompt, language, auto_detect_language, model, include_video, font_selection, font_file, font_color, font_size, outline_thickness, outline_color):
264
+ processed_path, split_status = check_file(audio_file_path)
265
+ full_srt_content = ""
266
+ total_duration = 0
267
+ segment_id_offset = 0
268
+
269
+ if split_status == "split":
270
+ srt_chunks = []
271
+ video_chunks = []
272
+ for i, chunk_path in enumerate(processed_path):
273
+ try:
274
+ with open(chunk_path, "rb") as file:
275
+ transcription_json_response = client.audio.transcriptions.create(
276
+ file=(os.path.basename(chunk_path), file.read()),
277
+ model=model,
278
+ prompt=prompt,
279
+ response_format="verbose_json",
280
+ language=None if auto_detect_language else language,
281
+ temperature=0.0,
282
+ )
283
+ transcription_json = transcription_json_response.segments
284
+
285
+ # Adjust timestamps and segment IDs
286
+ for segment in transcription_json:
287
+ segment['start'] += total_duration
288
+ segment['end'] += total_duration
289
+ segment['id'] += segment_id_offset
290
+ segment_id_offset += len(transcription_json)
291
+ total_duration += transcription_json[-1]['end'] # Update total duration
292
+
293
+ srt_content = json_to_srt(transcription_json)
294
+ full_srt_content += srt_content
295
+ temp_srt_path = f"{os.path.splitext(chunk_path)[0]}.srt"
296
+ with open(temp_srt_path, "w", encoding="utf-8") as temp_srt_file:
297
+ temp_srt_file.write(srt_content)
298
+ temp_srt_file.write("\n") # add a new line at the end of the srt chunk file to fix format when merged
299
+ srt_chunks.append(temp_srt_path)
300
+
301
+ if include_video and audio_file_path.lower().endswith((".mp4", ".webm")):
302
+ try:
303
+ output_file_path = chunk_path.replace(os.path.splitext(chunk_path)[1], "_with_subs" + os.path.splitext(chunk_path)[1])
304
+ # Handle font selection
305
+ if font_selection == "Custom Font File" and font_file:
306
+ font_name = os.path.splitext(os.path.basename(font_file.name))[0] # Get font filename without extension
307
+ font_dir = os.path.dirname(font_file.name) # Get font directory path
308
+ elif font_selection == "Custom Font File" and not font_file:
309
+ font_name = None # Let FFmpeg use its default Arial
310
+ font_dir = None # No font directory
311
+ gr.Warning(f"You want to use a Custom Font File, but uploaded none. Using the default Arial font.")
312
+ elif font_selection == "Arial":
313
+ font_name = None # Let FFmpeg use its default Arial
314
+ font_dir = None # No font directory
315
+
316
+ # FFmpeg command
317
+ subprocess.run(
318
+ [
319
+ "ffmpeg",
320
+ "-y",
321
+ "-i",
322
+ chunk_path,
323
+ "-vf",
324
+ f"subtitles={temp_srt_path}:fontsdir={font_dir}:force_style='Fontname={font_name},Fontsize={int(font_size)},PrimaryColour=&H{font_color[1:]}&,OutlineColour=&H{outline_color[1:]}&,BorderStyle={int(outline_thickness)},Outline=1'",
325
+ output_file_path,
326
+ ],
327
+ check=True,
328
+ )
329
+ video_chunks.append(output_file_path)
330
+ except subprocess.CalledProcessError as e:
331
+ raise gr.Error(f"Error during subtitle addition: {e}")
332
+ elif include_video and not audio_file_path.lower().endswith((".mp4", ".webm")):
333
+ gr.Warning(f"You have checked on the 'Include Video with Subtitles', but the input file {audio_file_path} isn't a video (.mp4 or .webm). Returning only the SRT File.", duration=15)
334
+ except groq.RateLimitError as e:
335
+ handle_groq_error(e, model)
336
+ gr.Warning(f"API limit reached during chunk {i+1}. Returning processed chunks only.")
337
+ if srt_chunks and video_chunks:
338
+ merge_audio(video_chunks, 'merged_output_video.mp4')
339
+ with open('merged_output.srt', 'w', encoding="utf-8") as outfile:
340
+ for chunk_srt in srt_chunks:
341
+ with open(chunk_srt, 'r', encoding="utf-8") as infile:
342
+ outfile.write(infile.read())
343
+ return 'merged_output.srt', 'merged_output_video.mp4'
344
+ else:
345
+ raise gr.Error("Subtitle generation failed due to API limits.")
346
+
347
+ # Merge SRT chunks
348
+ final_srt_path = os.path.splitext(audio_file_path)[0] + "_final.srt"
349
+ with open(final_srt_path, 'w', encoding="utf-8") as outfile:
350
+ for chunk_srt in srt_chunks:
351
+ with open(chunk_srt, 'r', encoding="utf-8") as infile:
352
+ outfile.write(infile.read())
353
+
354
+ # Merge video chunks
355
+ if video_chunks:
356
+ merge_audio(video_chunks, 'merged_output_video.mp4')
357
+ return final_srt_path, 'merged_output_video.mp4'
358
+ else:
359
+ return final_srt_path, None
360
+
361
+ else: # Single file processing (no splitting)
362
+ try:
363
+ with open(processed_path, "rb") as file:
364
+ transcription_json_response = client.audio.transcriptions.create(
365
+ file=(os.path.basename(processed_path), file.read()),
366
+ model=model,
367
+ prompt=prompt,
368
+ response_format="verbose_json",
369
+ language=None if auto_detect_language else language,
370
+ temperature=0.0,
371
+ )
372
+ transcription_json = transcription_json_response.segments
373
+
374
+ srt_content = json_to_srt(transcription_json)
375
+ temp_srt_path = os.path.splitext(audio_file_path)[0] + ".srt"
376
+ with open(temp_srt_path, "w", encoding="utf-8") as temp_srt_file:
377
+ temp_srt_file.write(srt_content)
378
+
379
+ if include_video and audio_file_path.lower().endswith((".mp4", ".webm")):
380
+ try:
381
+ output_file_path = audio_file_path.replace(
382
+ os.path.splitext(audio_file_path)[1], "_with_subs" + os.path.splitext(audio_file_path)[1]
383
+ )
384
+ # Handle font selection
385
+ if font_selection == "Custom Font File" and font_file:
386
+ font_name = os.path.splitext(os.path.basename(font_file.name))[0] # Get font filename without extension
387
+ font_dir = os.path.dirname(font_file.name) # Get font directory path
388
+ elif font_selection == "Custom Font File" and not font_file:
389
+ font_name = None # Let FFmpeg use its default Arial
390
+ font_dir = None # No font directory
391
+ gr.Warning(f"You want to use a Custom Font File, but uploaded none. Using the default Arial font.")
392
+ elif font_selection == "Arial":
393
+ font_name = None # Let FFmpeg use its default Arial
394
+ font_dir = None # No font directory
395
+
396
+ # FFmpeg command
397
+ subprocess.run(
398
+ [
399
+ "ffmpeg",
400
+ "-y",
401
+ "-i",
402
+ audio_file_path,
403
+ "-vf",
404
+ f"subtitles={temp_srt_path}:fontsdir={font_dir}:force_style='FontName={font_name},Fontsize={int(font_size)},PrimaryColour=&H{font_color[1:]}&,OutlineColour=&H{outline_color[1:]}&,BorderStyle={int(outline_thickness)},Outline=1'",
405
+ output_file_path,
406
+ ],
407
+ check=True,
408
+ )
409
+ return temp_srt_path, output_file_path
410
+ except subprocess.CalledProcessError as e:
411
+ raise gr.Error(f"Error during subtitle addition: {e}")
412
+ elif include_video and not audio_file_path.lower().endswith((".mp4", ".webm")):
413
+ gr.Warning(f"You have checked on the 'Include Video with Subtitles', but the input file {audio_file_path} isn't a video (.mp4 or .webm). Returning only the SRT File.", duration=15)
414
+
415
+ return temp_srt_path, None
416
+ except groq.RateLimitError as e:
417
+ handle_groq_error(e, model)
418
+ except ValueError as e:
419
+ raise gr.Error(f"Error creating SRT file: {e}")
420
+
421
+
422
+ theme = gr.themes.Soft(
423
+ primary_hue="sky",
424
+ secondary_hue="blue",
425
+ neutral_hue="neutral"
426
+ ).set(
427
+ border_color_primary='*neutral_300',
428
+ block_border_width='1px',
429
+ block_border_width_dark='1px',
430
+ block_title_border_color='*secondary_100',
431
+ block_title_border_color_dark='*secondary_200',
432
+ input_background_fill_focus='*secondary_300',
433
+ input_border_color='*border_color_primary',
434
+ input_border_color_focus='*secondary_500',
435
+ input_border_width='1px',
436
+ input_border_width_dark='1px',
437
+ slider_color='*secondary_500',
438
+ slider_color_dark='*secondary_600'
439
+ )
440
+
441
+ css = """
442
+ .gradio-container{max-width: 1400px !important}
443
+ h1{text-align:center}
444
+ .extra-option {
445
+ display: none;
446
+ }
447
+ .extra-option.visible {
448
+ display: block;
449
+ }
450
+ """
451
+
452
+
453
+ with gr.Blocks(theme=theme, css=css) as interface:
454
+ gr.Markdown(
455
+ """
456
+ # Fast Subtitle Maker
457
+ Inference by Groq API
458
+ If you are having API Rate Limit issues, you can retry later based on the [rate limits](https://console.groq.com/docs/rate-limits) or <a href="https://huggingface.co/spaces/Nick088/Fast-Subtitle-Maker?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank"> <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a> with <a href=https://console.groq.com/keys>your own API Key</a> </p>
459
+ Hugging Face Space by [Nick088](https://linktr.ee/Nick088)
460
+ <br> <a href="https://discord.gg/osai"> <img src="https://img.shields.io/discord/1198701940511617164?color=%23738ADB&label=Discord&style=for-the-badge" alt="Discord"> </a>
461
+ """
462
+ )
463
+ with gr.Row():
464
+ audio_input_subtitles = gr.File(label="Upload Audio/Video", file_types=[f".{ext}" for ext in ALLOWED_FILE_EXTENSIONS],)
465
+ model_choice_subtitles = gr.Dropdown(choices=["whisper-large-v3"], value="whisper-large-v3", label="Audio Speech Recogition (ASR) Model")
466
+ with gr.Row():
467
+ transcribe_prompt_subtitles = gr.Textbox(label="Prompt (Optional)", info="Specify any context or spelling corrections.")
468
+ with gr.Row():
469
+ language_subtitles = gr.Dropdown(choices=[(lang, code) for lang, code in LANGUAGE_CODES.items()], value="en", label="Language")
470
+ auto_detect_language_subtitles = gr.Checkbox(label="Auto Detect Language")
471
+ with gr.Row():
472
+ transcribe_button_subtitles = gr.Button("Generate Subtitles")
473
+ include_video_option = gr.Checkbox(label="Include Video with Subtitles")
474
+ gr.Markdown("The SubText Rip (SRT) File, contains the subtitles, you can upload this to any video editing app for adding the subs to your video and also modify/stilyze them")
475
+ srt_output = gr.File(label="SRT Output File")
476
+ show_subtitle_settings = gr.Checkbox(label="Show Subtitle Video Settings", visible=False)
477
+ with gr.Row(visible=False) as subtitle_video_settings:
478
+ with gr.Column():
479
+ font_selection = gr.Radio(["Arial", "Custom Font File"], value="Arial", label="Font Selection", info="Select what font to use")
480
+ font_file = gr.File(label="Upload Font File (TTF or OTF)", file_types=[".ttf", ".otf"], visible=False)
481
+ font_color = gr.ColorPicker(label="Font Color", value="#FFFFFF")
482
+ font_size = gr.Slider(label="Font Size (in pixels)", minimum=10, maximum=60, value=24, step=1)
483
+ outline_thickness = gr.Slider(label="Outline Thickness", minimum=0, maximum=5, value=1, step=1)
484
+ outline_color = gr.ColorPicker(label="Outline Color", value="#000000")
485
+
486
+
487
+ video_output = gr.Video(label="Output Video with Subtitles", visible=False)
488
+
489
+
490
+ # Event bindings
491
+
492
+ # show video output
493
+ include_video_option.change(lambda include_video: gr.update(visible=include_video), inputs=[include_video_option], outputs=[video_output])
494
+ # show video output subs settings checkbox
495
+ include_video_option.change(lambda include_video: gr.update(visible=include_video), inputs=[include_video_option], outputs=[show_subtitle_settings])
496
+ # show video output subs settings
497
+ show_subtitle_settings.change(lambda show: gr.update(visible=show), inputs=[show_subtitle_settings], outputs=[subtitle_video_settings])
498
+ # uncheck show subtitle settings checkbox if include video is unchecked (to make the output subs settings not visible)
499
+ show_subtitle_settings.change(lambda show, include_video: gr.update(visible=show and include_video), inputs=[show_subtitle_settings, include_video_option], outputs=[show_subtitle_settings])
500
+ # show custom font file selection
501
+ font_selection.change(lambda font_selection: gr.update(visible=font_selection == "Custom Font File"), inputs=[font_selection], outputs=[font_file])
502
+ # generate subtitles event
503
+ transcribe_button_subtitles.click(
504
+ generate_subtitles,
505
+ inputs=[
506
+ audio_input_subtitles,
507
+ transcribe_prompt_subtitles,
508
+ language_subtitles,
509
+ auto_detect_language_subtitles,
510
+ model_choice_subtitles,
511
+ include_video_option,
512
+ font_selection,
513
+ font_file,
514
+ font_color,
515
+ font_size,
516
+ outline_thickness,
517
+ outline_color,
518
+ ],
519
+ outputs=[srt_output, video_output],
520
+ )
521
+
522
+
523
+ interface.launch(share=True)
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio
2
+ groq