forked from ekimekim/rdp-cutter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cutting.py
154 lines (122 loc) · 4.16 KB
/
cutting.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
import logging
import os
import string
from glob import glob
from uuid import uuid4
from easycmd import cmd
from common import update_column
TMPDIR = './tmp'
def process(sheet, row, no_update_state=False):
"""For given row, perform the cutting process"""
def update_state(state):
if not no_update_state:
update_column(sheet, row['id'], 'Processed by VST', state)
filebase = '{}/{}'.format(TMPDIR, uuid4())
logging.info("Processing row {id}({Song!r}) at path {filebase}".format(filebase=filebase, **row))
logging.debug("Row values: {}".format(row))
try:
logging.debug("Downloading {}".format(filebase))
source_file = youtube_dl(row['YouTube Link'], '{}-source'.format(filebase))
dest_file = '{}-cut.m4a'.format(filebase)
logging.debug("Converting {} -> {}".format(source_file, dest_file))
convert(
source=source_file,
dest=dest_file,
start=parse_time(row['Start Time']),
end=parse_time(row['End Time']),
title=row['Song'],
artist=row['Artist'],
category=row['Category'],
fade_in=parse_time(row['Fade In?']),
fade_out=parse_time(row['Fade Out?']),
)
name = str(row['Song']) or 'no-title'.format(row['id'])
name = name.replace(' ', '_')
name = ''.join(c for c in name.lower() if c in string.letters + string.digits + '._-')
name = '{}-{}'.format(row['id'], name)
logging.debug("Uploading {} as {}".format(dest_file, name))
url = upload(dest_file, name)
update_column(sheet, row['id'], 'Processed Link', url)
except Exception:
logging.exception("Error while cutting {}".format(row))
update_state('Errored')
raise
else:
update_state('Complete')
logging.info("Processed row {id}({Song!r}) successfully".format(**row))
def youtube_dl(link, filebase):
cmd(['youtube-dl', link, '-o', '{}.%(ext)s'.format(filebase)])
filename, = glob('{}.*'.format(filebase))
return filename
def convert(source, dest, start, end, title, artist, category, fade_in, fade_out):
def format_filter(name, **kwargs):
return '{}={}'.format(name, ':'.join('{}={}'.format(k, v) for k, v in kwargs.items()))
# end is actually "end not including fade out"
if end and fade_out:
end += fade_out
cut_args = []
if start:
cut_args += ['-ss', start]
if end:
cut_args += ['-t', end - start]
map_args = ['-map', '0:a']
filters = []
if fade_in:
filters.append(format_filter('afade', type='in', start_time=0, duration=fade_in))
if fade_out:
# we need to know duration, hopefully we can work it out from inputs
# if we can't, we fall back to an ffprobe call
if not end:
end = get_audio_length(source)
if not start:
start = 0
duration = end - start
filters.append(format_filter('afade', type='out', start_time=duration-fade_out, duration=fade_out))
filter_args = ['-filter', ','.join(filters)] if filters else []
metadata = dict(title=title, artist=artist, genre=category)
metadata_args = sum((
['-metadata', '{}={}'.format(k, v)]
for k, v in metadata.items() if v
), [])
output_args = ['-strict', '-2'] + map_args + filter_args + metadata_args + [dest]
input_args = cut_args + ['-i', source]
cmd(['ffmpeg', '-y'] + input_args + output_args)
def get_audio_length(filename):
args = [
'ffprobe',
'-select_streams', 'a:0',
'-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
filename,
]
output = cmd(args)
return int(output)
def upload(source, name):
_, ext = os.path.splitext(source)
name = '{}.{}'.format(name, ext.lstrip('.'))
cmd(['scp', source, 'tyranicmoron:public_html/rdp/{}'.format(name)])
return 'http://tyranicmoron.uk/~ekimekim/rdp/{}'.format(name)
def parse_time(s):
if not isinstance(s, basestring):
return s
if not s:
return
if s.strip().lower() in ('no', 'none', '-', ''):
return
if ':' in s:
mins, secs = s.split(':')
elif 'm' in s:
mins, secs = s.rstrip('s').split('m')
else:
mins, secs = 0, s.rstrip('s')
if not mins:
mins = 0
if not secs:
secs = 0
return int(mins) * 60 + float(secs)
if __name__ == '__main__':
# for testing
import sys
logging.basicConfig(level=logging.DEBUG)
source, dest, start, end, title, artist, category, fade_in, fade_out = sys.argv[1:]
convert(source, dest, int(start), int(end), title, artist, category, int(fade_in), int(fade_out))