nifty-coder commited on
Commit
a95a00b
·
1 Parent(s): dc73a54

removed ytdlp

Browse files
Files changed (2) hide show
  1. __pycache__/main.cpython-314.pyc +0 -0
  2. main.py +21 -167
__pycache__/main.cpython-314.pyc CHANGED
Binary files a/__pycache__/main.cpython-314.pyc and b/__pycache__/main.cpython-314.pyc differ
 
main.py CHANGED
@@ -8,49 +8,17 @@ import re
8
  import json
9
  import hashlib
10
  import io
11
- from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Response, Request, Depends, Header
12
  from datetime import datetime
13
- from pytubefix import YouTube as PyT
14
- from pytubefix.cli import on_progress
15
  from fastapi.middleware.cors import CORSMiddleware
16
  from fastapi.responses import FileResponse
17
  from pydantic import BaseModel
 
18
 
19
- # Regex for basic YouTube URL validation
20
- YT_PATTERN = r'(https?://)?(www\.)?(youtube\.com|youtu\.be)/.+'
21
 
22
  # Logging setup
23
  logging.basicConfig(level=logging.INFO)
24
  logger = logging.getLogger(__name__)
25
 
26
- # --- YouTube Cookie & PO Token Setup ---
27
-
28
- # Read the cookie data from the environment variable (Netscape format preferred)
29
- cookies_content = os.environ.get('YTDLP_COOKIES_CONTENT')
30
- cookies_file_path = None
31
-
32
- try:
33
- # 1. Handle literal "\n" strings (common in Render/Heroku env vars)
34
- if '\\n' in cookies_content and '\n' not in cookies_content:
35
- cookies_content = cookies_content.replace('\\n', '\n')
36
- logger.info("Fixed escaped newlines in YTDLP_COOKIES_CONTENT")
37
-
38
- # Create a temporary file for yt-dlp to read
39
- with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as tmp_file:
40
- tmp_file.write(cookies_content)
41
- cookies_file_path = tmp_file.name
42
- os.environ['YTDLP_COOKIES_FILE'] = cookies_file_path
43
- logger.info(f"YTDLP_COOKIES_FILE set to temporary path: {cookies_file_path}")
44
- except Exception as e:
45
- logger.error(f"Failed to set up yt-dlp cookies: {e}")
46
- else:
47
- logger.warning("YTDLP_COOKIES_CONTENT not set. Downloads may fail on restricted videos.")
48
-
49
- # PO Token support for advanced bot detection bypass
50
- PO_TOKEN = os.environ.get('YTDLP_PO_TOKEN')
51
- if PO_TOKEN:
52
- logger.info("YTDLP_PO_TOKEN detected and will be used.")
53
-
54
  # ----------------------------------------
55
 
56
  # FastAPI app
@@ -74,9 +42,9 @@ app.add_middleware(
74
  allow_credentials=True,
75
  allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
76
  allow_headers=["Authorization", "Content-Type", "X-Requested-With"],
 
77
  )
78
 
79
- @app.options("/youtube")
80
  @app.options("/upload")
81
  def options_handler(request: Request):
82
  origin = request.headers.get("origin")
@@ -86,8 +54,7 @@ def options_handler(request: Request):
86
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
87
  })
88
 
89
- class YouTubeInput(BaseModel):
90
- youtube_url: str
91
 
92
  @app.get("/")
93
  def health_check():
@@ -95,9 +62,7 @@ def health_check():
95
 
96
  # --- Utility Functions ---
97
 
98
- def get_video_id_from_url(url: str) -> str:
99
- m = re.search(r'(?:v=|youtu\.be/)([A-Za-z0-9_-]{6,})', url)
100
- return m.group(1) if m else None
101
 
102
  def find_ffmpeg() -> str:
103
  common_paths = ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"]
@@ -284,110 +249,19 @@ def run_demucs_and_extract(input_path: str, tmpdir: str) -> str:
284
  logger.info(f"MP3 Directory contents: {os.listdir(mp3_dir)}")
285
  return mp3_dir
286
 
287
- @app.post("/youtube")
288
- def process_youtube_audio(data: YouTubeInput, background_tasks: BackgroundTasks):
289
- if not re.match(YT_PATTERN, data.youtube_url):
290
- raise HTTPException(status_code=400, detail="Invalid YouTube URL")
291
 
292
- vid = get_video_id_from_url(data.youtube_url)
293
- if vid:
294
- cache_path = os.path.join(CACHE_DIR, f"{vid}.zip")
295
- if os.path.exists(cache_path):
296
- return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip")
297
 
