import moviepy.editor as mp import speech_recognition as sr from googletrans import Translator import srt from datetime import timedelta import time def video_to_srt(video_path, output_srt_path): # Load the video file video = mp.VideoFileClip(video_path) # Extract the audio audio_path = "temp_audio.wav" video.audio.write_audiofile(audio_path) # Initialize recognizer recognizer = sr.Recognizer() # Load the audio file audio = sr.AudioFile(audio_path) # Split the audio into chunks def get_chunks(audio, chunk_length=30): with audio as source: recognizer.adjust_for_ambient_noise(source) duration = source.DURATION chunks = [(i, min(i + chunk_length, duration)) for i in range(0, int(duration), chunk_length)] return chunks # Transcribe each chunk with retries def transcribe_chunk(start, end): with audio as source: audio_data = recognizer.record(source, duration=end - start, offset=start) for _ in range(3): # Retry up to 3 times try: text = recognizer.recognize_google(audio_data) return text except sr.UnknownValueError: print(f"Google Speech Recognition could not understand audio chunk {start}-{end}") return "[INAUDIBLE]" except sr.RequestError as e: print(f"Request error from Google Speech Recognition service; {e}") time.sleep(1) return "[ERROR]" chunks = get_chunks(audio) transcript = [] for start, end in chunks: transcript.append(transcribe_chunk(start, end)) transcript = " ".join(transcript) # Detect the language translator = Translator() detected_lang = translator.detect(transcript).lang # Split text into chunks (simplified) sentences = transcript.split('. ') # Create subtitles subtitles = [] start_time = 0 for i, sentence in enumerate(sentences): end_time = start_time + (len(sentence.split()) / 3) # Assume 3 words per second subtitles.append(srt.Subtitle(index=i, start=timedelta(seconds=start_time), end=timedelta(seconds=end_time), content=sentence)) start_time = end_time # Write to .srt file with open(output_srt_path, "w") as f: f.write(srt.compose(subtitles)) # Example usage video_to_srt("Downloads/Avengers Endgame Movie Review _ Deeksha Sharma.mp4", "output_subtitles.srt")