arnaupq2 commited on
Commit
2a9456f
·
verified ·
1 Parent(s): 3dd345f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -44
app.py CHANGED
@@ -2,6 +2,7 @@ import os
2
  import uuid
3
  import json
4
  import yt_dlp
 
5
  from flask import Flask, render_template, request, send_file, jsonify, redirect
6
 
7
  app = Flask(__name__, template_folder='.')
@@ -52,19 +53,23 @@ def health():
52
 
53
  def get_yt_info(url):
54
  """Try multiple clients to bypass bot detection and return successful opts"""
 
55
  clients_to_try = [
56
- ['tv'],
57
- ['android_test'],
58
- ['ios'],
59
- ['android'],
60
- ['web_embedded'],
61
- ['web_creator'],
 
 
62
  ['web']
63
  ]
64
 
 
65
  format_str = 'bestvideo[height<=1080]+bestaudio/best[height<=1080]/bestvideo+bestaudio/best'
66
 
67
- ydl_opts = {
68
  'format': format_str,
69
  'quiet': False,
70
  'no_warnings': False,
@@ -73,20 +78,19 @@ def get_yt_info(url):
73
  'extractor_args': {
74
  'youtube': {
75
  'player_client': ['tv'],
76
- 'include_dash_manifest': True,
77
  'include_hls_manifest': True,
78
  }
79
  }
80
  }
81
 
82
  if os.path.exists(COOKIES_FILE):
83
- ydl_opts['cookiefile'] = COOKIES_FILE
84
 
85
- last_error = "Unknown error"
86
  for clients in clients_to_try:
87
- current_opts = ydl_opts.copy()
88
- current_opts['extractor_args'] = ydl_opts['extractor_args'].copy()
89
- current_opts['extractor_args']['youtube'] = ydl_opts['extractor_args']['youtube'].copy()
90
  current_opts['extractor_args']['youtube']['player_client'] = clients
91
 
92
  print(f"DEBUG: Trying extract_info with clients: {clients}")
@@ -95,14 +99,17 @@ def get_yt_info(url):
95
  info = ydl.extract_info(url, download=False)
96
  return info, None, current_opts
97
  except Exception as e:
98
- last_error = str(e)
99
- print(f"DEBUG: Client {clients} failed: {last_error[:150]}...")
100
- if "confirm you’re not a bot" in last_error or "403" in last_error or "Sign in" in last_error:
 
101
  continue
102
  else:
 
 
103
  continue
104
 
105
- return None, f"All extraction methods failed. Last error: {last_error}", None
106
 
107
  @app.route('/convert', methods=['POST'])
108
  def convert():
@@ -116,7 +123,7 @@ def convert():
116
  output_template = os.path.join(DOWNLOAD_FOLDER, f"{file_id}.%(ext)s")
117
 
118
  # Get info using fallback mechanism
119
- info, error, successful_ydl_opts = get_yt_info(url)
120
  if error:
121
  return jsonify({'error': error}), 500
122
 
@@ -134,33 +141,26 @@ def convert():
134
  actual_ext = ".mp4"
135
 
136
  if not is_live:
137
- # Download if not live - using SAME opts that worked for extraction
138
  try:
139
- ydl_opts_dl = successful_ydl_opts.copy()
140
  ydl_opts_dl.update({
141
  'outtmpl': output_template,
142
  'merge_output_format': 'mp4',
143
  'noplaylist': True,
144
  })
145
 
146
- # Special bypass for some Shorts/Videos that 403 on DASH
147
- if "Oxl4KVBFviE" in url:
148
- ydl_opts_dl['extractor_args']['youtube']['include_dash_manifest'] = False
149
-
150
- print(f"DEBUG: Starting download with successful opts ({ydl_opts_dl['extractor_args']['youtube']['player_client']})...")
151
  with yt_dlp.YoutubeDL(ydl_opts_dl) as ydl_dl:
152
  ydl_dl.download([url])
153
 
154
- # Find the actual downloaded file
155
  possible_files = [f for f in os.listdir(DOWNLOAD_FOLDER) if f.startswith(file_id) and not f.endswith('.m3u')]
156
  if possible_files:
157
  actual_filename = possible_files[0]
158
  actual_ext = os.path.splitext(actual_filename)[1]
159
  has_download = True
160
- else:
161
- print("DEBUG: Download finished but file not found in folder.")
162
  except Exception as e:
163
- print(f"DEBUG: MP4 Download failed: {str(e)}. Proceeding with M3U only.")
164
 
165
  # Generate the 'M3U' file
166
  m3u_content = f"#EXTM3U\n#EXTINF:-1 tvg-name=\"{title}\" tvg-logo=\"{thumbnail}\", {title}\n{dynamic_play_url}\n"
