CaptionGenerator / caption_generator.py
dljdd's picture
Upload caption_generator.py
4513217 verified
# Helper functions for the video and audio extraction
from pytube import YouTube
from moviepy.editor import VideoFileClip
import os
import stable_whisper
import gradio as gr
def download_video(youtube_url, save_path="./"):
try:
# Create a YouTube object with the link
yt = YouTube(youtube_url)
# Get the highest resolution stream
stream = yt.streams.get_highest_resolution()
# Generate a unique filename for the downloaded video
video_filename = "video.mp4"
# Download the video
video_path = stream.download(output_path=save_path, filename=video_filename)
print("Download complete!")
# Extract audio
audio_path = extract_audio(video_path, save_path)
if audio_path:
print("Audio extracted successfully at:", audio_path)
return [video_path, audio_path]
except Exception as e:
print("An error occurred:", str(e))
def extract_audio(video_path, save_path):
try:
# Load the video clip using moviepy
video_clip = VideoFileClip(video_path)
# Extract audio
audio_clip = video_clip.audio
# Create path for saving audio
audio_path = video_path[:-4] + ".mp3"
# Save audio
audio_clip.write_audiofile(audio_path)
return audio_path
except Exception as e:
print("An error occurred while extracting audio:", str(e))
# # Example usage
# youtube_link = input("Enter the YouTube link: ")
# download_video(youtube_link)
# BONUS 1: This cell contains the function for the gradio app
def vid_to_subs(link):
try:
# Download video and extract audio
# Construct the full path to the downloaded video
video_path = download_video(link)[0]
# Transcribe the audio
model = stable_whisper.load_model('medium')
result = model.transcribe(video_path)
# Store transcription result in a variable
transcription = result.to_txt()
return transcription
except Exception as e:
print("An error occurred:", str(e))
demo = gr.Interface(fn=vid_to_subs, inputs="textbox", outputs="textbox")
demo.launch(share=True, debug=True)