Skip to content

Instantly share code, notes, and snippets.

@parkanaur
Created March 20, 2022 19:18
Show Gist options
  • Save parkanaur/6595b780df943a1524bcce42bc39c56d to your computer and use it in GitHub Desktop.
Save parkanaur/6595b780df943a1524bcce42bc39c56d to your computer and use it in GitHub Desktop.
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