import os import uuid import asyncio from fastapi import FastAPI, HTTPException, BackgroundTasks from fastapi.responses import FileResponse from fastapi.middleware.cors import CORSMiddleware import yt_dlp app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) def remove_file(path: str): try: if os.path.exists(path): os.remove(path) except Exception as e: print(f"Error removing file {path}: {e}") @app.get("/extract") async def extract_video(url: str, background_tasks: BackgroundTasks): if not url: raise HTTPException(status_code=400, detail="URL is required") filename = f"{uuid.uuid4()}.mp4" ydl_opts = { 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', 'outtmpl': filename, 'quiet': True, 'no_warnings': True, # Avoid downloading very large videos 'max_filesize': 50 * 1024 * 1024, # 50 MB max } try: # Run yt-dlp synchronously in a thread def download(): with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) await asyncio.to_thread(download) if not os.path.exists(filename): # Sometimes yt-dlp might download as .mkv or other format depending on best available, # but we requested mp4. Let's find the downloaded file if it has a different extension. downloaded = [f for f in os.listdir('.') if f.startswith(filename.split('.mp4')[0])] if not downloaded: raise HTTPException(status_code=500, detail="Failed to download video") filename = downloaded[0] background_tasks.add_task(remove_file, filename) return FileResponse(filename, media_type="video/mp4", filename="video.mp4") except Exception as e: # Clean up any partial files partial_files = [f for f in os.listdir('.') if f.startswith(filename.split('.mp4')[0])] for f in partial_files: remove_file(f) raise HTTPException(status_code=500, detail=str(e))