rDrama/files/helpers/images.py

151 lines
3.8 KiB
Python
Raw Normal View History

2021-07-21 01:12:26 +00:00
import requests
2021-09-05 16:53:01 +00:00
from os import environ, path, remove
2021-09-15 00:45:01 +00:00
from PIL import Image, ImageSequence
2021-07-21 01:12:26 +00:00
import base64
2021-08-04 15:35:10 +00:00
from files.classes.images import *
2021-08-19 05:59:44 +00:00
from flask import g
2021-09-05 16:53:01 +00:00
from werkzeug.utils import secure_filename
2021-07-21 01:12:26 +00:00
2021-08-11 15:15:51 +00:00
CF_KEY = environ.get("CLOUDFLARE_KEY", "").strip()
CF_ZONE = environ.get("CLOUDFLARE_ZONE", "").strip()
IMGUR_KEY = environ.get("IMGUR_KEY", "").strip()
2021-09-02 14:06:28 +00:00
IBB_KEY = environ.get("IBB_KEY", "").strip()
2021-09-13 16:35:26 +00:00
def upload_ibb(file=None, resize=False):
if file: file.save("image.webp")
2021-09-13 17:01:55 +00:00
if resize:
2021-09-15 00:45:01 +00:00
i = Image.open("image.webp")
2021-09-13 17:01:55 +00:00
size = 100, 100
frames = ImageSequence.Iterator(i)
2021-09-13 16:56:22 +00:00
2021-09-13 17:01:55 +00:00
def thumbnails(frames):
for frame in frames:
2021-09-13 16:58:15 +00:00
thumbnail = frame.copy()
2021-09-15 00:45:01 +00:00
thumbnail.thumbnail(size, Image.ANTIALIAS)
2021-09-13 16:58:15 +00:00
yield thumbnail
2021-09-13 17:01:55 +00:00
frames = thumbnails(frames)
2021-09-13 16:56:22 +00:00
2021-09-13 17:01:55 +00:00
om = next(frames)
om.info = i.info
try: om.save("image.webp", save_all=True, append_images=list(frames), loop=0, optimize=True, quality=30)
except Exception as e:
print(e)
return
2021-09-15 00:42:12 +00:00
else:
sequence = []
im = Image.open("image.webp")
for frame in ImageSequence.Iterator(im):
sequence.append(frame.copy())
sequence[0].save("image.webp", save_all=True, append_images = sequence[1:])
2021-09-13 16:35:26 +00:00
try:
with open("image.webp", 'rb') as f:
data={'image': base64.b64encode(f.read())}
req = requests.post(f'https://api.imgbb.com/1/upload?key={IBB_KEY}', data=data)
resp = req.json()['data']
2021-09-13 17:05:58 +00:00
url = resp['url'].replace(".png", ".webp").replace(".jpg", ".webp").replace(".jpeg", ".webp")
2021-09-13 16:35:26 +00:00
except Exception as e:
print(e)
print(req.text)
return
return url
def upload_imgur(filepath=None, file=None, resize=False):
2021-09-10 02:25:27 +00:00
2021-09-10 04:10:43 +00:00
if file:
format = file.filename.split('.')[-1].lower().replace('jpg','png').replace('jpeg','png')
filepath = f"image.{format}"
file.save(filepath)
2021-09-10 04:22:29 +00:00
else: format = filepath.split('.')[-1].lower().replace('jpg','png').replace('jpeg','png')
2021-09-10 03:25:39 +00:00
2021-09-02 14:06:28 +00:00
if resize:
2021-09-15 00:45:01 +00:00
i = Image.open(filepath)
2021-09-02 14:06:28 +00:00
size = 100, 100
frames = ImageSequence.Iterator(i)
def thumbnails(frames):
for frame in frames:
thumbnail = frame.copy()
2021-09-15 00:45:01 +00:00
thumbnail.thumbnail(size, Image.ANTIALIAS)
2021-09-02 14:06:28 +00:00
yield thumbnail
frames = thumbnails(frames)
om = next(frames)
om.info = i.info
2021-09-11 16:22:28 +00:00
filepath = f"image.{i.format}".lower().replace('jpg','png').replace('jpeg','png')
2021-09-10 04:12:42 +00:00
try: om.save(filepath, save_all=True, append_images=list(frames), loop=0, optimize=True, quality=30)
2021-09-11 02:56:30 +00:00
except Exception as e:
print(e)
return
2021-09-10 04:23:24 +00:00
elif format != "gif":
2021-09-15 00:45:01 +00:00
i = Image.open(filepath)
2021-09-11 16:22:28 +00:00
filepath = f"image.{i.format}".lower().replace('jpg','png').replace('jpeg','png')
2021-09-10 04:14:52 +00:00
i.save(filepath, optimize=True, quality=30)
2021-09-10 04:08:32 +00:00
try:
2021-09-10 04:12:12 +00:00
with open(filepath, 'rb') as f:
2021-09-10 04:08:32 +00:00
data={'image': base64.b64encode(f.read())}
2021-09-13 16:35:26 +00:00
req = requests.post('https://api.imgur.com/3/upload.json', headers = {"Authorization": f"Client-ID {IMGUR_KEY}"}, data=data)
2021-09-10 04:08:32 +00:00
resp = req.json()['data']
2021-09-13 17:05:58 +00:00
url = resp['link'].replace(".png", ".webp").replace(".jpg", ".webp").replace(".jpeg", ".webp")
2021-09-11 02:56:30 +00:00
except Exception as e:
print(e)
2021-09-12 00:08:29 +00:00
print(req.text)
2021-09-10 04:08:32 +00:00
return
2021-09-10 02:29:05 +00:00
2021-09-13 16:35:26 +00:00
new_image = Image(text=url, deletehash=resp["deletehash"])
g.db.add(new_image)
2021-09-10 02:29:05 +00:00
return url
2021-09-05 16:53:01 +00:00
class UploadException(Exception):
"""Custom exception to raise if upload goes wrong"""
pass
def upload_video(file):
file_path = path.join("temp", secure_filename(file.filename))
2021-09-05 17:14:52 +00:00
file.save(file_path)
2021-09-05 16:53:01 +00:00
headers = {"Authorization": f"Client-ID {IMGUR_KEY}"}
with open(file_path, 'rb') as f:
try:
2021-09-05 17:52:40 +00:00
r = requests.post('https://api.imgur.com/3/upload', headers=headers, files={"video": f})
2021-09-05 17:54:02 +00:00
2021-09-05 18:14:44 +00:00
r.raise_for_status()
2021-09-05 16:53:01 +00:00
resp = r.json()['data']
except requests.HTTPError as e:
2021-09-05 18:14:44 +00:00
raise UploadException("Invalid video. Make sure it's 1 minute long or shorter.")
2021-09-07 02:07:11 +00:00
except:
2021-09-05 16:53:01 +00:00
raise UploadException("Error, please try again later.")
finally:
remove(file_path)
2021-09-06 21:38:17 +00:00
link = resp['link']
img = Image(text=link, deletehash=resp['deletehash'])
g.db.add(img)
2021-09-10 04:08:32 +00:00
return link