-
Notifications
You must be signed in to change notification settings - Fork 0
/
mkgif2.py
103 lines (93 loc) · 4.56 KB
/
mkgif2.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
from moviepy.editor import *
#import sys
from PIL import Image
import pyfiglet
import ffmpeg
import pyglet
import pathlib
from pyglet.window import key
import argparse
import os
def main():
parser = argparse.ArgumentParser(prog="MKGIF",conflict_handler='resolve',description="Create gifs from videos in command line or convert '.webp' files into '.gif'.",
epilog = "Do not spec -st/--start, -e/--end, -sz/--size and -spd/--speed args for '.webp' to '.gif' conversion")
parser.add_argument('-src','--source',required=True,type=str,help='Ruta archivo original')
parser.add_argument('-dest','--destination',default='my_gif.gif',type=str,help='Ruta archivo destino')
parser.add_argument('-st','--start',default=0.0,type=float,help='Segundo inicial del gif')
parser.add_argument('-e','--end',default=None,type=str,help='Segundo final del gif')
parser.add_argument('-shw','--show',help='Mostrar resultado',action='store_true')
parser.add_argument('-sz','--size',default=100,type=int,help='Tamaño relativo')
parser.add_argument('-spd','--speed',default=100,type=int,help='Velocidad relativa de animación')
parser.add_argument('-fps','--fraps',default=None,type=int,help='Frames por segundo')
args=parser.parse_args()
gm(args)
def show(f):
try:
animation = pyglet.image.load_animation(f)
bin = pyglet.image.atlas.TextureBin()
animation.add_to_texture_bin(bin)
sprite = pyglet.sprite.Sprite(animation)
w = sprite.width
h = sprite.height
window = pyglet.window.Window(width=w, height=h)
@window.event
def on_draw():
sprite.draw()
pyglet.app.run()
except Exception as e:
print("UNEXPECTED ERROR: ",str(e))
def get_size_format(b, factor=1024, suffix="B"):
for unit in ["","K","M","G","T","P","E","Z"]:
if b < factor:
return f"{b:.4f}{unit}{suffix}"
b /= factor
return f"{b:.4f}Y{suffix}"
def gm(args):
print(pyfiglet.figlet_format('MKGIF',font='graffiti'))
file_extension = pathlib.Path(args.source).suffix
result_extension = pathlib.Path(args.destination).suffix
if (file_extension == '.mp4' or file_extension == '.webp') and result_extension == '.gif':
if args.source in os.listdir():
try:
if file_extension == '.mp4':
probe = ffmpeg.probe(args.source)
video_streams = [stream for stream in probe["streams"] if stream["codec_type"] == "video"]
if args.end:
duration = float(args.end)
else:
duration = float(video_streams[0]['duration'])
if args.start < duration:
clip = (VideoFileClip(args.source)
.subclip((0,args.start),
(0,duration))
.resize(args.size/100)
.speedx(args.speed/100))
print('CREATING GIF...')
clip.write_gif(args.destination,fps=args.fraps)
clip.close()
size = get_size_format(os.stat(args.destination).st_size)
print(f"Created gif '{args.destination}' with size {size}.")
if args.show:
show(args.destination)
else:
print("ERROR: Start value must be smaller than end value.")
else:
if args.size == 100 and args.start == 0.0 and args.speed == 100 and not args.end:
print("CONVERTING...")
file = Image.open(args.source)
file.save(args.destination,'gif',save_all=True,background=0)
file.close()
size = get_size_format(os.stat(args.destination).st_size)
print(f"Created {args.destination} with size {size} from {args.source}")
if args.show:
show(args.destination)
else:
print("-st/--start, -e/--end, -sz/--size and -spd/--speed specs not allowed for '.webp' to '.gif' conversion")
except Exception as e:
print("UNEXPECTED ERROR: ",str(e))
else:
print(f"FILE NOT FOUND: File '{args.source}' not found.")
else:
print("WRONG FILE FORMAT: Source file must be '.mp4' or '.webp' and result file must be '.gif'.")
if __name__=='__main__':
main()