298
- tmpdir = tempfile.mkdtemp()
299
- try:
300
- audio_path = os.path.join(tmpdir, "audio.mp3")
301
-
302
- # 1. Fetch Title
303
- title_cmd = [
304
- "yt-dlp", "--get-title", "--no-warnings",
305
- "--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
306
- "--add-header", "Referer: https://www.google.com",
307
- data.youtube_url
308
- ]
309
- if os.environ.get('YTDLP_COOKIES_FILE'): title_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']])
310
- if PO_TOKEN: title_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"])
311
- try:
312
- res = subprocess.run(title_cmd, capture_output=True, text=True, check=True)
313
- video_title = res.stdout.strip()
314
- except subprocess.CalledProcessError as e:
315
- logger.error(f"yt-dlp title fetch failed: {e.stderr}")
316
- video_title = "Unknown Title"
317
-
318
- # 2. Download Audio
319
- dl_cmd = [
320
- "yt-dlp", "-x", "--audio-format", "mp3",
321
- "--force-ipv4", "--no-playlist", "--no-warnings",
322
- "--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
323
- "--add-header", "Referer: https://www.google.com",
324
- "-o", audio_path, data.youtube_url
325
- ]
326
- # if os.environ.get('YTDLP_COOKIES_FILE'): dl_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']])
327
- if PO_TOKEN: dl_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"])
328
- if FFMPEG_DIR: dl_cmd.extend(["--ffmpeg-location", FFMPEG_DIR])
329
-
330
- logger.info(f"Downloading: {data.youtube_url}")
331
- try:
332
- subprocess.run(dl_cmd, check=True, capture_output=True, text=True)
333
- except subprocess.CalledProcessError as e:
334
- logger.error(f"yt-dlp download failed: {e.stderr}")
335
- logger.info("Retrying with pytubefix fallback...")
336
-
337
- try:
338
- # Fallback to pytubefix which uses android clients by default to bypass bots
339
- yt = PyT(data.youtube_url, use_po_token=True if PO_TOKEN else False)
340
- # yt.streams.get_audio_only('mp4') download
341
- stream = yt.streams.get_audio_only()
342
- if not stream:
343
- raise Exception("No audio stream found with pytubefix")
344
-
345
- # Download to temp path
346
- downloaded_file = stream.download(output_path=tmpdir, filename="audio_temp")
347
-
348
- # Convert to mp3 using ffmpeg manually since pytubefix just downloads
349
- subprocess.run([FFMPEG_PATH, "-y", "-i", downloaded_file, "-ac", "2", "-ar", "44100", audio_path], check=True)
350
- except Exception as e2:
351
- logger.error(f"pytubefix fallback also failed: {e2}")
352
- # Raise the original yt-dlp error as it's usually more descriptive
353
- if "Incomplete YouTube ID" in e.stderr:
354
- raise HTTPException(status_code=400, detail="Invalid or truncated YouTube URL ID.")
355
- raise e
356
-
357
- # 3. Process with Demucs
358
- extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
359
-
360
- logger.info(f"Zipping directory: {extracted_dir}, Contents: {os.listdir(extracted_dir)}")
361
- final_zip_path = os.path.join(tmpdir, "extracted_stems.zip")
362
- with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
363
- for root, dirs, files in os.walk(extracted_dir):
364
- for file in files:
365
- file_path = os.path.join(root, file)
366
- arcname = os.path.relpath(file_path, extracted_dir)
367
- zipf.write(file_path, arcname)
368
-
369
- zip_size = os.path.getsize(final_zip_path)
370
- logger.info(f"Created zip file at {final_zip_path}, Size: {zip_size} bytes")
371
-
372
- if vid:
373
- cache_path = os.path.join(CACHE_DIR, f"{vid}.zip")
374
- shutil.copyfile(final_zip_path, cache_path)
375
- # Serve from cache to avoid race conditions with cleanup
376
- final_zip_path = cache_path
377
-
378
- # Sanitize title for HTTP header (prevent latin-1 encoding errors)
379
- safe_title = video_title.encode('ascii', 'ignore').decode('ascii')
380
-
381
- background_tasks.add_task(shutil.rmtree, tmpdir, True)
382
- return FileResponse(final_zip_path, filename="extracted_stems.zip", media_type="application/zip", headers={"X-Video-Title": safe_title})
383
 
384
- except Exception as e:
385
- shutil.rmtree(tmpdir, ignore_errors=True)
386
- logger.error(f"YouTube processing error: {e}")
387
- raise HTTPException(status_code=500, detail=str(e))
388
 
389
- @app.post("/upload")
390
- def process_upload(file: UploadFile = File(...), background_tasks: BackgroundTasks = None):
391
  tmpdir = tempfile.mkdtemp()
392
  try:
393
  input_path = os.path.join(tmpdir, file.filename)
