File size: 2,232 Bytes
4c74f21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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))