File size: 2,210 Bytes
485608a
faa2bdb
 
 
c8942d9
faa2bdb
 
7a80d3a
faa2bdb
5296733
faa2bdb
40446f2
d47c1c5
40446f2
ec46e62
 
 
701ed9a
 
 
b7d9c54
131761b
ca0877d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d220f
f8f7bf0
9bd2eae
7e0e151
c9de927
c137773
06412df
1819951
5d93f13
1819951
 
785f173
1819951
dd486c2
 
c137773
785f173
2d2e1e5
785f173
4c21960
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ace304
7a80d3a
2024db3
 
5ad04a9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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")
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: File, quality, aspect_ratio, video_url):
  if video_file is None:
    video_file = Path(video_url)

  # Get the file extension
  file_extension = video_file.name.split(".")[-1]

  # Remove the file extension
  output_path = video_file.name[:-len(file_extension)]

  # Add the .mp4 file extension
  output_path += ".mp4"

  # Set the output path to the temp directory
  output_path = os.path.join(temp_dir, output_path)

  if os.path.exists(output_path):
    # The file already exists, so we can just display it in the output viewer
    gr.outputs.Video(output_path)
  else:
    # The file does not exist, so we need to convert it
    ffmpeg_command = f"ffmpeg -i {video_file} -c:v libx264 -crf {quality} -f mp4 -aspect {aspect_ratio} {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
    gr.outputs.Video(output_path)

    # Add a button to download the file
    gr.outputs.Download(label="Download", output_path=output_path)

from gradio import outputs

gr.Interface(convert_video, inputs=[video_file, quality, aspect_ratio, video_url], outputs=[outputs.Video()]).launch()