Spaces:
Sleeping
Sleeping
File size: 2,053 Bytes
e7a5713 | 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 | 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)
@app.route("/")
def home():
return render_template("index.html")
@app.route("/download", methods=["POST"])
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) |