sanderl

YouTube Downloader

May 30th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.55 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Youtube downloader by _Sain
  4.  
  5. YouTube library used: https://github.com/nficano/pytube
  6. Audio Library used: https://github.com/Zulko/moviepy
  7.  
  8. also required FFMPEG for the audio library
  9.  
  10. How it works:
  11. You have a file each line contains a link and if you want a custom title
  12. the custom title will be used as a filename to save the downloaded video under
  13. it will be stored inside a folder that will be made with the same name
  14. as the file you enter that contains your url's
  15. After it finished downloading all the youtube videos,
  16. it will start converting them all into mp3's into a seperate folder named 'mp3'
  17.  
  18. Note for custom title's
  19. any reserved characters will be removed from the custom title
  20. reserved characters: ['<', '>', ':', '"', '/', '\\', '|', '?', '*']
  21.  
  22. Content for the file containing the videos you want to download:
  23. URL : Custom title (not required)
  24.  
  25. Example - playlist.txt:
  26. https://www.youtube.com/watch?v=uEpfPVQy_Bc : Fire From The Gods - Excuse Me
  27. https://www.youtube.com/watch?v=uk7OegsMOyM
  28. """
  29. from pytube import YouTube
  30. from pytube.utils import print_status
  31. import moviepy.editor as mp
  32. import sys
  33. import os
  34.  
  35. def download(url, folder):
  36.     if len(url) == 2:
  37.         # URL has custom filename:
  38.         custom_file = url[1]
  39.     else:
  40.         custom_file = None
  41.        
  42.     yt = YouTube(url[0])
  43.    
  44.     dir = folder.split('.')
  45.     dir = dir[0]
  46.    
  47.     if custom_file == None:
  48.         print (
  49.             "[*] Generated filename: %s" %
  50.             unicode(yt.filename).encode(sys.stdout.encoding, errors="replace")
  51.             )
  52.            
  53.         file_name = unicode(yt.filename).encode(sys.stdout.encoding, errors="replace")
  54.        
  55.     elif custom_file != None:
  56.         file_name = unicode(custom_file).encode(sys.stdout.encoding, errors="replace")
  57.        
  58.        
  59.     # Reserved characters that we cant use for filenames
  60.     reserved_chars = ['<','>',':','"', '/', '\\', '|', '?', '*']
  61.    
  62.     for ch in reserved_chars:
  63.         if ch in file_name:
  64.             file_name = file_name.replace(ch, "")
  65.            
  66.     print "[*] Cleaned filename: " + file_name
  67.     yt.set_filename(file_name)  # Should stop the unicode errors
  68.    
  69.     print "[*] Trying filters"
  70.    
  71.     # ===== / Filters / ===
  72.    
  73.     uhd = yt.filter(resolution='1080p')
  74.     if len(uhd) > 0:
  75.         print uhd
  76.        
  77.     hd = yt.filter(resolution='720p')
  78.     if len(hd) > 0:
  79.         print hd
  80.        
  81.     ld = yt.filter(resolution='480p')
  82.     if len(ld) > 0:
  83.         print ld
  84.        
  85.     lld = yt.filter(resolution='360p')
  86.     if len(lld) > 0:
  87.         print lld
  88.        
  89.     # ===== / Filters / ===
  90.    
  91.     print "[*] Getting video"
  92.        
  93.     if len(uhd) > 0:
  94.         print "[*] Got 1080p resolution video"
  95.         vid = yt.get('mp4', '1080p')
  96.     elif len(hd) > 0:
  97.         print "[*] Got 720p resolution video"
  98.         vid = yt.get('mp4', '720p')
  99.     elif len(ld) > 0:
  100.         print "Got 480p resolution video"
  101.         vid = yt.get('mp4', '480p')
  102.     elif len(lld) > 0:
  103.         print "Got 360p resolution video"
  104.         vid = yt.get('mp4', '360p')
  105.        
  106.     dir = os.getcwd() + "\\" + dir + "\\"
  107.     print "[*] Downloading video to " + dir
  108.    
  109.     try:
  110.         vid.download(dir, on_progress=print_status)
  111.        
  112.         del vid
  113.     except OSError:
  114.         print "[Warning] File [%s] already exists" % (dir + file_name)
  115.        
  116.     return file_name    # Need this part for converting them all to mp3's
  117.  
  118.  
  119. def convert_to_mp3(dir, filename):
  120.     dir = dir.split('.')[0]
  121.     dir = os.getcwd() + "\\" + dir + "\\"
  122.    
  123.     try:
  124.         os.makedirs(dir + 'mp3')
  125.     except OSError:
  126.         if not os.path.isdir(dir):
  127.             raise
  128.            
  129.     if not os.path.exists(dir + "mp3\\" + filename.split('.')[0] + ".mp3"):
  130.         print "[*] Directory: " + dir
  131.         print "[*] Converting [%s] " % filename
  132.        
  133.         clip = mp.VideoFileClip(dir + filename + ".mp4")
  134.         out = dir + "mp3\\" + filename.split('.')[0] + ".mp3"
  135.         clip.audio.write_audiofile(out)
  136.        
  137.         print "\n[*] Finished new filename = " + out
  138.         print "=" * 25
  139.        
  140.         # Cleanup
  141.         del clip.reader
  142.         del clip
  143.        
  144.     else:
  145.         file = dir + "mp3\\" + filename.split('.')[0] + ".mp3"
  146.         print "[Warning] File [%s] already exists" % file
  147.    
  148.    
  149. def get_links(file_loc):
  150.     urls = {}   # {0: [url, custom_filename], 1: ...}
  151.     custom_file = ""
  152.     counter = 0
  153.    
  154.     try:
  155.         f = open(file_loc, 'r')
  156.     except Exception as ex:
  157.         print ex
  158.         quit(0)
  159.    
  160.     for line in f:
  161.         a = line.split(" : ")
  162.         if len(a) == 2:
  163.             urls[counter] = [str(a[0]), str(a[1][:-1])]
  164.         else:
  165.             urls[counter] = [str(a[0])]
  166.         counter += 1
  167.        
  168.     return urls, counter
  169.    
  170.    
  171. def show_list(dict):
  172.     for x in range(len(dict)):
  173.         print "URL : " + str(dict[x][0])
  174.        
  175.         if len(dict[x]) == 2:
  176.             print "Custom filename : %s\n" % dict[x][1]
  177.         else:
  178.             print ""
  179.    
  180.    
  181. def main():
  182.     print "Youtube downloader"
  183.     print "Please enter the filename containing all the links"
  184.     print "For the video's you would like to download\n"
  185.    
  186.     file_name = raw_input("Filename: ")
  187.    
  188.     # Converter vars;
  189.     filename = []
  190.  
  191.     urls, vid_counter = get_links(file_name)
  192.    
  193.     print ""
  194.    
  195.     print "[*] %i URL'S RECEIVED" % vid_counter
  196.     print "[*] URL LIST:"
  197.    
  198.     show_list(urls)
  199.     dir = str(file_name).split('.')[0]
  200.    
  201.     try:
  202.         print "[*] Trying to make directory: " + dir
  203.         os.makedirs(dir)
  204.     except OSError:
  205.         if not os.path.isdir(dir):
  206.             raise
  207.    
  208.     for x in range(vid_counter):
  209.         if 'https://www.youtube.com/' in str(urls[x][0]):
  210.             print "\nDownloading URL : " + str(urls[x][0]) 
  211.            
  212.             if len(urls[x]) == 2:
  213.                 print "Custom title : " + str(urls[x][1])
  214.                
  215.             print "Progress: %i/%i" % (x, vid_counter)
  216.                
  217.             filename += [download(urls[x], file_name)]  # URL, (file_name = folder)
  218.            
  219.         else:
  220.             print "URL [%s] does not contain 'https://www.youtube.com/'" % str(urls[x][0])
  221.  
  222.        
  223.     for f in filename:
  224.         convert_to_mp3(file_name, f)        # Confusing name here file_name = folder/directory
  225.    
  226.     return 0
  227.    
  228.    
  229. if __name__ == "__main__":
  230.     main()
Add Comment
Please, Sign In to add comment