Skip to content

Instantly share code, notes, and snippets.

@ishanExtreme
Created March 18, 2023 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ishanExtreme/e414c7a9d30c78c2a282312a5adc0d7a to your computer and use it in GitHub Desktop.
Save ishanExtreme/e414c7a9d30c78c2a282312a5adc0d7a to your computer and use it in GitHub Desktop.
Gif maker
from moviepy.editor import VideoFileClip
import os
import urllib.request
import uuid
import logging
import boto3
from pathlib import Path
from dotenv import dotenv_values
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
config = dotenv_values(".env")
logging.basicConfig(
filename=str(Path(__file__).parents[2]) + "/logs/app.log",
format="%(name)s - %(levelname)s - %(message)s",
)
mp4UrlPrefix = config["CLOUDFRONT_VIDEO_PREFIX"]
def getGifUrlFromMp4Driver(params):
logging.info("Started getGifUrlFromMp4Driver")
if "mp4Url" not in params:
logging.error("mp4Url not in params")
return {"gifUrl": None}
if "s3Destination" not in params:
logging.error("s3Destination not in params")
return {"gifUrl": None}
mp4Url = mp4UrlPrefix + "/" + params["mp4Url"]
s3Destination = params["s3Destination"]
fps = params.get("fps", 20)
fuzz = params.get("fuzz", 1)
start = params.get("start", 5)
duration = params.get("duration", 5)
videoWidth = params.get("videoWidth", 144)
videoHeight = params.get("videoHeight", 256)
try:
session = boto3.Session(
aws_access_key_id=config["AWS_KEY"],
aws_secret_access_key=config["AWS_SECRET"],
)
s3 = session.resource("s3")
mp4_folder = ROOT_DIR + "/videos/"
gif_folder = ROOT_DIR + "/gifs/"
name = str(uuid.uuid4())
downloadedVideoPath = f"{mp4_folder}{name}.mp4"
urllib.request.urlretrieve(mp4Url, downloadedVideoPath)
counter = 0
convertedGifPath = f"{gif_folder}{name}.gif"
while True:
counter += 1
videoClip = VideoFileClip(downloadedVideoPath)
videoClip = videoClip.subclip(start, start + duration)
videoClip = videoClip.resize((videoWidth, videoHeight))
videoClip = videoClip.set_fps(fps)
videoClip.write_gif(
filename=convertedGifPath,
program="ImageMagick",
opt="optimizeplus",
tempfiles=True,
verbose=False,
fuzz=fuzz,
logger=None,
)
file_size = os.path.getsize(convertedGifPath)
# greater than 500Kb
if file_size > 500000 and counter <= 3:
if counter == 1:
fps = 15
elif counter == 2:
fps = 10
elif counter == 3:
fps = 5
continue
break
os.remove(downloadedVideoPath)
destBucketName = config["AWS_BUCKET_IMAGE_NAME"]
if s3Destination[-1] != "/":
s3Destination += "/"
gifPath = "gif" + ".gif"
s3.Bucket(destBucketName).upload_file(convertedGifPath, s3Destination + gifPath)
gifUrl = f"{s3Destination}{gifPath}"
os.remove(convertedGifPath)
return {"gifUrl": gifUrl}
except Exception as e:
logging.error(f"Error in getGifUrlFromMp4Driver: {e}")
os.remove(downloadedVideoPath)
return {"gifUrl": None}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment