MurderousCoder commited on
Commit
5bbd65a
·
verified ·
1 Parent(s): 924fcb0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -34
app.py CHANGED
@@ -4,17 +4,31 @@ import numpy as np
4
  import yt_dlp
5
  import os
6
  from pathlib import Path
 
7
 
8
- def download_youtube_music(url):
9
  """
10
- Download music from YouTube URL in best audio quality with advanced options
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  """
12
  try:
13
  # Create downloads directory if it doesn't exist
14
  download_dir = Path("downloads")
15
  download_dir.mkdir(exist_ok=True)
16
 
17
- # Configure yt-dlp options with advanced settings
18
  ydl_opts = {
19
  'format': 'bestaudio/best',
20
  'postprocessors': [{
@@ -25,26 +39,13 @@ def download_youtube_music(url):
25
  'outtmpl': str(download_dir / '%(title)s.%(ext)s'),
26
  'verbose': True,
27
  'progress_hooks': [lambda d: download_progress_hook(d)],
28
- # Add advanced options
29
- 'nocheckcertificate': True,
30
- 'extractor_retries': 3,
31
- 'ignoreerrors': True,
32
- 'no_warnings': True,
33
- 'quiet': False,
34
- # Add external downloader options
35
- 'external_downloader': 'aria2c',
36
- 'external_downloader_args': ['--min-split-size=1M', '--max-connection-per-server=16', '--max-concurrent-downloads=16', '--split=16'],
37
- # Add network options
38
- 'socket_timeout': 30,
39
- 'retries': 10,
40
- # Add headers to mimic browser
41
- 'headers': {
42
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
43
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
44
- 'Accept-Language': 'en-us,en;q=0.5',
45
- 'Sec-Fetch-Mode': 'navigate',
46
- }
47
  }
 
 
 
 
 
 
48
 
49
  # Show download starting message
50
  status = st.empty()
@@ -67,20 +68,14 @@ def download_youtube_music(url):
67
  mime='audio/mpeg'
68
  )
69
 
 
 
 
 
70
  except Exception as e:
71
  st.error(f'An error occurred: {str(e)}')
72
- # Add more detailed error handling
73
  if "HTTP Error 429" in str(e):
74
  st.error("Too many requests. Please wait a few minutes and try again.")
75
- elif "Requested format not available" in str(e):
76
- st.error("The requested format is not available. Trying alternative format...")
77
- # Try alternative format
78
- ydl_opts['format'] = 'worst[ext=m4a]'
79
- try:
80
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
81
- info = ydl.extract_info(url, download=True)
82
- except Exception as e2:
83
- st.error(f"Alternative format also failed: {str(e2)}")
84
 
85
  def download_progress_hook(d):
86
  """
@@ -108,13 +103,32 @@ def main():
108
 
109
  # Display input fields based on the selected option
110
  if input_option == "URL Input":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  url = st.text_input("Enter URL", placeholder="Enter URL here...")
112
- if url:
113
  if not url.startswith(('http://', 'https://')):
114
  st.warning('Please enter a valid URL starting with http:// or https://')
115
  else:
116
  st.write(f"You entered: {url}")
117
- download_youtube_music(url)
 
 
 
118
  elif input_option == "File Upload":
119
  uploaded_file = st.file_uploader("Upload a File", type=["txt", "mp3", "wav"])
120
  if uploaded_file:
 
4
  import yt_dlp
5
  import os
6
  from pathlib import Path
7
+ import json
8
 
9
+ def save_cookies(cookie_string):
10
  """
11
+ Save cookies to a file in Netscape format
12
+ """
13
+ try:
14
+ cookie_file = "youtube.txt"
15
+ with open(cookie_file, "w") as f:
16
+ f.write(cookie_string)
17
+ return cookie_file
18
+ except Exception as e:
19
+ st.error(f"Error saving cookies: {str(e)}")
20
+ return None
21
+
22
+ def download_youtube_music(url, cookie_string=None):
23
+ """
24
+ Download music from YouTube URL using provided cookies
25
  """
26
  try:
27
  # Create downloads directory if it doesn't exist
28
  download_dir = Path("downloads")
29
  download_dir.mkdir(exist_ok=True)
30
 
31
+ # Base options
32
  ydl_opts = {
33
  'format': 'bestaudio/best',
34
  'postprocessors': [{
 
39
  'outtmpl': str(download_dir / '%(title)s.%(ext)s'),
40
  'verbose': True,
41
  'progress_hooks': [lambda d: download_progress_hook(d)],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  }
43
+
44
+ # Add cookies if provided
45
+ if cookie_string:
46
+ cookie_file = save_cookies(cookie_string)
47
+ if cookie_file:
48
+ ydl_opts['cookiefile'] = cookie_file
49
 
50
  # Show download starting message
51
  status = st.empty()
 
68
  mime='audio/mpeg'
69
  )
70
 
71
+ # Clean up cookie file
72
+ if cookie_string and os.path.exists("youtube.txt"):
73
+ os.remove("youtube.txt")
74
+
75
  except Exception as e:
76
  st.error(f'An error occurred: {str(e)}')
 
77
  if "HTTP Error 429" in str(e):
78
  st.error("Too many requests. Please wait a few minutes and try again.")
 
 
 
 
 
 
 
 
 
79
 
80
  def download_progress_hook(d):
81
  """
 
103
 
104
  # Display input fields based on the selected option
105
  if input_option == "URL Input":
106
+ with st.expander("YouTube Cookie Settings (Required)"):
107
+ st.markdown("""
108
+ To get your YouTube cookies:
109
+ 1. Go to YouTube and make sure you're logged in
110
+ 2. Open Developer Tools (F12 or right-click > Inspect)
111
+ 3. Go to Network tab
112
+ 4. Visit any YouTube page
113
+ 5. Find a request to youtube.com
114
+ 6. In the request headers, find the 'cookie' header
115
+ 7. Copy the entire cookie value
116
+ """)
117
+ cookie_string = st.text_area(
118
+ "Paste your YouTube cookies here",
119
+ help="Paste the entire cookie string from YouTube's request headers"
120
+ )
121
+
122
  url = st.text_input("Enter URL", placeholder="Enter URL here...")
123
+ if url and cookie_string:
124
  if not url.startswith(('http://', 'https://')):
125
  st.warning('Please enter a valid URL starting with http:// or https://')
126
  else:
127
  st.write(f"You entered: {url}")
128
+ download_youtube_music(url, cookie_string)
129
+ elif url and not cookie_string:
130
+ st.warning("Please provide YouTube cookies to download the video")
131
+
132
  elif input_option == "File Upload":
133
  uploaded_file = st.file_uploader("Upload a File", type=["txt", "mp3", "wav"])
134
  if uploaded_file: