Spaces:
Running
Running
from fastapi import FastAPI, HTTPException | |
from fastapi.responses import StreamingResponse | |
import yt_dlp | |
import os | |
from pathlib import Path | |
app = FastAPI() | |
# Temporary directory for downloaded videos | |
DOWNLOAD_DIR = Path("downloads/") | |
# Ensure the directory exists | |
if not DOWNLOAD_DIR.exists(): | |
DOWNLOAD_DIR.mkdir(parents=True) | |
# Path to the cookies.txt file | |
COOKIES_FILE = Path("cookies.txt") | |
def greet_json(): | |
return {"Hello": "World!"} | |
def download_video(url: str): | |
try: | |
# Set up yt-dlp options to download the best video/audio | |
ydl_opts = { | |
'format': 'bestvideo+bestaudio/best', # Download the best video and audio | |
'outtmpl': str(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 | |
'cookies': str(COOKIES_FILE), # Use cookies from the specified file | |
} | |
# Create a temporary filename for the video | |
video_filename = DOWNLOAD_DIR / "temp_video.mp4" | |
# Use yt-dlp to download the video | |
with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
info_dict = ydl.extract_info(url, download=True) | |
video_filename = ydl.prepare_filename(info_dict) | |
# Check if the video was successfully downloaded | |
if not video_filename.exists(): | |
raise HTTPException(status_code=500, detail="Video download failed.") | |
# Open the video file and stream it | |
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)) | |