dragxd commited on
Commit
ca4952f
·
verified ·
1 Parent(s): 58e825a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -3
app.py CHANGED
@@ -1,11 +1,12 @@
1
  from fastapi import FastAPI, HTTPException, Query
2
  from fastapi.responses import RedirectResponse
3
  import subprocess
 
4
 
5
  app = FastAPI(
6
  title="YouTube Audio Streamer",
7
  description="Stream best audio of a YouTube video using yt-dlp.",
8
- version="1.0.1",
9
  docs_url="/docs",
10
  redoc_url="/redoc"
11
  )
@@ -16,14 +17,22 @@ async def root():
16
 
17
  @app.get("/stream", tags=["Stream"])
18
  async def stream_audio(url: str = Query(..., description="Full YouTube video URL")):
19
- if "youtube.com/watch?v=" not in url and "youtu.be/" not in url:
 
 
20
  raise HTTPException(status_code=400, detail="Invalid YouTube URL.")
21
 
 
 
 
22
  try:
23
  result = subprocess.run(
24
- ["yt-dlp", "-f", "bestaudio", "--get-url", url],
25
  capture_output=True, text=True
26
  )
 
 
 
27
  audio_url = result.stdout.strip()
28
  if not audio_url:
29
  raise HTTPException(status_code=404, detail="No audio URL found.")
 
1
  from fastapi import FastAPI, HTTPException, Query
2
  from fastapi.responses import RedirectResponse
3
  import subprocess
4
+ import urllib.parse
5
 
6
  app = FastAPI(
7
  title="YouTube Audio Streamer",
8
  description="Stream best audio of a YouTube video using yt-dlp.",
9
+ version="1.0.2",
10
  docs_url="/docs",
11
  redoc_url="/redoc"
12
  )
 
17
 
18
  @app.get("/stream", tags=["Stream"])
19
  async def stream_audio(url: str = Query(..., description="Full YouTube video URL")):
20
+ decoded_url = urllib.parse.unquote(url)
21
+
22
+ if "youtube.com/watch?v=" not in decoded_url and "youtu.be/" not in decoded_url:
23
  raise HTTPException(status_code=400, detail="Invalid YouTube URL.")
24
 
25
+ # Remove URL query params (yt-dlp can fail with things like ?si=xxx)
26
+ base_url = decoded_url.split("&")[0].split("?")[0]
27
+
28
  try:
29
  result = subprocess.run(
30
+ ["yt-dlp", "-f", "bestaudio", "--get-url", base_url],
31
  capture_output=True, text=True
32
  )
33
+ if result.returncode != 0:
34
+ raise HTTPException(status_code=500, detail=f"yt-dlp error: {result.stderr.strip()}")
35
+
36
  audio_url = result.stdout.strip()
37
  if not audio_url:
38
  raise HTTPException(status_code=404, detail="No audio URL found.")