-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
160 lines (133 loc) · 5.98 KB
/
app.py
File metadata and controls
160 lines (133 loc) · 5.98 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
from flask import Flask, render_template, request, flash, send_file, redirect, url_for, jsonify
import yt_dlp
import os
import threading
import uuid
import zipfile
import time
app = Flask(__name__)
app.secret_key = 'supersecretkey'
# Global store for progress
download_progress = {}
def progress_hook(d, task_id):
if d['status'] == 'downloading':
p = d.get('_percent_str', '0%').replace('%','')
try:
percent = float(p)
except:
percent = 0
if task_id in download_progress:
download_progress[task_id]['percent'] = percent
download_progress[task_id]['status'] = 'downloading'
download_progress[task_id]['speed'] = d.get('_speed_str', 'N/A')
download_progress[task_id]['eta'] = d.get('_eta_str', 'N/A')
def background_download(task_id, urls, download_folder, custom_filename=None):
try:
downloaded_files = []
total_videos = len(urls)
# Determine output template based on custom_filename and number of videos
if len(urls) == 1 and custom_filename:
# For single video with custom name, use that name
outtmpl = os.path.join(download_folder, f"{custom_filename}.%(ext)s")
else:
# Default behavior or multiple videos (will be zipped later)
outtmpl = os.path.join(download_folder, '%(title)s.%(ext)s')
ydl_opts = {
'format': 'best',
'outtmpl': outtmpl,
'noplaylist': True,
'quiet': True,
'progress_hooks': [lambda d: progress_hook(d, task_id)]
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
for index, url in enumerate(urls):
if task_id in download_progress:
download_progress[task_id]['current_video'] = index + 1
download_progress[task_id]['message'] = f"Downloading video {index + 1} of {total_videos}"
download_progress[task_id]['percent'] = 0
info = ydl.extract_info(url, download=True)
filename = ydl.prepare_filename(info)
downloaded_files.append(filename)
# If multiple files, zip them
final_file = None
if len(downloaded_files) > 1:
if task_id in download_progress:
download_progress[task_id]['message'] = "Zipping files..."
if custom_filename:
zip_name = custom_filename if custom_filename.lower().endswith('.zip') else f"{custom_filename}.zip"
zip_filename = os.path.join(download_folder, zip_name)
else:
zip_filename = os.path.join(download_folder, f"videos_{task_id}.zip")
with zipfile.ZipFile(zip_filename, 'w') as zipf:
for file in downloaded_files:
zipf.write(file, os.path.basename(file))
final_file = zip_filename
elif len(downloaded_files) == 1:
final_file = downloaded_files[0]
if final_file and task_id in download_progress:
download_progress[task_id]['status'] = 'completed'
download_progress[task_id]['filename'] = os.path.basename(final_file)
download_progress[task_id]['message'] = "Download complete!"
download_progress[task_id]['percent'] = 100
except Exception as e:
if task_id in download_progress:
download_progress[task_id]['status'] = 'error'
download_progress[task_id]['message'] = str(e)
@app.route('/', methods=['GET', 'POST'])
def index():
video_infos = []
if request.method == 'POST':
urls_input = request.form.get('url')
if urls_input:
# Split by newline or comma and strip whitespace
urls = [u.strip() for u in urls_input.replace(',', '\n').split('\n') if u.strip()]
ydl_opts = {
'format': 'best',
'noplaylist': True,
'quiet': True
}
for url in urls:
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
video_infos.append({
'title': info.get('title'),
'url': info.get('url'),
'original_url': url,
'thumbnail': info.get('thumbnail'),
'ext': info.get('ext'),
'duration': info.get('duration_string')
})
except Exception as e:
flash(f"Error processing URL {url}: {str(e)}")
return render_template('index.html', video_infos=video_infos)
@app.route('/start_download', methods=['POST'])
def start_download():
data = request.json
urls = data.get('urls', [])
custom_filename = data.get('custom_filename')
if not urls:
return jsonify({'error': 'No URLs provided'}), 400
task_id = str(uuid.uuid4())
download_folder = os.path.join(app.root_path, 'downloads')
os.makedirs(download_folder, exist_ok=True)
download_progress[task_id] = {
'status': 'starting',
'percent': 0,
'message': 'Starting download...',
'current_video': 0,
'total_videos': len(urls)
}
thread = threading.Thread(target=background_download, args=(task_id, urls, download_folder, custom_filename))
thread.start()
return jsonify({'task_id': task_id})
@app.route('/progress/<task_id>')
def get_progress(task_id):
return jsonify(download_progress.get(task_id, {'status': 'not_found'}))
@app.route('/get_file/<filename>')
def get_file(filename):
download_folder = os.path.join(app.root_path, 'downloads')
return send_file(os.path.join(download_folder, filename), as_attachment=True)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)