jasonanugrah commited on
Commit
e7a5713
·
verified ·
1 Parent(s): 725db4c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, send_file
2
+ import yt_dlp
3
+ import os
4
+ import glob
5
+
6
+ app = Flask(__name__)
7
+
8
+ # Folder untuk menyimpan file sementara
9
+ DOWNLOAD_FOLDER = "downloads"
10
+ if not os.path.exists(DOWNLOAD_FOLDER):
11
+ os.makedirs(DOWNLOAD_FOLDER)
12
+
13
+ @app.route("/")
14
+ def home():
15
+ return render_template("index.html")
16
+
17
+ @app.route("/download", methods=["POST"])
18
+ def download():
19
+ url = request.form.get("url")
20
+ quality = request.form.get("quality")
21
+ format_type = request.form.get("format")
22
+
23
+ # Bersihkan folder downloads sebelum download baru (agar storage tidak penuh)
24
+ files = glob.glob(os.path.join(DOWNLOAD_FOLDER, "*"))
25
+ for f in files:
26
+ try:
27
+ os.remove(f)
28
+ except:
29
+ pass
30
+
31
+ # Template nama file output
32
+ output_template = os.path.join(DOWNLOAD_FOLDER, "%(title)s.%(ext)s")
33
+
34
+ # Konfigurasi yt-dlp
35
+ ydl_opts = {
36
+ "outtmpl": output_template,
37
+ "format": f"bestvideo[height<={quality}]+bestaudio/best" if format_type == "mp4" else "bestaudio/best",
38
+ "merge_output_format": "mp4",
39
+ }
40
+
41
+ # Jika user minta MP3
42
+ if format_type == "mp3":
43
+ ydl_opts = {
44
+ "outtmpl": output_template,
45
+ "format": "bestaudio/best",
46
+ "postprocessors": [{
47
+ "key": "FFmpegExtractAudio",
48
+ "preferredcodec": "mp3",
49
+ "preferredquality": "192",
50
+ }],
51
+ }
52
+
53
+ try:
54
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
55
+ ydl.download([url])
56
+
57
+ # Cari file yang baru saja didownload
58
+ list_of_files = glob.glob(os.path.join(DOWNLOAD_FOLDER, "*"))
59
+ if not list_of_files:
60
+ return "Gagal: File tidak ditemukan."
61
+
62
+ latest_file = max(list_of_files, key=os.path.getctime)
63
+ return send_file(latest_file, as_attachment=True)
64
+
65
+ except Exception as e:
66
+ return f"Terjadi kesalahan: {str(e)}"
67
+
68
+ if __name__ == "__main__":
69
+ # Hugging Face Spaces berjalan di port 7860
70
+ app.run(host="0.0.0.0", port=7860)