import gradio as gr import cv2 import tempfile import os def process_video(video_path): # Open the video file cap = cv2.VideoCapture(video_path) if not cap.isOpened(): return None # Create a temporary file to save the processed video temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") output_path = temp_file.name # Get video properties frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) # Define the codec and create a VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height), isColor=False) # Process each frame while cap.isOpened(): ret, frame = cap.read() if not ret: break # Convert the frame to grayscale (example processing) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Write the processed frame to the output video out.write(gray_frame) # Release everything cap.release() out.release() return output_path def preview_video(video): # Save the uploaded video to a temporary file temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") temp_path = temp_file.name with open(temp_path, "wb") as f: f.write(video) # Process the video using OpenCV processed_video_path = process_video(temp_path) # Clean up the temporary file os.unlink(temp_path) return processed_video_path # Define the Gradio interface iface = gr.Interface( fn=preview_video, # Function to call inputs=gr.Video(label="Upload Video"), # Input component: Video upload outputs=gr.Video(label="Preview Video"), # Output component: Video preview title="Video Preview with OpenCV", description="Upload a video, and it will be processed (e.g., grayscale) and displayed." ) # Launch the interface iface.launch()