Spaces:
Running
Running
import base64 | |
import json | |
import requests | |
from io import BytesIO | |
import re, os | |
from PIL import Image | |
from datetime import datetime | |
import random | |
import socket | |
r_b64_prefix = r'^data:image/.+;base64,' | |
from PIL import ImageOps | |
def resize_keep_hw_rate(image, tar_res): | |
w, h = image.size | |
if w > h: | |
tar_w = tar_res | |
tar_h = int(tar_w * h / w) | |
elif h > w: | |
tar_h = tar_res | |
tar_w = int(tar_h * w / h) | |
else: | |
tar_w = tar_res | |
tar_h = tar_res | |
image = image.resize((tar_w, tar_h), Image.LANCZOS) | |
return image | |
def decode_img_from_url(url): | |
import requests | |
from io import BytesIO | |
for _ in range(5): | |
try: | |
content = requests.get(url, stream=True, timeout=10).content | |
img = Image.open(BytesIO(content)) | |
img = ImageOps.exif_transpose(img) | |
break | |
except Exception as e: | |
print_with_datetime(f"url decode error {url} {str(e)}") | |
img = None | |
return img | |
def make_sub_file_folder(file_path): | |
subdir = file_path.split(os.path.basename(file_path))[0] | |
os.makedirs(subdir, exist_ok=True) | |
def get_random_file_name(): | |
timing_cur = datetime.now().timestamp() * 1000000 | |
timing_cur = str(int(timing_cur)) + f'-{random.randint(0,99999999)}' | |
return timing_cur | |
def print_with_datetime(string): | |
print(f'{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: {string}', flush=True) | |
def b64_pil(base64Data, mode = 'RGB'): | |
try: | |
base64Data = re.sub(r_b64_prefix, '', base64Data) | |
imgData = base64.b64decode(base64Data) | |
image = Image.open(BytesIO(imgData)) | |
except: | |
image = None | |
return image | |
def pil_b64(pil_img, fmt='jpeg', quality=75): | |
output_buffer = BytesIO() | |
pil_img.save(output_buffer, format=fmt, quality=quality) | |
byte_data = output_buffer.getvalue() | |
base64_str = base64.b64encode(byte_data).decode('utf-8') | |
if fmt == 'jpeg': | |
fmt_out = 'jpg' | |
else: | |
fmt_out = fmt | |
return f'data:image/{fmt_out};base64,' + base64_str | |
def get_ip(): | |
hostname = socket.gethostname() | |
ip_address = socket.gethostbyname(hostname) | |
return ip_address | |