Skip to content

Instantly share code, notes, and snippets.

@n1chre
Last active August 21, 2018 03:35
Show Gist options
  • Save n1chre/81881165512fdaf38f3bf34bf275ea7d to your computer and use it in GitHub Desktop.
Save n1chre/81881165512fdaf38f3bf34bf275ea7d to your computer and use it in GitHub Desktop.
Download the first song from youtube by searching for "artist - song"
#!/usr/bin/env python3
import fileinput
import os
import random
import re
import string
import subprocess
def rand_str(k=12):
cs = string.ascii_uppercase + string.digits
return ''.join(random.choice(cs) for _ in range(k))
def run(args, quiet):
fds = {}
if quiet:
fds = {'stdout':subprocess.DEVNULL, 'stderr':subprocess.DEVNULL}
return subprocess.run(args, **fds)
def run_youtube_dl(output_format, arg, quiet):
args = ['youtube-dl', '-o', output_format, arg]
if run(args, quiet).returncode != 0:
raise Exception("youtube-dl error")
def run_ffmpeg(filename, output, quiet, **kw):
args = ['ffmpeg', '-loglevel', 'error', '-y', '-i', filename, '-acodec', 'copy']
for k in kw:
v = kw[k]
if v is not None:
args.append('-metadata')
args.append('{key}={value}'.format(key=k, value=v))
args.append(output)
if run(args, quiet).returncode != 0:
raise Exception("ffmpeg error")
def download(artist, title, dl_link=None, quiet=True, delete=True, **kwargs):
prefix_len = 12
prefix = rand_str(prefix_len)
output_format = prefix + '%(title)s+++++%(id)s.%(ext)s'
arg = dl_link or 'ytsearch1:{artist} - {title}'.format(artist=artist, title=title)
run_youtube_dl(output_format, arg, quiet)
tmp_file = [p for p in os.listdir('.') if p.startswith(prefix)][0]
tmp = tmp_file[prefix_len:tmp_file.rfind('.')] # remove prefix and extension
yt_title, video_id = tmp.split('+++++')
ys = re.findall(r'\b\d{4}\b', yt_title)
year = ys[0] if len(ys)==1 else None
out_file = title + '.mp3'
run_ffmpeg(
tmp_file, out_file, quiet,
title=title, artist=artist,
year=year, date=year,
comments='yt:{id}'.format(id=video_id),
**kwargs
)
if delete:
os.unlink(tmp_file)
if __name__ == '__main__':
for line in fileinput.input():
line = line.strip()
if not line:
continue
args = line.split()
if args[-1].startswith('http'):
dl_link = args.pop()
else:
dl_link = None
sep = args.index('-')
artist = ' '.join(args[:sep])
title = ' '.join(args[sep+1:])
print('Downloading: %s - %s' % (artist, title))
#download(artist, title, dl_link=dl_link, genre='Cajke')
--ignore-errors
--mark-watched
--output '%(title)s.%(ext)s'
--restrict-filenames # ascii only
--no-mtime
--user-agent 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
--extract-audio
--audio-format mp3
--format bestaudio
--embed-thumbnail
--prefer-ffmpeg
--hls-prefer-ffmpeg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment