⚡ Media Studio PWA

STEP 1: COLAB & BACKEND CONNECTION
📋 Colab Setup Codes (Cell 1 & Cell 2 — 1-Tap Copy)
Cell 1: Install yt-dlp, FastAPI, FFmpeg & Cloudflared
!pip install -q -U yt-dlp fastapi uvicorn python-multipart
!apt-get update -qq && apt-get install -y -qq ffmpeg zip
!wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
!dpkg -i cloudflared-linux-amd64.deb
Cell 2: FastAPI Server + Exact YouTube Title + Tunnel URL
import os, glob, uuid, zipfile, subprocess, threading, time, re
from urllib.parse import quote
from fastapi import FastAPI, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
import uvicorn

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["Content-Disposition", "X-File-Name"],
)

VIDEO_PRESETS = {
    "720p": (720, None),
    "1080p30": (1080, 30),
    "2k30": (1440, 30),
    "4k": (2160, None),
    "4k50": (2160, 50),
}

def parse_urls(raw: str):
    return [u.strip() for line in (raw or "").splitlines() for u in line.split(",") if u.strip()]

def sanitize_filename(name: str) -> str:
    cleaned = re.sub(r'[\\/:*?"<>|\r\n]+', " ", name)
    cleaned = re.sub(r"\s+", " ", cleaned).strip(" .")
    return cleaned or "download"

@app.get("/health")
def health():
    return {"status": "online"}

@app.post("/download")
def download(
    urls_text: str = Form(...),
    mode: str = Form(...),
    quality: str = Form(...)
):
    urls = parse_urls(urls_text)
    if not urls:
        return JSONResponse({"error": "Kam se kam ek URL daalein."}, status_code=400)

    job_id = uuid.uuid4().hex[:6]
    out_dir = f"/content/job_{job_id}"
    os.makedirs(out_dir, exist_ok=True)
    out_tpl = f"{out_dir}/%(title).80s.%(ext)s"
    errors = []

    for url in urls:
        if mode == "video":
            max_h, max_fps = VIDEO_PRESETS.get(quality, (1080, 30))
            fps_filter = f"[fps<={max_fps}]" if max_fps else ""
            fmt = (
                f"bv*[height<={max_h}]{fps_filter}+ba/"
                f"bv*[height<={max_h}]+ba/"
                f"b[height<={max_h}]"
            )
            cmd = [
                "yt-dlp", "--no-playlist",
                "-f", fmt,
                "--merge-output-format", "mp4",
                "-o", out_tpl, url
            ]
        else:
            bitrate = quality if quality in ("320K", "192K") else "320K"
            cmd = [
                "yt-dlp", "--no-playlist",
                "-x", "--audio-format", "mp3", "--audio-quality", bitrate,
                "-o", out_tpl, url
            ]

        res = subprocess.run(cmd, capture_output=True, text=True)
        if res.returncode != 0:
            last_lines = [ln.strip() for ln in (res.stderr or res.stdout or "").splitlines() if ln.strip()]
            detail = " | ".join(last_lines[-3:]) if last_lines else "Unknown yt-dlp error"
            errors.append(f"{url}: {detail}")

    files = [f for f in glob.glob(f"{out_dir}/*") if os.path.isfile(f) and not f.endswith(".zip")]
    if not files:
        msg = " | ".join(errors) if errors else "Download fail ho gaya."
        return JSONResponse({"error": msg[:400]}, status_code=500)

    if len(files) == 1:
        target = files[0]
        raw_name = os.path.basename(target)
        base_no_ext, ext = os.path.splitext(raw_name)
        safe_fname = sanitize_filename(base_no_ext) + ext.lower()
        encoded_name = quote(safe_fname)
        return FileResponse(
            target,
            filename=safe_fname,
            media_type="application/octet-stream",
            headers={
                "X-File-Name": encoded_name,
                "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_name}",
            },
        )
    else:
        zip_path = f"/content/media_{job_id}.zip"
        with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
            for f in files:
                rn = os.path.basename(f)
                b, e = os.path.splitext(rn)
                zf.write(f, arcname=sanitize_filename(b) + e.lower())
        zname = f"media_{job_id}.zip"
        encoded_zname = quote(zname)
        return FileResponse(
            zip_path,
            filename=zname,
            media_type="application/zip",
            headers={
                "X-File-Name": encoded_zname,
                "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_zname}",
            },
        )

def run_server():
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="warning")

threading.Thread(target=run_server, daemon=True).start()
time.sleep(2)

proc = subprocess.Popen(
    ["cloudflared", "tunnel", "--url", "http://localhost:8000"],
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
)
for line in proc.stdout:
    m = re.search(r"https://[a-zA-Z0-9-]+\.trycloudflare\.com", line)
    if m:
        print()
        print("APNA BACKEND API URL COPY KAREIN:")
        print(m.group(0))
        break
VIDEO MP4 (Single = MP4 | Multiple = ZIP)
Idle0%
MP3 AUDIO (Single = .mp3 | Multiple = .zip)
Idle0%