vikarshana commited on
Commit
b605d72
·
verified ·
1 Parent(s): 29b0711

Update srv.py

Browse files
Files changed (1) hide show
  1. srv.py +47 -77
srv.py CHANGED
@@ -1,27 +1,9 @@
1
- """
2
- ------------------------------------------------------------
3
- YouTube Video & Audio Downloader API
4
- ------------------------------------------------------------
5
- ✨ Developed by: Mr. Asitha
6
- ✅ Contact: +94743381623
7
- 📅 Created: 2025-03-18
8
- 🔗 Join WhatsApp Channel: https://whatsapp.com/channel/0029VaeyMWv3QxRu4hA6c33Z
9
- 🚀 Program: Flask API for Downloading YouTube Videos & MP3
10
- ------------------------------------------------------------
11
- """
12
-
13
  from flask import Flask, request, jsonify, send_file, render_template
14
  from yt_dlp import YoutubeDL
15
  import os
16
- import uuid
17
- import logging
18
- import time
19
 
20
  app = Flask(__name__)
21
 
22
- # Set up logging
23
- logging.basicConfig(level=logging.DEBUG)
24
-
25
  @app.route('/')
26
  def home():
27
  return render_template('index.html')
@@ -49,77 +31,65 @@ def get_info():
49
  })
50
 
51
  except Exception as e:
52
- app.logger.error(f"Error fetching video info: {str(e)}")
53
  return jsonify({'error': str(e)}), 500
54
 
55
  @app.route('/download', methods=['POST'])
56
  def download_media():
57
  data = request.json
58
  url = data.get('url')
59
- format_type = data.get('format_type', 'mp3')
60
- quality = str(data.get('quality', 'best'))
61
 
62
  if not url:
63
  return jsonify({'error': 'URL is required'}), 400
64
 
65
- max_retries = 3
66
- retry_delay = 5 # seconds
67
-
68
- for attempt in range(max_retries):
69
- try:
70
- unique_id = str(uuid.uuid4()) # Generate a unique ID for the file
71
- if format_type == 'mp4':
72
- quality_map = {
73
- '144': 'bv*[height=144][ext=mp4]+ba[ext=m4a]/b[height=144][ext=mp4]',
74
- '240': 'bv*[height=240][ext=mp4]+ba[ext=m4a]/b[height=240][ext=mp4]',
75
- '360': 'bv*[height=360][ext=mp4]+ba[ext=m4a]/b[height=360][ext=mp4]',
76
- '480': 'bv*[height=480][ext=mp4]+ba[ext=m4a]/b[height=480][ext=mp4]',
77
- '720': 'bv*[height=720][ext=mp4]+ba[ext=m4a]/b[height=720][ext=mp4]',
78
- '1080': 'bv*[height=1080][ext=mp4]+ba[ext=m4a]/b[height=1080][ext=mp4]',
79
- 'best': 'bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]'
80
- }
81
-
82
- ydl_opts = {
83
- 'format': quality_map.get(quality, quality_map['best']),
84
- 'merge_output_format': 'mp4',
85
- 'outtmpl': f'%(title)s_{unique_id}.%(ext)s', # Unique filename
86
- 'cookiefile': 'www.youtube.com_cookies.txt'
87
- }
88
- else:
89
- ydl_opts = {
90
- 'format': 'bestaudio',
91
- 'outtmpl': f'%(title)s_{unique_id}.%(ext)s', # Unique filename
92
- 'cookiefile': 'www.youtube.com_cookies.txt',
93
- 'postprocessors': [{
94
- 'key': 'FFmpegExtractAudio',
95
- 'preferredcodec': 'mp3',
96
- 'preferredquality': '64',
97
- }],
98
- }
99
-
100
- with YoutubeDL(ydl_opts) as ydl:
101
- info = ydl.extract_info(url, download=True)
102
- file_ext = "mp4" if format_type == "mp4" else "mp3"
103
- file_name = ydl.prepare_filename(info).rsplit(".", 1)[0] + f".{file_ext}"
104
 
