forked from crisbal/album-splitter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplit.py
executable file
·211 lines (190 loc) · 6.92 KB
/
split.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env python3
import argparse
import os
import re
from queue import Queue
from threading import Thread
from urllib.parse import urlparse, parse_qs
from uuid import uuid4
from pydub import AudioSegment
from youtube_dl import YoutubeDL
from split_init import METADATA_PROVIDERS, ydl_opts
from utils import (split_song, time_to_seconds, track_parser, update_time_change)
def thread_func(album, tracks_start, queue, FOLDER, ARTIST, ALBUM):
while not queue.empty():
song_tuple = queue.get()
split_song(album, tracks_start, song_tuple[0], song_tuple[1], FOLDER, ARTIST, ALBUM, BITRATE)
if __name__ == "__main__":
# arg parsing
parser = argparse.ArgumentParser(description='Split a single-file mp3 Album into its tracks.')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-mp3", help="The .mp3 file you want to split.", metavar="mp3_file")
group.add_argument(
"-yt", help="The YouTube video url you want to download and split.", metavar="youtube_url"
)
parser.add_argument(
"-a", "--artist",
help="Specify the artist that the mp3s will be ID3-tagged with. Default: no tag",
default=None
)
parser.add_argument(
"-A", "--album",
help="Specify the album that the mp3s will be ID3-tagged with. Default: no tag",
default=None
)
parser.add_argument(
"-t", "--tracks", help="Specify the tracks file. Default: tracks.txt", default="tracks.txt"
)
parser.add_argument(
"-f", "--folder",
help="Specify the folder the mp3s will be put in. Default: splits/",
default=None
)
parser.add_argument(
"-d", "--duration",
dest='duration',
action='store_true',
help="Specify track time format will use the duration of each individual song. "
"Default: False",
default=False
)
parser.add_argument(
"-th", "--threaded",
dest='threaded',
action='store_true',
help="Specify the script should use threads. Default: False",
default=False
)
parser.add_argument(
"--num-threads",
dest='num_threads',
help="Specify the (whole/non-negative) number of threads the script should spawn when "
"using threads. Default: 3",
default='3'
)
parser.add_argument(
"--metadata",
dest='metadata',
help="Specify the source for the Album Metadata.",
default="file"
)
parser.add_argument(
"--dry-run",
dest='dry',
action='store_true',
help="Don't split the file, just output the tracks, useful for seeing if the tracks.txt "
"format is ok or needs tweaking.",
default=False
)
parser.add_argument(
"-bitrate",
help="Specify the bitrate of the export. Default: '320k'",
default="320k"
)
args = parser.parse_args()
TRACKS_FILE_NAME = args.tracks
FILENAME = args.mp3
YT_URL = args.yt
ALBUM = args.album
ARTIST = args.artist
DURATION = args.duration
THREADED = args.threaded
NUM_THREADS = int(args.num_threads)
METASRC = args.metadata
DRYRUN = args.dry
BITRATE = args.bitrate
if DRYRUN:
print("**** DRY RUN ****")
if args.folder is None:
if ALBUM and ARTIST:
FOLDER = "{} - {}".format(ARTIST, ALBUM)
else:
if YT_URL:
url_data = urlparse(YT_URL)
query = parse_qs(url_data.query)
video_id = query["v"][0]
FOLDER = "./splits/{}".format(video_id)
else:
FOLDER = "./splits/{}".format(str(uuid4())[:16])
else:
FOLDER = args.folder
# create destination folder
if not os.path.exists(FOLDER) and not DRYRUN:
os.makedirs(FOLDER)
if METASRC != "file":
found_a_source = False
for provider in METADATA_PROVIDERS:
pattern = re.compile(provider.VALID_URL)
if pattern.match(METASRC):
print("Matched with a metadata provider...")
if not provider.lookup(METASRC, TRACKS_FILE_NAME):
print("Can't find a track list in the provided source. Shutting Down.")
exit()
else:
found_a_source = True
break
if not found_a_source:
print("There was no provider able to get data from your source!")
exit()
tracks_start = []
tracks_titles = []
print("Parsing " + TRACKS_FILE_NAME)
with open(TRACKS_FILE_NAME) as tracks_file:
time_elapsed = '0:00:00'
for i, line in enumerate(tracks_file):
if len(line.strip()) > 0:
curr_start, curr_title = track_parser(line)
if DRYRUN:
print(curr_title + " *** " + curr_start)
if DURATION:
t_start = time_to_seconds(time_elapsed)
time_elapsed = update_time_change(time_elapsed, curr_start)
else:
t_start = time_to_seconds(curr_start)
tracks_start.append(t_start*1000)
tracks_titles.append(curr_title)
if DRYRUN:
exit()
print("Tracks file parsed")
album = None
if YT_URL:
url_data = urlparse(YT_URL)
query = parse_qs(url_data.query)
video_id = query["v"][0]
FILENAME = video_id + ".wav"
if not os.path.isfile(FILENAME):
print("Downloading video from YouTube")
with YoutubeDL(ydl_opts) as ydl:
ydl.download(['http://www.youtube.com/watch?v=' + video_id])
print("\nConversion complete")
else:
print("Found matching file")
print("Loading audio file")
album = AudioSegment.from_file(FILENAME, 'wav')
else:
print("Loading audio file")
album = AudioSegment.from_file(FILENAME, 'mp3')
print("Audio file loaded")
tracks_start.append(len(album)) # we need this for the last track/split
print("Starting to split")
if THREADED and NUM_THREADS > 1:
# Create our queue of indexes and track titles
queue = Queue()
for index, track in enumerate(tracks_titles):
queue.put((index, track))
# initialize/start threads
threads = []
for i in range(NUM_THREADS):
new_thread = Thread(target=thread_func, args=(album, tracks_start, queue, FOLDER, ARTIST, ALBUM))
new_thread.start()
threads.append(new_thread)
# wait for them to finish
for thread in threads:
thread.join()
# Non threaded execution
else:
tracks_titles.append("END")
for i, track in enumerate(tracks_titles):
if i != len(tracks_titles)-1:
split_song(album, tracks_start, i, track, FOLDER, ARTIST, ALBUM, BITRATE)
print("All Done")