@@ -412,42 +286,22 @@ def process_upload(file: UploadFile = File(...), background_tasks: BackgroundTas
412
  shutil.copyfile(final_zip_path, cache_path)
413
 
414
  if background_tasks: background_tasks.add_task(shutil.rmtree, tmpdir, True)
415
- return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip")
 
 
 
416
  except Exception as e:
417
  shutil.rmtree(tmpdir, ignore_errors=True)
418
  logger.error(f"Upload processing error: {e}")
419
  raise HTTPException(status_code=500, detail=str(e))
420
 
421
- @app.post("/youtube/extracted")
422
- def process_youtube_audio_extracted(data: YouTubeInput):
423
- if not re.match(YT_PATTERN, data.youtube_url):
424
- raise HTTPException(status_code=400, detail="Invalid YouTube URL")
425
 
426
- tmpdir = tempfile.mkdtemp()
427
- try:
428
- audio_path = os.path.join(tmpdir, "audio.mp3")
429
- dl_cmd = ["yt-dlp", "-x", "--audio-format", "mp3", "--force-ipv4", "--no-playlist", "-o", audio_path, data.youtube_url]
430
- if os.environ.get('YTDLP_COOKIES_FILE'): dl_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']])
431
- if PO_TOKEN: dl_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"])
432
-
433
- try:
434
- subprocess.run(dl_cmd, check=True, capture_output=True, text=True)
435
- except subprocess.CalledProcessError as e:
436
- logger.error(f"yt-dlp extracted download failed: {e.stderr}")
437
- raise e
438
- extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
439
-
440
- files = []
441
- for f in os.listdir(extracted_dir):
442
- files.append({"filename": f, "path": os.path.join(extracted_dir, f)})
443
-
444
- return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir}
445
- except Exception as e:
446
- shutil.rmtree(tmpdir, ignore_errors=True)
447
- raise HTTPException(status_code=500, detail=str(e))
448
 
449
  @app.post("/upload/extracted")
450
- def process_upload_extracted(file: UploadFile = File(...)):
 
 
 
451
  tmpdir = tempfile.mkdtemp()
452
  try:
453
  input_path = os.path.join(tmpdir, file.filename)
 
8
  import json
9
  import hashlib
10
  import io
 
11
  from datetime import datetime
 
 
12
  from fastapi.middleware.cors import CORSMiddleware
13
  from fastapi.responses import FileResponse
14
  from pydantic import BaseModel
15
+ from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Response, Request, Depends, Header, Form
16
 
 
 
17
 
18
  # Logging setup
19
  logging.basicConfig(level=logging.INFO)
20
  logger = logging.getLogger(__name__)
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  # ----------------------------------------
23
 
24
  # FastAPI app
 
42
  allow_credentials=True,
43
  allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
44
  allow_headers=["Authorization", "Content-Type", "X-Requested-With"],
45
+ expose_headers=["X-Cache-Key", "X-Video-Title", "Content-Disposition"],
46
  )
47
 
 
48
  @app.options("/upload")
49
  def options_handler(request: Request):
50
  origin = request.headers.get("origin")
 
54
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
55
  })
56
 
57
+
 
58
 
59
  @app.get("/")
60
  def health_check():
 
62
 
63
  # --- Utility Functions ---
64
 
65
+
 
 
66
 
67
  def find_ffmpeg() -> str:
68
  common_paths = ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"]
 
249
  logger.info(f"MP3 Directory contents: {os.listdir(mp3_dir)}")
250
  return mp3_dir
251
 
 
 
 
 
252
 
 
 
 
 
 
253
 
254
+ @app.post("/upload")
255
+ def process_upload(
256
+ file: UploadFile = File(...),
257
+ tos_agreed: bool = Form(...),
258
+ background_tasks: BackgroundTasks = None
259
+ ):
260
+ if not tos_agreed:
261
+ raise HTTPException(status_code=400, detail="You must agree to the Terms of Service to upload content.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
+ # (Optional) Content ID check would go here
 
 
 
264
 
 
 
265
  tmpdir = tempfile.mkdtemp()
266
  try:
267
  input_path = os.path.join(tmpdir, file.filename)
 
286
  shutil.copyfile(final_zip_path, cache_path)
287
 
288
  if background_tasks: background_tasks.add_task(shutil.rmtree, tmpdir, True)
289
+ return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip", headers={"X-Cache-Key": digest})
290
+ except HTTPException as he:
291
+ shutil.rmtree(tmpdir, ignore_errors=True)
292
+ raise he
293
  except Exception as e:
294
  shutil.rmtree(tmpdir, ignore_errors=True)
295
  logger.error(f"Upload processing error: {e}")
296
  raise HTTPException(status_code=500, detail=str(e))
297
 
 
 
 
 
298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
 
300
  @app.post("/upload/extracted")
301
+ def process_upload_extracted(file: UploadFile = File(...), tos_agreed: bool = Form(...)):
302
+ if not tos_agreed:
303
+ raise HTTPException(status_code=400, detail="You must agree to the Terms of Service to upload content.")
304
+
305
  tmpdir = tempfile.mkdtemp()
306
  try:
307
  input_path = os.path.join(tmpdir, file.filename)