105
- return send_file(
106
- file_name,
107
- as_attachment=True,
108
- download_name=os.path.basename(file_name)
109
- )
 
110
 
111
- except Exception as e:
112
- if attempt < max_retries - 1:
113
- app.logger.warning(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds...")
114
- time.sleep(retry_delay)
115
- continue
116
- else:
117
- app.logger.error(f"Error downloading media: {str(e)}")
118
- return jsonify({'error': str(e)}), 500
119
 
120
- finally:
121
- if 'file_name' in locals() and os.path.exists(file_name):
122
- os.remove(file_name)
 
123
 
124
  if __name__ == '__main__':
125
- app.run(host='0.0.0.0', port=7860, debug=True, threaded=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from flask import Flask, request, jsonify, send_file, render_template
2
  from yt_dlp import YoutubeDL
3
  import os
 
 
 
4
 
5
  app = Flask(__name__)
6
 
 
 
 
7
  @app.route('/')
8
  def home():
9
  return render_template('index.html')
 
31
  })
32
 
33
  except Exception as e:
 
34
  return jsonify({'error': str(e)}), 500
35
 
36
  @app.route('/download', methods=['POST'])
37
  def download_media():
38
  data = request.json
39
  url = data.get('url')
40
+ format_type = data.get('format', 'mp4') # Default format: MP4
41
+ quality = str(data.get('quality', 'best')) # Default: best quality
42
 
43
  if not url:
44
  return jsonify({'error': 'URL is required'}), 400
45
 
46
+ try:
47
+ if format_type == 'mp4':
48
+ quality_map = {
49
+ '144': 'bv*[height=144][ext=mp4]+ba[ext=m4a]/b[height=144][ext=mp4]',
50
+ '360': 'bv*[height=360][ext=mp4]+ba[ext=m4a]/b[height=360][ext=mp4]',
51
+ '480': 'bv*[height=480][ext=mp4]+ba[ext=m4a]/b[height=480][ext=mp4]',
52
+ '720': 'bv*[height=720][ext=mp4]+ba[ext=m4a]/b[height=720][ext=mp4]',
53
+ '1080': 'bv*[height=1080][ext=mp4]+ba[ext=m4a]/b[height=1080][ext=mp4]',
54
+ 'best': 'bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]' # Best available
55
+ }
56
+
57
+ ydl_opts = {
58
+ 'format': quality_map.get(quality, quality_map['best']),
59
+ 'merge_output_format': 'mp4',
60
+ 'outtmpl': '%(title)s.%(ext)s',
61
+ 'cookiefile': 'www.youtube.com_cookies.txt'
62
+ }
63
+ else: # Default: MP3
64
+ ydl_opts = {
65
+ 'format': 'bestaudio',
66
+ 'outtmpl': '%(title)s.%(ext)s',
67
+ 'cookiefile': 'www.youtube.com_cookies.txt',
68
+ 'postprocessors': [{
69
+ 'key': 'FFmpegExtractAudio',
70
+ 'preferredcodec': 'mp3',
71
+ 'preferredquality': '64',
72
+ }],
73
+ }
74
+ with YoutubeDL(ydl_opts) as ydl:
75
+ info = ydl.extract_info(url, download=True)
76
+ file_ext = "mp4" if format_type == "mp4" else "mp3"
77
+ file_name = ydl.prepare_filename(info).rsplit(".", 1)[0] + f".{file_ext}"
 
 
 
 
 
 
 
78
 
79
+ # Send file to client
80
+ return send_file(
81
+ file_name,
82
+ as_attachment=True,
83
+ download_name=os.path.basename(file_name)
84
+ )
85
 
86
+ except Exception as e:
87
+ return jsonify({'error': str(e)}), 500
 
 
 
 
 
 
88
 
89
+ finally:
90
+ # Delete file after sending
91
+ if 'file_name' in locals() and os.path.exists(file_name):
92
+ os.remove(file_name)
93
 
94
  if __name__ == '__main__':
95
+ app.run(host='0.0.0.0', port=7860, debug=True)