Git Product home page Git Product logo

giftolottie's People

Contributors

bodqhrohro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

giftolottie's Issues

ModuleNotFoundError: No module named 'pkg_resources'

I get the following error when executing your code:

$ python3 read.py input.gif output.tgs
Traceback (most recent call last):
  File "read.py", line 8, in <module>
    import vendor.gif2numpy
  File "/Users/jonasfrey/Desktop/temp/giftolottie/vendor/gif2numpy.py", line 30, in <module>
    from pkg_resources import parse_version
ModuleNotFoundError: No module named 'pkg_resources'

I uploaded my Terminal output to Pastebin, so you can see the exact steps I took to install the dependencies and your script and see if I made any errors there: https://pastebin.com/qnBsDLcY

I was trying to execute the script on macOS 10.15.4 and was therefore using HomeBrew to install gifsicle.

Exception: unexpected fixed contents: got b'', was waiting for b'GIF'

There seems to be a problem with gif2numpy. I'm running on Windows10 by the way.

Traceback (most recent call last):
  File "read.py", line 22, in <module>
    frames, exts, image_specs = vendor.gif2numpy.convert(tmpfile.name, BGR2RGB=False)
  File "C:\Users\Cesar MLW\Desktop\Projects\gif_converter\giftolottie\vendor\gif2numpy.py", line 550, in convert
    data = Gif(KaitaiStream(BytesIO(raw)))
  File "C:\Users\Cesar MLW\Desktop\Projects\gif_converter\giftolottie\vendor\gif2numpy.py", line 82, in __init__
    self._read()
  File "C:\Users\Cesar MLW\Desktop\Projects\gif_converter\giftolottie\vendor\gif2numpy.py", line 85, in _read
    self.hdr = self._root.Header(self._io, self, self._root)
  File "C:\Users\Cesar MLW\Desktop\Projects\gif_converter\giftolottie\vendor\gif2numpy.py", line 263, in __init__
    self._read()
  File "C:\Users\Cesar MLW\Desktop\Projects\gif_converter\giftolottie\vendor\gif2numpy.py", line 266, in _read
    self.magic = self._io.ensure_fixed_contents(b"\x47\x49\x46")
  File "C:\Users\Cesar MLW\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kaitaistruct.py", line 279, in ensure_fixed_contents
    (actual, expected)
Exception: unexpected fixed contents: got b'', was waiting for b'GIF'

error while converting to .gif

Traceback (most recent call last):
  File "read.py", line 22, in <module>
    frames, exts, image_specs = vendor.gif2numpy.convert(tmpfile.name, BGR2RGB=False)
  File "/media/data/Sources/giftolottie/vendor/gif2numpy.py", line 660, in convert
    transp_idx = color_table[exts[-1]['transparent_idx']] # RGB -> RGB
IndexError: list index out of range

Enable multiprocessing

I'm currently trying to implement multiprocessing, but I'm having troubles with shared memory:

#!/usr/bin/env python

import sys
import os
from subprocess import run
from tempfile import NamedTemporaryFile

import vendor.gif2numpy
import numpy as np

from pprint import pprint

from utils.rect import rects_of_color
from utils.scale import scale
from export.svg import save as svg_save
from export.tgs import save as tgs_save

import time
import multiprocessing

processes = []
PROCESS_COUNT = 0

tmpfile = NamedTemporaryFile(delete=False)
run(["gifsicle", "-U", sys.argv[1]], stdout=tmpfile)
tmpfile.close()

frames, exts, image_specs = vendor.gif2numpy.convert(tmpfile.name, BGR2RGB=False)

os.remove(tmpfile.name)

colors = image_specs['Color table values']
size = image_specs['Image Size']

# dedup colors
i = 0
while i < len(colors):
    color = colors[i]
    if color in colors[(i+1):]:
        colors.pop(i)
    else:
        i = i + 1

processed_frames = []

def preprocess_frame(i, frame, PROCESS_COUNT, processed_frames):
    all_rects = []
    for color in colors:
        if color == (254, 0, 254):
            continue

        rects = rects_of_color(frame, color)

        rects.sort(key=lambda rect: rect['coords'][0])
        runs = []
        for rect in rects:
            is_included_in_run = False
            if rect['coords'][0][0] != 0:
                for run in runs:
                    if run['coords'][1][0] == rect['coords'][0][0] \
                            and run['coords'][0][1] == rect['coords'][0][1]:
                        run['coords'] = (run['coords'][0], rect['coords'][1])
                        is_included_in_run = True
            if not is_included_in_run:
                runs.append(rect)

        all_rects.extend(runs)

    sizeX, sizeY = size
    ratio = (512 / sizeY) if sizeX < sizeY else (512 / sizeX)
    all_rects = scale(all_rects, ratio)

    for rect in all_rects:
        rect['startFrame'] = i
        rect['endFrame'] = i

    # svg_save(all_rects, "/tmp/smile%s.svg" % i)

    while True:
        try:
            processed_frames[i] = all_rects
            break
        except Exception as e:
            print("Appending item")
            processed_frames.append(0)
    
    print("decreasing")
    PROCESS_COUNT-=1

