How can I filter and limit filesize that PyTube downloads?

Viewed 732

I am writing a Python script that is supposed to download YouTube videos using the PyTube Python library. However the downloaded video must not exceed file size of 200MB. At the same time I don't want to just assume and download a low quality 480p stream because of this limitation. And so I have been trying to setup a solution that would always try to download the next possible highest resolution if the video filesize would no longer exceed 200MB.

To better explain if the video exceeds 200MB in file size in 4K let's say I want the script to download the next possible 2K stream which would have smaller file size and wouldn't exceed 200MB. If 2K still would be too big move on to 1080p and so forth.

For this to my understanding I have tried setting up the filesize that I found in this API communication.

However I cannot seem to get it working and I always get the following error :

AttributeError: 'NoneType' object has no attribute 'filesize'

I tried searching for a solution myself but couldn't figure it out. Here is my code that I am trying to get the relevant video with :

video = YouTube("https://www.youtube.com/watch?v=lM02vNMRRB0")

while True:
    switch = input("Download stream?: ").lower()
    if "y" or "yes" in switch:
        output_adaptive = True
        break
    elif "n" or "no" in switch:
        output_progressive = True
        break
    else:
        print("Invalid answer input")
        continue
if output_adaptive == True:
    filter = video.streams.filter(adaptive=True, file_extension='mp4').get_highest_resolution()
    if filter.filesize() < 1950000000:
        filter.download()
else:
    filter = video.streams.filter(adaptive=output_adaptive, file_extension='mp4').get_by_resolution("2160p")
    if filter.filesize() < 1950000000:
        filter.download()
    else:
        filter = video.streams.filter(adaptive=output_adaptive, file_extension='mp4').get_by_resolution("1080p")
        if filter.filesize() < 1950000000:
            filter.download()
        else:
            filter = video.streams.filter(adaptive=output_adaptive, file_extension='mp4').get_by_resolution("720p")
            if filter.filesize() < 1950000000:
                filter.download()
            else:
                print(
                    "Could not download video.")

How can I make sure that the downloaded video won't exceed 200MB in filesize without encountering this error? Thanks for any help with this!

1 Answers

Use filter.filesize instead of filter.filesize()

Related