Guest User

Untitled

a guest
Jul 23rd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. from __future__ import unicode_literals
  2. import youtube_dl
  3. from os import path, listdir, rename, mkdir
  4. import sys
  5. # sudo apt-get install ffmpeg ## Also required
  6.  
  7. # RUN:
  8. # Python3 mp3_downloader.py (assumes songs.txt in the same dir with links)
  9. # Python3 mp3_downloader.py <file_with_links_relative_to_script>
  10.  
  11.  
  12. def get_all_links(this_dir, file_name):
  13. with open(path.join(this_dir, './%s' % file_name)) as f:
  14. return [w.rstrip() for w in f.readlines() if w.strip()]
  15.  
  16.  
  17. def all_links_valid(links):
  18. ydl_opts = {
  19. 'quiet': True,
  20. 'skip_download': True,
  21. 'format': 'bestaudio/best',
  22. 'postprocessors': [{
  23. 'key': 'FFmpegExtractAudio',
  24. 'preferredcodec': 'mp3',
  25. 'preferredquality': '320',
  26. }],
  27. }
  28. with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  29. try:
  30. ydl.download(links)
  31. except:
  32. return False
  33. return True
  34.  
  35.  
  36. def download_all(links):
  37. ydl_opts = {
  38. 'format': 'bestaudio/best',
  39. 'postprocessors': [{
  40. 'key': 'FFmpegExtractAudio',
  41. 'preferredcodec': 'mp3',
  42. 'preferredquality': '320',
  43. }],
  44. }
  45. with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  46. ydl.download(links)
  47.  
  48.  
  49. def get_all_file_names(this_dir, script_files):
  50. return {x for x in listdir(this_dir) if path.isfile(path.join(this_dir, x))} - script_files
  51.  
  52.  
  53. def new_name(old_name):
  54. return '-'.join(old_name.split('-')[:-1]) + '.mp3'
  55.  
  56.  
  57. def move_all_files(this_dir, script_files):
  58. for name in get_all_file_names(this_dir, script_files):
  59. rename(path.join(this_dir, name), path.join(path.join(this_dir, './output/'), new_name(name)))
  60.  
  61.  
  62. def check_folder(this_dir):
  63. folder = path.join(this_dir, './output/')
  64. if not path.exists(folder):
  65. mkdir(folder)
  66.  
  67.  
  68. def main(args):
  69. file_name = args[0] if args else 'songs.txt'
  70. script_files = {file_name, 'downloader.py'}
  71. this_dir = path.abspath(path.dirname(__file__))
  72. links = get_all_links(this_dir, file_name)
  73. if not all_links_valid(links):
  74. print('At least one link is invalid')
  75. return
  76. download_all(links)
  77. check_folder(this_dir)
  78. move_all_files(this_dir, script_files)
  79.  
  80.  
  81. if __name__ == '__main__':
  82. main(sys.argv[1:])
Add Comment
Please, Sign In to add comment