for i, frame in enumerate(frames):
    print(PROCESS_COUNT)
    p = multiprocessing.Process(target=preprocess_frame, args=(i,frame,PROCESS_COUNT,processed_frames,))
    processes.append(p)
    PROCESS_COUNT+=1
    while PROCESS_COUNT > 12:
        print(PROCESS_COUNT)
        time.sleep(0.1)

    p.start()
    PROCESS_COUNT += 1

for process in processes:
    process.join()

def process_frame(i, PROCESS_COUNT, processed_frames):
    frame = processed_frames[i]
    prev_frame = processed_frames[i - 1]
    for shape in frame:
        if shape['type'] == 'rect':
            for prev_shape in prev_frame:
                if prev_shape['type'] == 'rect' \
                    and prev_shape['coords'] == shape['coords'] \
                    and prev_shape['color'] == shape['color'] \
                    and shape['startFrame'] == prev_shape['endFrame'] + 1:
                        prev_shape['endFrame'] = shape['endFrame']
                        frame.remove(shape)
                        break
    PROCESS_COUNT-=1

PROCESS_COUNT = 0
for i in range(len(processed_frames) - 1, 0, -1):
    print(PROCESS_COUNT)
    p = multiprocessing.Process(target=process_frame, args=(i,PROCESS_COUNT, processed_frames,))
    processes.append(p)
    PROCESS_COUNT+=1
    while PROCESS_COUNT > 12:
        time.sleep(0.1)

    p.start()
    PROCESS_COUNT += 1

for process in processes:
    process.join()

tgs_save(processed_frames, sys.argv[2], exts)

FileNotFoundError: [WinError 2]

Traceback (most recent call last):
File "read.py", line 19, in
run(["gifsicle", "-U", sys.argv[1]], stdout=tmpfile)
File "D:\ProgramFiles\miniconda3\lib\subprocess.py", line 488, in run
with Popen(*popenargs, **kwargs) as process:
File "D:\ProgramFiles\miniconda3\lib\subprocess.py", line 800, in init
restore_signals, start_new_session)
File "D:\ProgramFiles\miniconda3\lib\subprocess.py", line 1207, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] Nie można odnaleźć określonego pliku

while executing

python read.py wale.gif wale.tgs

wale.gif is in the read.py's directory

Выскакиывает надпись 'Python' и на этом все

Все установил, ввожу команду: python3 C:\Users\IGOR\Downloads\giftolottie-master\read.py C:\Users\IGOR\Downloads\nerima.gif C:\Users\IGOR\Downloads\nerima.tgs и получаю в следующей строке лишь Python
image

Мне уже даже нейронки не помогают, что не так делаю?

ColorTable error

root@loli:/giftolottie# python3 read.py tenor.gif test.tgs
gifsicle:tenor.gif: warning: GIF too complex to unoptimize
(The reason was local color tables or complex transparency.
Try running the GIF through ‘gifsicle --colors=255’ first.)
gifsicle: warning: too many colors, using local colormaps
(You may want to try ‘--colors 256’.)
Traceback (most recent call last):
File "read.py", line 22, in
frames, exts, image_specs = vendor.gif2numpy.convert(tmpfile.name, BGR2RGB=False)
File "/root/giftolottie/vendor/gif2numpy.py", line 629, in convert
np_image = np.array([local_color_table[byt] if byt != exts[-1]['transparent_idx'] else (254, 0, 254) for byt in uncompressed])
File "/root/giftolottie/vendor/gif2numpy.py", line 629, in
np_image = np.array([local_color_table[byt] if byt != exts[-1]['transparent_idx'] else (254, 0, 254) for byt in uncompressed])
TypeError: 'ColorTable' object does not support indexing
root@loli:
/giftolottie# apt install colortable
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package colortable
root@loli:~/giftolottie#

Telegram жалуется на формат файла

Нарисовал двухцветную гифку из 4 слайдов, конвертировал в 30-килобайтный tgs. При загрузке в Telegram получаю следующее сообщение:

Увы, такой формат файла не поддерживается. Пожалуйста, сконвертируйте изображение в TGS.