@@ -182,7 +182,7 @@ def convert():
182
 
183
  @app.route('/play/youtube/<file_id>.m3u8')
184
  def play(file_id):
185
- # Check if we have a local download first
186
  target_file = None
187
  if os.path.exists(DOWNLOAD_FOLDER):
188
  for f in os.listdir(DOWNLOAD_FOLDER):
@@ -191,19 +191,15 @@ def play(file_id):
191
  break
192
 
193
  if target_file:
194
- # Serve the local file instead of redirecting to YouTube
195
- # This bypasses the YouTube IP-lock!
196
  print(f"DEBUG: Serving local file for {file_id}")
197
  return redirect(f"/download/{file_id}/video.mp4")
198
 
199
- # Fallback to YouTube if no local file exists (e.g. live stream)
200
  mappings = load_mappings()
201
  if file_id not in mappings:
202
  return "Not found", 404
203
 
204
  youtube_url = mappings[file_id]['url']
205
-
206
- # Get info using fallback mechanism
207
  info, error, _ = get_yt_info(youtube_url)
208
  if error:
209
  return f"Extraction failed: {error}", 500
@@ -213,7 +209,6 @@ def play(file_id):
213
  if not stream_url:
214
  formats = info.get('formats', [])
215
  if formats:
216
- # Try to find a direct URL in formats
217
  for f in reversed(formats):
218
  if f.get('url') and ('manifest' not in f.get('url')):
219
  stream_url = f.get('url')
@@ -222,7 +217,6 @@ def play(file_id):
222
  stream_url = formats[-1].get('url')
223
 
224
  if stream_url:
225
- # Note: This might still fail in external players due to IP-lock
226
  return redirect(stream_url)
227
  else:
228
  return "Stream URL not found", 404
@@ -230,7 +224,7 @@ def play(file_id):
230
  return str(e), 500
231
 
232
  @app.after_request
233
- def add_header(response):
234
  response.headers['Access-Control-Allow-Origin'] = '*'
235
  response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
236
  response.headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS'
@@ -245,18 +239,16 @@ def download_m3u(file_id, filename):
245
 
246
  @app.route('/download/<file_id>/<path:filename>')
247
  def download(file_id, filename):
248
- target_file = None
249
  if os.path.exists(DOWNLOAD_FOLDER):
250
  for f in os.listdir(DOWNLOAD_FOLDER):
251
  if f.startswith(file_id) and not f.endswith('.m3u'):
252
- target_file = os.path.join(DOWNLOAD_FOLDER, f)
253
  break
254
 
255
- if target_file and os.path.exists(target_file):
256
- # as_attachment=False is better for streaming in IPTV players
257
- return send_file(target_file, as_attachment=False, conditional=True, mimetype='video/mp4')
258
  return "File not found", 404
259
 
260
  if __name__ == '__main__':
261
- # Local port 5000 (Dockerfile handles 7860 in HF)
262
  app.run(debug=True, port=5000)
 
2
  import uuid
3
  import json
4
  import yt_dlp
5
+ import copy
6
  from flask import Flask, render_template, request, send_file, jsonify, redirect
7
 
8
  app = Flask(__name__, template_folder='.')
 
53
 
54
  def get_yt_info(url):
55
  """Try multiple clients to bypass bot detection and return successful opts"""
56
+ # Progressive client trial
57
  clients_to_try = [
58
+ ['tv'],
59
+ ['tvhtml5'],
60
+ ['android_test'],
61
+ ['ios'],
62
+ ['web_embedded'],
63
+ ['mweb'],
64
+ ['android'],
65
+ ['web_creator'],
66
  ['web']
67
  ]
68
 
69
+ # Ultra-flexible format selection
70
  format_str = 'bestvideo[height<=1080]+bestaudio/best[height<=1080]/bestvideo+bestaudio/best'
71
 
72
+ base_ydl_opts = {
73
  'format': format_str,
74
  'quiet': False,
75
  'no_warnings': False,
 
78
  'extractor_args': {
79
  'youtube': {
80
  'player_client': ['tv'],
81
+ 'include_dash_manifest': False,
82
  'include_hls_manifest': True,
83
  }
84
  }
85
  }
86
 
87
  if os.path.exists(COOKIES_FILE):
88
+ base_ydl_opts['cookiefile'] = COOKIES_FILE
89
 
90
+ last_err = "No error recorded"
91
  for clients in clients_to_try:
92
+ # Deep copy manually to avoid nested dict issues
93
+ current_opts = copy.deepcopy(base_ydl_opts)
 
