File size: 1,749 Bytes
20cfce6
a90b1ae
20cfce6
 
b35c517
a90b1ae
b35c517
20cfce6
 
b35c517
20cfce6
 
 
 
 
 
 
 
 
ca4952f
b35c517
20cfce6
 
 
 
 
 
 
 
b35c517
20cfce6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
51
52
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))