Spaces:
Runtime error
Runtime error
from flask import Flask, request, jsonify, send_file | |
from yt_dlp import YoutubeDL | |
import os | |
app = Flask(__name__) | |
def home(): | |
return jsonify({ 'message': 'Hallo, Welcome' }) | |
def get_formats(): | |
data = request.json | |
url = data.get('url') | |
if not url: | |
return jsonify({'error': 'URL is required'}), 400 | |
try: | |
with YoutubeDL({'listformats': True}) as ydl: | |
info = ydl.extract_info(url, download=False) | |
formats = [{ | |
'format_id': f['format_id'], | |
'format_note': f.get('format_note', 'N/A'), | |
'ext': f['ext'], | |
'filesize': f.get('filesize'), | |
'resolution': f.get('resolution', 'audio only'), | |
} for f in info['formats']] | |
return jsonify({'title': info['title'], 'formats': formats}) | |
except Exception as e: | |
return jsonify({'error': str(e)}), 500 | |
# Endpoint untuk mendownload video atau audio | |
def download_file(): | |
data = request.json | |
url = data.get('url') | |
format_id = data.get('format_id') | |
if not url or not format_id: | |
return jsonify({'error': 'URL and format_id are required'}), 400 | |
try: | |
# Konfigurasi yt-dlp | |
ydl_opts = { | |
'format': format_id, | |
'outtmpl': '%(title)s.%(ext)s', | |
'cookiefile': 'www.youtube.com_cookies.txt' # Jika dibutuhkan | |
} | |
with YoutubeDL(ydl_opts) as ydl: | |
info = ydl.extract_info(url, download=True) | |
file_name = ydl.prepare_filename(info) | |
# Kirim file ke client | |
return send_file(file_name, as_attachment=True) | |
except Exception as e: | |
return jsonify({'error': str(e)}), 500 | |
finally: | |
# Bersihkan file setelah dikirim | |
if os.path.exists(file_name): | |
os.remove(file_name) | |