Spaces:
Paused
Paused
| import os | |
| import requests | |
| import subprocess | |
| from urllib.parse import urlparse | |
| import math | |
| def download_file(url, local_filename): | |
| with requests.get(url, stream=True) as r: | |
| r.raise_for_status() | |
| with open(local_filename, 'wb') as f: | |
| for chunk in r.iter_content(chunk_size=8192): | |
| f.write(chunk) | |
| return local_filename | |
| def calculate_aspect_ratio(width, height): | |
| try: | |
| gcd = math.gcd(width, height) | |
| return f'{width//gcd}:{height//gcd}' | |
| except ZeroDivisionError: | |
| return "1:1" | |
| def convert_video(input_file, output_file, width, height): | |
| aspect_ratio = calculate_aspect_ratio(width, height) | |
| ffmpeg_command = f'ffmpeg -i {input_file} -vf scale={width}:{height},setsar={aspect_ratio} -y -f hls {output_file}' | |
| try: | |
| process = subprocess.run(ffmpeg_command, shell=True, timeout=600, capture_output=True, text=True) | |
| except subprocess.TimeoutExpired: | |
| return "ffmpeg command timed out." | |
| except FileNotFoundError: | |
| return "ffmpeg is not installed." | |
| except Exception as e: | |
| return f"An error occurred: {str(e)}" | |
| if process.returncode != 0: | |
| return f"ffmpeg command failed with output: {process.stderr}" | |
| return "Video conversion completed successfully." | |
| def main(): | |
| url = 'http://techslides.com/demos/sample-videos/small.mp4' | |
| local_file = os.path.join('/tmp', os.path.basename(urlparse(url).path)) | |
| download_file(url, local_file) | |
| width = 480 | |
| height = 720 | |
| output_file = '/tmp/output.m3u8' | |
| convert_result = convert_video(local_file, output_file, width, height) | |
| print(convert_result) | |
| if __name__ == "__main__": | |
| main() |