from pytube import YouTube
+import ffmpeg
-SAVE_PATH = "D:/Youtube/"
-with open('links_file.txt', 'r') as f:
- links = f.read().split('\n')
- if links[-1] == "":
- links = links[:-1]
+RES = ["1440p", "1080p", "720p", "480p", "360p", "240p", "144p"]
+ABR = ["160kbps", "128kbps", "70kbps", "50kbps", "48kbps"]
+target_res = 0
+target_abr=0
-VIDEO = False
+if __name__ == "__main__":
+
+ # get list of links from file
+ links = []
+ with open('links.txt', 'r') as f:
+ links = f.read().split('\n')
+ if links[-1] == "":
+ links = links[:-1]
+
+ # download links one by one
+ for link in links:
+ success = True
+ yt = YouTube(link)
+ video_streams = []
+ while len(video_streams) == 0:
+ video_streams = yt.streams.filter(file_extension='mp4', res=RES[target_res]) # find available streams
+ if target_res + 1 < len(RES):
+ target_res = target_res + 1
+ else:
+ success = False
+ break
+ if not success:
+ print(f"Unable to find video stream for {yt.title}")
+ break
+ vstream = video_streams[0]
+
+
+ # audio
+ audio_streams = []
+ while len(audio_streams) == 0:
+ audio_streams = yt.streams.filter(only_audio=True, abr=ABR[target_abr]) # find available streams
+
+ if target_abr + 1 < len(RES):
+ target_abr = target_abr + 1
+ else:
+ success = False
+ break
+ if not success:
+ print(f"Unable to find audio stream for {yt.title}")
+ break
+ astream = audio_streams[0]
+
+
+ vstream.download(output_path="downloaded/video_only")
+ astream.download(output_path="downloaded/audio_only")
+
+ input_video = ffmpeg.input(f"downloaded/video_only/{vstream.default_filename}")
+ input_audio = ffmpeg.input(f"downloaded/audio_only/{astream.default_filename}")
+
+ ffmpeg.concat(input_video, input_audio, v=1, a=1).output(f'downloaded/{yt.title}.mp4').run()
-def download_video(link):
- yt = YouTube(link)
- mp4_files = yt.streams.filter(file_extension="mp4")
- mp4_files = mp4_files.get_highest_resolution()
- mp4_files.download(output_path=SAVE_PATH)
- print("Download is completed successfully")
-def download_audio(link):
- yt = YouTube(link)
- audio = yt.streams.filter(only_audio=True).get_audio_only()
- audio.download(output_path=SAVE_PATH)
- print("Download is completed successfully")
-for i in links:
- if VIDEO:
- download_video(i)
- else:
- download_audio(i)
-print('Items Downloaded!')