Yt-dlp DownloadError: "Requested format is not available" when downloading specific YouTube video in Python

I am using yt-dlp within a Python 3.13 virtual environment on macOS to download videos. However, for a specific video (QageNN-V8rY), the download fails with a DownloadError.

File "/Users/ashazakhtar/coding/project-idea/.venv/lib/python3.13/site-packages/yt_dlp/YoutubeDL.py", line 1093, in trouble
    raise DownloadError(message, exc_info)
yt_dlp.utils.DownloadError: ERROR: [youtube] QageNN-V8rY: Requested format is not available. Use --list-formats for a list of available formats

My Current Code:

def transcript_video(self, url):
    with tempfile.TemporaryDirectory() as temp_dir:
        output_path = os.path.join(temp_dir, "audio.m4a")
        cookie_path = os.path.join(settings.BASE_DIR, "www.youtube.com_cookies.txt")
        ydl_opts = {
            "format": "bestaudio[ext=m4a]/bestaudio[ext=webm]/bestaudio",
            "quiet": True,
            "outtmpl": output_path,
            "cookiefile": cookie_path,
            "nocheckcertificate": True,
            "user_agent": "Mozilla/5.0",
            "cookies_readonly": True,
        }

        with YoutubeDL(ydl_opts) as ydl:  # type: ignore
            ydl.download([url])  # type: ignore

        print(f"Audio file size: {os.path.getsize(output_path)} bytes")

        # Send audio file to local FastAPI
        with open(output_path, "rb") as audio_file:
            response = requests.post(
                f"{FASTAPI_BASE_URL}/transcribe",
                files={"file": ("audio.m4a", audio_file, "audio/m4a")},
                timeout=300,  # whisper can be slow on CPU
            )

        response.raise_for_status()
        result = response.json()
        print(f"Transcription done: {result['text'][:100]}...")
        return result["text"]

What I have tried:

  1. I verified that the video URL is correct and accessible in my browser.

  2. I updated yt-dlp to the latest version inside my virtual environment (pip install -U yt-dlp).

  3. Running yt-dlp --list-formats https://www.youtube.com/watch?v=QageNN-V8rY via the command line shows available formats, but my Python script still fails with the format error.

How can I configure my ydl_opts dictionary so that it dynamically selects the best available format for this video instead of throwing a missing format exception?

Вернуться на верх