Spaces:
Paused
Paused
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import subprocess
|
4 |
+
from urllib.parse import urlparse
|
5 |
+
import math
|
6 |
+
|
7 |
+
def download_file(url, local_filename):
|
8 |
+
with requests.get(url, stream=True) as r:
|
9 |
+
r.raise_for_status()
|
10 |
+
with open(local_filename, 'wb') as f:
|
11 |
+
for chunk in r.iter_content(chunk_size=8192):
|
12 |
+
f.write(chunk)
|
13 |
+
return local_filename
|
14 |
+
|
15 |
+
def calculate_aspect_ratio(width, height):
|
16 |
+
try:
|
17 |
+
gcd = math.gcd(width, height)
|
18 |
+
return f'{width//gcd}:{height//gcd}'
|
19 |
+
except ZeroDivisionError:
|
20 |
+
return "1:1"
|
21 |
+
|
22 |
+
def convert_video(input_file, output_file, width, height):
|
23 |
+
aspect_ratio = calculate_aspect_ratio(width, height)
|
24 |
+
ffmpeg_command = f'ffmpeg -i {input_file} -vf scale={width}:{height},setsar={aspect_ratio} -y -f hls {output_file}'
|
25 |
+
|
26 |
+
try:
|
27 |
+
process = subprocess.run(ffmpeg_command, shell=True, timeout=600, capture_output=True, text=True)
|
28 |
+
except subprocess.TimeoutExpired:
|
29 |
+
return "ffmpeg command timed out."
|
30 |
+
except FileNotFoundError:
|
31 |
+
return "ffmpeg is not installed."
|
32 |
+
except Exception as e:
|
33 |
+
return f"An error occurred: {str(e)}"
|
34 |
+
|
35 |
+
if process.returncode != 0:
|
36 |
+
return f"ffmpeg command failed with output: {process.stderr}"
|
37 |
+
|
38 |
+
return "Video conversion completed successfully."
|
39 |
+
|
40 |
+
def main():
|
41 |
+
url = 'http://techslides.com/demos/sample-videos/small.mp4'
|
42 |
+
local_file = os.path.join('/tmp', os.path.basename(urlparse(url).path))
|
43 |
+
download_file(url, local_file)
|
44 |
+
|
45 |
+
width = 480
|
46 |
+
height = 720
|
47 |
+
output_file = '/tmp/output.m3u8'
|
48 |
+
convert_result = convert_video(local_file, output_file, width, height)
|
49 |
+
|
50 |
+
print(convert_result)
|
51 |
+
|
52 |
+
if __name__ == "__main__":
|
53 |
+
main()
|