import gradio as gr from Lex import * ''' lex = Lexica(query="man woman fire snow").images() ''' from PIL import Image import imagehash import requests from time import sleep sleep_time = 0.5 hash_func_name = list(filter(lambda x: x.endswith("hash") and "hex" not in x ,dir(imagehash))) hash_func_name = ['average_hash', 'colorhash', 'dhash', 'phash', 'whash', 'crop_resistant_hash',] def min_dim_to_size(img, size = 512): h, w = img.size ratio = size / max(h, w) h, w = map(lambda x: int(x * ratio), [h, w]) return ( ratio ,img.resize((h, w)) ) #ratio_size = 512 #ratio, img_rs = min_dim_to_size(img, ratio_size) def image_click(images, evt: gr.SelectData): img_selected = images[evt.index] return images[evt.index]['name'] def swap_gallery(im, images, func_name): #### name data is_file #print(images[0].keys()) if im is None: return list(map(lambda x: x["name"], images)) hash_func = getattr(imagehash, func_name) im_hash = hash_func(Image.fromarray(im)) t2_list = sorted(images, key = lambda imm: hash_func(Image.open(imm["name"])) - im_hash, reverse = False) return list(map(lambda x: x["name"], t2_list)) def lexica(prompt, limit_size = 128, ratio_size = 256 + 128): lex = Lexica(query=prompt).images() lex = lex[:limit_size] lex = list(map(lambda x: x.replace("full_jpg", "sm2"), lex)) lex_ = [] for ele in lex: try: im = Image.open( requests.get(ele, stream = True).raw ) lex_.append(im) except: print("err") sleep(sleep_time) assert lex_ lex = list(map(lambda x: min_dim_to_size(x, ratio_size)[1], lex_)) return lex def enterpix(prompt, limit_size = 100, ratio_size = 256 + 128, use_key = "bigThumbnailUrl"): resp = requests.post( url = "https://www.enterpix.app/enterpix/v1/image/prompt-search", data= { "length": limit_size, "platform": "stable-diffusion,midjourney", "prompt": prompt, "start": 0 } ) resp = resp.json() resp = list(map(lambda x: x[use_key], resp["images"])) lex_ = [] for ele in resp: try: im = Image.open( requests.get(ele, stream = True).raw ) lex_.append(im) except: print("err") sleep(sleep_time) assert lex_ resp = list(map(lambda x: min_dim_to_size(x, ratio_size)[1], lex_)) return resp def search(prompt, search_name): if search_name == "lexica": return lexica(prompt) else: return enterpix(prompt) with gr.Blocks(css="custom.css") as demo: title = gr.HTML( """