File size: 1,292 Bytes
0b5dc96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
import yt_dlp
import os

app = FastAPI()

# Temporary download directory
DOWNLOAD_DIR = "downloads/"

# Ensure the directory exists
if not os.path.exists(DOWNLOAD_DIR):
    os.makedirs(DOWNLOAD_DIR)

@app.get("/")
def greet_json():
    return {"Hello": "World!"}

@app.get("/download_video")
def download_video(url: str):
    try:
        # Set up yt-dlp options to avoid downloading .webm files
        ydl_opts = {
            'format': 'bestvideo+bestaudio/best',  # Download the best video and audio
            'outtmpl': DOWNLOAD_DIR + '%(id)s.%(ext)s',  # Output path template
            'noplaylist': True,  # Avoid downloading playlists, if it's a playlist URL
            'quiet': True,  # Suppress unnecessary output
        }

        # Download video using yt-dlp
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(url, download=True)
            video_filename = ydl.prepare_filename(info_dict)

        # Return the video file as a response
        video_file = open(video_filename, "rb")
        return StreamingResponse(video_file, media_type="video/mp4")

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))