Skip to content

Instantly share code, notes, and snippets.

@parkanaur
Created Mar 20, 2022
Embed
What would you like to do?
Telegram animated stickers helper (GIF -> WEBM; ffmpeg-python)
import os
import glob
from pathlib import Path
import ffmpeg
DEFAULT_FPS = 30
DEFAULT_SMART_DURATION_LIMIT = "2.9"
DEFAULT_SPEED_ADJUST_MODE = "smart"
DEFAULT_FALLBACK_PTS = "1.0"
def process_file(filepath):
p = Path(filepath)
job = ffmpeg.input(filepath)
job = job.filter('fps', fps=DEFAULT_FPS)
info = ffmpeg.probe(filepath)
stream = info['streams'][0]
fmt = info['format']
if stream['width'] >= stream['height']:
job = job.filter('scale', 512, -1)
else:
job = job.filter('scale', -1, 512)
if 'duration' in fmt:
duration = float(fmt['duration'])
if duration > 3.0:
job = job.filter('setpts', f"({DEFAULT_SMART_DURATION_LIMIT}/{duration})*PTS")
else:
job = job.filter('setpts', f"{DEFAULT_FALLBACK_PTS}*PTS")
out_path = str(p.with_suffix('.webm'))
if os.path.exists(out_path):
out_path = str(p.with_suffix('.telegram.webm'))
job = (
job
.output(
out_path,
pix_fmt='yuva420p',
vcodec='libvpx-vp9',
an=None,
)
.overwrite_output()
)
job.run()
if __name__ == "__main__":
for file in glob.glob("*.gif"):
process_file(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment