Files
python_scripts/transcribe_video.py
T
2026-07-28 04:14:59 +00:00

67 lines
2.2 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import subprocess
import whisper
import linux
from moviepy import VideoFileClip
from whisper.utils import get_writer
model = whisper.load_model("base")
def extract_audio(video_path: str):
# Create a temporary path for a sanitized copy of the video
sanitized_video_path = video_path.replace(".mp4", "_clean.mp4")
audio_temp_path = video_path.replace(".mp4", ".wav")
print("Sanitizing video metadata for MoviePy parser...")
# -map_chapters -1 removes chapter layouts that break the parser.
# -sn strips text/subtitle streams that crash MoviePy.
# -c copy copies video and audio instantly without quality loss.
linux.run_command_ffmpeg(f"ffmpeg -y -i {video_path} -map_chapters -1 -sn -c copy {sanitized_video_path}")
print("Extracting uncompressed WAV audio...")
try:
# Load the sanitized file instead of the raw Twitch clip
with VideoFileClip(sanitized_video_path) as video:
video.audio.write_audiofile(
audio_temp_path,
fps=16000,
codec="pcm_s16le",
ffmpeg_params=["-ac", "1"]
)
finally:
# Always clean up the temporary sanitized video on Windows 11
if os.path.exists(sanitized_video_path):
os.remove(sanitized_video_path)
def transcribe_to_srt(video_path: str):
extract_audio(video_path)
transcribe_path = video_path.replace(".mp4", ".str")
audio_path = video_path.replace(".mp4", ".wav")
print("Transcribing audio...")
result = model.transcribe(audio_path)
print("Creating SRT file...")
srt_writer = get_writer("srt", transcribe_path)
srt_writer(result, transcribe_path, {})
print(f"SRT subtitle file saved in: {transcribe_path}")
if os.path.exists(audio_path):
os.remove(audio_path)
if __name__ == "__main__":
video_path = "my_video.mp4"
audio_temp_path = "temp_audio.wav" # Changed extension to .wav
output_dir = os.getcwd()
output_prefix = "my_video_subtitles"
extract_audio(video_path, audio_temp_path)
transcribe_to_srt(audio_temp_path, output_dir, output_prefix)
if os.path.exists(audio_temp_path):
os.remove(audio_temp_path)