94
  current_opts['extractor_args']['youtube']['player_client'] = clients
95
 
96
  print(f"DEBUG: Trying extract_info with clients: {clients}")
 
99
  info = ydl.extract_info(url, download=False)
100
  return info, None, current_opts
101
  except Exception as e:
102
+ last_err = str(e)
103
+ print(f"DEBUG: Client {clients} failed: {last_err[:150]}...")
104
+ # If it's a "Sign in" or "Bot" error, try next client
105
+ if "confirm you’re not a bot" in last_err or "403" in last_err or "Sign in" in last_err:
106
  continue
107
  else:
108
+ # For other errors (like invalid URL), maybe break early?
109
+ # But let's try others just in case
110
  continue
111
 
112
+ return None, f"All extraction methods failed. Last error: {last_err}", None
113
 
114
  @app.route('/convert', methods=['POST'])
115
  def convert():
 
123
  output_template = os.path.join(DOWNLOAD_FOLDER, f"{file_id}.%(ext)s")
124
 
125
  # Get info using fallback mechanism
126
+ info, error, successful_opts = get_yt_info(url)
127
  if error:
128
  return jsonify({'error': error}), 500
129
 
 
141
  actual_ext = ".mp4"
142
 
143
  if not is_live:
 
144
  try:
145
+ ydl_opts_dl = copy.deepcopy(successful_opts)
146
  ydl_opts_dl.update({
147
  'outtmpl': output_template,
148
  'merge_output_format': 'mp4',
149
  'noplaylist': True,
150
  })
151
 
152
+ print(f"DEBUG: Starting download with successful opts...")
 
 
 
 
153
  with yt_dlp.YoutubeDL(ydl_opts_dl) as ydl_dl:
154
  ydl_dl.download([url])
155
 
156
+ # Check results
157
  possible_files = [f for f in os.listdir(DOWNLOAD_FOLDER) if f.startswith(file_id) and not f.endswith('.m3u')]
158
  if possible_files:
159
  actual_filename = possible_files[0]
160
  actual_ext = os.path.splitext(actual_filename)[1]
161
  has_download = True
 
 
162
  except Exception as e:
163
+ print(f"DEBUG: MP4 Download failed: {str(e)}")
164
 
165
  # Generate the 'M3U' file
166
  m3u_content = f"#EXTM3U\n#EXTINF:-1 tvg-name=\"{title}\" tvg-logo=\"{thumbnail}\", {title}\n{dynamic_play_url}\n"
 
182
 
183
  @app.route('/play/youtube/<file_id>.m3u8')
184
  def play(file_id):
185
+ # Local file check
186
  target_file = None
187
  if os.path.exists(DOWNLOAD_FOLDER):
188
  for f in os.listdir(DOWNLOAD_FOLDER):
 
191
  break
192
 
193
  if target_file:
 
 
194
  print(f"DEBUG: Serving local file for {file_id}")
195
  return redirect(f"/download/{file_id}/video.mp4")
196
 
197
+ # Fallback to dynamic resolution
198
  mappings = load_mappings()
199
  if file_id not in mappings:
200
  return "Not found", 404
201
 
202
  youtube_url = mappings[file_id]['url']
 
 
203
  info, error, _ = get_yt_info(youtube_url)
204
  if error:
205
  return f"Extraction failed: {error}", 500
 
209
  if not stream_url:
210
  formats = info.get('formats', [])
211
  if formats:
 
212
  for f in reversed(formats):
213
  if f.get('url') and ('manifest' not in f.get('url')):
214
  stream_url = f.get('url')
 
217
  stream_url = formats[-1].get('url')
218
 
219
  if stream_url:
 
220
  return redirect(stream_url)
221
  else:
222
  return "Stream URL not found", 404
 
224
  return str(e), 500
225
 
226
  @app.after_request
227
+ def add_cors_headers(response):
228
  response.headers['Access-Control-Allow-Origin'] = '*'
229
  response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
230
  response.headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS'
 
239
 
240
  @app.route('/download/<file_id>/<path:filename>')
241
  def download(file_id, filename):
242
+ target_path = None
243
  if os.path.exists(DOWNLOAD_FOLDER):
244
  for f in os.listdir(DOWNLOAD_FOLDER):
245
  if f.startswith(file_id) and not f.endswith('.m3u'):
246
+ target_path = os.path.join(DOWNLOAD_FOLDER, f)
247
  break
248
 
249
+ if target_path and os.path.exists(target_path):
250
+ return send_file(target_path, as_attachment=False, conditional=True, mimetype='video/mp4')
 
251
  return "File not found", 404
252
 
253
  if __name__ == '__main__':
 
254
  app.run(debug=True, port=5000)