Jeffgold's picture
Update app.py
6f1f7b0
raw
history blame
2.4 kB
import time
import os
import gradio as gr
import ffmpeg
import subprocess
from gradio import components
import tempfile
from pathlib import Path
from gradio import inputs
# Define File object
File = Path
# Define temp directory
temp_dir = tempfile.mkdtemp()
video_file = gr.inputs.File(label="Video File", type="file")
quality = gr.inputs.Dropdown(choices=["18", "23", "28", "32"], label="Quality", default="23")
def get_aspect_ratio(video_file):
# Get the path to the ffprobe binary
ffprobe_path = ffmpeg.probe_path()
# Get the command to get the aspect ratio of the video
ffprobe_command = f"{ffprobe_path} -show_entries stream=width,height -of compact=p=0:nk=1 {video_file}"
# Run the command and get the output
output = subprocess.check_output(ffprobe_command, shell=True).decode("utf-8")
# Get the aspect ratio from the output
aspect_ratio = output.split()[0].split(":")[1]
return aspect_ratio
def convert_video(video_file: File, quality, aspect_ratio):
if video_file is None:
video_file = Path(video_url)
# Get the original aspect ratio of the video
original_aspect_ratio = get_aspect_ratio(video_file)
# Check if the aspect ratio is already set
if aspect_ratio == original_aspect_ratio:
return video_file
# Set the aspect ratio
ffmpeg_command = f"ffmpeg -i {video_file} -c:v libx264 -crf {quality} -f mp4 -aspect {aspect_ratio} {video_file}"
try:
subprocess.run(ffmpeg_command, shell=True, timeout=10)
except subprocess.TimeoutExpired:
print("ffmpeg timed out")
return None
except FileNotFoundError:
print("ffmpeg is not installed.")
return None
for i in range(10):
if os.path.exists(video_file):
break
else:
time.sleep(1)
# The file has now been converted, so we can display it in the output viewer
if os.path.exists(video_file):
gr.components.Video(video_file)
else:
print("File does not exist.")
# Create a temporary file to store the download link
# with tempfile.NamedTemporaryFile(delete=False) as f:
# f.write(output_path.encode())
# download_link = f.name
# Add a button to download the file
# gr.components.HTML("""
# <a href="{}" download="downloaded_file.mp4">Download</a>
# """.format(download_link))
from gradio import outputs
gr.Interface(convert_video, inputs=[video_file, quality], outputs=[outputs.Video()]).launch(share=True)