-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube2mp3.py
129 lines (97 loc) · 3.37 KB
/
youtube2mp3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import json
import os
import re
import shutil
import requests
import eyed3
from youtube_dl import YoutubeDL as ydl
ENTRY_DIR = 'entriesjson'
DOWNLOADS_DIR = 'downloads'
NEEDS_ACTION = 'downloads/NEEDS_ACTION!!!'
YLD_OPTIONS = {
'format':
'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'cachedire': False,
'outtmpl': 'downloads/%(title)s.%(ext)s'
}
def extract_url(entry):
return entry['webpage_url']
def has_artist(entry):
return 'artist' in entry and entry['artist'] is not None
def title_already_contains_artist(entry):
return entry['artist'] in entry['title']
def compute_out_tmpl(info, options):
if has_artist(info) and not title_already_contains_artist(info):
options['outtmpl'] = 'downloads/%(artist)s - %(title)s.%(ext)s'
else:
options['outtmpl'] = 'downloads/%(title)s.%(ext)s'
return options
def download_songs():
url = input('Enter the YouTube url to download as mp3 (songs or playlist): ')
url_info = ydl().extract_info(url, download=False)
entries = []
if 'entries' in url_info:
entries = url_info['entries']
else:
entries = [url_info]
for entry in entries:
title = entry['title']
try:
os.stat(ENTRY_DIR)
except Exception as err:
os.mkdir(ENTRY_DIR)
title = re.sub('[<>:"/\|?*]', '', title)
with open("% s/% s.json" % (ENTRY_DIR, title), 'w') as outfile:
json.dump(entry, outfile)
try:
os.stat(DOWNLOADS_DIR)
except Exception as err:
os.mkdir(DOWNLOADS_DIR)
try:
ydl(YLD_OPTIONS).download([extract_url(entry)])
except Exception as e:
print(e)
continue
set_metadata(entry, title)
def set_metadata(entry, title):
audiofile = eyed3.load(f'./{DOWNLOADS_DIR}/{title}.mp3')
thumbnails_len = len(entry['thumbnails'])
if thumbnails_len > 0:
def get_width(index): return entry['thumbnails'][index]['width']
max_index = max(range(thumbnails_len), key=get_width)
response = requests.get(entry['thumbnails'][max_index]['url'])
if response.ok:
audiofile.tag.images.set(3, response.content, 'image/png')
if 'artist' in entry:
audiofile.tag.artist = entry['artist']
if 'title' in entry:
audiofile.tag.title = entry['title']
audiofile.tag.save()
if(not has_artist(entry) or title_already_contains_artist(entry)):
try:
os.stat(NEEDS_ACTION)
except Exception as err:
os.mkdir(NEEDS_ACTION)
shutil.move(f'{DOWNLOADS_DIR}/{title}.mp3',
f'{NEEDS_ACTION}')
def improve_file_names(directory):
for filename in os.listdir(directory):
try:
dst = re.sub('[\[|(].*?[\]|)]', '', filename)
splitted = dst.split('.')
ext = splitted.pop(len(splitted) - 1)
name = ''.join(splitted).strip()
name_ext = name + '.' + ext
os.rename(f'{directory}/{filename}', f'{directory}/{name_ext}')
except Exception as err:
print(err)
print('AN ERROR HAS OCCURED RENAMING: % s' % (filename))
continue
if __name__ == '__main__':
download_songs()
improve_file_names(DOWNLOADS_DIR)