Spaces:
Running
Running
import gradio as gr | |
import subprocess | |
import os | |
def compress_video(video_file): | |
if video_file is None: | |
return None, "No video uploaded" | |
try: | |
# Get the input file path | |
input_path = video_file | |
# Create output filename - in the same directory as input | |
base_dir = os.path.dirname(input_path) | |
filename = os.path.basename(input_path) | |
name, ext = os.path.splitext(filename) | |
output_path = os.path.join(base_dir, f"{name}_compressed{ext}") | |
# Execute ffmpeg command | |
command = [ | |
"ffmpeg", | |
"-i", input_path, | |
"-vcodec", "libx264", | |
"-crf", "28", | |
"-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", | |
"-y", | |
output_path | |
] | |
# Run the command | |
process = subprocess.Popen( | |
command, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE | |
) | |
stdout, stderr = process.communicate() | |
if process.returncode != 0: | |
return None, f"Error: {stderr.decode()}" | |
# Return the processed video file | |
return output_path, "Video compressed successfully" | |
except Exception as e: | |
return None, f"An error occurred: {str(e)}" | |
with gr.Blocks() as app: | |
gr.Markdown("# Video Compression with FFmpeg") | |
gr.Markdown(""" | |
This app compresses videos using FFmpeg with the following parameters: | |
``` | |
ffmpeg -i input.mp4 -vcodec libx264 -crf 28 -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" -y output.mp4 | |
``` | |
- Uses H.264 codec | |
- CRF 28 (higher values = more compression, lower quality) | |
- Pads dimensions to ensure they're even numbers (required by some codecs) | |
""") | |
with gr.Row(): | |
with gr.Column(): | |
input_video = gr.Video(label="Upload Video") | |
compress_btn = gr.Button("Compress Video", variant="primary") | |
with gr.Column(): | |
output_video = gr.Video(label="Compressed Video") | |
status = gr.Markdown("Upload a video and click 'Compress Video'") | |
compress_btn.click( | |
fn=compress_video, | |
inputs=[input_video], | |
outputs=[output_video, status] | |
) | |
if __name__ == "__main__": | |
app.launch() | |