pip install pytube tqdm. pip install --upgrade pytube

 from pytube import YouTube

from tqdm import tqdm

import os


def download_video():

    # Ask for video URL

    url = input("Enter YouTube video URL: ")

    

    try:

        # Create YouTube object

        yt = YouTube(url, on_progress_callback=progress_callback)

        

        # Select highest quality stream (mp4 with audio)

        stream = yt.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution()

        

        # Set download folder

        download_path = os.path.join(os.getcwd(), "downloads")

        os.makedirs(download_path, exist_ok=True)

        

        print(f"Downloading: {yt.title} (Highest Quality: {stream.resolution})")

        stream.download(output_path=download_path)

        print("\nDownload completed successfully!")

        

    except Exception as e:

        print(f"Error: {str(e)}")


def progress_callback(stream, chunk, bytes_remaining):

    """Displays a progress bar using tqdm"""

    total_size = stream.filesize

    downloaded = total_size - bytes_remaining

    progress_bar.update(downloaded - progress_bar.n)  # Update by delta


# Initialize progress bar

progress_bar = tqdm(total=1, unit='B', unit_scale=True, desc="Progress")


if __name__ == "__main__":

    download_video()

Comments