Jeffgold's picture
Update app.py
79683ca
raw
history blame
3.3 kB
import time
import os
import gradio as gr
import requests
import subprocess
from gradio import components
import tempfile
from pathlib import Path
from gradio import inputs, outputs
# 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")
aspect_ratio = gr.inputs.Dropdown(choices=[
"1:1",
"4:3",
"3:2",
"5:4",
"16:9",
"21:9",
"1.85:1",
"2.35:1",
"3:1",
"360",
"9:16",
"16:9",
"2:1",
"1:2",
"9:1",
], label="Aspect Ratio", default="16:9")
video_url = gr.inputs.Textbox(label="Video URL")
def convert_video(video_file: dict, quality, aspect_ratio, video_url):
# If a file was uploaded
if video_file is not None:
# Get the file extension
file_extension = video_file['name'].split(".")[-1]
# Define output file name
output_file_name = video_file['name'][:-len(file_extension)] + ".m3u8"
# Write the uploaded file to the temporary directory
with open(os.path.join(temp_dir, video_file['name']), 'wb') as f:
f.write(video_file['content'])
input_path = os.path.join(temp_dir, video_file['name'])
# If a URL was provided
elif video_url is not None:
# Get the file extension
file_extension = video_url.split(".")[-1]
# Define output file name
output_file_name = video_url.split("/")[-1][:-len(file_extension)] + ".m3u8"
# Download the file to the temporary directory
response = requests.get(video_url)
if response.status_code == 200:
with open(os.path.join(temp_dir, output_file_name), 'wb') as f:
f.write(response.content)
input_path = os.path.join(temp_dir, output_file_name)
else:
print("Failed to download file from URL.")
return None
else:
print("No input was provided.")
return None
# Define the output path
output_path = os.path.join(temp_dir, output_file_name)
# Check if the output file exists
if os.path.exists(output_path):
# The file already exists, so we can just display it in the output viewer
return gr.outputs.File(output_path, label="Download")
else:
# The file does not exist, so we need to convert it
ffmpeg_command = f"ffmpeg -i {input_path} -c:v libx264 -crf {quality} -vf scale=-1:720,setsar=1:1 -hls_time 6 -hls_playlist_type vod -f hls {output_path}"
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(output_path):
break
else:
time.sleep(1)
# The file has now been converted, so we can display it in the output viewer
return gr.outputs.File(output_path, label="Download")
gr.Interface(convert_video, inputs=[video_file, quality, aspect_ratio, video_url], outputs='file').launch()