|
|
from fastapi import FastAPI, HTTPException, Query |
|
|
from fastapi.responses import JSONResponse, FileResponse |
|
|
import os |
|
|
from yt_dlp import YoutubeDL |
|
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
DOWNLOAD_DIR = "downloads" |
|
|
os.makedirs(DOWNLOAD_DIR, exist_ok=True) |
|
|
|
|
|
@app.get("/") |
|
|
def read_root(): |
|
|
return {"message": "Welcome to the Instagram Reel Downloader API"} |
|
|
|
|
|
@app.get("/download/") |
|
|
def download_instagram_reel( |
|
|
reel_url: str = Query(..., description="The URL of the Instagram Reel to download"), |
|
|
): |
|
|
""" |
|
|
Download an Instagram Reel using yt-dlp and provide a download link. |
|
|
|
|
|
Args: |
|
|
reel_url (str): The URL of the Instagram Reel. |
|
|
|
|
|
Returns: |
|
|
JSONResponse: A JSON object containing the download link. |
|
|
""" |
|
|
if not reel_url: |
|
|
raise HTTPException(status_code=400, detail="The 'reel_url' parameter is required.") |
|
|
|
|
|
|
|
|
ydl_opts = { |
|
|
"outtmpl": os.path.join(DOWNLOAD_DIR, "%(title)s.%(ext)s"), |
|
|
"quiet": True, |
|
|
"merge_output_format": "mp4", |
|
|
} |
|
|
|
|
|
try: |
|
|
with YoutubeDL(ydl_opts) as ydl: |
|
|
info = ydl.extract_info(reel_url, download=True) |
|
|
original_filename = ydl.prepare_filename(info) |
|
|
|
|
|
|
|
|
if not os.path.exists(original_filename): |
|
|
raise HTTPException(status_code=500, detail="Failed to download the Reel.") |
|
|
|
|
|
|
|
|
base_name = os.path.basename(original_filename) |
|
|
sanitized_name = base_name.replace(" ", "_") |
|
|
sanitized_path = os.path.join(DOWNLOAD_DIR, sanitized_name) |
|
|
|
|
|
|
|
|
os.rename(original_filename, sanitized_path) |
|
|
|
|
|
|
|
|
download_link = f"https://r3hab-ir.hf.space/files/{sanitized_name}" |
|
|
|
|
|
return JSONResponse(content={"download_link": download_link}) |
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") |
|
|
|
|
|
@app.get("/files/{file_name}") |
|
|
def serve_file(file_name: str): |
|
|
""" |
|
|
Serve the downloaded file for users to download. |
|
|
""" |
|
|
file_path = os.path.join(DOWNLOAD_DIR, file_name) |
|
|
if not os.path.exists(file_path): |
|
|
raise HTTPException(status_code=404, detail="File not found.") |
|
|
return FileResponse(path=file_path, filename=file_name, media_type="video/mp4") |
|
|
|