-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
245 lines (174 loc) · 8.74 KB
/
main.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
from moviepy.editor import *
from moviepy.video.tools.drawing import circle
from giphy import fetch_gifs
import requests
import os
import random
import sys
import logging
import argparse
def create_movie(search_expression, results):
# Search Giphy
# (optional) convert to argv
rating = 'Y' # Y, G, PG, PG-13, and R # Y is strictly illustrated content only, ie cartoons.
results = int(results)
logging.info("Fetching matching gifs from giphy")
data = fetch_gifs(search_expression, results, rating) # Y, G, PG, PG-13, and R
W, H = 720, 404 # dimensions of the final video
logging.info(f"Setting output video width and height to {W} and {H}")
# resize the clips to the dimensions of the final video
VideoFileClip.reW = lambda clip: clip.resize(width=W)
VideoFileClip.reH = lambda clip: clip.resize(height=H)
# title screen
title_clip_tmp = (TextClip(search_expression.title(), font="assets/fonts/Mini_Square.ttf", fontsize=50, color='white'))
title_clip_tmp = (title_clip_tmp.set_pos('center'))
# random colors for the color clip on title
R,G,B = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
r_color_clip = (ColorClip(size =(W, H), color=[R,G,B]))
title_clip_w_color = CompositeVideoClip([r_color_clip, title_clip_tmp]).set_duration(3).fadeout(1)
clips = list() # list to hold video clips from gifs
del_clips = list()
for item in data:
try:
url = item['gif_url']
title = item['title']
vid_title = title.replace(" ", "_") # remove white spaces
del_clips.append(vid_title+'.mp4') # add extension
# print(f"processing item = {item}")
with open('temp.gif', 'wb') as f:
f.write(requests.get(url).content)
os.chdir(os.getcwd())
# Use ffmpeg to convert to get best results
# brew install ffmpeg (https://formulae.brew.sh/formula/ffmpeg)
os.system(f"echo 'y'| ffmpeg -i temp.gif -movflags faststart -pix_fmt yuv420p -vf 'scale=trunc(iw/2)*2:trunc(ih/2)*2' {vid_title}.mp4 > /dev/null 2>&1")
v_clip = VideoFileClip(f"{vid_title}.mp4") # .set_duration(10)
v_clip_duration = v_clip.duration
print(f"{title} duration = {v_clip_duration}")
# final_clip = final_clip.fx(vfx.blackwhite) # black and white
final_clip = v_clip.fx(vfx.colorx, 1.25) # brighten by 1.5 times colorx
# Append
clips.append(final_clip)
# Clean Up
f.close()
# os.system(f"echo 'removing {vid_title}.mp4'")
# os.system(f'rm {vid_title}.mp4') # removing throws an error
except:
print(f"{title} --> errored")
pass
clips_combined = concatenate_videoclips(clips, method='compose')
d = clips_combined.duration
t = time_quotient = d // 4
t_2 = t*2
t_3 = t*3
# print(f"d = {d} t = {t} t_2 = {t_2} t_3 = {t_3}")
title_vid_top_right_tmp = clips_combined.subclip(0, t) # 0, t is blank
title_vid_top_left_tmp = clips_combined.subclip(t, t_2)
title_vid_bottom_right_tmp = clips_combined.subclip(t_2,t_3)
title_vid_bottom_left_tmp = clips_combined.subclip(t_3, d)
title_vid_top_right = (title_vid_top_right_tmp.
resize((W/3,H/3)). # one third of the total screen
margin(2,color=(255,255,255)). # white margin
margin(top=10, right=10, opacity=0). # transparent
set_pos(('right','top')).set_duration(3))
title_vid_top_left = (title_vid_top_left_tmp.
resize((W/3,H/3)). # one third of the total screen
margin(2,color=(255,255,255)). # white margin
margin(top=10, left=10, opacity=0). # transparent
set_pos(('left','top')).set_duration(3))
title_vid_bottom_right = (title_vid_bottom_right_tmp.
resize((W/3,H/3)). # one third of the total screen
margin(2,color=(255,255,255)). # white margin
margin(bottom=10, right=10, opacity=0). # transparent
set_pos(('right','bottom')).set_duration(3))
title_vid_bottom_left = (title_vid_bottom_left_tmp.
resize((W/3,H/3)). # one third of the total screen
margin(2,color=(255,255,255)). # white margin
margin(bottom=10, left=10, opacity=0). # transparent
set_pos(('left','bottom')).set_duration(3))
# Create title clip with 4 subclips
title_clip = CompositeVideoClip([title_clip_w_color,
title_vid_bottom_right,
title_vid_top_right,
title_vid_bottom_left,
title_vid_top_left]).set_duration(3).fadeout(0.5)
filename_prefixes = [
"Apps & Hacks | "
# "Hilarious compilation | ",
# "Ultimate cute and funny | ",
# "Awesome funny compilation | ",
# "Funniest moments from ",
# "New episodes of ",
# "The funniest mix of "
]
r_pref_id = random.randint(0, len(filename_prefixes)-1)
selected_prefix = filename_prefixes[r_pref_id]
filename_suffixes = [
" | Autogenerated Video"
]
r_sufx_id = random.randint(0, len(filename_suffixes)-1)
selected_suffix = filename_suffixes[r_sufx_id]
final_filename = selected_prefix + search_expression.title() + selected_suffix + '.mp4'
## Credits
credits_text = f"""
CREDITS
Title: {search_expression.title()}
Music by Titan0346
https://soundcloud.com/shaurya-m
"""
# credits
the_end = (TextClip(credits_text,
fontsize=30, interline=15, bg_color='black', font="assets/fonts/Mini_Square.ttf",
size=(W, H), color='white').set_pos(('center', 'center')).set_duration(4).fadein(0.5))
# Main sequence
main_vid = concatenate([title_clip, clips_combined, the_end], method='compose')
main_vid.add_mask()
# The mask is a circle with vanishing radius r(t) = 800-200*t
main_vid.mask.get_frame = lambda t: circle(screensize=(W,H),
center=(W/2, H/4),
radius=max(0,int(800-200*t)),
col1=1, col2=0, blur=4)
# pick a random audio clip from a list of clips
audio_clips = ['assets/music/titan0346_8bit_invaders.wav', 'assets/music/titan0346_cyberpunk.wav']
# Don't forget to give credit to the author
r_audio_id = random.randint(0, len(audio_clips)-1)
r_audio_clip = audio_clips[r_audio_id]
print(f"audio clip in use = {r_audio_clip}")
music_loop = afx.audio_loop(AudioFileClip(r_audio_clip).fx(afx.volumex, 0.2), duration=int(main_vid.duration))
# music_loop.preview() # works
video_with_audio = main_vid.set_audio(music_loop)
# video_with_audio.preview()
logging.info(f"Writing video output file - {final_filename}")
try:
video_with_audio.write_videofile(f"out/{final_filename}", fps=25, bitrate="10000k", audio_bitrate='1000k',
audio=True,
codec='libx264', # libx264, mpeg4
audio_codec='aac',
temp_audiofile='temp-audio.m4a',
remove_temp=True,
# logger=None,
threads=4) # for performance boost
except:
# delete tmp clips in case of error making vid
for item in del_clips:
# os.system(f"echo 'removing {item}'")
os.system(f"rm {item}")
os.system(f"rm temp.gif > /dev/null")
os.system(f"rm temp-audio.m4a > /dev/null")
# Cleanup
for item in del_clips:
# os.system(f"echo 'removing {item}'")
os.system(f"rm {item}")
os.system(f"rm temp.gif > /dev/null")
os.system(f"rm temp-audio.m4a > /dev/null")
if __name__ == '__main__':
logging.basicConfig(level='INFO')
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--search", type=str, help="search term(s) for the video, e.g. 'peppa pig' or 'godzilla' ")
parser.add_argument("-r", "--results", type=int, help="Number of gifs to stitch in output vide, Max 25")
args = parser.parse_args()
# expressions_list = ["machine learning"]
# for se in expressions_list:
# create_movie(se)
search_term = args.search
results = args.results
create_movie(search_term, results)