Spaces:
Paused
Paused
| from flask import Flask, request, jsonify, send_file, render_template | |
| from yt_dlp import YoutubeDL | |
| import os | |
| app = Flask(__name__) | |
| def home(): | |
| return render_template('index.html') | |
| 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 | |
| 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) |