Chrunos commited on
Commit
c60a310
·
verified ·
1 Parent(s): 2086f36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -3
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import sys
2
  import time
3
- from fastapi import FastAPI, BackgroundTasks, Request, HTTPException, Security
4
  from fastapi.security import APIKeyHeader
5
  from fastapi.responses import FileResponse
6
  from fastapi.concurrency import run_in_threadpool
@@ -27,6 +27,8 @@ import logging
27
  import gc
28
  from typing import Dict, Any
29
  import re
 
 
30
 
31
  tmp_dir = tempfile.gettempdir()
32
  BASE_URL = "https://chrunos-zam.hf.space"
@@ -174,6 +176,79 @@ def get_user_ip(request: Request) -> str:
174
  return request.client.host
175
 
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
 
179
  @app.post("/maxs")
@@ -233,9 +308,16 @@ async def download_high_quality_video(request: Request):
233
  }
234
 
235
  if is_youtube_url:
236
- ydl_opts['cookiefile'] = cookiefile
 
 
 
 
 
 
 
237
 
238
-
239
  await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([video_url]))
240
 
241
  downloaded_files = list(Path(global_download_dir).glob(f"*_{timestamp}.mp4"))
 
1
  import sys
2
  import time
3
+ from fastapi import FastAPI, BackgroundTasks, Request, HTTPException, Security, render_template, jsonify
4
  from fastapi.security import APIKeyHeader
5
  from fastapi.responses import FileResponse
6
  from fastapi.concurrency import run_in_threadpool
 
27
  import gc
28
  from typing import Dict, Any
29
  import re
30
+ import asyncio
31
+ import cloudscraper
32
 
33
  tmp_dir = tempfile.gettempdir()
34
  BASE_URL = "https://chrunos-zam.hf.space"
 
176
  return request.client.host
177
 
178
 
179
+ class ApiRotator:
180
+ def __init__(self, apis):
181
+ self.apis = apis
182
+ self.last_successful_index = None
183
+
184
+ def get_prioritized_apis(self):
185
+ if self.last_successful_index is not None:
186
+ # Move the last successful API to the front
187
+ rotated_apis = (
188
+ [self.apis[self.last_successful_index]] +
189
+ self.apis[:self.last_successful_index] +
190
+ self.apis[self.last_successful_index+1:]
191
+ )
192
+ return rotated_apis
193
+ return self.apis
194
+
195
+ def update_last_successful(self, index):
196
+ self.last_successful_index = index
197
+
198
+ # In your function:
199
+ api_rotator = ApiRotator([
200
+ "https://cblt.fariz.dev",
201
+ "https://cobalt-api.ayo.tf",
202
+ "http://34.107.254.11",
203
+ "https://dwnld.nichind.dev",
204
+ "https://cobalt-api.kwiatekmiki.com",
205
+ "https://yt.edd1e.xyz/"
206
+
207
+ ])
208
+
209
+
210
+
211
+ async def get_track_download_url(video_url: str) -> str:
212
+ apis = api_rotator.get_prioritized_apis()
213
+ session = cloudscraper.create_scraper() # Requires cloudscraper package
214
+ headers = {
215
+ "Accept": "application/json",
216
+ "Content-Type": "application/json",
217
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
218
+ }
219
+
220
+ for i, api_url in enumerate(apis):
221
+ try:
222
+ logger.info(f"Attempting to get download URL from: {api_url}")
223
+ y_url = video_url
224
+ response = session.post(
225
+ api_url,
226
+ timeout=20,
227
+ json={"url": y_url, "videoQuality": "720"},
228
+ headers=headers
229
+ )
230
+ logger.info(f"Response status: {response.status_code}")
231
+ logger.info(f"Response content: {response.content}")
232
+
233
+ if response.headers.get('content-type', '').startswith('application/json'):
234
+ json_response = response.json()
235
+ error_code = json_response.get("error", {}).get("code", "")
236
+
237
+ if error_code == "error.api.content.video.unavailable":
238
+ logger.warning(f"Video unavailable error from {api_url}")
239
+ break # Only break for specific error
240
+
241
+ if "url" in json_response:
242
+ api_rotator.update_last_successful(i)
243
+ return json_response["url"]
244
+
245
+ except Exception as e:
246
+ logger.error(f"Failed with {api_url}: {str(e)}")
247
+ continue
248
+
249
+ logger.error(f"No download URL found")
250
+ return {"error": "Download URL not found"}
251
+
252
 
253
 
254
  @app.post("/maxs")
 
308
  }
309
 
310
  if is_youtube_url:
311
+ dl_url = await get_track_download_url(video_url)
312
+ if dl_url and "http" in dl_url:
313
+ result = {"url": dl_url}
314
+ return jsonify(result)
315
+ else:
316
+ return {
317
+ "error": "Failed to Fetch the video."
318
+ }
319
 
320
+ else:
321
  await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([video_url]))
322
 
323
  downloaded_files = list(Path(global_download_dir).glob(f"*_{timestamp}.mp4"))