Chrunos commited on
Commit
4a5a3f2
verified
1 Parent(s): fb55b5a

Update srv.py

Browse files
Files changed (1) hide show
  1. srv.py +79 -36
srv.py CHANGED
@@ -2,6 +2,8 @@ from flask import Flask, request, jsonify
2
  from yt_dlp import YoutubeDL
3
  import os
4
  import uuid
 
 
5
 
6
  app = Flask(__name__)
7
 
@@ -84,42 +86,83 @@ def download_audio():
84
  return jsonify({'error': str(e)}), 500
85
 
86
 
87
- @app.route('/audio', methods=['POST'])
88
- def download_high_audio():
89
- data = request.json
90
- url = data.get('url')
91
-
92
- if not url:
93
- return jsonify({'error': 'URL is required'}), 400
94
-
95
- try:
96
- # 鐢熸垚鍞竴鐨勬枃浠跺悕
97
- unique_id = str(uuid.uuid4())
98
- file_name = os.path.join(DOWNLOAD_DIR, f'{unique_id}.mp3')
99
-
100
- # Set up yt-dlp options to download only audio
101
- ydl_opts = {
102
- 'format': 'bestaudio/best', # Download the best available audio
103
- 'outtmpl': file_name.rsplit('.', 1)[0] + '.%(ext)s', # Output filename format
104
- 'cookiefile': 'www.youtube.com_cookies.txt', # Use cookies file if needed
105
- 'postprocessors': [{
106
- 'key': 'FFmpegExtractAudio', # Extract audio with FFmpeg
107
- 'preferredcodec': 'mp3', # Convert to MP3
108
- 'preferredquality': '320', # Set audio quality
109
- }],
110
- 'noplaylist': True, # Avoid downloading entire playlists
111
- }
112
-
113
- with YoutubeDL(ydl_opts) as ydl:
114
- # Extract video info and download the audio
115
- ydl.extract_info(url, download=True)
116
-
117
- # 杩斿洖鍙笅杞界殑鍦板潃
118
- download_url = f'{request.host_url}{DOWNLOAD_DIR}/{os.path.basename(file_name)}'
119
- return jsonify({'download_url': download_url})
120
-
121
- except Exception as e:
122
- return jsonify({'error': str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
 
125
  if __name__ == '__main__':
 
2
  from yt_dlp import YoutubeDL
3
  import os
4
  import uuid
5
+ import threading
6
+ import hashlib
7
 
8
  app = Flask(__name__)
9
 
 
86
  return jsonify({'error': str(e)}), 500
87
 
88
 
89
+
90
+
91
+ # In-memory cache for downloaded videos
92
+ download_cache = {} # url_hash -> file_path
93
+ download_status = {} # download_id -> status
94
+
95
+ def get_url_hash(url):
96
+ """Generate a hash of the URL for caching"""
97
+ return hashlib.md5(url.encode()).hexdigest()
98
+
99
+ def download_in_background(url, file_name, download_id, url_hash):
100
+ try:
101
+ ydl_opts = {
102
+ 'format': 'bestaudio/best',
103
+ 'outtmpl': file_name.rsplit('.', 1)[0] + '.%(ext)s',
104
+ 'cookiefile': 'www.youtube.com_cookies.txt',
105
+ 'postprocessors': [{
106
+ 'key': 'FFmpegExtractAudio',
107
+ 'preferredcodec': 'mp3',
108
+ 'preferredquality': '320',
109
+ }],
110
+ 'noplaylist': True,
111
+ }
112
+
113
+ with YoutubeDL(ydl_opts) as ydl:
114
+ ydl.extract_info(url, download=True)
115
+
116
+ # Update cache and status
117
+ actual_file = f"{file_name.rsplit('.', 1)[0]}.mp3"
118
+ download_cache[url_hash] = actual_file
119
+ download_status[download_id] = {
120
+ 'status': 'completed',
121
+ 'download_url': f'{request.host_url}{DOWNLOAD_DIR}/{os.path.basename(actual_file)}'
122
+ }
123
+ except Exception as e:
124
+ download_status[download_id] = {
125
+ 'status': 'error',
126
+ 'error': str(e)
127
+ }
128
+
129
+ @app.route('/audio', methods=['POST'])
130
+ def download_high_audio():
131
+ data = request.json
132
+ url = data.get('url')
133
+
134
+ if not url:
135
+ return jsonify({'error': 'URL is required'}), 400
136
+
137
+ # Check cache first
138
+ url_hash = get_url_hash(url)
139
+ cached_file = download_cache.get(url_hash)
140
+
141
+ if cached_file and os.path.exists(cached_file):
142
+ # Return cached file immediately
143
+ return jsonify({
144
+ 'status': 'completed',
145
+ 'download_url': f'{request.host_url}{DOWNLOAD_DIR}/{os.path.basename(cached_file)}'
146
+ })
147
+
148
+ # Start new download
149
+ download_id = str(uuid.uuid4())
150
+ file_name = os.path.join(DOWNLOAD_DIR, f'{download_id}.mp3')
151
+
152
+ download_status[download_id] = {'status': 'processing'}
153
+ thread = Thread(target=download_in_background, args=(url, file_name, download_id, url_hash))
154
+ thread.daemon = True
155
+ thread.start()
156
+
157
+ return jsonify({
158
+ 'download_id': download_id,
159
+ 'status': 'processing'
160
+ })
161
+
162
+ @app.route('/audio/status/<download_id>', methods=['GET'])
163
+ def check_download_status(download_id):
164
+ status = download_status.get(download_id, {'status': 'not_found'})
165
+ return jsonify(status)
166
 
167
 
168
  if __name__ == '__main__':