Atuluo commited on
Commit
13e86b5
·
verified ·
1 Parent(s): 350d573
Files changed (6) hide show
  1. LICENSE.md +36 -0
  2. README.md +13 -0
  3. app.py +597 -0
  4. gitattributes +35 -0
  5. packages.txt +1 -0
  6. requirements.txt +4 -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.
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Fast Subtitle Maker
3
+ emoji: 🔥
4
+ colorFrom: purple
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 4.38.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: other
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import json
4
+ from datetime import timedelta
5
+ import tempfile
6
+ import re
7
+ import yt_dlp
8
+ import gradio as gr
9
+ import groq
10
+ from groq import Groq
11
+
12
+
13
+ # setup groq
14
+
15
+ client = Groq(api_key=os.environ.get("Groq_Api_Key"))
16
+
17
+ def handle_groq_error(e, model_name):
18
+ error_data = e.args[0]
19
+
20
+ if isinstance(error_data, str):
21
+ # Use regex to extract the JSON part of the string
22
+ json_match = re.search(r'(\{.*\})', error_data)
23
+ if json_match:
24
+ json_str = json_match.group(1)
25
+ # Ensure the JSON string is well-formed
26
+ json_str = json_str.replace("'", '"') # Replace single quotes with double quotes
27
+ error_data = json.loads(json_str)
28
+
29
+ if isinstance(e, groq.AuthenticationError):
30
+ if isinstance(error_data, dict) and 'error' in error_data and 'message' in error_data['error']:
31
+ error_message = error_data['error']['message']
32
+ raise gr.Error(error_message)
33
+ elif isinstance(e, groq.RateLimitError):
34
+ if isinstance(error_data, dict) and 'error' in error_data and 'message' in error_data['error']:
35
+ error_message = error_data['error']['message']
36
+ error_message = re.sub(r'org_[a-zA-Z0-9]+', 'org_(censored)', error_message) # censor org
37
+ raise gr.Error(error_message)
38
+ else:
39
+ raise gr.Error(f"Error during Groq API call: {e}")
40
+
41
+
42
+ # language codes for subtitle maker
43
+
44
+ LANGUAGE_CODES = {
45
+ "English": "en",
46
+ "Chinese": "zh",
47
+ "German": "de",
48
+ "Spanish": "es",
49
+ "Russian": "ru",
50
+ "Korean": "ko",
51
+ "French": "fr",
52
+ "Japanese": "ja",
53
+ "Portuguese": "pt",
54
+ "Turkish": "tr",
55
+ "Polish": "pl",
56
+ "Catalan": "ca",
57
+ "Dutch": "nl",
58
+ "Arabic": "ar",
59
+ "Swedish": "sv",
60
+ "Italian": "it",
61
+ "Indonesian": "id",
62
+ "Hindi": "hi",
63
+ "Finnish": "fi",
64
+ "Vietnamese": "vi",
65
+ "Hebrew": "he",
66
+ "Ukrainian": "uk",
67
+ "Greek": "el",
68
+ "Malay": "ms",
69
+ "Czech": "cs",
70
+ "Romanian": "ro",
71
+ "Danish": "da",
72
+ "Hungarian": "hu",
73
+ "Tamil": "ta",
74
+ "Norwegian": "no",
75
+ "Thai": "th",
76
+ "Urdu": "ur",
77
+ "Croatian": "hr",
78
+ "Bulgarian": "bg",
79
+ "Lithuanian": "lt",
80
+ "Latin": "la",
81
+ "Māori": "mi",
82
+ "Malayalam": "ml",
83
+ "Welsh": "cy",
84
+ "Slovak": "sk",
85
+ "Telugu": "te",
86
+ "Persian": "fa",
87
+ "Latvian": "lv",
88
+ "Bengali": "bn",
89
+ "Serbian": "sr",
90
+ "Azerbaijani": "az",
91
+ "Slovenian": "sl",
92
+ "Kannada": "kn",
93
+ "Estonian": "et",
94
+ "Macedonian": "mk",
95
+ "Breton": "br",
96
+ "Basque": "eu",
97
+ "Icelandic": "is",
98
+ "Armenian": "hy",
99
+ "Nepali": "ne",
100
+ "Mongolian": "mn",
101
+ "Bosnian": "bs",
102
+ "Kazakh": "kk",
103
+ "Albanian": "sq",
104
+ "Swahili": "sw",
105
+ "Galician": "gl",
106
+ "Marathi": "mr",
107
+ "Panjabi": "pa",
108
+ "Sinhala": "si",
109
+ "Khmer": "km",
110
+ "Shona": "sn",
111
+ "Yoruba": "yo",
112
+ "Somali": "so",
113
+ "Afrikaans": "af",
114
+ "Occitan": "oc",
115
+ "Georgian": "ka",
116
+ "Belarusian": "be",
117
+ "Tajik": "tg",
118
+ "Sindhi": "sd",
119
+ "Gujarati": "gu",
120
+ "Amharic": "am",
121
+ "Yiddish": "yi",
122
+ "Lao": "lo",
123
+ "Uzbek": "uz",
124
+ "Faroese": "fo",
125
+ "Haitian": "ht",
126
+ "Pashto": "ps",
127
+ "Turkmen": "tk",
128
+ "Norwegian Nynorsk": "nn",
129
+ "Maltese": "mt",
130
+ "Sanskrit": "sa",
131
+ "Luxembourgish": "lb",
132
+ "Burmese": "my",
133
+ "Tibetan": "bo",
134
+ "Tagalog": "tl",
135
+ "Malagasy": "mg",
136
+ "Assamese": "as",
137
+ "Tatar": "tt",
138
+ "Hawaiian": "haw",
139
+ "Lingala": "ln",
140
+ "Hausa": "ha",
141
+ "Bashkir": "ba",
142
+ "jw": "jw",
143
+ "Sundanese": "su",
144
+ }
145
+
146
+
147
+ # download link input
148
+ def yt_dlp_download(link):
149
+ try:
150
+ ydl_opts = {
151
+ 'format': 'bestvideo+bestaudio/best', # Download best video and audio or best available
152
+ 'outtmpl': '%(title)s.%(ext)s',
153
+ 'nocheckcertificate': True,
154
+ 'ignoreerrors': False,
155
+ 'no_warnings': True,
156
+ 'quiet': True,
157
+ }
158
+
159
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
160
+ ydl.download([link])
161
+ result = ydl.extract_info(link, download=False)
162
+ download_path = ydl.prepare_filename(result)
163
+
164
+ return download_path
165
+ except yt_dlp.utils.DownloadError as e:
166
+ raise gr.Error(f"Download Error: {e}")
167
+ except ValueError as e:
168
+ raise gr.Error(f"Invalid Link or Format Error: {e}")
169
+ except Exception as e:
170
+ raise gr.Error(f"An unexpected error occurred: {e}")
171
+
172
+
173
+ # helper functions
174
+
175
+ def split_audio(input_file_path, chunk_size_mb):
176
+ chunk_size = chunk_size_mb * 1024 * 1024 # Convert MB to bytes
177
+ file_number = 1
178
+ chunks = []
179
+ with open(input_file_path, 'rb') as f:
180
+ chunk = f.read(chunk_size)
181
+ while chunk:
182
+ chunk_name = f"{os.path.splitext(input_file_path)[0]}_part{file_number:03}.mp3" # Pad file number for correct ordering
183
+ with open(chunk_name, 'wb') as chunk_file:
184
+ chunk_file.write(chunk)
185
+ chunks.append(chunk_name)
186
+ file_number += 1
187
+ chunk = f.read(chunk_size)
188
+ return chunks
189
+
190
+ def merge_audio(chunks, output_file_path):
191
+ with open("temp_list.txt", "w") as f:
192
+ for file in chunks:
193
+ f.write(f"file '{file}'\n")
194
+ try:
195
+ subprocess.run(
196
+ [
197
+ "ffmpeg",
198
+ "-f",
199
+ "concat",
200
+ "-safe", "0",
201
+ "-i",
202
+ "temp_list.txt",
203
+ "-c",
204
+ "copy",
205
+ "-y",
206
+ output_file_path
207
+ ],
208
+ check=True
209
+ )
210
+ os.remove("temp_list.txt")
211
+ for chunk in chunks:
212
+ os.remove(chunk)
213
+ except subprocess.CalledProcessError as e:
214
+ raise gr.Error(f"Error during audio merging: {e}")
215
+
216
+
217
+ # Checks file extension, size, and downsamples or splits if needed.
218
+
219
+ ALLOWED_FILE_EXTENSIONS = ["mp3", "mp4", "mpeg", "mpga", "m4a", "wav", "webm"]
220
+ MAX_FILE_SIZE_MB = 25
221
+ CHUNK_SIZE_MB = 25
222
+
223
+ def check_file(input_file_path):
224
+ if not input_file_path:
225
+ raise gr.Error("Please upload an audio/video file.")
226
+
227
+ file_size_mb = os.path.getsize(input_file_path) / (1024 * 1024)
228
+ file_extension = input_file_path.split(".")[-1].lower()
229
+
230
+ if file_extension not in ALLOWED_FILE_EXTENSIONS:
231
+ raise gr.Error(f"Invalid file type (.{file_extension}). Allowed types: {', '.join(ALLOWED_FILE_EXTENSIONS)}")
232
+
233
+ if file_size_mb > MAX_FILE_SIZE_MB:
234
+ gr.Warning(
235
+ 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"
236
+ )
237
+
238
+ output_file_path = os.path.splitext(input_file_path)[0] + "_downsampled.mp3"
239
+ try:
240
+ subprocess.run(
241
+ [
242
+ "ffmpeg",
243
+ "-i",
244
+ input_file_path,
245
+ "-ar",
246
+ "16000",
247
+ "-ab",
248
+ "128k",
249
+ "-ac",
250
+ "1",
251
+ "-f",
252
+ "mp3",
253
+ "-y",
254
+ output_file_path,
255
+ ],
256
+ check=True
257
+ )
258
+
259
+ # Check size after downsampling
260
+ downsampled_size_mb = os.path.getsize(output_file_path) / (1024 * 1024)
261
+ if downsampled_size_mb > MAX_FILE_SIZE_MB:
262
+ gr.Warning(f"File still too large after downsampling ({downsampled_size_mb:.2f} MB). Splitting into {CHUNK_SIZE_MB} MB chunks.")
263
+ return split_audio(output_file_path, CHUNK_SIZE_MB), "split"
264
+
265
+ return output_file_path, None
266
+ except subprocess.CalledProcessError as e:
267
+ raise gr.Error(f"Error during downsampling: {e}")
268
+ return input_file_path, None
269
+
270
+
271
+ # subtitle maker
272
+
273
+ def format_time(seconds):
274
+ hours = int(seconds // 3600)
275
+ minutes = int((seconds % 3600) // 60)
276
+ seconds = int(seconds % 60)
277
+ milliseconds = int((seconds % 1) * 1000)
278
+
279
+ return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
280
+
281
+ def json_to_srt(transcription_json):
282
+ srt_lines = []
283
+
284
+ for segment in transcription_json:
285
+ start_time = format_time(segment['start'])
286
+ end_time = format_time(segment['end'])
287
+ text = segment['text']
288
+
289
+ srt_line = f"{segment['id']+1}\n{start_time} --> {end_time}\n{text}\n"
290
+ srt_lines.append(srt_line)
291
+
292
+ return '\n'.join(srt_lines)
293
+
294
+
295
+ def generate_subtitles(input_mode, input_file, link_input, prompt, language, auto_detect_language, model, include_video, font_selection, font_file, font_color, font_size, outline_thickness, outline_color):
296
+ if input_mode == "Upload Video/Audio File":
297
+ input_file_path = input_file
298
+ elif input_mode == "Link Video/Audio":
299
+ input_file_path = yt_dlp_download(link_input)
300
+
301
+ processed_path, split_status = check_file(input_file_path)
302
+ full_srt_content = ""
303
+ total_duration = 0
304
+ segment_id_offset = 0
305
+
306
+ if split_status == "split":
307
+ srt_chunks = []
308
+ video_chunks = []
309
+ for i, chunk_path in enumerate(processed_path):
310
+ try:
311
+ with open(chunk_path, "rb") as file:
312
+ transcription_json_response = client.audio.transcriptions.create(
313
+ file=(os.path.basename(chunk_path), file.read()),
314
+ model=model,
315
+ prompt=prompt,
316
+ response_format="verbose_json",
317
+ language=None if auto_detect_language else language,
318
+ temperature=0.0,
319
+ )
320
+ transcription_json = transcription_json_response.segments
321
+
322
+ # Adjust timestamps and segment IDs
323
+ for segment in transcription_json:
324
+ segment['start'] += total_duration
325
+ segment['end'] += total_duration
326
+ segment['id'] += segment_id_offset
327
+ segment_id_offset += len(transcription_json)
328
+ total_duration += transcription_json[-1]['end'] # Update total duration
329
+
330
+ srt_content = json_to_srt(transcription_json)
331
+ full_srt_content += srt_content
332
+ temp_srt_path = f"{os.path.splitext(chunk_path)[0]}.srt"
333
+ with open(temp_srt_path, "w", encoding="utf-8") as temp_srt_file:
334
+ temp_srt_file.write(srt_content)
335
+ temp_srt_file.write("\n") # add a new line at the end of the srt chunk file to fix format when merged
336
+ srt_chunks.append(temp_srt_path)
337
+
338
+ if include_video and input_file_path.lower().endswith((".mp4", ".webm")):
339
+ try:
340
+ output_file_path = chunk_path.replace(os.path.splitext(chunk_path)[1], "_with_subs" + os.path.splitext(chunk_path)[1])
341
+ # Handle font selection
342
+ if font_selection == "Custom Font File" and font_file:
343
+ font_name = os.path.splitext(os.path.basename(font_file.name))[0] # Get font filename without extension
344
+ font_dir = os.path.dirname(font_file.name) # Get font directory path
345
+ elif font_selection == "Custom Font File" and not font_file:
346
+ font_name = None # Let FFmpeg use its default Arial
347
+ font_dir = None # No font directory
348
+ gr.Warning(f"You want to use a Custom Font File, but uploaded none. Using the default Arial font.")
349
+ elif font_selection == "Arial":
350
+ font_name = None # Let FFmpeg use its default Arial
351
+ font_dir = None # No font directory
352
+
353
+ # FFmpeg command
354
+ subprocess.run(
355
+ [
356
+ "ffmpeg",
357
+ "-y",
358
+ "-i",
359
+ chunk_path,
360
+ "-vf",
361
+ 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'",
362
+ "-preset", "fast",
363
+ output_file_path,
364
+ ],
365
+ check=True,
366
+ )
367
+ video_chunks.append(output_file_path)
368
+ except subprocess.CalledProcessError as e:
369
+ raise gr.Error(f"Error during subtitle addition: {e}")
370
+ elif include_video and not input_file_path.lower().endswith((".mp4", ".webm")):
371
+ gr.Warning(f"You have checked on the 'Include Video with Subtitles', but the input file {input_file_path} isn't a video (.mp4 or .webm). Returning only the SRT File.", duration=15)
372
+ except groq.AuthenticationError as e:
373
+ handle_groq_error(e, model)
374
+ except groq.RateLimitError as e:
375
+ handle_groq_error(e, model)
376
+ gr.Warning(f"API limit reached during chunk {i+1}. Returning processed chunks only.")
377
+ if srt_chunks and video_chunks:
378
+ merge_audio(video_chunks, 'merged_output_video.mp4')
379
+ with open('merged_output.srt', 'w', encoding="utf-8") as outfile:
380
+ for chunk_srt in srt_chunks:
381
+ with open(chunk_srt, 'r', encoding="utf-8") as infile:
382
+ outfile.write(infile.read())
383
+ return 'merged_output.srt', 'merged_output_video.mp4'
384
+ else:
385
+ raise gr.Error("Subtitle generation failed due to API limits.")
386
+
387
+ # Merge SRT chunks
388
+ final_srt_path = os.path.splitext(input_file_path)[0] + "_final.srt"
389
+ with open(final_srt_path, 'w', encoding="utf-8") as outfile:
390
+ for chunk_srt in srt_chunks:
391
+ with open(chunk_srt, 'r', encoding="utf-8") as infile:
392
+ outfile.write(infile.read())
393
+
394
+ # Merge video chunks
395
+ if video_chunks:
396
+ merge_audio(video_chunks, 'merged_output_video.mp4')
397
+ return final_srt_path, 'merged_output_video.mp4'
398
+ else:
399
+ return final_srt_path, None
400
+
401
+ else: # Single file processing (no splitting)
402
+ try:
403
+ with open(processed_path, "rb") as file:
404
+ transcription_json_response = client.audio.transcriptions.create(
405
+ file=(os.path.basename(processed_path), file.read()),
406
+ model=model,
407
+ prompt=prompt,
408
+ response_format="verbose_json",
409
+ language=None if auto_detect_language else language,
410
+ temperature=0.0,
411
+ )
412
+ transcription_json = transcription_json_response.segments
413
+
414
+ srt_content = json_to_srt(transcription_json)
415
+ temp_srt_path = os.path.splitext(input_file_path)[0] + ".srt"
416
+ with open(temp_srt_path, "w", encoding="utf-8") as temp_srt_file:
417
+ temp_srt_file.write(srt_content)
418
+
419
+ if include_video and input_file_path.lower().endswith((".mp4", ".webm")):
420
+ try:
421
+ output_file_path = input_file_path.replace(
422
+ os.path.splitext(input_file_path)[1], "_with_subs" + os.path.splitext(input_file_path)[1]
423
+ )
424
+ # Handle font selection
425
+ if font_selection == "Custom Font File" and font_file:
426
+ font_name = os.path.splitext(os.path.basename(font_file.name))[0] # Get font filename without extension
427
+ font_dir = os.path.dirname(font_file.name) # Get font directory path
428
+ elif font_selection == "Custom Font File" and not font_file:
429
+ font_name = None # Let FFmpeg use its default Arial
430
+ font_dir = None # No font directory
431
+ gr.Warning(f"You want to use a Custom Font File, but uploaded none. Using the default Arial font.")
432
+ elif font_selection == "Arial":
433
+ font_name = None # Let FFmpeg use its default Arial
434
+ font_dir = None # No font directory
435
+
436
+ # FFmpeg command
437
+ subprocess.run(
438
+ [
439
+ "ffmpeg",
440
+ "-y",
441
+ "-i",
442
+ input_file_path,
443
+ "-vf",
444
+ 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'",
445
+ "-preset", "fast",
446
+ output_file_path,
447
+ ],
448
+ check=True,
449
+ )
450
+ return temp_srt_path, output_file_path
451
+ except subprocess.CalledProcessError as e:
452
+ raise gr.Error(f"Error during subtitle addition: {e}")
453
+ elif include_video and not input_file_path.lower().endswith((".mp4", ".webm")):
454
+ gr.Warning(f"You have checked on the 'Include Video with Subtitles', but the input file {input_file_path} isn't a video (.mp4 or .webm). Returning only the SRT File.", duration=15)
455
+
456
+ return temp_srt_path, None
457
+ except groq.AuthenticationError as e:
458
+ handle_groq_error(e, model)
459
+ except groq.RateLimitError as e:
460
+ handle_groq_error(e, model)
461
+ except ValueError as e:
462
+ raise gr.Error(f"Error creating SRT file: {e}")
463
+
464
+
465
+ theme = gr.themes.Soft(
466
+ primary_hue="sky",
467
+ secondary_hue="blue",
468
+ neutral_hue="neutral"
469
+ ).set(
470
+ border_color_primary='*neutral_300',
471
+ block_border_width='1px',
472
+ block_border_width_dark='1px',
473
+ block_title_border_color='*secondary_100',
474
+ block_title_border_color_dark='*secondary_200',
475
+ input_background_fill_focus='*secondary_300',
476
+ input_border_color='*border_color_primary',
477
+ input_border_color_focus='*secondary_500',
478
+ input_border_width='1px',
479
+ input_border_width_dark='1px',
480
+ slider_color='*secondary_500',
481
+ slider_color_dark='*secondary_600'
482
+ )
483
+
484
+ css = """
485
+ .gradio-container{max-width: 1400px !important}
486
+ h1{text-align:center}
487
+ .extra-option {
488
+ display: none;
489
+ }
490
+ .extra-option.visible {
491
+ display: block;
492
+ }
493
+ """
494
+
495
+
496
+
497
+ with gr.Blocks(theme=theme, css=css) as interface:
498
+ gr.Markdown(
499
+ """
500
+ # Fast Subtitle Maker
501
+ Inference by Groq API
502
+ 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>
503
+ Hugging Face Space by [Nick088](https://linktr.ee/Nick088)
504
+ <br> <a href="https://discord.gg/AQsmBmgEPy"> <img src="https://img.shields.io/discord/1198701940511617164?color=%23738ADB&label=Discord&style=for-the-badge" alt="Discord"> </a>
505
+ """
506
+ )
507
+
508
+ with gr.Column():
509
+ # Input mode selection
510
+ input_mode = gr.Dropdown(choices=["Upload Video/Audio File", "Link Video/Audio"], value="Upload Video/Audio File", label="Input Mode")
511
+ # Input components
512
+ input_file = gr.File(label="Upload Audio/Video", file_types=[f".{ext}" for ext in ALLOWED_FILE_EXTENSIONS], visible=True)
513
+ link_input_info = gr.Markdown("Using yt-dlp to download Youtube Video Links + other platform's ones. Check [all supported sites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md)!", visible=False)
514
+ link_input = gr.Textbox(label="Enter Video/Audio Link", visible=False)
515
+
516
+ # Model and options
517
+ model_choice_subtitles = gr.Dropdown(choices=["whisper-large-v3", "distil-whisper-large-v3-en"], value="whisper-large-v3", label="Audio Speech Recogition (ASR) Model")
518
+ transcribe_prompt_subtitles = gr.Textbox(label="Prompt (Optional)", info="Specify any context or spelling corrections.")
519
+ with gr.Row():
520
+ language_subtitles = gr.Dropdown(choices=[(lang, code) for lang, code in LANGUAGE_CODES.items()], value="en", label="Language")
521
+ auto_detect_language_subtitles = gr.Checkbox(label="Auto Detect Language")
522
+
523
+ # Generate button
524
+ transcribe_button_subtitles = gr.Button("Generate Subtitles")
525
+
526
+ # Output and settings
527
+ include_video_option = gr.Checkbox(label="Include Video with Subtitles")
528
+ 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")
529
+ srt_output = gr.File(label="SRT Output File")
530
+ show_subtitle_settings = gr.Checkbox(label="Show Subtitle Video Settings", visible=False)
531
+ with gr.Row(visible=False) as subtitle_video_settings:
532
+ with gr.Column():
533
+ font_selection = gr.Radio(["Arial", "Custom Font File"], value="Arial", label="Font Selection", info="Select what font to use")
534
+ font_file = gr.File(label="Upload Font File (TTF or OTF)", file_types=[".ttf", ".otf"], visible=False)
535
+ font_color = gr.ColorPicker(label="Font Color", value="#FFFFFF")
536
+ font_size = gr.Slider(label="Font Size (in pixels)", minimum=10, maximum=60, value=24, step=1)
537
+ outline_thickness = gr.Slider(label="Outline Thickness", minimum=0, maximum=5, value=1, step=1)
538
+ outline_color = gr.ColorPicker(label="Outline Color", value="#000000")
539
+
540
+
541
+ video_output = gr.Video(label="Output Video with Subtitles", visible=False)
542
+
543
+
544
+ # Event bindings
545
+
546
+ # input mode
547
+ def toggle_input(mode):
548
+ if mode == "Upload Video/Audio File":
549
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
550
+ else:
551
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)
552
+
553
+ input_mode.change(fn=toggle_input, inputs=[input_mode], outputs=[input_file, link_input_info, link_input])
554
+
555
+ # show video output
556
+ include_video_option.change(lambda include_video: gr.update(visible=include_video), inputs=[include_video_option], outputs=[video_output])
557
+ # show video output subs settings checkbox
558
+ include_video_option.change(lambda include_video: gr.update(visible=include_video), inputs=[include_video_option], outputs=[show_subtitle_settings])
559
+ # show video output subs settings
560
+ show_subtitle_settings.change(lambda show: gr.update(visible=show), inputs=[show_subtitle_settings], outputs=[subtitle_video_settings])
561
+ # uncheck show subtitle settings checkbox if include video is unchecked (to make the output subs settings not visible)
562
+ 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])
563
+ # show custom font file selection
564
+ font_selection.change(lambda font_selection: gr.update(visible=font_selection == "Custom Font File"), inputs=[font_selection], outputs=[font_file])
565
+
566
+ # Update language dropdown based on model selection
567
+ def update_language_options(model):
568
+ if model == "distil-whisper-large-v3-en":
569
+ return gr.update(choices=[("English", "en")], value="en", interactive=False)
570
+ else:
571
+ return gr.update(choices=[(lang, code) for lang, code in LANGUAGE_CODES.items()], value="en", interactive=True)
572
+
573
+ model_choice_subtitles.change(fn=update_language_options, inputs=[model_choice_subtitles], outputs=[language_subtitles])
574
+
575
+ # Modified generate subtitles event
576
+ transcribe_button_subtitles.click(
577
+ fn=generate_subtitles,
578
+ inputs=[
579
+ input_mode,
580
+ input_file,
581
+ link_input,
582
+ transcribe_prompt_subtitles,
583
+ language_subtitles,
584
+ auto_detect_language_subtitles,
585
+ model_choice_subtitles,
586
+ include_video_option,
587
+ font_selection,
588
+ font_file,
589
+ font_color,
590
+ font_size,
591
+ outline_thickness,
592
+ outline_color,
593
+ ],
594
+ outputs=[srt_output, video_output],
595
+ )
596
+
597
+ interface.launch(share=True)
gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm 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
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ certifi
2
+ yt-dlp
3
+ gradio
4
+ groq