Código de Python - Generador de gifs a partir de video, en línea de comandos.

Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Generador de gifs a partir de video, en línea de comandos.gráfica de visualizaciones


Python

Actualizado el 3 de Abril del 2024 por Antonio (76 códigos) (Publicado el 9 de Diciembre del 2022)
8.234 visualizaciones desde el 9 de Diciembre del 2022
Programa para generar gifs animados a partir de vídeos, que se ejecuta en la línea de comandos.
ARGUMENTOS:
-src/--source: Nombre del vídeo original (obligatorio).
-dest/--destination: Nombre del archivo a generar (opcional).
-sz/--size: Tamaño en porcentaje del gif respecto al vídeo original (opcional).
-shw/--show: Muestra resultado en ventana emergente al finalizar el proceso de generado (opcional).
-st/--start: Segundo inicial para gif (opcional).
-e/--end: Segundo final (opcional).
-spd/--speed: Velocidad relativa de la animación (opcional)

PARA CUALQUIER DUDA U OBSERVACIÓN, USEN LA SECCIÓN DE COMENTARIOS.

mk

Requerimientos

Lenguaje: Python
Librerías y recursos: moviepy, pyfiglet, ffmpeg, pathlib, pyglet, argparse y os

1.0

Actualizado el 20 de Enero del 2023 (Publicado el 9 de Diciembre del 2022)gráfica de visualizaciones de la versión: 1.0
1.641 visualizaciones desde el 9 de Diciembre del 2022

2.0
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 15 de Abril del 2023 (Publicado el 13 de Febrero del 2023)gráfica de visualizaciones de la versión: 2.0
1.770 visualizaciones desde el 13 de Febrero del 2023

2.1
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 27 de Septiembre del 2023 (Publicado el 16 de Abril del 2023)gráfica de visualizaciones de la versión: 2.1
2.425 visualizaciones desde el 16 de Abril del 2023
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

Se introducen mejoras en el sistema de comprobación de los datos introducidos por el usuario, mediante el empleo de diferentes funciones.
PARA CUALQUIER DUDA U OBSERVACIÓN, USEN LA SECCIÓN DE COMENTARIOS.
mk
mk2
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from moviepy.editor import VideoFileClip
from PIL import Image
import pyfiglet
import ffmpeg
import pyglet
import pathlib
from pyglet.window import key
import argparse
import random
from colorama import Fore, init, Style
import os
 
init()
color = {0:Fore.RED,1:Fore.GREEN,2:Fore.YELLOW,
         3:Fore.BLUE,4:Fore.CYAN,5:Fore.MAGENTA,6:Fore.WHITE}
 
bright = {0:Style.DIM,1:Style.NORMAL,2:Style.BRIGHT}
 
c_index = color[random.randint(0,6)]
b_index = bright[random.randint(0,2)]
 
def main():
    global file_extension
    parser = argparse.ArgumentParser(prog="MKGIF 2.1",conflict_handler='resolve',
                                     description="Create gifs from videos in command line or convert '.webp' files into '.gif'.",
                                     epilog = "REPO: https://github.com/antonioam82/MKGIF")
    parser.add_argument('-src','--source',required=True,type=check_source_ext,help='Nombre archivo original')
    parser.add_argument('-dest','--destination',default='my_gif.gif',type=check_result_ext,help='Nombre archivo destino')
    parser.add_argument('-st','--start',default=0.0,type=check_time,help='Segundo inicial del gif')
    parser.add_argument('-e','--end',default=None,type=check_time,help='Segundo final del gif')
    parser.add_argument('-shw','--show',help='Mostrar resultado',action='store_true')
    parser.add_argument('-sz','--size',default=100,type=check_positive,help='Tamaño relativo (100 por defecto)')
    parser.add_argument('-spd','--speed',default=100,type=check_positive,help='Velocidad relativa de animación (100 por defecto)')
    parser.add_argument('-fps','--fraps',default=None,type=int,help='Frames por segundo')
 
    args=parser.parse_args()
    file_extension = pathlib.Path(args.source).suffix
 
    if file_extension == '.webp':
        if args.start != 0.0 or args.end is not None or args.speed != 100 or args.size != 100:
            parser.error(Fore.RED+Style.BRIGHT+"-st/--start, -e/--end, -sz/--size and -spd/--speed specs not allowed for '.webp' to '.gif' conversion."+Fore.RESET+Style.RESET_ALL)
    else:
        probe = ffmpeg.probe(args.source)
        video_streams = [stream for stream in probe["streams"] if stream["codec_type"] == "video"]
 
        if args.end:
            args.end = float(args.end)
        else:
            args.end = float(video_streams[0]['duration'])
 
        if args.start > args.end:
            parser.error(Fore.RED+Style.BRIGHT+"start value must be smaller than end value."+Fore.RESET+Style.RESET_ALL)
 
    gm(args)
 
 
def check_time(val):
    time = float(val)
    if time < 0.0:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"time values must be equal or bigger than 0.00 ('{val}' is not valid)."+Fore.RESET+Style.RESET_ALL)
    return time
 
def check_positive(val):
    ivalue = int(val)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"speed and size values must be positive ('{val}' is not valid)."+Fore.RESET+Style.RESET_ALL)
    return ivalue
 
def check_source_ext(file):
    supported_formats = ['.mp4','.avi','.mov','.wmv','.rm','.webp']
    file_extension = pathlib.Path(file).suffix
    if file in os.listdir():
        if file_extension not in supported_formats:
            raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"Source file must be '.mp4', '.avi', '.mov', '.wmv', '.rm' or '.webp' ('{file_extension}' is not valid)."+Fore.RESET+Style.RESET_ALL)
    else:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"FILE NOT FOUND: File '{file}' not found."+Fore.RESET+Style.RESET_ALL)
    return file
 
def check_result_ext(file):
    file_extension = pathlib.Path(file).suffix
    if file_extension != '.gif':
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"result file must be '.gif' ('{file_extension}' is not valid)."+Fore.RESET+Style.RESET_ALL)
    return file
 
def show(f):
    print("GENERATING VIEW...")
    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()
        print(f"Successfully generated view from '{f}'.")
    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(c_index+b_index+pyfiglet.figlet_format('MKGIF',font='graffiti')+Fore.RESET+Style.RESET_ALL)
    try:
        if file_extension != '.webp':
            clip = (VideoFileClip(args.source,audio=False)
            .subclip((0,args.start),
                     (0,args.end))
            .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}.")
 
        else:
            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)
 
    except Exception as e:
        print("UNEXPECTED ERROR: "+str(e))
 
if __name__=='__main__':
    main()



Comentarios sobre la versión: 2.1 (1)

Imágen de perfil
16 de Abril del 2023
estrellaestrellaestrellaestrellaestrella
Recuerden usar la sección de comentarios para las dudas u observaciones.
Responder

Comentar la versión: 2.1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

2.2
estrellaestrellaestrellaestrellaestrella(2)

Actualizado el 3 de Abril del 2024 (Publicado el 28 de Septiembre del 2023)gráfica de visualizaciones de la versión: 2.2
2.399 visualizaciones desde el 28 de Septiembre del 2023
http://lwp-l.com/s7318