Add application file
Browse filesFiles changed (13)
- README.md+10-6
- app.pyAdded+288
- checkers.pngAdded
- checkers_mid.jpgAdded
- funky.jpegAdded
- illusion_style.pyAdded+10
- pattern.pngAdded
- requirements.txtAdded+9
- safety_checker.pyAdded+137
- share_btn.pyAdded+83
- spiral.jpegAdded
- ultra_checkers.pngAdded
- user_history.pyAdded+423
123456789101112---title: Illusiondiffusionsemoji: 🐠colorFrom: pinkcolorTo: yellowsdk: gradiosdk_version: 5.4.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516---title: IllusionDiffusionemoji: 🔥colorFrom: redcolorTo: pinksdk: gradiosdk_version: 4.36.1app_file: app.pypinned: falselicense: openrailhf_oauth: truedisable_embedding: trueshort_description: Generate stunning high quality illusion artwork---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288import spacesimport torchimport gradio as grfrom gradio import processing_utils, utilsfrom PIL import Imageimport random
from diffusers import ( DiffusionPipeline, AutoencoderKL, StableDiffusionControlNetPipeline, ControlNetModel, StableDiffusionLatentUpscalePipeline, StableDiffusionImg2ImgPipeline, StableDiffusionControlNetImg2ImgPipeline, DPMSolverMultistepScheduler, EulerDiscreteScheduler)import tempfileimport timefrom share_btn import community_icon_html, loading_icon_html, share_jsimport user_historyfrom illusion_style import cssimport osfrom transformers import CLIPImageProcessorfrom diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
BASE_MODEL = "SG161222/Realistic_Vision_V5.1_noVAE"
# Initialize both pipelinesvae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)controlnet = ControlNetModel.from_pretrained("monster-labs/control_v1p_sd15_qrcode_monster", torch_dtype=torch.float16)
# Initialize the safety checker conditionallySAFETY_CHECKER_ENABLED = os.environ.get("SAFETY_CHECKER", "0") == "1"safety_checker = Nonefeature_extractor = Noneif SAFETY_CHECKER_ENABLED: safety_checker = StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-safety-checker").to("cuda") feature_extractor = CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32")
main_pipe = StableDiffusionControlNetPipeline.from_pretrained( BASE_MODEL, controlnet=controlnet, vae=vae, safety_checker=safety_checker, feature_extractor=feature_extractor, torch_dtype=torch.float16,).to("cuda")
# Function to check NSFW images#def check_nsfw_images(images: list[Image.Image]) -> tuple[list[Image.Image], list[bool]]:# if SAFETY_CHECKER_ENABLED:# safety_checker_input = feature_extractor(images, return_tensors="pt").to("cuda")# has_nsfw_concepts = safety_checker(# images=[images],# clip_input=safety_checker_input.pixel_values.to("cuda")# )# return images, has_nsfw_concepts# else:# return images, [False] * len(images) #main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)#main_pipe.unet.to(memory_format=torch.channels_last)#main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)#model_id = "stabilityai/sd-x2-latent-upscaler"image_pipe = StableDiffusionControlNetImg2ImgPipeline(**main_pipe.components)
#image_pipe.unet = torch.compile(image_pipe.unet, mode="reduce-overhead", fullgraph=True)#upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)#upscaler.to("cuda")
# Sampler mapSAMPLER_MAP = { "DPM++ Karras SDE": lambda config: DPMSolverMultistepScheduler.from_config(config, use_karras=True, algorithm_type="sde-dpmsolver++"), "Euler": lambda config: EulerDiscreteScheduler.from_config(config),}
def center_crop_resize(img, output_size=(512, 512)): width, height = img.size
# Calculate dimensions to crop to the center new_dimension = min(width, height) left = (width - new_dimension)/2 top = (height - new_dimension)/2 right = (width + new_dimension)/2 bottom = (height + new_dimension)/2
# Crop and resize img = img.crop((left, top, right, bottom)) img = img.resize(output_size)
return img
def common_upscale(samples, width, height, upscale_method, crop=False): if crop == "center": old_width = samples.shape[3] old_height = samples.shape[2] old_aspect = old_width / old_height new_aspect = width / height x = 0 y = 0 if old_aspect > new_aspect: x = round((old_width - old_width * (new_aspect / old_aspect)) / 2) elif old_aspect < new_aspect: y = round((old_height - old_height * (old_aspect / new_aspect)) / 2) s = samples[:,:,y:old_height-y,x:old_width-x] else: s = samples
return torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method)
def upscale(samples, upscale_method, scale_by): #s = samples.copy() width = round(samples["images"].shape[3] * scale_by) height = round(samples["images"].shape[2] * scale_by) s = common_upscale(samples["images"], width, height, upscale_method, "disabled") return (s)
def check_inputs(prompt: str, control_image: Image.Image): if control_image is None: raise gr.Error("Please select or upload an Input Illusion") if prompt is None or prompt == "": raise gr.Error("Prompt is required")
def convert_to_pil(base64_image): pil_image = Image.open(base64_image) return pil_image
def convert_to_base64(pil_image): with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file: image.save(temp_file.name) return temp_file.name
# Inference function@spaces.GPUdef inference( control_image: Image.Image, prompt: str, negative_prompt: str, guidance_scale: float = 8.0, controlnet_conditioning_scale: float = 1, control_guidance_start: float = 1, control_guidance_end: float = 1, upscaler_strength: float = 0.5, seed: int = -1, sampler = "DPM++ Karras SDE", progress = gr.Progress(track_tqdm=True), profile: gr.OAuthProfile | None = None,): start_time = time.time() start_time_struct = time.localtime(start_time) start_time_formatted = time.strftime("%H:%M:%S", start_time_struct) print(f"Inference started at {start_time_formatted}") # Generate the initial image #init_image = init_pipe(prompt).images[0]
# Rest of your existing code control_image_small = center_crop_resize(control_image) control_image_large = center_crop_resize(control_image, (1024, 1024))
main_pipe.scheduler = SAMPLER_MAP[sampler](main_pipe.scheduler.config) my_seed = random.randint(0, 2**32 - 1) if seed == -1 else seed generator = torch.Generator(device="cuda").manual_seed(my_seed) out = main_pipe( prompt=prompt, negative_prompt=negative_prompt, image=control_image_small, guidance_scale=float(guidance_scale), controlnet_conditioning_scale=float(controlnet_conditioning_scale), generator=generator, control_guidance_start=float(control_guidance_start), control_guidance_end=float(control_guidance_end), num_inference_steps=15, output_type="latent" ) upscaled_latents = upscale(out, "nearest-exact", 2) out_image = image_pipe( prompt=prompt, negative_prompt=negative_prompt, control_image=control_image_large, image=upscaled_latents, guidance_scale=float(guidance_scale), generator=generator, num_inference_steps=20, strength=upscaler_strength, control_guidance_start=float(control_guidance_start), control_guidance_end=float(control_guidance_end), controlnet_conditioning_scale=float(controlnet_conditioning_scale) ) end_time = time.time() end_time_struct = time.localtime(end_time) end_time_formatted = time.strftime("%H:%M:%S", end_time_struct) print(f"Inference ended at {end_time_formatted}, taking {end_time-start_time}s")
# Save image + metadata user_history.save_image( label=prompt, image=out_image["images"][0], profile=profile, metadata={ "prompt": prompt, "negative_prompt": negative_prompt, "guidance_scale": guidance_scale, "controlnet_conditioning_scale": controlnet_conditioning_scale, "control_guidance_start": control_guidance_start, "control_guidance_end": control_guidance_end, "upscaler_strength": upscaler_strength, "seed": seed, "sampler": sampler, }, )
return out_image["images"][0], gr.update(visible=True), gr.update(visible=True), my_seed with gr.Blocks() as app: gr.Markdown( ''' <div style="text-align: center;"> <h1>Illusion Diffusion HQs 🌀</h1> <p style="font-size:16px;">Generate stunning high quality illusion artwork with Stable Diffusion</p> <p>Illusion Diffusion is back up with a safety checker! Because I have been asked, if you would like to support me, consider using <a href="https://abielai.uk.to">abielai.uk.to</a></p> <p>A space by Abiel <a href="https://github.com/Abiel0">Follow on Github</a> with big contributions from <a href="https://twitter.com/multimodalart">multimodalart</a></p> <p>This project works by using <a href="https://huggingface.co/monster-labs/control_v1p_sd15_qrcode_monster">Monster Labs QR Control Net</a>. Given a prompt and your pattern, we use a QR code conditioned controlnet to create a stunning illusion! Credit to: <a href="https://twitter.com/MrUgleh">MrUgleh</a> for discovering the workflow :)</p> </div> ''' )
state_img_input = gr.State() state_img_output = gr.State() with gr.Row(): with gr.Column(): control_image = gr.Image(label="Input Illusion", type="pil", elem_id="control_image") controlnet_conditioning_scale = gr.Slider(minimum=0.0, maximum=5.0, step=0.01, value=0.8, label="Illusion strength", elem_id="illusion_strength", info="ControlNet conditioning scale") gr.Examples(examples=["checkers.png", "checkers_mid.jpg", "pattern.png", "ultra_checkers.png", "spiral.jpeg", "funky.jpeg" ], inputs=control_image) prompt = gr.Textbox(label="Prompt", elem_id="prompt", info="Type what you want to generate", placeholder="Medieval village scene with busy streets and castle in the distance") negative_prompt = gr.Textbox(label="Negative Prompt", info="Type what you don't want to see", value="low quality", elem_id="negative_prompt") with gr.Accordion(label="Advanced Options", open=False): guidance_scale = gr.Slider(minimum=0.0, maximum=50.0, step=0.25, value=7.5, label="Guidance Scale") sampler = gr.Dropdown(choices=list(SAMPLER_MAP.keys()), value="Euler") control_start = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0, label="Start of ControlNet") control_end = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="End of ControlNet") strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="Strength of the upscaler") seed = gr.Slider(minimum=-1, maximum=9999999999, step=1, value=-1, label="Seed", info="-1 means random seed") used_seed = gr.Number(label="Last seed used",interactive=False) run_btn = gr.Button("Run") with gr.Column(): result_image = gr.Image(label="Illusion Diffusion Output", interactive=False, elem_id="output") with gr.Group(elem_id="share-btn-container", visible=False) as share_group: community_icon = gr.HTML(community_icon_html) loading_icon = gr.HTML(loading_icon_html) share_button = gr.Button("Share to community", elem_id="share-btn")
prompt.submit( check_inputs, inputs=[prompt, control_image], queue=False ).success( inference, inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler], outputs=[result_image, result_image, share_group, used_seed]) run_btn.click( check_inputs, inputs=[prompt, control_image], queue=False ).success( inference, inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler], outputs=[result_image, result_image, share_group, used_seed]) share_button.click(None, [], [], js=share_js)
with gr.Blocks(css=css) as app_with_history: with gr.Tab("Demo"): app.render() with gr.Tab("Past generations"): user_history.render()
app_with_history.queue(max_size=20,api_open=False )
if __name__ == "__main__": app_with_history.launch(max_threads=400,share=True)12345678910css='''#share-btn-container {padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; max-width: 13rem; margin-left: auto;}div#share-btn-container > div {flex-direction: row;background: black;align-items: center}#share-btn-container:hover {background-color: #060606}#share-btn {all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.5rem !important; padding-bottom: 0.5rem !important;right:0;}#share-btn * {all: unset}#share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;}#share-btn-container .wrap {display: none !important}#share-btn-container.hidden {display: none!important}'''123456789diffuserstransformersacceleratexformersPillowqrcodefilelock--extra-index-url https://download.pytorch.org/whl/cu118torch123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Copyright 2023 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import numpy as npimport torchimport torch.nn as nnfrom transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel
def cosine_distance(image_embeds, text_embeds): normalized_image_embeds = nn.functional.normalize(image_embeds) normalized_text_embeds = nn.functional.normalize(text_embeds) return torch.mm(normalized_image_embeds, normalized_text_embeds.t())
class StableDiffusionSafetyChecker(PreTrainedModel): config_class = CLIPConfig
_no_split_modules = ["CLIPEncoderLayer"]
def __init__(self, config: CLIPConfig): super().__init__(config)
self.vision_model = CLIPVisionModel(config.vision_config) self.visual_projection = nn.Linear( config.vision_config.hidden_size, config.projection_dim, bias=False )
self.concept_embeds = nn.Parameter( torch.ones(17, config.projection_dim), requires_grad=False ) self.special_care_embeds = nn.Parameter( torch.ones(3, config.projection_dim), requires_grad=False )
self.concept_embeds_weights = nn.Parameter(torch.ones(17), requires_grad=False) self.special_care_embeds_weights = nn.Parameter( torch.ones(3), requires_grad=False )
@torch.no_grad() def forward(self, clip_input, images): pooled_output = self.vision_model(clip_input)[1] # pooled_output image_embeds = self.visual_projection(pooled_output)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 special_cos_dist = ( cosine_distance(image_embeds, self.special_care_embeds) .cpu() .float() .numpy() ) cos_dist = ( cosine_distance(image_embeds, self.concept_embeds).cpu().float().numpy() )
result = [] batch_size = image_embeds.shape[0] for i in range(batch_size): result_img = { "special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": [], }
# increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images adjustment = 0.0
for concept_idx in range(len(special_cos_dist[0])): concept_cos = special_cos_dist[i][concept_idx] concept_threshold = self.special_care_embeds_weights[concept_idx].item() result_img["special_scores"][concept_idx] = round( concept_cos - concept_threshold + adjustment, 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append( {concept_idx, result_img["special_scores"][concept_idx]} ) adjustment = 0.01
for concept_idx in range(len(cos_dist[0])): concept_cos = cos_dist[i][concept_idx] concept_threshold = self.concept_embeds_weights[concept_idx].item() result_img["concept_scores"][concept_idx] = round( concept_cos - concept_threshold + adjustment, 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(concept_idx)
result.append(result_img)
has_nsfw_concepts = [len(res["bad_concepts"]) > 0 for res in result]
return has_nsfw_concepts
@torch.no_grad() def forward_onnx(self, clip_input: torch.FloatTensor, images: torch.FloatTensor): pooled_output = self.vision_model(clip_input)[1] # pooled_output image_embeds = self.visual_projection(pooled_output)
special_cos_dist = cosine_distance(image_embeds, self.special_care_embeds) cos_dist = cosine_distance(image_embeds, self.concept_embeds)
# increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images adjustment = 0.0
special_scores = ( special_cos_dist - self.special_care_embeds_weights + adjustment ) # special_scores = special_scores.round(decimals=3) special_care = torch.any(special_scores > 0, dim=1) special_adjustment = special_care * 0.01 special_adjustment = special_adjustment.unsqueeze(1).expand( -1, cos_dist.shape[1] )
concept_scores = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) has_nsfw_concepts = torch.any(concept_scores > 0, dim=1)
images[has_nsfw_concepts] = 0.0 # black image
return images, has_nsfw_concepts1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"> <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path> <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path></svg>"""
loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin" style="color: #ffffff; " xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
share_js = """async () => { async function uploadFile(file){ const UPLOAD_URL = 'https://huggingface.co/uploads'; const response = await fetch(UPLOAD_URL, { method: 'POST', headers: { 'Content-Type': file.type, 'X-Requested-With': 'XMLHttpRequest', }, body: file, /// <- File inherits from Blob }); const url = await response.text(); return url; } async function getInputImgFile(imgEl){ const res = await fetch(imgEl.src); const blob = await res.blob(); const imgId = Date.now() % 200; const isPng = imgEl.src.startsWith(`data:image/png`); if(isPng){ const fileName = `sd-perception-${{imgId}}.png`; return new File([blob], fileName, { type: 'image/png' }); }else{ const fileName = `sd-perception-${{imgId}}.jpg`; return new File([blob], fileName, { type: 'image/jpeg' }); } } const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app'); const inputPrompt = gradioEl.querySelector('#prompt textarea').value; const negativePrompt = gradioEl.querySelector('#negative_prompt textarea').value; const illusionStrength = gradioEl.querySelector('#illusion_strength input[type="number"]').value; const controlImage = gradioEl.querySelector('#control_image img'); const outputImgEl = gradioEl.querySelector('#output img'); const shareBtnEl = gradioEl.querySelector('#share-btn'); const shareIconEl = gradioEl.querySelector('#share-btn-share-icon'); const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon'); shareBtnEl.style.pointerEvents = 'none'; shareIconEl.style.display = 'none'; loadingIconEl.style.removeProperty('display'); const inputFile = await getInputImgFile(outputImgEl); const urlInputImg = await uploadFile(inputFile);
const controlFile = await getInputImgFile(controlImage); const urlControlImg = await uploadFile(controlFile); const descriptionMd = `### Prompt- *Prompt*: ${inputPrompt}- *Negative prompt*: ${negativePrompt}- *Illusion strength*: ${illusionStrength}#### Generated Image:<img src="${urlInputImg}" />
#### Control Image: <img src="${urlControlImg}" />`; const params = new URLSearchParams({ title: inputPrompt, description: descriptionMd, preview: true }); const paramsStr = params.toString(); window.open(`https://huggingface.co/spaces/AP123/IllusionDiffusion/discussions/new?${paramsStr}`, '_blank'); shareBtnEl.style.removeProperty('pointer-events'); shareIconEl.style.removeProperty('display'); loadingIconEl.style.display = 'none';}"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423"""User History is a plugin that you can add to your Spaces to cache generated images for your users.
Key features:- 🤗 Sign in with Hugging Face- Save generated images with their metadata: prompts, timestamp, hyper-parameters, etc.- Export your history as zip.- Delete your history to respect privacy.- Compatible with Persistent Storage for long-term storage.- Admin panel to check configuration and disk usage .
Useful links:- Demo: https://huggingface.co/spaces/Wauplin/gradio-user-history- README: https://huggingface.co/spaces/Wauplin/gradio-user-history/blob/main/README.md- Source file: https://huggingface.co/spaces/Wauplin/gradio-user-history/blob/main/user_history.py- Discussions: https://huggingface.co/spaces/Wauplin/gradio-user-history/discussions"""import jsonimport osimport shutilimport warningsfrom datetime import datetimefrom functools import cachefrom pathlib import Pathfrom typing import Callable, Dict, List, Tuplefrom uuid import uuid4
import gradio as grimport numpy as npimport requestsfrom filelock import FileLockfrom PIL.Image import Image
def setup(folder_path: str | Path | None = None) -> None: user_history = _UserHistory() user_history.folder_path = _resolve_folder_path(folder_path) user_history.initialized = True
def render() -> None: user_history = _UserHistory()
# initialize with default config if not user_history.initialized: print("Initializing user history with default config. Use `user_history.setup(...)` to customize folder_path.") setup()
# Render user history tab gr.Markdown( "## Your past generations\n\nLog in to keep a gallery of your previous generations. Your history will be saved" " and available on your next visit. Make sure to export your images from time to time as this gallery may be" " deleted in the future." )
if os.getenv("SYSTEM") == "spaces" and not os.path.exists("/data"): gr.Markdown( "**⚠️ Persistent storage is disabled, meaning your history will be lost if the Space gets restarted." " Only the Space owner can setup a Persistent Storage. If you are not the Space owner, consider" " duplicating this Space to set your own storage.⚠️**" )
with gr.Row(): gr.LoginButton(min_width=250) gr.LoginButton(min_width=250) refresh_button = gr.Button( "Refresh", icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_refresh.png", ) export_button = gr.Button( "Export", icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_download.png", ) delete_button = gr.Button( "Delete history", icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_delete.png", )
# "Export zip" row (hidden by default) with gr.Row(): export_file = gr.File(file_count="single", file_types=[".zip"], label="Exported history", visible=False)
# "Config deletion" row (hidden by default) with gr.Row(): confirm_button = gr.Button("Confirm delete all history", variant="stop", visible=False) cancel_button = gr.Button("Cancel", visible=False)
# Gallery gallery = gr.Gallery( label="Past images", show_label=True, elem_id="gallery", object_fit="contain", columns=5, height=600, preview=False, show_share_button=False, show_download_button=False, ) gr.Markdown( "User history is powered by" " [Wauplin/gradio-user-history](https://huggingface.co/spaces/Wauplin/gradio-user-history). Integrate it to" " your own Space in just a few lines of code!" ) gallery.attach_load_event(_fetch_user_history, every=None)
# Interactions refresh_button.click(fn=_fetch_user_history, inputs=[], outputs=[gallery], queue=False) export_button.click(fn=_export_user_history, inputs=[], outputs=[export_file], queue=False)
# Taken from https://github.com/gradio-app/gradio/issues/3324#issuecomment-1446382045 delete_button.click( lambda: [gr.update(visible=True), gr.update(visible=True)], outputs=[confirm_button, cancel_button], queue=False, ) cancel_button.click( lambda: [gr.update(visible=False), gr.update(visible=False)], outputs=[confirm_button, cancel_button], queue=False, ) confirm_button.click(_delete_user_history).then( lambda: [gr.update(visible=False), gr.update(visible=False)], outputs=[confirm_button, cancel_button], queue=False, )
# Admin section (only shown locally or when logged in as Space owner) _admin_section()
def save_image( profile: gr.OAuthProfile | None, image: Image | np.ndarray | str | Path, label: str | None = None, metadata: Dict | None = None,): # Ignore images from logged out users if profile is None: return username = profile["preferred_username"]
# Ignore images if user history not used user_history = _UserHistory() if not user_history.initialized: warnings.warn( "User history is not set in Gradio demo. Saving image is ignored. You must use `user_history.render(...)`" " first." ) return
# Copy image to storage image_path = _copy_image(image, dst_folder=user_history._user_images_path(username))
# Save new image + metadata if metadata is None: metadata = {} if "datetime" not in metadata: metadata["datetime"] = str(datetime.now()) data = {"path": str(image_path), "label": label, "metadata": metadata} with user_history._user_lock(username): with user_history._user_jsonl_path(username).open("a") as f: f.write(json.dumps(data) + "\n")
############## Internals ##############
class _UserHistory(object): _instance = None initialized: bool = False folder_path: Path
def __new__(cls): # Using singleton pattern => we don't want to expose an object (more complex to use) but still want to keep # state between `render` and `save_image` calls. if cls._instance is None: cls._instance = super(_UserHistory, cls).__new__(cls) return cls._instance
def _user_path(self, username: str) -> Path: path = self.folder_path / username path.mkdir(parents=True, exist_ok=True) return path
def _user_lock(self, username: str) -> FileLock: """Ensure history is not corrupted if concurrent calls.""" return FileLock(self.folder_path / f"{username}.lock") # lock outside of folder => better when exporting ZIP
def _user_jsonl_path(self, username: str) -> Path: return self._user_path(username) / "history.jsonl"
def _user_images_path(self, username: str) -> Path: path = self._user_path(username) / "images" path.mkdir(parents=True, exist_ok=True) return path
def _fetch_user_history(profile: gr.OAuthProfile | None) -> List[Tuple[str, str]]: """Return saved history for that user, if it exists.""" # Cannot load history for logged out users if profile is None: return [] username = profile["preferred_username"]
user_history = _UserHistory() if not user_history.initialized: warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.") return []
with user_history._user_lock(username): # No file => no history saved yet jsonl_path = user_history._user_jsonl_path(username) if not jsonl_path.is_file(): return []
# Read history images = [] for line in jsonl_path.read_text().splitlines(): data = json.loads(line) images.append((data["path"], data["label"] or "")) return list(reversed(images))
def _export_user_history(profile: gr.OAuthProfile | None) -> Dict | None: """Zip all history for that user, if it exists and return it as a downloadable file.""" # Cannot load history for logged out users if profile is None: return None username = profile["preferred_username"]
user_history = _UserHistory() if not user_history.initialized: warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.") return None
# Zip history with user_history._user_lock(username): path = shutil.make_archive( str(_archives_path() / f"history_{username}"), "zip", user_history._user_path(username) )
return gr.update(visible=True, value=path)
def _delete_user_history(profile: gr.OAuthProfile | None) -> None: """Delete all history for that user.""" # Cannot load history for logged out users if profile is None: return username = profile["preferred_username"]
user_history = _UserHistory() if not user_history.initialized: warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.") return
with user_history._user_lock(username): shutil.rmtree(user_history._user_path(username))
##################### Internal helpers #####################
def _copy_image(image: Image | np.ndarray | str | Path, dst_folder: Path) -> Path: """Copy image to the images folder.""" # Already a path => copy it if isinstance(image, str): image = Path(image) if isinstance(image, Path): dst = dst_folder / f"{uuid4().hex}_{Path(image).name}" # keep file ext shutil.copyfile(image, dst) return dst
# Still a Python object => serialize it if isinstance(image, np.ndarray): image = Image.fromarray(image) if isinstance(image, Image): dst = dst_folder / f"{uuid4().hex}.png" image.save(dst) return dst
raise ValueError(f"Unsupported image type: {type(image)}")
def _resolve_folder_path(folder_path: str | Path | None) -> Path: if folder_path is not None: return Path(folder_path).expanduser().resolve()
if os.getenv("SYSTEM") == "spaces" and os.path.exists("/data"): # Persistent storage is enabled! return Path("/data") / "_user_history"
# Not in a Space or Persistent storage not enabled => local folder return Path(__file__).parent / "_user_history"
def _archives_path() -> Path: # Doesn't have to be on persistent storage as it's only used for download path = Path(__file__).parent / "_user_history_exports" path.mkdir(parents=True, exist_ok=True) return path
################## Admin section ##################
def _admin_section() -> None: title = gr.Markdown() title.attach_load_event(_display_if_admin(), every=None)
def _display_if_admin() -> Callable: def _inner(profile: gr.OAuthProfile | None) -> str: if profile is None: return "" if profile["preferred_username"] in _fetch_admins(): return _admin_content() return ""
return _inner
def _admin_content() -> str: return f"""## Admin section
Running on **{os.getenv("SYSTEM", "local")}** (id: {os.getenv("SPACE_ID")}). {_get_msg_is_persistent_storage_enabled()}
Admins: {', '.join(_fetch_admins())}
{_get_nb_users()} user(s), {_get_nb_images()} image(s)
### Configuration
History folder: *{_UserHistory().folder_path}*
Exports folder: *{_archives_path()}*
### Disk usage
{_disk_space_warning_message()}"""
def _get_nb_users() -> int: user_history = _UserHistory() if not user_history.initialized: return 0 if user_history.folder_path is not None and user_history.folder_path.exists(): return len([path for path in user_history.folder_path.iterdir() if path.is_dir()]) return 0
def _get_nb_images() -> int: user_history = _UserHistory() if not user_history.initialized: return 0 if user_history.folder_path is not None and user_history.folder_path.exists(): return len([path for path in user_history.folder_path.glob("*/images/*")]) return 0
def _get_msg_is_persistent_storage_enabled() -> str: if os.getenv("SYSTEM") == "spaces": if os.path.exists("/data"): return "Persistent storage is enabled." else: return ( "Persistent storage is not enabled. This means that user histories will be deleted when the Space is" " restarted. Consider adding a Persistent Storage in your Space settings." ) return ""
def _disk_space_warning_message() -> str: user_history = _UserHistory() if not user_history.initialized: return ""
message = "" if user_history.folder_path is not None: total, used, _ = _get_disk_usage(user_history.folder_path) message += f"History folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
total, used, _ = _get_disk_usage(_archives_path()) message += f"\n\nExports folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
return f"{message.strip()}"
def _get_disk_usage(path: Path) -> Tuple[int, int, int]: for path in [path] + list(path.parents): # first check target_dir, then each parents one by one try: return shutil.disk_usage(path) except OSError: # if doesn't exist or can't read => fail silently and try parent one pass return 0, 0, 0
@cachedef _fetch_admins() -> List[str]: # Running locally => fake user is admin if os.getenv("SYSTEM") != "spaces": return ["FakeGradioUser"]
# Running in Space but no space_id => ??? space_id = os.getenv("SPACE_ID") if space_id is None: return ["Unknown"]
# Running in Space => try to fetch organization members # Otherwise, it's not an organization => namespace is the user namespace = space_id.split("/")[0] response = requests.get(f"https://huggingface.co/api/organizations/{namespace}/members") if response.status_code == 200: return sorted((member["user"] for member in response.json()), key=lambda x: x.lower()) return [namespace]README.md+10-6
app.pyAdded+288
checkers.pngAdded

checkers_mid.jpgAdded

funky.jpegAdded

illusion_style.pyAdded+10
pattern.pngAdded

requirements.txtAdded+9
safety_checker.pyAdded+137
share_btn.pyAdded+83
spiral.jpegAdded

ultra_checkers.pngAdded

user_history.pyAdded+423