Spaces:
Sleeping
Sleeping
import streamlit as st | |
from moviepy.editor import VideoFileClip, CompositeVideoClip | |
import ffmpeg | |
import tempfile | |
import os | |
import shutil | |
import subprocess | |
def save_uploaded_file(uploaded_file): | |
try: | |
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp_file: | |
shutil.copyfileobj(uploaded_file, tmp_file) | |
return tmp_file.name | |
except Exception as e: | |
st.error(f"Error saving file: {e}") | |
return None | |
def add_hard_subtitle_to_video(input_video_path, subtitle_file_path): | |
output_video = tempfile.mktemp(suffix=".mp4") | |
stream = ffmpeg.output( | |
ffmpeg.input(input_video_path), | |
ffmpeg.input(subtitle_file_path), | |
output_video, | |
vf=f"subtitles={subtitle_file_path}:force_style='FontName=Arial,FontSize=24'" | |
) | |
try: | |
# Use subprocess to capture stdout and stderr | |
out, err = ffmpeg.run(stream, overwrite_output=True, capture_stdout=True, capture_stderr=True) | |
return output_video | |
except ffmpeg.Error as e: | |
# Print stderr to Streamlit to help diagnose the issue | |
st.error(f"FFMPEG error: {e.stderr}") | |
return None | |
def video_demo(video, subtitle): | |
video_path = save_uploaded_file(video) | |
subtitle_path = save_uploaded_file(subtitle) | |
if video_path and subtitle_path: | |
processed_video_path = add_hard_subtitle_to_video(video_path, subtitle_path) | |
return processed_video_path | |
else: | |
return None | |
# Streamlit UI | |
st.title("Video Subtitler") | |
uploaded_video = st.file_uploader("Upload a video", type=["mp4", "avi", "mov"]) | |
uploaded_subtitle = st.file_uploader("Upload subtitle file", type=["srt", "vtt"]) | |
if uploaded_video and uploaded_subtitle: | |
processed_video_path = video_demo(uploaded_video, uploaded_subtitle) | |
if processed_video_path: | |
st.video(processed_video_path) | |
else: | |
st.write("An error occurred. Please try again.") | |
else: | |
st.write("Please upload both a video and a subtitle file.") | |