Spaces:
Sleeping
Sleeping
| from flask import Flask, render_template, request, send_file | |
| import yt_dlp | |
| import os | |
| import glob | |
| app = Flask(__name__) | |
| # Folder untuk menyimpan file sementara | |
| DOWNLOAD_FOLDER = "downloads" | |
| if not os.path.exists(DOWNLOAD_FOLDER): | |
| os.makedirs(DOWNLOAD_FOLDER) | |
| def home(): | |
| return render_template("index.html") | |
| def download(): | |
| url = request.form.get("url") | |
| quality = request.form.get("quality") | |
| format_type = request.form.get("format") | |
| # Bersihkan folder downloads sebelum download baru (agar storage tidak penuh) | |
| files = glob.glob(os.path.join(DOWNLOAD_FOLDER, "*")) | |
| for f in files: | |
| try: | |
| os.remove(f) | |
| except: | |
| pass | |
| # Template nama file output | |
| output_template = os.path.join(DOWNLOAD_FOLDER, "%(title)s.%(ext)s") | |
| # Konfigurasi yt-dlp | |
| ydl_opts = { | |
| "outtmpl": output_template, | |
| "format": f"bestvideo[height<={quality}]+bestaudio/best" if format_type == "mp4" else "bestaudio/best", | |
| "merge_output_format": "mp4", | |
| } | |
| # Jika user minta MP3 | |
| if format_type == "mp3": | |
| ydl_opts = { | |
| "outtmpl": output_template, | |
| "format": "bestaudio/best", | |
| "postprocessors": [{ | |
| "key": "FFmpegExtractAudio", | |
| "preferredcodec": "mp3", | |
| "preferredquality": "192", | |
| }], | |
| } | |
| try: | |
| with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
| ydl.download([url]) | |
| # Cari file yang baru saja didownload | |
| list_of_files = glob.glob(os.path.join(DOWNLOAD_FOLDER, "*")) | |
| if not list_of_files: | |
| return "Gagal: File tidak ditemukan." | |
| latest_file = max(list_of_files, key=os.path.getctime) | |
| return send_file(latest_file, as_attachment=True) | |
| except Exception as e: | |
| return f"Terjadi kesalahan: {str(e)}" | |
| if __name__ == "__main__": | |
| # Hugging Face Spaces berjalan di port 7860 | |
| app.run(host="0.0.0.0", port=7860) |