У меня есть найденный в интернете tgs на 40КБ - его принимает на ура. Подозреваю, дело не в формате файла, а в его параметрах.
Есть какие-нибудь средние параметры для гифок, с которыми Telegram будет «съедать» конвертированный tgs? Например, DPI холста или количество цветов.

Нихуя не понял как этим пользоваться

Все установил. Вот эти штуки kaitaistruct, svgwrite, numpy и даже gif2numpy зачем-то. Но что дальше?? В usage у него написано использоваться вот эту команду: python3 read.py input.gif output.tgs, но он выдает следующее: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

Шо делать помогите

new idea

can you make an app that does the opposite and convert .tgs to .gif?

TypeError: 'ColorTable' object is not subscriptable

First, I had this error:

Traceback (most recent call last):
  File "giftotgs/giftolottie/read.py", line 19, in <module>
    run(["gifsicle", "-U", sys.argv[1]], stdout=tmpfile)
  File "/usr/local/Cellar/[email protected]/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 505, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/local/Cellar/[email protected]/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/local/Cellar/[email protected]/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1821, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'gifsicle'

So, I run pip3 install pygifsicle; Which I'm not if that was correct way to have gifsicle!

Then, I got this:

giftolottie git:(master) python3 read.py sample.gif output.tgs
gifsicle:sample.gif: warning: GIF too complex to unoptimize
  (The reason was local color tables or complex transparency.
  Try running the GIF throughgifsicle --colors=255first.)
gifsicle: warning: too many colors, using local colormaps
  (You may want to try--colors 256’.)
Traceback (most recent call last):
  File "giftotgs/giftolottie/read.py", line 22, in <module>
    frames, exts, image_specs = vendor.gif2numpy.convert(tmpfile.name, BGR2RGB=False)
  File "giftotgs/giftolottie/vendor/gif2numpy.py", line 629, in convert
    np_image = np.array([local_color_table[byt] if byt != exts[-1]['transparent_idx'] else (254, 0, 254) for byt in uncompressed])
  File "giftotgs/giftolottie/vendor/gif2numpy.py", line 629, in <listcomp>
    np_image = np.array([local_color_table[byt] if byt != exts[-1]['transparent_idx'] else (254, 0, 254) for byt in uncompressed])
TypeError: 'ColorTable' object is not subscriptable

File "read.py", line 15, in <module>

Traceback (most recent call last):
File "read.py", line 15, in
from export.svg import save as svg_save
File "/home/pavel08052002/giftolottie/export/svg.py", line 1, in
import svgwrite
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/init.py", line 53, in
from svgwrite.drawing import Drawing
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/drawing.py", line 29, in
from svgwrite.container import SVG, Defs
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/container.py", line 28, in
from svgwrite.base import BaseElement
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/base.py", line 16, in
from svgwrite.params import Parameter
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/params.py", line 9, in
from svgwrite.validator2 import get_validator
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/validator2.py", line 9, in
from svgwrite.data import full11
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/data/full11.py", line 11, in
from svgwrite.data.typechecker import Full11TypeChecker as TypeChecker
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/data/typechecker.py", line 13, in
from svgwrite.data.svgparser import is_valid_transferlist, is_valid_pathdata, is_valid_animation_timing
File "/home/pavel08052002/.local/lib/python3.5/site-packages/svgwrite/data/svgparser.py", line 24
nonnegative_number = fr"(\d+.?\d*|.\d+){exponent}?"
^
SyntaxError: invalid syntax

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/smile0.svg'

Traceback (most recent call last):
File "C:/Users/user/Desktop/giftolottie-5131a368607ebb177f2d61d6564c61264dbfbcd0/read.py", line 71, in
svg_save(all_rects, "/tmp/smile%s.svg" % i)
File "C:\Users\user\Desktop\giftolottie-5131a368607ebb177f2d61d6564c61264dbfbcd0\export\svg.py", line 18, in save
svg.save()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\svgwrite\drawing.py", line 121, in save
fileobj = io.open(self.filename, mode='w', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/smile0.svg'

FileNotFoundError: [Errno 2] No such file or directory: 'gifsicle'

Getting this error

python3 read.py input.gif output.tgs
Traceback (most recent call last):
File "read.py", line 19, in
run(["gifsicle", "-U", sys.argv[1]], stdout=tmpfile)
File "/data/data/com.termux/files/usr/lib/python3.8/subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "/data/data/com.termux/files/usr/lib/python3.8/subprocess.py", line 854, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/data/data/com.termux/files/usr/lib/python3.8/subprocess.py", line 1700, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'gifsicle'

Qs

Hey can I please know what to do with this?
Actually I really wanna convert Gif/Webm totgs for making some telegram stickers.. I found this but I really dont know what to do:(

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.