-
Notifications
You must be signed in to change notification settings - Fork 18
/
deep-fryer.py
254 lines (193 loc) · 7.96 KB
/
deep-fryer.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import os
import random
import ffmpy
import argparse
from collections import OrderedDict
from shutil import copyfile, rmtree
from utils import line_break, make_random_value, get_total_seconds, get_dimensions
TMP_FOLDER = './tmp'
if not os.path.exists(TMP_FOLDER):
os.makedirs(TMP_FOLDER)
def create_base_args():
return [
'-y', # overwrite existing
'-vb', '2M', # shitty bit rate to create compression effect
] + create_audio_args()
def increase_audio(input_audio, amt):
output_args = ['-y', '-af', 'volume=3, bass=g=5, treble=g=-10']
audio_file = None
for idx in xrange(0, amt):
input_file = audio_file or input_audio
output = '{}/tmp_audio_{}.wav'.format(TMP_FOLDER, idx)
ff = ffmpy.FFmpeg(inputs={input_file: None}, outputs={output: output_args})
try:
ff.run()
audio_file = output
except Exception as e:
line_break(3)
print('Failed to increase audio.\n{}'.format(e))
return audio_file
def extract_audio(input_file):
output_args = ['-y', '-vn', '-acodec', 'copy']
output = '{}/input_audio.aac'.format(TMP_FOLDER)
ff = ffmpy.FFmpeg(inputs={input_file: None}, outputs={output: output_args})
try:
ff.run()
except Exception as e:
line_break(3)
print('Failed to increase audio.\n{}'.format(e))
return output
def create_audio_args():
return ['-af', 'bass=g=8, treble=g=-2, volume=10dB']
def create_filter_args():
"""
Create randomized "deep fried" visual filters
returns command line args for ffmpeg's filter flag -vf
"""
saturation = make_random_value([2, 3])
contrast = make_random_value([1.5, 2])
noise = make_random_value([30, 60])
gamma_r = make_random_value([1, 3])
gamma_g = make_random_value([1, 3])
gamma_b = make_random_value([1, 3])
eq_str = 'eq=saturation={}:contrast={}'.format(saturation, contrast)
eq_str += ':gamma_r={}:gamma_g={}:gamma_b={}'.format(gamma_r, gamma_g, gamma_b)
noise_str = 'noise=alls={}:allf=t'.format(noise)
sharpness_str = 'unsharp=5:5:1.25:5:5:1'
return ['-vf', ','.join([eq_str, noise_str, sharpness_str])]
def get_random_emoji():
"""
Return a random emoji file from './emoji'. To avoid errors when using the
same file more than once, each file is given a random name and copied into './tmp'
"""
emoji_choices = filter(lambda x: not x.startswith('.'), os.listdir('./emoji'))
rand_choice = random.choice(emoji_choices)
new_name = str(random.randint(0, 99999999)) + '.png'
new_dest = '{}/{}'.format(TMP_FOLDER, new_name)
copyfile('./emoji/{}'.format(rand_choice), new_dest)
return new_dest
def get_random_emojis(amt):
"""
Create emoji inputs, returning an OrderedDict where each key is the emoji
comp name and the value includes size and filter str. eg:
[emoji_4]: {
filter_str: [4:v]scale=30:30,rotate=12*PI/180:c=none[emoji_4],
size: 30,
}
"""
emojis = OrderedDict({})
for idx in xrange(1, amt + 1):
size = random.randint(50, 200)
rotation = random.randint(-180, 180)
input_comp = '{}:v'.format(idx)
output_comp = 'emoji_{}'.format(idx)
transform = 'scale={}:{},rotate={}*PI/180:c=none'.format(size, size, rotation)
filter_str = '[{}]{}[{}]'.format(input_comp, transform, output_comp)
emojis[output_comp] = {'size': size, 'filter_str': filter_str}
return emojis
def create_emoji_filters(input_file):
comp_name = '0:v'
seconds = get_total_seconds(input_file)
width, height = get_dimensions(input_file)
emoji_filters = []
emoji_amt = make_random_value([0.75, 0.95])
random_emojis = get_random_emojis(int(seconds * emoji_amt))
emoji_keys = random_emojis.keys()
for idx, emoji in enumerate(emoji_keys):
size = random_emojis[emoji]['size']
filter_str = random_emojis[emoji]['filter_str']
max_x = width - size
max_y = height - size
pos_x = make_random_value([0, max_x])
pos_y = make_random_value([0, max_y])
dur = make_random_value([2, 5])
max_start = seconds - dur
start = make_random_value([0, max_start])
end = start + dur
new_comp = 'comp_{}'.format(idx)
overlay = "overlay={}:{}:enable='between(t, {}, {})'".format(pos_x, pos_y, start, end)
emoji_filter = ';'.join([filter_str, '[{}][{}]{}'.format(comp_name, emoji, overlay)])
if idx < (len(emoji_keys) - 1):
emoji_filter += '[{}];'.format(new_comp)
comp_name = new_comp
emoji_filters.append(emoji_filter)
return emoji_filters
def create_inputs(input_file, emoji_filters=[]):
"""
Special input creator with optional emoji_filters argument
that adds emoji input for every emoji filter passed
"""
inputs = [(input_file, None)]
# add an actual emoji file input for every filter created
for _ in emoji_filters:
inputs.append((get_random_emoji(), None))
return OrderedDict(inputs)
def create_outputs(output_file, output_args):
return OrderedDict([(output_file, output_args)])
def add_random_emojis(input_file):
"""
Overlays emojis at random angles, size, durations, and start frames over a
given input file. The amount of emojis is based on input file length.
"""
emoji_filters = create_emoji_filters(input_file)
inputs = create_inputs(input_file, emoji_filters)
output_args = ['-an'] + create_base_args()
output_args += ['-filter_complex', ''.join(emoji_filters)]
tmp_output = '{}/emojied_video.mp4'.format(TMP_FOLDER)
outputs = create_outputs(tmp_output, output_args)
ff = ffmpy.FFmpeg(inputs=inputs, outputs=outputs)
try:
ff.run()
return tmp_output
except Exception as e:
line_break(3)
print('Failed to add emojis.\n{}'.format(e))
def create_final_video(fried_video, boosted_audio, output_file):
inputs = OrderedDict([
(fried_video, None),
(boosted_audio, None),
])
outputs = OrderedDict([
(output_file, ['-y', '-vcodec', 'libx264']),
])
ff = ffmpy.FFmpeg(inputs=inputs, outputs=outputs)
try:
ff.run()
line_break(3)
print('Succesfully deep fried video at {}!'.format(output_file))
line_break(3)
return output_file
except Exception as e:
line_break(3)
print('Failed to create final video.\n{}'.format(e))
def deep_fry_video(input_file, video_dip):
emojified_video = add_random_emojis(input_file)
inputs = create_inputs(emojified_video)
output_args = create_base_args() + create_filter_args()
for idx in xrange(0, video_dip):
output = '{}/deep_fried_{}.mp4'.format(TMP_FOLDER, idx)
outputs = create_outputs(output, output_args)
ff = ffmpy.FFmpeg(inputs=inputs, outputs=outputs)
try:
ff.run()
inputs = create_inputs(output)
except Exception as e:
line_break(3)
print('Failed to deep fry video.\n{}'.format(e))
return output
def main(input_file, output_file, video_dip, audio_dip):
extracted_audio = extract_audio(input_file)
boosted_audio = increase_audio(extracted_audio, audio_dip)
fried_video = deep_fry_video(input_file, video_dip)
create_final_video(fried_video, boosted_audio, output_file)
rmtree(TMP_FOLDER)
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--input_file', help='input file')
ap.add_argument('-o', '--output_file', help='output file')
ap.add_argument('-vd', '--video_dip', help='amount of times to run video through filter', default=3, type=int)
ap.add_argument('-ad', '--audio_dip', help='amount of times to run audio through filter', default=10, type=int)
args = ap.parse_args()
assert args.input_file is not None, 'No input file provided...'
assert args.output_file is not None, 'No output file provided...'
main(args.input_file, args.output_file, args.video_dip, args.audio_dip)