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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code written by me, organized with the help of AI.
|
| 2 |
+
"""
|
| 3 |
+
A comprehensive toolkit for generating and translating subtitles from media files.
|
| 4 |
+
|
| 5 |
+
This module provides functionalities to:
|
| 6 |
+
1. Download AI models from Hugging Face without requiring a token.
|
| 7 |
+
2. Transcribe audio from media files using a high-performance Whisper model.
|
| 8 |
+
3. Generate multiple formats of SRT subtitles (default, professional multi-line, word-level, and shorts-style).
|
| 9 |
+
4. Translate subtitles into different languages.
|
| 10 |
+
5. Orchestrate the entire process through a simple-to-use main function.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
# ==============================================================================
|
| 14 |
+
# --- 1. IMPORTS
|
| 15 |
+
# ==============================================================================
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import re
|
| 19 |
+
import gc
|
| 20 |
+
import uuid
|
| 21 |
+
import math
|
| 22 |
+
import shutil
|
| 23 |
+
import string
|
| 24 |
+
import requests
|
| 25 |
+
import urllib.request
|
| 26 |
+
import urllib.error
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import pysrt
|
| 30 |
+
from tqdm.auto import tqdm
|
| 31 |
+
from faster_whisper import WhisperModel
|
| 32 |
+
from deep_translator import GoogleTranslator
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ==============================================================================
|
| 36 |
+
# --- 2. CONSTANTS & CONFIGURATION
|
| 37 |
+
# ==============================================================================
|
| 38 |
+
|
| 39 |
+
# Folder paths for storing generated files and temporary audio
|
| 40 |
+
SUBTITLE_FOLDER = "./generated_subtitle"
|
| 41 |
+
TEMP_FOLDER = "./subtitle_audio"
|
| 42 |
+
|
| 43 |
+
# Mapping of language names to their ISO 639-1 codes
|
| 44 |
+
LANGUAGE_CODE = {
|
| 45 |
+
'Akan': 'aka', 'Albanian': 'sq', 'Amharic': 'am', 'Arabic': 'ar', 'Armenian': 'hy',
|
| 46 |
+
'Assamese': 'as', 'Azerbaijani': 'az', 'Basque': 'eu', 'Bashkir': 'ba', 'Bengali': 'bn',
|
| 47 |
+
'Bosnian': 'bs', 'Bulgarian': 'bg', 'Burmese': 'my', 'Catalan': 'ca', 'Chinese': 'zh',
|
| 48 |
+
'Croatian': 'hr', 'Czech': 'cs', 'Danish': 'da', 'Dutch': 'nl', 'English': 'en',
|
| 49 |
+
'Estonian': 'et', 'Faroese': 'fo', 'Finnish': 'fi', 'French': 'fr', 'Galician': 'gl',
|
| 50 |
+
'Georgian': 'ka', 'German': 'de', 'Greek': 'el', 'Gujarati': 'gu', 'Haitian Creole': 'ht',
|
| 51 |
+
'Hausa': 'ha', 'Hebrew': 'he', 'Hindi': 'hi', 'Hungarian': 'hu', 'Icelandic': 'is',
|
| 52 |
+
'Indonesian': 'id', 'Italian': 'it', 'Japanese': 'ja', 'Kannada': 'kn', 'Kazakh': 'kk',
|
| 53 |
+
'Korean': 'ko', 'Kurdish': 'ckb', 'Kyrgyz': 'ky', 'Lao': 'lo', 'Lithuanian': 'lt',
|
| 54 |
+
'Luxembourgish': 'lb', 'Macedonian': 'mk', 'Malay': 'ms', 'Malayalam': 'ml', 'Maltese': 'mt',
|
| 55 |
+
'Maori': 'mi', 'Marathi': 'mr', 'Mongolian': 'mn', 'Nepali': 'ne', 'Norwegian': 'no',
|
| 56 |
+
'Norwegian Nynorsk': 'nn', 'Pashto': 'ps', 'Persian': 'fa', 'Polish': 'pl', 'Portuguese': 'pt',
|
| 57 |
+
'Punjabi': 'pa', 'Romanian': 'ro', 'Russian': 'ru', 'Serbian': 'sr', 'Sinhala': 'si',
|
| 58 |
+
'Slovak': 'sk', 'Slovenian': 'sl', 'Somali': 'so', 'Spanish': 'es', 'Sundanese': 'su',
|
| 59 |
+
'Swahili': 'sw', 'Swedish': 'sv', 'Tamil': 'ta', 'Telugu': 'te', 'Thai': 'th',
|
| 60 |
+
'Turkish': 'tr', 'Ukrainian': 'uk', 'Urdu': 'ur', 'Uzbek': 'uz', 'Vietnamese': 'vi',
|
| 61 |
+
'Welsh': 'cy', 'Yiddish': 'yi', 'Yoruba': 'yo', 'Zulu': 'zu'
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ==============================================================================
|
| 66 |
+
# --- 3. FILE & MODEL DOWNLOADING UTILITIES
|
| 67 |
+
# ==============================================================================
|
| 68 |
+
|
| 69 |
+
def download_file(url, download_file_path, redownload=False):
|
| 70 |
+
"""Download a single file with urllib and a tqdm progress bar."""
|
| 71 |
+
base_path = os.path.dirname(download_file_path)
|
| 72 |
+
os.makedirs(base_path, exist_ok=True)
|
| 73 |
+
|
| 74 |
+
if os.path.exists(download_file_path):
|
| 75 |
+
if redownload:
|
| 76 |
+
os.remove(download_file_path)
|
| 77 |
+
tqdm.write(f"♻️ Redownloading: {os.path.basename(download_file_path)}")
|
| 78 |
+
elif os.path.getsize(download_file_path) > 0:
|
| 79 |
+
tqdm.write(f"✔️ Skipped (already exists): {os.path.basename(download_file_path)}")
|
| 80 |
+
return True
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
request = urllib.request.urlopen(url)
|
| 84 |
+
total = int(request.headers.get('Content-Length', 0))
|
| 85 |
+
except urllib.error.URLError as e:
|
| 86 |
+
print(f"❌ Error: Unable to open URL: {url}")
|
| 87 |
+
print(f"Reason: {e.reason}")
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
with tqdm(total=total, desc=os.path.basename(download_file_path), unit='B', unit_scale=True, unit_divisor=1024) as progress:
|
| 91 |
+
try:
|
| 92 |
+
urllib.request.urlretrieve(
|
| 93 |
+
url,
|
| 94 |
+
download_file_path,
|
| 95 |
+
reporthook=lambda count, block_size, total_size: progress.update(block_size)
|
| 96 |
+
)
|
| 97 |
+
except urllib.error.URLError as e:
|
| 98 |
+
print(f"❌ Error: Failed to download {url}")
|
| 99 |
+
print(f"Reason: {e.reason}")
|
| 100 |
+
return False
|
| 101 |
+
|
| 102 |
+
tqdm.write(f"⬇️ Downloaded: {os.path.basename(download_file_path)}")
|
| 103 |
+
return True
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def download_model(repo_id, download_folder="./", redownload=False):
|
| 107 |
+
"""
|
| 108 |
+
Downloads all files from a Hugging Face repository using the public API,
|
| 109 |
+
avoiding the need for a Hugging Face token for public models.
|
| 110 |
+
"""
|
| 111 |
+
if not download_folder.strip():
|
| 112 |
+
download_folder = "."
|
| 113 |
+
|
| 114 |
+
api_url = f"https://huggingface.co/api/models/{repo_id}"
|
| 115 |
+
model_name = repo_id.split('/')[-1]
|
| 116 |
+
download_dir = os.path.abspath(f"{download_folder.rstrip('/')}/{model_name}")
|
| 117 |
+
os.makedirs(download_dir, exist_ok=True)
|
| 118 |
+
|
| 119 |
+
print(f"📂 Download directory: {download_dir}")
|
| 120 |
+
|
| 121 |
+
try:
|
| 122 |
+
response = requests.get(api_url)
|
| 123 |
+
response.raise_for_status()
|
| 124 |
+
except requests.exceptions.RequestException as e:
|
| 125 |
+
print(f"❌ Error fetching repo info: {e}")
|
| 126 |
+
return None
|
| 127 |
+
|
| 128 |
+
data = response.json()
|
| 129 |
+
files_to_download = [f["rfilename"] for f in data.get("siblings", [])]
|
| 130 |
+
|
| 131 |
+
if not files_to_download:
|
| 132 |
+
print(f"⚠️ No files found in repo '{repo_id}'.")
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
print(f"📦 Found {len(files_to_download)} files in repo '{repo_id}'. Checking cache...")
|
| 136 |
+
|
| 137 |
+
for file in tqdm(files_to_download, desc="Processing files", unit="file"):
|
| 138 |
+
file_url = f"https://huggingface.co/{repo_id}/resolve/main/{file}"
|
| 139 |
+
file_path = os.path.join(download_dir, file)
|
| 140 |
+
download_file(file_url, file_path, redownload=redownload)
|
| 141 |
+
|
| 142 |
+
return download_dir
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# ==============================================================================
|
| 146 |
+
# --- 4. CORE TRANSCRIPTION & PROCESSING LOGIC
|
| 147 |
+
# ==============================================================================
|
| 148 |
+
|
| 149 |
+
def get_language_name(code):
|
| 150 |
+
"""Retrieves the full language name from its code."""
|
| 151 |
+
for name, value in LANGUAGE_CODE.items():
|
| 152 |
+
if value == code:
|
| 153 |
+
return name
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
def clean_file_name(file_path):
|
| 157 |
+
"""Generates a clean, unique file name to avoid path issues."""
|
| 158 |
+
dir_name = os.path.dirname(file_path)
|
| 159 |
+
base_name, extension = os.path.splitext(os.path.basename(file_path))
|
| 160 |
+
|
| 161 |
+
cleaned_base = re.sub(r'[^a-zA-Z\d]+', '_', base_name)
|
| 162 |
+
cleaned_base = re.sub(r'_+', '_', cleaned_base).strip('_')
|
| 163 |
+
random_uuid = uuid.uuid4().hex[:6]
|
| 164 |
+
|
| 165 |
+
return os.path.join(dir_name, f"{cleaned_base}_{random_uuid}{extension}")
|
| 166 |
+
|
| 167 |
+
def format_segments(segments):
|
| 168 |
+
"""Formats the raw segments from Whisper into structured lists."""
|
| 169 |
+
sentence_timestamp = []
|
| 170 |
+
words_timestamp = []
|
| 171 |
+
speech_to_text = ""
|
| 172 |
+
|
| 173 |
+
for i in segments:
|
| 174 |
+
text = i.text.strip()
|
| 175 |
+
sentence_id = len(sentence_timestamp)
|
| 176 |
+
sentence_timestamp.append({
|
| 177 |
+
"id": sentence_id,
|
| 178 |
+
"text": text,
|
| 179 |
+
"start": i.start,
|
| 180 |
+
"end": i.end,
|
| 181 |
+
"words": []
|
| 182 |
+
})
|
| 183 |
+
speech_to_text += text + " "
|
| 184 |
+
|
| 185 |
+
for word in i.words:
|
| 186 |
+
word_data = {
|
| 187 |
+
"word": word.word.strip(),
|
| 188 |
+
"start": word.start,
|
| 189 |
+
"end": word.end
|
| 190 |
+
}
|
| 191 |
+
sentence_timestamp[sentence_id]["words"].append(word_data)
|
| 192 |
+
words_timestamp.append(word_data)
|
| 193 |
+
|
| 194 |
+
return sentence_timestamp, words_timestamp, speech_to_text.strip()
|
| 195 |
+
|
| 196 |
+
def get_audio_file(uploaded_file):
|
| 197 |
+
"""Copies the uploaded media file to a temporary location for processing."""
|
| 198 |
+
temp_path = os.path.join(TEMP_FOLDER, os.path.basename(uploaded_file))
|
| 199 |
+
cleaned_path = clean_file_name(temp_path)
|
| 200 |
+
shutil.copy(uploaded_file, cleaned_path)
|
| 201 |
+
return cleaned_path
|
| 202 |
+
|
| 203 |
+
def whisper_subtitle(uploaded_file, source_language):
|
| 204 |
+
"""
|
| 205 |
+
Main transcription function. Loads the model, transcribes the audio,
|
| 206 |
+
and generates subtitle files.
|
| 207 |
+
"""
|
| 208 |
+
# 1. Configure device and model
|
| 209 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 210 |
+
compute_type = "float16" if torch.cuda.is_available() else "int8"
|
| 211 |
+
model_dir = download_model(
|
| 212 |
+
"deepdml/faster-whisper-large-v3-turbo-ct2",
|
| 213 |
+
download_folder="./",
|
| 214 |
+
redownload=False
|
| 215 |
+
)
|
| 216 |
+
model = WhisperModel(model_dir, device=device, compute_type=compute_type)
|
| 217 |
+
# model = WhisperModel("deepdml/faster-whisper-large-v3-turbo-ct2",device=device, compute_type=compute_type)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# 2. Process audio file
|
| 221 |
+
audio_file_path = get_audio_file(uploaded_file)
|
| 222 |
+
|
| 223 |
+
# 3. Transcribe
|
| 224 |
+
detected_language = source_language
|
| 225 |
+
if source_language == "Automatic":
|
| 226 |
+
segments, info = model.transcribe(audio_file_path, word_timestamps=True)
|
| 227 |
+
detected_lang_code = info.language
|
| 228 |
+
detected_language = get_language_name(detected_lang_code)
|
| 229 |
+
else:
|
| 230 |
+
lang_code = LANGUAGE_CODE[source_language]
|
| 231 |
+
segments, _ = model.transcribe(audio_file_path, word_timestamps=True, language=lang_code)
|
| 232 |
+
|
| 233 |
+
sentence_timestamps, word_timestamps, transcript_text = format_segments(segments)
|
| 234 |
+
|
| 235 |
+
# 4. Cleanup
|
| 236 |
+
if os.path.exists(audio_file_path):
|
| 237 |
+
os.remove(audio_file_path)
|
| 238 |
+
del model
|
| 239 |
+
gc.collect()
|
| 240 |
+
if torch.cuda.is_available():
|
| 241 |
+
torch.cuda.empty_cache()
|
| 242 |
+
|
| 243 |
+
# 5. Prepare output file paths
|
| 244 |
+
base_filename = os.path.splitext(os.path.basename(uploaded_file))[0][:30]
|
| 245 |
+
srt_base = f"{SUBTITLE_FOLDER}/{base_filename}_{detected_language}.srt"
|
| 246 |
+
clean_srt_path = clean_file_name(srt_base)
|
| 247 |
+
txt_path = clean_srt_path.replace(".srt", ".txt")
|
| 248 |
+
word_srt_path = clean_srt_path.replace(".srt", "_word_level.srt")
|
| 249 |
+
custom_srt_path = clean_srt_path.replace(".srt", "_Multiline.srt")
|
| 250 |
+
shorts_srt_path = clean_srt_path.replace(".srt", "_shorts.srt")
|
| 251 |
+
|
| 252 |
+
# 6. Generate all subtitle files
|
| 253 |
+
generate_srt_from_sentences(sentence_timestamps, srt_path=clean_srt_path)
|
| 254 |
+
word_level_srt(word_timestamps, srt_path=word_srt_path)
|
| 255 |
+
write_sentence_srt(
|
| 256 |
+
word_timestamps, output_file=shorts_srt_path, max_lines=1,
|
| 257 |
+
max_duration_s=3.0, max_chars_per_line=17
|
| 258 |
+
)
|
| 259 |
+
write_sentence_srt(
|
| 260 |
+
word_timestamps, output_file=custom_srt_path, max_lines=2,
|
| 261 |
+
max_duration_s=7.0, max_chars_per_line=38
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
with open(txt_path, 'w', encoding='utf-8') as f:
|
| 265 |
+
f.write(transcript_text)
|
| 266 |
+
|
| 267 |
+
return (
|
| 268 |
+
clean_srt_path, custom_srt_path, word_srt_path, shorts_srt_path,
|
| 269 |
+
txt_path, transcript_text, detected_language
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# ==============================================================================
|
| 274 |
+
# --- 5. SUBTITLE GENERATION & FORMATTING
|
| 275 |
+
# ==============================================================================
|
| 276 |
+
|
| 277 |
+
def convert_time_to_srt_format(seconds):
|
| 278 |
+
"""Converts seconds to the standard SRT time format (HH:MM:SS,ms)."""
|
| 279 |
+
hours = int(seconds // 3600)
|
| 280 |
+
minutes = int((seconds % 3600) // 60)
|
| 281 |
+
secs = int(seconds % 60)
|
| 282 |
+
milliseconds = round((seconds - int(seconds)) * 1000)
|
| 283 |
+
|
| 284 |
+
if milliseconds == 1000:
|
| 285 |
+
milliseconds = 0
|
| 286 |
+
secs += 1
|
| 287 |
+
if secs == 60:
|
| 288 |
+
secs, minutes = 0, minutes + 1
|
| 289 |
+
if minutes == 60:
|
| 290 |
+
minutes, hours = 0, hours + 1
|
| 291 |
+
|
| 292 |
+
return f"{hours:02}:{minutes:02}:{secs:02},{milliseconds:03}"
|
| 293 |
+
|
| 294 |
+
def split_line_by_char_limit(text, max_chars_per_line=38):
|
| 295 |
+
"""Splits a string into multiple lines based on a character limit."""
|
| 296 |
+
words = text.split()
|
| 297 |
+
lines = []
|
| 298 |
+
current_line = ""
|
| 299 |
+
for word in words:
|
| 300 |
+
if not current_line:
|
| 301 |
+
current_line = word
|
| 302 |
+
elif len(current_line + " " + word) <= max_chars_per_line:
|
| 303 |
+
current_line += " " + word
|
| 304 |
+
else:
|
| 305 |
+
lines.append(current_line)
|
| 306 |
+
current_line = word
|
| 307 |
+
if current_line:
|
| 308 |
+
lines.append(current_line)
|
| 309 |
+
return lines
|
| 310 |
+
|
| 311 |
+
def merge_punctuation_glitches(subtitles):
|
| 312 |
+
"""Cleans up punctuation artifacts at the boundaries of subtitle entries."""
|
| 313 |
+
if not subtitles:
|
| 314 |
+
return []
|
| 315 |
+
|
| 316 |
+
cleaned = [subtitles[0]]
|
| 317 |
+
for i in range(1, len(subtitles)):
|
| 318 |
+
prev = cleaned[-1]
|
| 319 |
+
curr = subtitles[i]
|
| 320 |
+
|
| 321 |
+
prev_text = prev["text"].rstrip()
|
| 322 |
+
curr_text = curr["text"].lstrip()
|
| 323 |
+
|
| 324 |
+
match = re.match(r'^([,.:;!?]+)(\s*)(.+)', curr_text)
|
| 325 |
+
if match:
|
| 326 |
+
punct, _, rest = match.groups()
|
| 327 |
+
if not prev_text.endswith(tuple(punct)):
|
| 328 |
+
prev["text"] = prev_text + punct
|
| 329 |
+
curr_text = rest.strip()
|
| 330 |
+
|
| 331 |
+
unwanted_chars = ['"', '“', '”', ';', ':']
|
| 332 |
+
for ch in unwanted_chars:
|
| 333 |
+
curr_text = curr_text.replace(ch, '')
|
| 334 |
+
curr_text = curr_text.strip()
|
| 335 |
+
|
| 336 |
+
if not curr_text or re.fullmatch(r'[.,!?]+', curr_text):
|
| 337 |
+
prev["end"] = curr["end"]
|
| 338 |
+
continue
|
| 339 |
+
|
| 340 |
+
curr["text"] = curr_text
|
| 341 |
+
prev["text"] = prev["text"].replace('"', '').replace('“', '').replace('”', '')
|
| 342 |
+
cleaned.append(curr)
|
| 343 |
+
|
| 344 |
+
return cleaned
|
| 345 |
+
|
| 346 |
+
def write_sentence_srt(
|
| 347 |
+
word_level_timestamps, output_file="subtitles_professional.srt", max_lines=2,
|
| 348 |
+
max_duration_s=7.0, max_chars_per_line=38, hard_pause_threshold=0.5,
|
| 349 |
+
merge_pause_threshold=0.4
|
| 350 |
+
):
|
| 351 |
+
"""Creates professional-grade SRT files with smart line breaking and merging."""
|
| 352 |
+
if not word_level_timestamps:
|
| 353 |
+
return
|
| 354 |
+
|
| 355 |
+
# Phase 1: Generate draft subtitles based on timing and length rules
|
| 356 |
+
draft_subtitles = []
|
| 357 |
+
i = 0
|
| 358 |
+
while i < len(word_level_timestamps):
|
| 359 |
+
start_time = word_level_timestamps[i]["start"]
|
| 360 |
+
current_words = []
|
| 361 |
+
j = i
|
| 362 |
+
while j < len(word_level_timestamps):
|
| 363 |
+
entry = word_level_timestamps[j]
|
| 364 |
+
potential_text = " ".join(current_words + [entry["word"]])
|
| 365 |
+
|
| 366 |
+
if len(split_line_by_char_limit(potential_text, max_chars_per_line)) > max_lines: break
|
| 367 |
+
if (entry["end"] - start_time) > max_duration_s and current_words: break
|
| 368 |
+
|
| 369 |
+
if j > i:
|
| 370 |
+
prev_entry = word_level_timestamps[j-1]
|
| 371 |
+
pause = entry["start"] - prev_entry["end"]
|
| 372 |
+
if pause >= hard_pause_threshold: break
|
| 373 |
+
if prev_entry["word"].endswith(('.','!','?')): break
|
| 374 |
+
|
| 375 |
+
current_words.append(entry["word"])
|
| 376 |
+
j += 1
|
| 377 |
+
|
| 378 |
+
if not current_words:
|
| 379 |
+
current_words.append(word_level_timestamps[i]["word"])
|
| 380 |
+
j = i + 1
|
| 381 |
+
|
| 382 |
+
text = " ".join(current_words)
|
| 383 |
+
end_time = word_level_timestamps[j - 1]["end"]
|
| 384 |
+
draft_subtitles.append({ "start": start_time, "end": end_time, "text": text })
|
| 385 |
+
i = j
|
| 386 |
+
|
| 387 |
+
# Phase 2: Post-process to merge single-word "orphan" subtitles
|
| 388 |
+
if not draft_subtitles: return
|
| 389 |
+
final_subtitles = [draft_subtitles[0]]
|
| 390 |
+
for k in range(1, len(draft_subtitles)):
|
| 391 |
+
prev_sub = final_subtitles[-1]
|
| 392 |
+
current_sub = draft_subtitles[k]
|
| 393 |
+
is_orphan = len(current_sub["text"].split()) == 1
|
| 394 |
+
pause_from_prev = current_sub["start"] - prev_sub["end"]
|
| 395 |
+
|
| 396 |
+
if is_orphan and pause_from_prev < merge_pause_threshold:
|
| 397 |
+
merged_text = prev_sub["text"] + " " + current_sub["text"]
|
| 398 |
+
if len(split_line_by_char_limit(merged_text, max_chars_per_line)) <= max_lines:
|
| 399 |
+
prev_sub["text"] = merged_text
|
| 400 |
+
prev_sub["end"] = current_sub["end"]
|
| 401 |
+
continue
|
| 402 |
+
|
| 403 |
+
final_subtitles.append(current_sub)
|
| 404 |
+
|
| 405 |
+
final_subtitles = merge_punctuation_glitches(final_subtitles)
|
| 406 |
+
|
| 407 |
+
# Phase 3: Write the final SRT file
|
| 408 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 409 |
+
for idx, sub in enumerate(final_subtitles, start=1):
|
| 410 |
+
text = sub["text"].replace(" ,", ",").replace(" .", ".")
|
| 411 |
+
formatted_lines = split_line_by_char_limit(text, max_chars_per_line)
|
| 412 |
+
f.write(f"{idx}\n")
|
| 413 |
+
f.write(f"{convert_time_to_srt_format(sub['start'])} --> {convert_time_to_srt_format(sub['end'])}\n")
|
| 414 |
+
f.write("\n".join(formatted_lines) + "\n\n")
|
| 415 |
+
|
| 416 |
+
def write_subtitles_to_file(subtitles, filename="subtitles.srt"):
|
| 417 |
+
"""Writes a dictionary of subtitles to a standard SRT file."""
|
| 418 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
| 419 |
+
for id, entry in subtitles.items():
|
| 420 |
+
if entry['start'] is None or entry['end'] is None:
|
| 421 |
+
print(f"Skipping subtitle ID {id} due to missing timestamps.")
|
| 422 |
+
continue
|
| 423 |
+
start_time = convert_time_to_srt_format(entry['start'])
|
| 424 |
+
end_time = convert_time_to_srt_format(entry['end'])
|
| 425 |
+
f.write(f"{id}\n")
|
| 426 |
+
f.write(f"{start_time} --> {end_time}\n")
|
| 427 |
+
f.write(f"{entry['text']}\n\n")
|
| 428 |
+
|
| 429 |
+
def word_level_srt(words_timestamp, srt_path="word_level_subtitle.srt", shorts=False):
|
| 430 |
+
"""Generates an SRT file with one word per subtitle entry."""
|
| 431 |
+
punctuation = re.compile(r'[.,!?;:"\–—_~^+*|]')
|
| 432 |
+
with open(srt_path, 'w', encoding='utf-8') as srt_file:
|
| 433 |
+
for i, word_info in enumerate(words_timestamp, start=1):
|
| 434 |
+
start = convert_time_to_srt_format(word_info['start'])
|
| 435 |
+
end = convert_time_to_srt_format(word_info['end'])
|
| 436 |
+
word = re.sub(punctuation, '', word_info['word'])
|
| 437 |
+
if word.strip().lower() == 'i': word = "I"
|
| 438 |
+
if not shorts: word = word.replace("-", "")
|
| 439 |
+
srt_file.write(f"{i}\n{start} --> {end}\n{word}\n\n")
|
| 440 |
+
|
| 441 |
+
def generate_srt_from_sentences(sentence_timestamp, srt_path="default_subtitle.srt"):
|
| 442 |
+
"""Generates a standard SRT file from sentence-level timestamps."""
|
| 443 |
+
with open(srt_path, 'w', encoding='utf-8') as srt_file:
|
| 444 |
+
for index, sentence in enumerate(sentence_timestamp, start=1):
|
| 445 |
+
start = convert_time_to_srt_format(sentence['start'])
|
| 446 |
+
end = convert_time_to_srt_format(sentence['end'])
|
| 447 |
+
srt_file.write(f"{index}\n{start} --> {end}\n{sentence['text']}\n\n")
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
# ==============================================================================
|
| 451 |
+
# --- 6. TRANSLATION UTILITIES
|
| 452 |
+
# ==============================================================================
|
| 453 |
+
|
| 454 |
+
def translate_text(text, source_language, destination_language):
|
| 455 |
+
"""Translates a single block of text using GoogleTranslator."""
|
| 456 |
+
source_code = LANGUAGE_CODE[source_language]
|
| 457 |
+
target_code = LANGUAGE_CODE[destination_language]
|
| 458 |
+
if destination_language == "Chinese":
|
| 459 |
+
target_code = 'zh-CN'
|
| 460 |
+
|
| 461 |
+
translator = GoogleTranslator(source=source_code, target=target_code)
|
| 462 |
+
return str(translator.translate(text.strip()))
|
| 463 |
+
|
| 464 |
+
def translate_subtitle(subtitles, source_language, destination_language):
|
| 465 |
+
"""Translates the text content of a pysrt Subtitle object."""
|
| 466 |
+
translated_text_dump = ""
|
| 467 |
+
for sub in subtitles:
|
| 468 |
+
translated_text = translate_text(sub.text, source_language, destination_language)
|
| 469 |
+
sub.text = translated_text
|
| 470 |
+
translated_text_dump += translated_text.strip() + " "
|
| 471 |
+
return subtitles, translated_text_dump.strip()
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
# ==============================================================================
|
| 475 |
+
# --- 7. MAIN ORCHESTRATOR FUNCTION
|
| 476 |
+
# ==============================================================================
|
| 477 |
+
|
| 478 |
+
def subtitle_maker(media_file, source_lang, target_lang):
|
| 479 |
+
"""
|
| 480 |
+
The main entry point to generate and optionally translate subtitles.
|
| 481 |
+
|
| 482 |
+
Args:
|
| 483 |
+
media_file (str): Path to the input media file.
|
| 484 |
+
source_lang (str): The source language ('Automatic' for detection).
|
| 485 |
+
target_lang (str): The target language for translation.
|
| 486 |
+
|
| 487 |
+
Returns:
|
| 488 |
+
A tuple containing paths to all generated files and the transcript text.
|
| 489 |
+
"""
|
| 490 |
+
try:
|
| 491 |
+
(
|
| 492 |
+
default_srt, custom_srt, word_srt, shorts_srt,
|
| 493 |
+
txt_path, transcript, detected_lang
|
| 494 |
+
) = whisper_subtitle(media_file, source_lang)
|
| 495 |
+
except Exception as e:
|
| 496 |
+
print(f"❌ An error occurred during transcription: {e}")
|
| 497 |
+
return (None, None, None, None, None, None, f"Error: {e}")
|
| 498 |
+
|
| 499 |
+
translated_srt_path = None
|
| 500 |
+
if detected_lang and detected_lang != target_lang:
|
| 501 |
+
print(f"TRANSLATING from {detected_lang} to {target_lang}")
|
| 502 |
+
original_subs = pysrt.open(default_srt, encoding='utf-8')
|
| 503 |
+
translated_subs, _ = translate_subtitle(original_subs, detected_lang, target_lang)
|
| 504 |
+
base_name, ext = os.path.splitext(os.path.basename(default_srt))
|
| 505 |
+
translated_filename = f"{base_name}_to_{target_lang}{ext}"
|
| 506 |
+
translated_srt_path = os.path.join(SUBTITLE_FOLDER, translated_filename)
|
| 507 |
+
translated_subs.save(translated_srt_path, encoding='utf-8')
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
return (
|
| 511 |
+
default_srt, translated_srt_path, custom_srt, word_srt,
|
| 512 |
+
shorts_srt, txt_path, transcript
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
# ==============================================================================
|
| 517 |
+
# --- 8. INITIALIZATION
|
| 518 |
+
# ==============================================================================
|
| 519 |
+
os.makedirs(SUBTITLE_FOLDER, exist_ok=True)
|
| 520 |
+
os.makedirs(TEMP_FOLDER, exist_ok=True)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# from subtitle import subtitle_maker
|
| 524 |
+
|
| 525 |
+
# media_file = "video.mp4"
|
| 526 |
+
# source_lang = "English"
|
| 527 |
+
# target_lang = "English"
|
| 528 |
+
|
| 529 |
+
# default_srt, translated_srt, custom_srt, word_srt, shorts_srt, txt_path, transcript = subtitle_maker(
|
| 530 |
+
# media_file, source_lang, target_lang
|
| 531 |
+
# )
|
| 532 |
+
# If source_lang and target_lang are the same, translation will be skipped.
|
| 533 |
+
|
| 534 |
+
# default_srt -> Original subtitles generated directly by Whisper-Large-V3-Turbo-CT2
|
| 535 |
+
# translated_srt -> Translated subtitles (only generated if source_lang ≠ target_lang,
|
| 536 |
+
# e.g., English → Hindi)
|
| 537 |
+
# custom_srt -> Modified version of default subtitles with shorter segments
|
| 538 |
+
# (better readability for horizontal videos, Maximum 38 characters per segment. )
|
| 539 |
+
# word_srt -> Word-level timestamps (useful for creating YouTube Shorts/Reels)
|
| 540 |
+
# shorts_srt -> Optimized subtitles for vertical videos (displays 3–4 words at a time , Maximum 17 characters per segment.)
|
| 541 |
+
# txt_path -> Full transcript as plain text (useful for video summarization or for asking questions about the video or audio data with other LLM tools)
|
| 542 |
+
# transcript -> Transcript text directly returned by the function, if you just need the transcript
|
| 543 |
+
|
| 544 |
+
# All functionality is contained in a single file, making it portable
|
| 545 |
+
# and reusable across multiple projects for different purposes.
|