import gradio as gr import subprocess import os import re def compress_video(input_video, resolution, progress=gr.Progress()): if not input_video: raise gr.Error("Please upload a video file!") output_filename = "compressed_" + os.path.basename(input_video) output_path = os.path.join(os.path.dirname(input_video), output_filename) try: # Get video duration (for progress calculation) duration_cmd = [ "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", input_video ] duration_output = subprocess.check_output(duration_cmd, text=True, stderr=subprocess.STDOUT) total_duration = float(duration_output.strip()) command = [ "ffmpeg", "-y", # Overwrite output file (if exists) "-i", input_video, "-vf", f"scale=-2:{resolution}", "-c:v", "libx264", "-crf", "28", "-preset", "veryslow", "-c:a", "aac", "-b:a", "64k", "-movflags", "+faststart", output_path, ] # Use Popen to read output in real-time process = subprocess.Popen(command, stderr=subprocess.PIPE, text=True, encoding='utf-8') progress(0, desc="Starting compression...") for line in process.stderr: # Use regex to match time progress (hh:mm:ss.ss) match = re.search(r"time=(\d+:\d+:\d+\.\d+)", line) if match: current_time_str = match.group(1) # Convert time string to seconds h, m, s = map(float, current_time_str.split(':')) current_time = h * 3600 + m * 60 + s # Calculate progress percentage percentage = min(current_time / total_duration, 1.0) # Prevent exceeding 100% progress(percentage, desc=f"Compressing: {int(percentage * 100)}%") process.stderr.close() return_code = process.wait() if return_code != 0: raise subprocess.CalledProcessError(return_code,command, process.stderr) except subprocess.CalledProcessError as e: error_message = e.stderr.decode('utf-8', 'ignore') # Decode and ignore errors if "width not divisible by 2" in error_message: error_message += "\n\nError: Video width is not divisible by 2. FFmpeg requires both width and height to be even numbers. Please try a different video or pre-process it with a video editing software." elif "No such file or directory" in error_message: error_message += "\n\nError: Input file or FFmpeg not found. Please check if the file path is correct and FFmpeg is installed." elif "Permission denied" in error_message: error_message +="\n\nError: Permission denied to access the file. Please check the file permissions." elif "Invalid data found when processing input" in error_message: error_message += "\n\nError: Input file is invalid or corrupted. Please check if the video file can be played correctly." else: error_message += "\n\nFFmpeg error output:\n" + error_message raise gr.Error(f"Video compression failed: {error_message}") except FileNotFoundError: raise gr.Error("FFmpeg or ffprobe not found. Please ensure FFmpeg is installed and added to your system's PATH environment variable.") except ValueError: raise gr.Error("Could not retrieve video duration. Please check if the video file is valid.") except Exception as e: raise gr.Error("An unknown error occurred: " + str(e)) return output_path # Gradio Interface css = """ .container { max-width: 800px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; } h1 { text-align: center; color: #333; } .description { text-align: center; margin-bottom: 20px; color: #555; } .instructions { margin-top: 20px; padding: 10px; border: 1px dashed #aaa; border-radius: 5px; color: #444; } """ with gr.Blocks(css=css, title="Video Compressor") as demo: # English title gr.HTML("