Skip to content

Instantly share code, notes, and snippets.

@NicholasTD07
Created July 26, 2023 01:51
Show Gist options
  • Save NicholasTD07/2b5aacc5e0b3e9af0ca9293fc7cf6b8b to your computer and use it in GitHub Desktop.
Save NicholasTD07/2b5aacc5e0b3e9af0ca9293fc7cf6b8b to your computer and use it in GitHub Desktop.
# coding: utf-8
from pytube import (
Playlist as P,
Stream as S,
YouTube as Y
)
from pytube.cli import on_progress
async def download_best_quality_streams(youtube: Y):
hq = best_quality_stream(youtube, must_have_audio=False)
hq_with_audio = best_quality_stream(youtube, must_have_audio=True)
def resolution(stream: S) -> int:
string = stream.resolution # 2160p / 1080p / 720p etc.
number = string[:-1] # Hardcoded logic
return int(number)
# if the best quality stream has no audio track
if not hq.includes_audio_track:
# and its resolution is lower or equal to the one has audio
if resolution(hq) <= resolution(hq_with_audio):
video = hq_with_audio
audio = None
print(f"Downloading the {video.resolution} video with audio")
else:
video = hq
audio = youtube.streams.get_audio_only()
print(f"Downloading the {video.resolution} video and the audio track separately")
video.download()
if audio:
audio.download()
def best_quality_stream(youtube: Y, must_have_audio: bool=False) -> S:
streams = youtube.streams
if must_have_audio:
streams = streams.filter(
custom_filter_functions=[
has_audio
]
)
return streams.order_by('resolution').desc().first()
def has_audio(stream: S) -> bool:
return stream.includes_audio_track
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment