-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmp42gif.py
401 lines (375 loc) · 14.9 KB
/
mp42gif.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import argparse
import ffmpeg
import io
import tkinter as tk
from tkinter import filedialog as fd
import os
import sys
import colorama
from colorama import Fore,Back,Style,init
import shutil
init()
parser = argparse.ArgumentParser(description='Specify how your video gets converted into a GIF')
parser.add_argument(
'--input',
action='store',
dest='VIDIN',
type=str,
help='--input <str>(file path to your mp4 file)',
default=None,
required=False
)
parser.add_argument(
'--slice',
action='store_true',
dest='should_slice',
help='--slice --startframe <int>(the frame from wich to start capturing the video slice) --stopframe <int>(the frame from wich to stop capturing the video slice) :: both arguments reflect the amount of frames relative to the start of the video',
default=None,
required=False
)
parser.add_argument(
'--startframe',
action='append',
dest='slice_time',
type=int,
help='--startframe <int>(the frame from wich to start capturing the video slice)',
default=None,
required='--slice' in sys.argv
)
parser.add_argument(
'--stopframe',
action='append',
dest='slice_time',
type=int,
help='--stopframe <int>(the frame from wich to stop capturing the video slice)',
default=None,
required='--slice' in sys.argv
)
parser.add_argument(
'--playbackrate',
action='store',
dest='pbrate',
type=float,
help='--playbackrate <float>(integer or decimal that is non-negative, non-zero, & not 1) :: numbers greater than 1 speed the video up and numbers between 0 and 1 slow the video down',
default=None,
required=False
)
parser.add_argument(
'--blend',
action='store_true',
dest='should_blend',
help='--blend <bool>(true or false) :: Determines whether the video gets "minterpolated"',
default=None,
required=False
)
results = parser.parse_args()
print(Style.BRIGHT)
for i in list(range(0,90)):
print(Fore.WHITE + '#', end='')
print(Fore.WHITE + '#')
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "888b d888 8888888b. d8888 Y88b .d8888b. 8888888 8888888888 ", end='')
print(Fore.WHITE + "#")
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "8888b d8888 888 Y88b d8P888 Y88b d88P Y88b 888 888 ", end='')
print(Fore.WHITE + "#")
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "88888b.d88888 888 888 d8P 888 Y88b 888 888 888 888 ", end='')
print(Fore.WHITE + "#")
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "888Y88888P888 888 d88P d8P 888 888888 Y88b 888 888 8888888 ", end='')
print(Fore.WHITE + "#")
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "888 Y888P 888 8888888P\" d88 888 d88P 888 88888 888 888 ", end='')
print(Fore.WHITE + "#")
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "888 Y8P 888 888 8888888888 888888 d88P 888 888 888 888 ", end='')
print(Fore.WHITE + "#")
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "888 \" 888 888 888 d88P Y88b d88P 888 888 ", end='')
print(Fore.WHITE + "#")
print(Fore.WHITE + "# ", end='')
print(Fore.YELLOW + "888 888 888 888 d88P \"Y8888P88 8888888 888 ", end='')
print(Fore.WHITE + "#")
for i in list(range(0,90)):
print(Fore.WHITE + '#', end='')
print(Fore.WHITE + '#')
def cls():
import os
import sys
if not sys.platform == "win32":
os.system('cls')
else:
os.system('clear')
def openafile():
master = tk.Tk()
master.title("Open your MP4 file")
def callback():
global TIOW
TIOW=fd.askopenfile()
master.destroy()
tk.Label(master,text="Click 'Next' and then select your MP4 file.").grid(row=0)
tk.Button(master,text='Next',command=callback).grid(row=1)
master.attributes("-topmost", True)
tk.mainloop()
def mp4Slice(VIDIN,startframe,endframe):
os.mkdir(WORKDIR + "/slice/")
VIDOUT = WORKDIR + "/slice/" + VIDIN.split("/")[(len(VIDIN.split("/")) - 1)] # Full path to output video
INPATH = []
count = 0
for i in VIDIN.split('/'):
if count > (len(VIDIN.split('/')) - 4):
INPATH.append(i)
count = count + 1
INDIR = '/'.join(INPATH)
VIDPATH = []
count = 0
for i in VIDOUT.split('/'):
if count > (len(VIDOUT.split('/')) - 4):
VIDPATH.append(i)
count = count + 1
VIDDIR = '/'.join(VIDPATH)
print(Fore.GREEN + "Slicing:\n ", end='')
print(Fore.YELLOW + "'./" + INDIR + "'")
print(Fore.WHITE + " start_frame:",end='')
print(Fore.YELLOW + " " + str(startframe))
print(Fore.WHITE + " end_frame:",end='')
print(Fore.YELLOW + " " + str(endframe))
print(Fore.GREEN + "Sliced output file will be saved to:\n ", end='')
print(Fore.YELLOW + "'./" + VIDDIR + "'")
try:
ffmpeg.run(ffmpeg.output(ffmpeg.input(VIDIN).trim(start_frame=startframe,end_frame=endframe),VIDOUT),capture_stdout=True, capture_stderr=True, input=None, quiet=True, overwrite_output=True)
except:
ERRCATCH = 1
GARBAGE.append(VIDOUT)
GARBAGE.append(WORKDIR + "/slice")
return VIDOUT
def dRate(VIDIN,RATE=0.5):
INPATH = []
count = 0
for i in VIDIN.split('/'):
if count > (len(VIDIN.split('/')) - 4):
INPATH.append(i)
count = count + 1
INDIR = '/'.join(INPATH)
FOLRA = []
count = 0
for i in VIDIN.split("."):
if count < (len(VIDIN.split(".")) - 1):
FOLRA.append(i)
count = count + 1
INVE = float(1) / float(RATE) # Value needed for 'setpts' is the inverse of 'pbrate'
PTS = str(INVE) + '*PTS' # Create string for 'setpts'
os.mkdir(WORKDIR + "/rate/") # New folder with same name as previous mkdir command, but with '_rate_' appended
VIDOUT = WORKDIR + "/rate/" + VIDIN.split("/")[(len(VIDIN.split("/")) - 1)] # Full path to output video
VIDPATH = []
count = 0
for i in VIDOUT.split('/'):
if count > (len(VIDOUT.split('/')) - 4):
VIDPATH.append(i)
count = count + 1
VIDDIR = '/'.join(VIDPATH)
print(Fore.GREEN + "Setting playback rate for:\n ", end='')
print(Fore.YELLOW + "'./" + INDIR + "'")
print(Fore.WHITE + " to: ", end='')
print(Fore.YELLOW + str(RATE))
print(Fore.GREEN + "Resultant video will be saved to:\n ", end='')
print(Fore.YELLOW + "'./" + VIDDIR + "'")
try:
LOG2 = ffmpeg.run(ffmpeg.output(ffmpeg.input(VIDIN).setpts(PTS),VIDOUT),capture_stdout=True, capture_stderr=True, input=None, quiet=True, overwrite_output=True)
except:
ERRCATCH = 1
GARBAGE.append(VIDOUT)
GARBAGE.append(WORKDIR + "/rate")
return VIDOUT
def blend(VIDIN):
FOLRA = []
count = 0
for i in VIDIN.split("/"):
if count > (len(VIDIN.split("/")) - 4):
FOLRA.append(i)
count = count + 1
VIDP = '/'.join(FOLRA)
PROBE=ffmpeg.probe(VIDIN) # Probe for video data
FPS=int(PROBE['streams'][0]['avg_frame_rate'].split('/')[0]) / int(PROBE['streams'][0]['avg_frame_rate'].split('/')[1]) # determine video FPS as a decimal
os.mkdir(WORKDIR + "/blend/") # New folder with same name as previous mkdir command, but with '_rate_' appended
VIDOUT = WORKDIR + "/blend/" + VIDIN.split("/")[(len(VIDIN.split("/")) - 1)] # Full path to output video
VIDPATH = []
count = 0
for i in VIDOUT.split('/'):
if count > (len(VIDOUT.split('/')) - 4):
VIDPATH.append(i)
count = count + 1
VIDDIR = '/'.join(VIDPATH)
print(Fore.GREEN + "Blending frames for:\n ", end='')
print(Fore.YELLOW + "'./" + VIDP + "'")
print(Fore.GREEN + "Resultant output file will be saved to:\n ", end='')
print(Fore.YELLOW + "'./" + VIDDIR + "'")
try:
ffmpeg.run(ffmpeg.output(ffmpeg.input(VIDIN).filter('minterpolate',round(FPS,2),"blend"),VIDOUT),capture_stdout=True, capture_stderr=True, input=None, quiet=True, overwrite_output=True)
except:
ERRCATCH = 1
GARBAGE.append(VIDOUT)
GARBAGE.append(WORKDIR + "/blend")
return VIDOUT
def palette(VIDIN):
FOLRA = []
count = 0
for i in VIDIN.split("."):
if count < (len(VIDIN.split(".")) - 1):
FOLRA.append(i)
count = count + 1
PAL = WORKDIR + "/palette.png" # Full path to palette.png file
VIDPATH = []
count = 0
for i in VIDIN.split('/'):
if count > (len(VIDIN.split('/')) - 4):
VIDPATH.append(i)
count = count + 1
VIDDIR = '/'.join(VIDPATH)
PNGPATH = []
count = 0
for i in PAL.split('/'):
if count > (len(PAL.split('/')) - 4):
PNGPATH.append(i)
count = count + 1
PNGDIR = '/'.join(PNGPATH)
print(Fore.GREEN + "Creating reference palette for:\n ", end='')
print(Fore.YELLOW + "'./" + VIDDIR + "'")
print(Fore.GREEN + "Saving reference palette to:\n ", end='')
print(Fore.YELLOW + "'./" + PNGDIR + "'")
try:
ffmpeg.run(ffmpeg.output(ffmpeg.input(VIDIN).filter('palettegen',256,False,'ffffff','diff'),PAL),capture_stdout=True, capture_stderr=True, input=None, quiet=True, overwrite_output=True)
except:
ERRCATCH = 1
GARBAGE.append(PAL)
GARBAGE.append(WORKDIR)
return PAL
def mkGIF(VIDIN,PAL):
OUTFO = []
count = 0
for i in WORKDIR.split('/'):
if count < (len(WORKDIR.split('/')) -1):
OUTFO.append(i)
count = count + 1
OUTDIR = '/'.join(OUTFO)
OUTNAME = []
count = 0
for i in (VIDIN.split('/')[(len(VIDIN.split('/')) - 1)]).split('.'):
if count < (len((VIDIN.split('/')[(len(VIDIN.split('/')) - 1)]).split('.')) -1):
OUTNAME.append(i)
count = count + 1
OUTFILE = '/'.join(OUTNAME)
GIF = OUTDIR + "/" + OUTFILE + ".gif" # Full path to GIF file
VIDPATH = []
count = 0
for i in VIDIN.split('/'):
if count > (len(VIDIN.split('/')) - 4):
VIDPATH.append(i)
count = count + 1
VIDDIR = '/'.join(VIDPATH)
GIFPATH = []
count = 0
for i in GIF.split('/'):
if count > (len(GIF.split('/')) - 4):
GIFPATH.append(i)
count = count + 1
GIFDIR = '/'.join(GIFPATH)
print(Fore.GREEN + "Creating GIF file from:\n ", end='')
print(Fore.YELLOW + "'./" + VIDDIR + "'")
print(Fore.GREEN + " Saving GIF file to:\n ", end='')
print(Fore.YELLOW + "'./" + GIFDIR + "'")
try:
ffmpeg.run(ffmpeg.output(ffmpeg.overlay(
ffmpeg.filter(
[
ffmpeg.input(VIDIN).filter_multi_output('split')[1], # Video stream copy 2 from 'split' filter
ffmpeg.input(PAL) # Stream from PNG palette
],
'paletteuse'
),
ffmpeg.input(VIDIN).filter_multi_output('split').stream(0) # Video stream copy 1 from 'split' filter
),GIF),capture_stdout=True, capture_stderr=True, input=None, quiet=True, overwrite_output=True)
except:
ERRCATCH = 1
return GIF
global ERRCATCH
global GARBAGE
global WORKDIR
ERRCATCH = 0
GARBAGE = []
if results.VIDIN == None:
openafile()
VIDIN = TIOW.name
else:
VIDIN = results.VIDIN.replace("\\","/")
FOLRA = []
print(VIDIN)
count = 0
for i in VIDIN.split("."):
if count < (len(VIDIN.split(".")) - 1):
FOLRA.append(i)
count = count + 1
WORKDIR = ".".join(FOLRA)
os.mkdir(WORKDIR) # Create new folder named after the video file
print(Fore.GREEN + "Working directory:\n ",end='')
print(Fore.YELLOW + WORKDIR + '/')
if ERRCATCH == 0:
if results.should_slice:
if not results.slice_time[0] == None and not results.slice_time[1] == None:
OUTVID = mp4Slice(VIDIN,results.slice_time[0],results.slice_time[1])
if ERRCATCH == 0:
print(Fore.WHITE + " Slicing succeeded!\n")
else:
print(Fore.RED + "Slicing failed!`n")
else:
OUTVID = VIDIN
if ERRCATCH == 0:
if not results.pbrate == None:
OUTVID = dRate(OUTVID,results.pbrate)
if ERRCATCH == 0:
print(Fore.WHITE + " Playback rate change succeeded!\n")
else:
print(Fore.RED + "Playback rate reduction failed!`n")
if ERRCATCH == 0:
if results.should_blend:
OUTVID = blend(OUTVID)
if ERRCATCH == 0:
print(Fore.WHITE + " Frame blending succeeded!\n")
else:
print(Fore.RED + "Frame blending failed!`n")
if ERRCATCH == 0:
PAL = palette(OUTVID)
if ERRCATCH == 0:
print(Fore.WHITE + " Reference palette creation succeeded!\n")
OUTGIF = mkGIF(OUTVID,PAL)
if ERRCATCH == 0:
print(Fore.WHITE + " GIF creation succeeded!\n")
print(Fore.YELLOW + "Cleaning up intermediate files:")
for fsitem in GARBAGE:
if os.path.isfile(fsitem):
VIDPATH = []
count = 0
for i in fsitem.split('/'):
if count > (len(fsitem.split('/')) - 4):
VIDPATH.append(i)
count = count + 1
VIDDIR = '/'.join(VIDPATH)
print(Fore.RED + " Deleting: ", end='')
print(Fore.YELLOW + "./" + VIDDIR)
os.remove(fsitem)
else:
VIDPATH = []
count = 0
for i in fsitem.split('/'):
if count > (len(fsitem.split('/')) - 4):
VIDPATH.append(i)
count = count + 1
VIDDIR = '/'.join(VIDPATH)
print(Fore.RED + " Deleting: ", end='')
print(Fore.YELLOW + "./" + VIDDIR + '/')
shutil.rmtree(fsitem)
else:
print(Fore.RED + "GIF creation failed!`n")
else:
print(Fore.RED + "Reference palette creation failed!`n")