developer28 commited on
Commit
a204567
·
verified ·
1 Parent(s): c963386

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -26
app.py CHANGED
@@ -93,59 +93,65 @@ def download_audio(url, cookies_file_path=None):
93
  """Download audio from YouTube URL and return the file path"""
94
  if not YT_DLP_AVAILABLE:
95
  raise Exception("yt-dlp is not available. Please check the installation.")
96
-
97
  try:
98
  # Create a temporary directory for downloads
99
  temp_dir = tempfile.mkdtemp()
100
  output_path = os.path.join(temp_dir, "audio")
101
-
 
102
  ydl_opts = {
103
  'format': 'bestaudio[ext=m4a]/bestaudio/best',
104
  'outtmpl': output_path + '.%(ext)s',
105
  'quiet': True,
106
  'no_warnings': True,
107
- # Anti-bot detection measures
108
- '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',
109
  'referer': 'https://www.youtube.com/',
 
110
  'extractor_retries': 3,
111
  'fragment_retries': 3,
112
  'retry_sleep_functions': {'http': lambda n: 2 ** n},
113
  }
114
-
115
  # Add cookies file if provided
116
  if cookies_file_path and os.path.exists(cookies_file_path):
 
117
  ydl_opts['cookiefile'] = cookies_file_path
118
- print(f"Using cookies file: {cookies_file_path}")
119
  else:
120
- print("No cookies file provided - may encounter bot detection")
121
- # Additional headers without cookies
122
- ydl_opts.update({
123
- 'headers': {
124
- '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',
125
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
126
- 'Accept-Language': 'en-us,en;q=0.5',
127
- 'Accept-Encoding': 'gzip,deflate',
128
- 'DNT': '1',
129
- 'Connection': 'keep-alive',
130
- 'Upgrade-Insecure-Requests': '1',
131
- }
132
- })
133
-
 
 
134
  with YoutubeDL(ydl_opts) as ydl:
135
  info_dict = ydl.extract_info(url, download=True)
136
  filename = ydl.prepare_filename(info_dict)
137
-
138
- # Find the downloaded file
139
  for ext in ['.m4a', '.webm', '.mp4', '.mp3']:
140
  potential_file = output_path + ext
141
  if os.path.exists(potential_file):
 
142
  return potential_file
143
-
144
- raise FileNotFoundError(f"Downloaded audio file not found")
145
-
146
  except Exception as e:
 
 
147
  if "403" in str(e) or "Forbidden" in str(e):
148
- raise Exception(f"YouTube blocked the request (403 Forbidden). Please upload your cookies.txt file to bypass bot detection. Original error: {str(e)}")
149
  else:
150
  raise Exception(f"Failed to download audio: {str(e)}")
151
 
 
93
  """Download audio from YouTube URL and return the file path"""
94
  if not YT_DLP_AVAILABLE:
95
  raise Exception("yt-dlp is not available. Please check the installation.")
96
+
97
  try:
98
  # Create a temporary directory for downloads
99
  temp_dir = tempfile.mkdtemp()
100
  output_path = os.path.join(temp_dir, "audio")
101
+
102
+ # Base yt-dlp options
103
  ydl_opts = {
104
  'format': 'bestaudio[ext=m4a]/bestaudio/best',
105
  'outtmpl': output_path + '.%(ext)s',
106
  'quiet': True,
107
  'no_warnings': True,
108
+ 'force_ipv4': True,
 
109
  'referer': 'https://www.youtube.com/',
110
+ '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',
111
  'extractor_retries': 3,
112
  'fragment_retries': 3,
113
  'retry_sleep_functions': {'http': lambda n: 2 ** n},
114
  }
115
+
116
  # Add cookies file if provided
117
  if cookies_file_path and os.path.exists(cookies_file_path):
118
+ print(f"✅ Using cookies file: {cookies_file_path}")
119
  ydl_opts['cookiefile'] = cookies_file_path
 
120
  else:
121
+ print("⚠️ No valid cookies file provided likely to hit 403 Forbidden.")
122
+
123
+ # Extra headers to mimic real browser
124
+ ydl_opts['http_headers'] = {
125
+ 'User-Agent': ydl_opts['user_agent'],
126
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
127
+ 'Accept-Language': 'en-US,en;q=0.5',
128
+ 'Accept-Encoding': 'gzip, deflate',
129
+ 'DNT': '1',
130
+ 'Connection': 'keep-alive',
131
+ 'Upgrade-Insecure-Requests': '1',
132
+ 'Referer': 'https://www.youtube.com/',
133
+ }
134
+
135
+ print(f"🔧 yt-dlp options:\n{ydl_opts}")
136
+
137
  with YoutubeDL(ydl_opts) as ydl:
138
  info_dict = ydl.extract_info(url, download=True)
139
  filename = ydl.prepare_filename(info_dict)
140
+
141
+ # Search for the downloaded audio file
142
  for ext in ['.m4a', '.webm', '.mp4', '.mp3']:
143
  potential_file = output_path + ext
144
  if os.path.exists(potential_file):
145
+ print(f"✅ Audio file downloaded: {potential_file}")
146
  return potential_file
147
+
148
+ raise FileNotFoundError("Downloaded audio file not found.")
149
+
150
  except Exception as e:
151
+ import traceback
152
+ traceback.print_exc() # For debugging
153
  if "403" in str(e) or "Forbidden" in str(e):
154
+ raise Exception(f"YouTube blocked the request (403 Forbidden). Please upload a valid cookies.txt file. Original error: {str(e)}")
155
  else:
156
  raise Exception(f"Failed to download audio: {str(e)}")
157