import streamlit as st import cv2 import numpy as np import tempfile import os # Function to reverse the frames of a video and save as a new file def reverse_video(input_path, output_path): """ Reverse the frames of a video. Args: input_path (str): Path to the input video file. output_path (str): Path to save the reversed video. """ # Open the video file cap = cv2.VideoCapture(input_path) # Check if the video file is successfully opened if not cap.isOpened(): raise ValueError("Error opening video file.") # Get video properties frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height)) # Read frames in reverse order frames = [] for i in range(frame_count): ret, frame = cap.read() if not ret: break frames.append(frame) # Ensure frames were read correctly if not frames: raise ValueError("No frames read from the video file.") # Write frames in reverse order to the output video for frame in reversed(frames): out.write(frame) # Release resources cap.release() out.release() # Verify the output file is created if not os.path.exists(output_path): raise ValueError("Output video file was not created.") # Streamlit app st.set_page_config(page_title="Video Reverser App") st.title("Video Reverser App") # File uploader for video uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov", "mkv"]) if uploaded_file is not None: # Save the uploaded file to a temporary location with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file: temp_file.write(uploaded_file.read()) input_video_path = temp_file.name # Reverse the video try: output_video_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name reverse_video(input_video_path, output_video_path) # Display the reversed video st.success("Video reversed successfully!") st.video(output_video_path) # Provide a download button for the reversed video with open(output_video_path, "rb") as file: st.download_button( label="Download Reversed Video", data=file, file_name="reversed_video.mp4", mime="video/mp4" ) except Exception as e: st.error(f"An error occurred: {e}")