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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
from faster_whisper import WhisperModel
|
| 5 |
+
from moviepy.video.io.VideoFileClip import VideoFileClip
|
| 6 |
+
import logging
|
| 7 |
+
import google.generativeai as genai
|
| 8 |
+
|
| 9 |
+
# Suppress moviepy logs
|
| 10 |
+
logging.getLogger("moviepy").setLevel(logging.ERROR)
|
| 11 |
+
|
| 12 |
+
# Configure Gemini API
|
| 13 |
+
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
|
| 14 |
+
|
| 15 |
+
# Create the Gemini model
|
| 16 |
+
generation_config = {
|
| 17 |
+
"temperature": 1,
|
| 18 |
+
"top_p": 0.95,
|
| 19 |
+
"top_k": 40,
|
| 20 |
+
"max_output_tokens": 8192,
|
| 21 |
+
"response_mime_type": "text/plain",
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
model = genai.GenerativeModel(
|
| 25 |
+
model_name="gemini-2.0-flash-exp",
|
| 26 |
+
generation_config=generation_config,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Define the Whisper model and device
|
| 30 |
+
MODEL_NAME = "Systran/faster-whisper-large-v3"
|
| 31 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 32 |
+
compute_type = "float32" if device == "cuda" else "int8"
|
| 33 |
+
|
| 34 |
+
# Load the Whisper model
|
| 35 |
+
whisper_model = WhisperModel(MODEL_NAME, device=device, compute_type=compute_type)
|
| 36 |
+
|
| 37 |
+
# List of all supported languages in Whisper
|
| 38 |
+
SUPPORTED_LANGUAGES = [
|
| 39 |
+
"Auto Detect", "English", "Chinese", "German", "Spanish", "Russian", "Korean",
|
| 40 |
+
"French", "Japanese", "Portuguese", "Turkish", "Polish", "Catalan", "Dutch",
|
| 41 |
+
"Arabic", "Swedish", "Italian", "Indonesian", "Hindi", "Finnish", "Vietnamese",
|
| 42 |
+
"Hebrew", "Ukrainian", "Greek", "Malay", "Czech", "Romanian", "Danish",
|
| 43 |
+
"Hungarian", "Tamil", "Norwegian", "Thai", "Urdu", "Croatian", "Bulgarian",
|
| 44 |
+
"Lithuanian", "Latin", "Maori", "Malayalam", "Welsh", "Slovak", "Telugu",
|
| 45 |
+
"Persian", "Latvian", "Bengali", "Serbian", "Azerbaijani", "Slovenian",
|
| 46 |
+
"Kannada", "Estonian", "Macedonian", "Breton", "Basque", "Icelandic",
|
| 47 |
+
"Armenian", "Nepali", "Mongolian", "Bosnian", "Kazakh", "Albanian",
|
| 48 |
+
"Swahili", "Galician", "Marathi", "Punjabi", "Sinhala", "Khmer", "Shona",
|
| 49 |
+
"Yoruba", "Somali", "Afrikaans", "Occitan", "Georgian", "Belarusian",
|
| 50 |
+
"Tajik", "Sindhi", "Gujarati", "Amharic", "Yiddish", "Lao", "Uzbek",
|
| 51 |
+
"Faroese", "Haitian Creole", "Pashto", "Turkmen", "Nynorsk", "Maltese",
|
| 52 |
+
"Sanskrit", "Luxembourgish", "Burmese", "Tibetan", "Tagalog", "Malagasy",
|
| 53 |
+
"Assamese", "Tatar", "Hawaiian", "Lingala", "Hausa", "Bashkir", "Javanese",
|
| 54 |
+
"Sundanese"
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
def extract_audio_from_video(video_file):
|
| 58 |
+
"""Extract audio from a video file and save it as a WAV file."""
|
| 59 |
+
video = VideoFileClip(video_file)
|
| 60 |
+
audio_file = "extracted_audio.wav"
|
| 61 |
+
video.audio.write_audiofile(audio_file, fps=16000, logger=None) # Suppress logs
|
| 62 |
+
return audio_file
|
| 63 |
+
|
| 64 |
+
def generate_subtitles(audio_file, language="Auto Detect"):
|
| 65 |
+
"""Generate subtitles from an audio file using Whisper."""
|
| 66 |
+
# Transcribe the audio
|
| 67 |
+
segments, info = whisper_model.transcribe(
|
| 68 |
+
audio_file,
|
| 69 |
+
task="transcribe",
|
| 70 |
+
language=None if language == "Auto Detect" else language.lower(),
|
| 71 |
+
word_timestamps=True
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Generate SRT format subtitles
|
| 75 |
+
srt_subtitles = ""
|
| 76 |
+
for i, segment in enumerate(segments, start=1):
|
| 77 |
+
start_time = segment.start
|
| 78 |
+
end_time = segment.end
|
| 79 |
+
text = segment.text.strip()
|
| 80 |
+
|
| 81 |
+
# Format timestamps for SRT
|
| 82 |
+
start_time_srt = format_timestamp(start_time)
|
| 83 |
+
end_time_srt = format_timestamp(end_time)
|
| 84 |
+
|
| 85 |
+
# Add to SRT
|
| 86 |
+
srt_subtitles += f"{i}\n{start_time_srt} --> {end_time_srt}\n{text}\n\n"
|
| 87 |
+
|
| 88 |
+
return srt_subtitles, info.language
|
| 89 |
+
|
| 90 |
+
def format_timestamp(seconds):
|
| 91 |
+
"""Convert seconds to SRT timestamp format (HH:MM:SS,mmm)."""
|
| 92 |
+
hours = int(seconds // 3600)
|
| 93 |
+
minutes = int((seconds % 3600) // 60)
|
| 94 |
+
seconds = seconds % 60
|
| 95 |
+
milliseconds = int((seconds - int(seconds)) * 1000)
|
| 96 |
+
return f"{hours:02}:{minutes:02}:{int(seconds):02},{milliseconds:03}"
|
| 97 |
+
|
| 98 |
+
def translate_srt(srt_text, target_language):
|
| 99 |
+
"""Translate an SRT file while preserving timestamps."""
|
| 100 |
+
# Magic prompt for Gemini
|
| 101 |
+
prompt = f"Translate the following SRT subtitles into {target_language}. Preserve the SRT format (timestamps and structure). Translate only the text after the timestamp. Do not add explanations or extra text.\n\n{srt_text}"
|
| 102 |
+
|
| 103 |
+
# Send the prompt to Gemini
|
| 104 |
+
response = model.generate_content(prompt)
|
| 105 |
+
return response.text
|
| 106 |
+
|
| 107 |
+
def process_video(video_file, language="Auto Detect", translate_to=None):
|
| 108 |
+
"""Process a video file to generate and translate subtitles."""
|
| 109 |
+
# Extract audio from the video
|
| 110 |
+
audio_file = extract_audio_from_video(video_file)
|
| 111 |
+
|
| 112 |
+
# Generate subtitles
|
| 113 |
+
subtitles, detected_language = generate_subtitles(audio_file, language)
|
| 114 |
+
|
| 115 |
+
# Save original subtitles to an SRT file
|
| 116 |
+
original_srt_file = "original_subtitles.srt"
|
| 117 |
+
with open(original_srt_file, "w", encoding="utf-8") as f:
|
| 118 |
+
f.write(subtitles)
|
| 119 |
+
|
| 120 |
+
# Translate subtitles if a target language is provided
|
| 121 |
+
translated_srt_file = None
|
| 122 |
+
if translate_to and translate_to != "None":
|
| 123 |
+
translated_subtitles = translate_srt(subtitles, translate_to)
|
| 124 |
+
translated_srt_file = "translated_subtitles.srt"
|
| 125 |
+
with open(translated_srt_file, "w", encoding="utf-8") as f:
|
| 126 |
+
f.write(translated_subtitles)
|
| 127 |
+
|
| 128 |
+
# Clean up extracted audio file
|
| 129 |
+
os.remove(audio_file)
|
| 130 |
+
|
| 131 |
+
return original_srt_file, translated_srt_file, detected_language
|
| 132 |
+
|
| 133 |
+
# Define the Gradio interface
|
| 134 |
+
with gr.Blocks(title="AutoSubGen - AI Video Subtitle Generator") as demo:
|
| 135 |
+
# Header
|
| 136 |
+
with gr.Column():
|
| 137 |
+
gr.Markdown("# 🎥 AutoSubGen")
|
| 138 |
+
gr.Markdown("### AI-Powered Video Subtitle Generator")
|
| 139 |
+
gr.Markdown("Automatically generate and translate subtitles for your videos in **SRT format**. Supports **100+ languages** and **auto-detection**.")
|
| 140 |
+
|
| 141 |
+
# Main content
|
| 142 |
+
with gr.Tab("Generate Subtitles"):
|
| 143 |
+
gr.Markdown("### Upload a video file to generate subtitles.")
|
| 144 |
+
with gr.Row():
|
| 145 |
+
video_input = gr.Video(label="Upload Video File", scale=2)
|
| 146 |
+
language_dropdown = gr.Dropdown(
|
| 147 |
+
choices=SUPPORTED_LANGUAGES,
|
| 148 |
+
label="Select Language",
|
| 149 |
+
value="Auto Detect",
|
| 150 |
+
scale=1
|
| 151 |
+
)
|
| 152 |
+
translate_to_dropdown = gr.Dropdown(
|
| 153 |
+
choices=["None"] + SUPPORTED_LANGUAGES[1:], # Exclude "Auto Detect"
|
| 154 |
+
label="Translate To",
|
| 155 |
+
value="None",
|
| 156 |
+
scale=1
|
| 157 |
+
)
|
| 158 |
+
generate_button = gr.Button("Generate Subtitles", variant="primary")
|
| 159 |
+
with gr.Row():
|
| 160 |
+
original_subtitle_output = gr.File(label="Download Original Subtitles (SRT)")
|
| 161 |
+
translated_subtitle_output = gr.File(label="Download Translated Subtitles (SRT)")
|
| 162 |
+
detected_language_output = gr.Textbox(label="Detected Language")
|
| 163 |
+
|
| 164 |
+
# Link button to function
|
| 165 |
+
generate_button.click(
|
| 166 |
+
process_video,
|
| 167 |
+
inputs=[video_input, language_dropdown, translate_to_dropdown],
|
| 168 |
+
outputs=[original_subtitle_output, translated_subtitle_output, detected_language_output]
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# Launch the Gradio interface with a public link
|
| 172 |
+
demo.launch(share=True)
|