Yt-api / app.py
dragxd's picture
Update app.py
20cfce6 verified
raw
history blame
1.75 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import yt_dlp
import base64
app = FastAPI()
class VideoRequest(BaseModel):
video_id: str
@app.post("/audio/")
def get_audio_link(req: VideoRequest):
url = f"https://www.youtube.com/watch?v={req.video_id}"
ydl_opts = {
'quiet': True,
'format': 'bestaudio/best',
'skip_download': True,
'forceurl': True,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
for f in info['formats']:
if f.get('acodec') != 'none' and f.get('vcodec') == 'none':
audio_url = f['url']
b64 = base64.b64encode(audio_url.encode()).decode()
return {"status": "success", "audio_url": b64}
raise Exception("No audio found")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/video/")
def get_video_link(req: VideoRequest):
url = f"https://www.youtube.com/watch?v={req.video_id}"
ydl_opts = {
'quiet': True,
'format': 'best[height<=720][width<=1280]',
'skip_download': True,
'forceurl': True,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
for f in info['formats']:
if f.get('vcodec') != 'none':
video_url = f['url']
b64 = base64.b64encode(video_url.encode()).decode()
return {"status": "success", "video_url": b64}
raise Exception("No video found")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))