Spaces:
Sleeping
Sleeping
File size: 2,140 Bytes
76bc4e4 3212948 |
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 |
from flask import Flask, request, jsonify, send_file, render_template
from yt_dlp import YoutubeDL
import os
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/get-info', methods=['POST'])
def get_info():
data = request.json
url = data.get('url')
if not url:
return jsonify({'error': 'URL is required'}), 400
try:
ydl_opts = {
'cookiefile': 'www.youtube.com_cookies.txt'
}
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
return jsonify({
'title': info['title'],
'thumbnail': info.get('thumbnail'),
'duration': info.get('duration'),
'channel': info.get('channel')
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/download', methods=['POST'])
def download_audio():
data = request.json
url = data.get('url')
if not url:
return jsonify({'error': 'URL is required'}), 400
try:
ydl_opts = {
'format': '251/bestaudio', # Format untuk audio terbaik
'outtmpl': '%(title)s.%(ext)s',
'cookiefile': 'www.youtube.com_cookies.txt',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
file_name = ydl.prepare_filename(info).rsplit(".", 1)[0] + ".mp3"
# Kirim file ke client
return send_file(
file_name,
as_attachment=True,
download_name=os.path.basename(file_name)
)
except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
# Bersihkan file setelah dikirim
if 'file_name' in locals() and os.path.exists(file_name):
os.remove(file_name)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True) |