File size: 1,493 Bytes
58e825a b35c517 ca4952f b35c517 7451bec ca4952f 7451bec b35c517 7451bec b35c517 58e825a ca4952f 58e825a ca4952f b35c517 ca4952f b35c517 ca4952f 58e825a b35c517 58e825a b35c517 7451bec |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import RedirectResponse
import subprocess
import urllib.parse
app = FastAPI(
title="YouTube Audio Streamer",
description="Stream best audio of a YouTube video using yt-dlp.",
version="1.0.2",
docs_url="/docs",
redoc_url="/redoc"
)
@app.get("/", tags=["Health"])
async def root():
return {"status": "FastAPI working", "message": "YT-DLP backend ready"}
@app.get("/stream", tags=["Stream"])
async def stream_audio(url: str = Query(..., description="Full YouTube video URL")):
decoded_url = urllib.parse.unquote(url)
if "youtube.com/watch?v=" not in decoded_url and "youtu.be/" not in decoded_url:
raise HTTPException(status_code=400, detail="Invalid YouTube URL.")
# Remove URL query params (yt-dlp can fail with things like ?si=xxx)
base_url = decoded_url.split("&")[0].split("?")[0]
try:
result = subprocess.run(
["yt-dlp", "-f", "bestaudio", "--get-url", base_url],
capture_output=True, text=True
)
if result.returncode != 0:
raise HTTPException(status_code=500, detail=f"yt-dlp error: {result.stderr.strip()}")
audio_url = result.stdout.strip()
if not audio_url:
raise HTTPException(status_code=404, detail="No audio URL found.")
return RedirectResponse(audio_url)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {str(e)}") |