Spaces:
Runtime error
Runtime error
spzla
commited on
Commit
Β·
1dd85d4
1
Parent(s):
b37dc57
glob
Browse files- README.md +8 -5
- app.py +281 -0
- checkers.png +0 -0
- checkers_mid.jpg +0 -0
- funky.jpeg +0 -0
- illusion_style.py +10 -0
- pattern.png +0 -0
- requirements.txt +11 -0
- share_btn.py +83 -0
- spiral.jpeg +0 -0
- ultra_checkers.png +0 -0
- user_history.py +423 -0
README.md
CHANGED
@@ -1,12 +1,15 @@
|
|
1 |
---
|
2 |
title: IllusionDiffusion
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 3.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
|
|
|
|
|
|
10 |
---
|
11 |
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
title: IllusionDiffusion
|
3 |
+
emoji: π
|
4 |
+
colorFrom: red
|
5 |
+
colorTo: pink
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.44.3
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
license: openrail
|
11 |
+
hf_oauth: true
|
12 |
+
disable_embedding: true
|
13 |
---
|
14 |
|
15 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
from gradio import processing_utils, utils
|
4 |
+
from PIL import Image
|
5 |
+
import random
|
6 |
+
from diffusers import (
|
7 |
+
DiffusionPipeline,
|
8 |
+
AutoencoderKL,
|
9 |
+
StableDiffusionControlNetPipeline,
|
10 |
+
ControlNetModel,
|
11 |
+
StableDiffusionLatentUpscalePipeline,
|
12 |
+
StableDiffusionImg2ImgPipeline,
|
13 |
+
StableDiffusionControlNetImg2ImgPipeline,
|
14 |
+
DPMSolverMultistepScheduler, # <-- Added import
|
15 |
+
EulerDiscreteScheduler # <-- Added import
|
16 |
+
)
|
17 |
+
import time
|
18 |
+
from share_btn import community_icon_html, loading_icon_html, share_js
|
19 |
+
import user_history
|
20 |
+
from illusion_style import css
|
21 |
+
|
22 |
+
BASE_MODEL = "SG161222/Realistic_Vision_V5.1_noVAE"
|
23 |
+
|
24 |
+
# Initialize both pipelines
|
25 |
+
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
|
26 |
+
#init_pipe = DiffusionPipeline.from_pretrained("SG161222/Realistic_Vision_V5.1_noVAE", torch_dtype=torch.float16)
|
27 |
+
controlnet = ControlNetModel.from_pretrained("monster-labs/control_v1p_sd15_qrcode_monster", torch_dtype=torch.float16)#, torch_dtype=torch.float16)
|
28 |
+
main_pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
29 |
+
BASE_MODEL,
|
30 |
+
controlnet=controlnet,
|
31 |
+
vae=vae,
|
32 |
+
safety_checker=None,
|
33 |
+
torch_dtype=torch.float16,
|
34 |
+
).to("cuda")
|
35 |
+
|
36 |
+
#main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
37 |
+
#main_pipe.unet.to(memory_format=torch.channels_last)
|
38 |
+
#main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
39 |
+
#model_id = "stabilityai/sd-x2-latent-upscaler"
|
40 |
+
image_pipe = StableDiffusionControlNetImg2ImgPipeline(**main_pipe.components)
|
41 |
+
|
42 |
+
#image_pipe.unet = torch.compile(image_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
43 |
+
#upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
44 |
+
#upscaler.to("cuda")
|
45 |
+
|
46 |
+
|
47 |
+
# Sampler map
|
48 |
+
SAMPLER_MAP = {
|
49 |
+
"DPM++ Karras SDE": lambda config: DPMSolverMultistepScheduler.from_config(config, use_karras=True, algorithm_type="sde-dpmsolver++"),
|
50 |
+
"Euler": lambda config: EulerDiscreteScheduler.from_config(config),
|
51 |
+
}
|
52 |
+
|
53 |
+
def center_crop_resize(img, output_size=(512, 512)):
|
54 |
+
width, height = img.size
|
55 |
+
|
56 |
+
# Calculate dimensions to crop to the center
|
57 |
+
new_dimension = min(width, height)
|
58 |
+
left = (width - new_dimension)/2
|
59 |
+
top = (height - new_dimension)/2
|
60 |
+
right = (width + new_dimension)/2
|
61 |
+
bottom = (height + new_dimension)/2
|
62 |
+
|
63 |
+
# Crop and resize
|
64 |
+
img = img.crop((left, top, right, bottom))
|
65 |
+
img = img.resize(output_size)
|
66 |
+
|
67 |
+
return img
|
68 |
+
|
69 |
+
def common_upscale(samples, width, height, upscale_method, crop=False):
|
70 |
+
if crop == "center":
|
71 |
+
old_width = samples.shape[3]
|
72 |
+
old_height = samples.shape[2]
|
73 |
+
old_aspect = old_width / old_height
|
74 |
+
new_aspect = width / height
|
75 |
+
x = 0
|
76 |
+
y = 0
|
77 |
+
if old_aspect > new_aspect:
|
78 |
+
x = round((old_width - old_width * (new_aspect / old_aspect)) / 2)
|
79 |
+
elif old_aspect < new_aspect:
|
80 |
+
y = round((old_height - old_height * (old_aspect / new_aspect)) / 2)
|
81 |
+
s = samples[:,:,y:old_height-y,x:old_width-x]
|
82 |
+
else:
|
83 |
+
s = samples
|
84 |
+
|
85 |
+
return torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method)
|
86 |
+
|
87 |
+
def upscale(samples, upscale_method, scale_by):
|
88 |
+
#s = samples.copy()
|
89 |
+
width = round(samples["images"].shape[3] * scale_by)
|
90 |
+
height = round(samples["images"].shape[2] * scale_by)
|
91 |
+
s = common_upscale(samples["images"], width, height, upscale_method, "disabled")
|
92 |
+
return (s)
|
93 |
+
|
94 |
+
def check_inputs(prompt: str, control_image: Image.Image):
|
95 |
+
if control_image is None:
|
96 |
+
raise gr.Error("Please select or upload an Input Illusion")
|
97 |
+
if prompt is None or prompt == "":
|
98 |
+
raise gr.Error("Prompt is required")
|
99 |
+
|
100 |
+
def convert_to_pil(base64_image):
|
101 |
+
pil_image = processing_utils.decode_base64_to_image(base64_image)
|
102 |
+
return pil_image
|
103 |
+
|
104 |
+
def convert_to_base64(pil_image):
|
105 |
+
base64_image = processing_utils.encode_pil_to_base64(pil_image)
|
106 |
+
return base64_image
|
107 |
+
|
108 |
+
# Inference function
|
109 |
+
def inference(
|
110 |
+
control_image: Image.Image,
|
111 |
+
prompt: str,
|
112 |
+
negative_prompt: str,
|
113 |
+
guidance_scale: float = 8.0,
|
114 |
+
controlnet_conditioning_scale: float = 1,
|
115 |
+
control_guidance_start: float = 1,
|
116 |
+
control_guidance_end: float = 1,
|
117 |
+
upscaler_strength: float = 0.5,
|
118 |
+
seed: int = -1,
|
119 |
+
sampler = "DPM++ Karras SDE",
|
120 |
+
progress = gr.Progress(track_tqdm=True),
|
121 |
+
profile: gr.OAuthProfile | None = None,
|
122 |
+
):
|
123 |
+
start_time = time.time()
|
124 |
+
start_time_struct = time.localtime(start_time)
|
125 |
+
start_time_formatted = time.strftime("%H:%M:%S", start_time_struct)
|
126 |
+
print(f"Inference started at {start_time_formatted}")
|
127 |
+
|
128 |
+
# Generate the initial image
|
129 |
+
#init_image = init_pipe(prompt).images[0]
|
130 |
+
|
131 |
+
# Rest of your existing code
|
132 |
+
control_image_small = center_crop_resize(control_image)
|
133 |
+
control_image_large = center_crop_resize(control_image, (1024, 1024))
|
134 |
+
|
135 |
+
main_pipe.scheduler = SAMPLER_MAP[sampler](main_pipe.scheduler.config)
|
136 |
+
my_seed = random.randint(0, 2**32 - 1) if seed == -1 else seed
|
137 |
+
generator = torch.Generator(device="cuda").manual_seed(my_seed)
|
138 |
+
|
139 |
+
out = main_pipe(
|
140 |
+
prompt=prompt,
|
141 |
+
negative_prompt=negative_prompt,
|
142 |
+
image=control_image_small,
|
143 |
+
guidance_scale=float(guidance_scale),
|
144 |
+
controlnet_conditioning_scale=float(controlnet_conditioning_scale),
|
145 |
+
generator=generator,
|
146 |
+
control_guidance_start=float(control_guidance_start),
|
147 |
+
control_guidance_end=float(control_guidance_end),
|
148 |
+
num_inference_steps=15,
|
149 |
+
output_type="latent"
|
150 |
+
)
|
151 |
+
upscaled_latents = upscale(out, "nearest-exact", 2)
|
152 |
+
out_image = image_pipe(
|
153 |
+
prompt=prompt,
|
154 |
+
negative_prompt=negative_prompt,
|
155 |
+
control_image=control_image_large,
|
156 |
+
image=upscaled_latents,
|
157 |
+
guidance_scale=float(guidance_scale),
|
158 |
+
generator=generator,
|
159 |
+
num_inference_steps=20,
|
160 |
+
strength=upscaler_strength,
|
161 |
+
control_guidance_start=float(control_guidance_start),
|
162 |
+
control_guidance_end=float(control_guidance_end),
|
163 |
+
controlnet_conditioning_scale=float(controlnet_conditioning_scale)
|
164 |
+
)
|
165 |
+
end_time = time.time()
|
166 |
+
end_time_struct = time.localtime(end_time)
|
167 |
+
end_time_formatted = time.strftime("%H:%M:%S", end_time_struct)
|
168 |
+
print(f"Inference ended at {end_time_formatted}, taking {end_time-start_time}s")
|
169 |
+
|
170 |
+
# Save image + metadata
|
171 |
+
user_history.save_image(
|
172 |
+
label=prompt,
|
173 |
+
image=out_image["images"][0],
|
174 |
+
profile=profile,
|
175 |
+
metadata={
|
176 |
+
"prompt": prompt,
|
177 |
+
"negative_prompt": negative_prompt,
|
178 |
+
"guidance_scale": guidance_scale,
|
179 |
+
"controlnet_conditioning_scale": controlnet_conditioning_scale,
|
180 |
+
"control_guidance_start": control_guidance_start,
|
181 |
+
"control_guidance_end": control_guidance_end,
|
182 |
+
"upscaler_strength": upscaler_strength,
|
183 |
+
"seed": seed,
|
184 |
+
"sampler": sampler,
|
185 |
+
},
|
186 |
+
)
|
187 |
+
|
188 |
+
return out_image["images"][0], gr.update(visible=True), gr.update(visible=True), my_seed
|
189 |
+
|
190 |
+
with gr.Blocks() as app:
|
191 |
+
gr.Markdown(
|
192 |
+
'''
|
193 |
+
<center><h1>Illusion Diffusion HQ π</h1></span>
|
194 |
+
<span font-size:16px;">Generate stunning high quality illusion artwork with Stable Diffusion</span>
|
195 |
+
</center>
|
196 |
+
|
197 |
+
A space by AP [Follow me on Twitter](https://twitter.com/angrypenguinPNG) with big contributions from [multimodalart](https://twitter.com/multimodalart)
|
198 |
+
|
199 |
+
This project works by using [Monster Labs QR Control Net](https://huggingface.co/monster-labs/control_v1p_sd15_qrcode_monster).
|
200 |
+
Given a prompt and your pattern, we use a QR code conditioned controlnet to create a stunning illusion! Credit to: [MrUgleh](https://twitter.com/MrUgleh) for discovering the workflow :)
|
201 |
+
'''
|
202 |
+
)
|
203 |
+
state_img_input = gr.State()
|
204 |
+
state_img_output = gr.State()
|
205 |
+
with gr.Row():
|
206 |
+
with gr.Column():
|
207 |
+
control_image = gr.Image(label="Input Illusion", type="pil", elem_id="control_image")
|
208 |
+
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")
|
209 |
+
gr.Examples(examples=["checkers.png", "checkers_mid.jpg", "pattern.png", "ultra_checkers.png", "spiral.jpeg", "funky.jpeg" ], inputs=control_image)
|
210 |
+
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")
|
211 |
+
negative_prompt = gr.Textbox(label="Negative Prompt", info="Type what you don't want to see", value="low quality", elem_id="negative_prompt")
|
212 |
+
with gr.Accordion(label="Advanced Options", open=False):
|
213 |
+
guidance_scale = gr.Slider(minimum=0.0, maximum=50.0, step=0.25, value=7.5, label="Guidance Scale")
|
214 |
+
sampler = gr.Dropdown(choices=list(SAMPLER_MAP.keys()), value="Euler")
|
215 |
+
control_start = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0, label="Start of ControlNet")
|
216 |
+
control_end = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="End of ControlNet")
|
217 |
+
strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="Strength of the upscaler")
|
218 |
+
seed = gr.Slider(minimum=-1, maximum=9999999999, step=1, value=-1, label="Seed", info="-1 means random seed")
|
219 |
+
used_seed = gr.Number(label="Last seed used",interactive=False)
|
220 |
+
run_btn = gr.Button("Run")
|
221 |
+
with gr.Column():
|
222 |
+
result_image = gr.Image(label="Illusion Diffusion Output", interactive=False, elem_id="output")
|
223 |
+
with gr.Group(elem_id="share-btn-container", visible=False) as share_group:
|
224 |
+
community_icon = gr.HTML(community_icon_html)
|
225 |
+
loading_icon = gr.HTML(loading_icon_html)
|
226 |
+
share_button = gr.Button("Share to community", elem_id="share-btn")
|
227 |
+
|
228 |
+
prompt.submit(
|
229 |
+
check_inputs,
|
230 |
+
inputs=[prompt, control_image],
|
231 |
+
queue=False
|
232 |
+
).success(
|
233 |
+
convert_to_pil,
|
234 |
+
inputs=[control_image],
|
235 |
+
outputs=[state_img_input],
|
236 |
+
queue=False,
|
237 |
+
preprocess=False,
|
238 |
+
).success(
|
239 |
+
inference,
|
240 |
+
inputs=[state_img_input, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler],
|
241 |
+
outputs=[state_img_output, result_image, share_group, used_seed]
|
242 |
+
).success(
|
243 |
+
convert_to_base64,
|
244 |
+
inputs=[state_img_output],
|
245 |
+
outputs=[result_image],
|
246 |
+
queue=False,
|
247 |
+
postprocess=False
|
248 |
+
)
|
249 |
+
run_btn.click(
|
250 |
+
check_inputs,
|
251 |
+
inputs=[prompt, control_image],
|
252 |
+
queue=False
|
253 |
+
).success(
|
254 |
+
convert_to_pil,
|
255 |
+
inputs=[control_image],
|
256 |
+
outputs=[state_img_input],
|
257 |
+
queue=False,
|
258 |
+
preprocess=False,
|
259 |
+
).success(
|
260 |
+
inference,
|
261 |
+
inputs=[state_img_input, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler],
|
262 |
+
outputs=[state_img_output, result_image, share_group, used_seed]
|
263 |
+
).success(
|
264 |
+
convert_to_base64,
|
265 |
+
inputs=[state_img_output],
|
266 |
+
outputs=[result_image],
|
267 |
+
queue=False,
|
268 |
+
postprocess=False
|
269 |
+
)
|
270 |
+
share_button.click(None, [], [], _js=share_js)
|
271 |
+
|
272 |
+
with gr.Blocks(css=css) as app_with_history:
|
273 |
+
with gr.Tab("Demo"):
|
274 |
+
app.render()
|
275 |
+
with gr.Tab("Past generations"):
|
276 |
+
user_history.render()
|
277 |
+
|
278 |
+
app_with_history.queue(max_size=20,api_open=False )
|
279 |
+
|
280 |
+
if __name__ == "__main__":
|
281 |
+
app_with_history.launch(max_threads=400)
|
checkers.png
ADDED
checkers_mid.jpg
ADDED
funky.jpeg
ADDED
illusion_style.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
css='''
|
2 |
+
#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;}
|
3 |
+
div#share-btn-container > div {flex-direction: row;background: black;align-items: center}
|
4 |
+
#share-btn-container:hover {background-color: #060606}
|
5 |
+
#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;}
|
6 |
+
#share-btn * {all: unset}
|
7 |
+
#share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;}
|
8 |
+
#share-btn-container .wrap {display: none !important}
|
9 |
+
#share-btn-container.hidden {display: none!important}
|
10 |
+
'''
|
pattern.png
ADDED
requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
diffusers
|
2 |
+
transformers
|
3 |
+
accelerate
|
4 |
+
xformers
|
5 |
+
gradio
|
6 |
+
Pillow
|
7 |
+
qrcode
|
8 |
+
filelock
|
9 |
+
https://gradio-builds.s3.amazonaws.com/52ceac5ecd12fa0990273dcb69c899abfb9c6a27/gradio-3.45.1-py3-none-any.whl
|
10 |
+
--extra-index-url https://download.pytorch.org/whl/cu118
|
11 |
+
torch
|
share_btn.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
community_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">
|
2 |
+
<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>
|
3 |
+
<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>
|
4 |
+
</svg>"""
|
5 |
+
|
6 |
+
loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
|
7 |
+
style="color: #ffffff;
|
8 |
+
"
|
9 |
+
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>"""
|
10 |
+
|
11 |
+
share_js = """async () => {
|
12 |
+
async function uploadFile(file){
|
13 |
+
const UPLOAD_URL = 'https://huggingface.co/uploads';
|
14 |
+
const response = await fetch(UPLOAD_URL, {
|
15 |
+
method: 'POST',
|
16 |
+
headers: {
|
17 |
+
'Content-Type': file.type,
|
18 |
+
'X-Requested-With': 'XMLHttpRequest',
|
19 |
+
},
|
20 |
+
body: file, /// <- File inherits from Blob
|
21 |
+
});
|
22 |
+
const url = await response.text();
|
23 |
+
return url;
|
24 |
+
}
|
25 |
+
|
26 |
+
async function getInputImgFile(imgEl){
|
27 |
+
const res = await fetch(imgEl.src);
|
28 |
+
const blob = await res.blob();
|
29 |
+
const imgId = Date.now() % 200;
|
30 |
+
const isPng = imgEl.src.startsWith(`data:image/png`);
|
31 |
+
if(isPng){
|
32 |
+
const fileName = `sd-perception-${{imgId}}.png`;
|
33 |
+
return new File([blob], fileName, { type: 'image/png' });
|
34 |
+
}else{
|
35 |
+
const fileName = `sd-perception-${{imgId}}.jpg`;
|
36 |
+
return new File([blob], fileName, { type: 'image/jpeg' });
|
37 |
+
}
|
38 |
+
}
|
39 |
+
|
40 |
+
const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
|
41 |
+
|
42 |
+
const inputPrompt = gradioEl.querySelector('#prompt textarea').value;
|
43 |
+
const negativePrompt = gradioEl.querySelector('#negative_prompt textarea').value;
|
44 |
+
const illusionStrength = gradioEl.querySelector('#illusion_strength input[type="number"]').value;
|
45 |
+
const controlImage = gradioEl.querySelector('#control_image img');
|
46 |
+
const outputImgEl = gradioEl.querySelector('#output img');
|
47 |
+
|
48 |
+
const shareBtnEl = gradioEl.querySelector('#share-btn');
|
49 |
+
const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
|
50 |
+
const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
|
51 |
+
|
52 |
+
shareBtnEl.style.pointerEvents = 'none';
|
53 |
+
shareIconEl.style.display = 'none';
|
54 |
+
loadingIconEl.style.removeProperty('display');
|
55 |
+
|
56 |
+
const inputFile = await getInputImgFile(outputImgEl);
|
57 |
+
const urlInputImg = await uploadFile(inputFile);
|
58 |
+
|
59 |
+
const controlFile = await getInputImgFile(controlImage);
|
60 |
+
const urlControlImg = await uploadFile(controlFile);
|
61 |
+
|
62 |
+
const descriptionMd = `
|
63 |
+
### Prompt
|
64 |
+
- *Prompt*: ${inputPrompt}
|
65 |
+
- *Negative prompt*: ${negativePrompt}
|
66 |
+
- *Illusion strength*: ${illusionStrength}
|
67 |
+
#### Generated Image:
|
68 |
+
<img src="${urlInputImg}" />
|
69 |
+
|
70 |
+
#### Control Image:
|
71 |
+
<img src="${urlControlImg}" />
|
72 |
+
`;
|
73 |
+
const params = new URLSearchParams({
|
74 |
+
title: inputPrompt,
|
75 |
+
description: descriptionMd,
|
76 |
+
preview: true
|
77 |
+
});
|
78 |
+
const paramsStr = params.toString();
|
79 |
+
window.open(`https://huggingface.co/spaces/AP123/IllusionDiffusion/discussions/new?${paramsStr}`, '_blank');
|
80 |
+
shareBtnEl.style.removeProperty('pointer-events');
|
81 |
+
shareIconEl.style.removeProperty('display');
|
82 |
+
loadingIconEl.style.display = 'none';
|
83 |
+
}"""
|
spiral.jpeg
ADDED
ultra_checkers.png
ADDED
user_history.py
ADDED
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
User History is a plugin that you can add to your Spaces to cache generated images for your users.
|
3 |
+
|
4 |
+
Key features:
|
5 |
+
- π€ Sign in with Hugging Face
|
6 |
+
- Save generated images with their metadata: prompts, timestamp, hyper-parameters, etc.
|
7 |
+
- Export your history as zip.
|
8 |
+
- Delete your history to respect privacy.
|
9 |
+
- Compatible with Persistent Storage for long-term storage.
|
10 |
+
- Admin panel to check configuration and disk usage .
|
11 |
+
|
12 |
+
Useful links:
|
13 |
+
- Demo: https://huggingface.co/spaces/Wauplin/gradio-user-history
|
14 |
+
- README: https://huggingface.co/spaces/Wauplin/gradio-user-history/blob/main/README.md
|
15 |
+
- Source file: https://huggingface.co/spaces/Wauplin/gradio-user-history/blob/main/user_history.py
|
16 |
+
- Discussions: https://huggingface.co/spaces/Wauplin/gradio-user-history/discussions
|
17 |
+
"""
|
18 |
+
import json
|
19 |
+
import os
|
20 |
+
import shutil
|
21 |
+
import warnings
|
22 |
+
from datetime import datetime
|
23 |
+
from functools import cache
|
24 |
+
from pathlib import Path
|
25 |
+
from typing import Callable, Dict, List, Tuple
|
26 |
+
from uuid import uuid4
|
27 |
+
|
28 |
+
import gradio as gr
|
29 |
+
import numpy as np
|
30 |
+
import requests
|
31 |
+
from filelock import FileLock
|
32 |
+
from PIL.Image import Image
|
33 |
+
|
34 |
+
|
35 |
+
def setup(folder_path: str | Path | None = None) -> None:
|
36 |
+
user_history = _UserHistory()
|
37 |
+
user_history.folder_path = _resolve_folder_path(folder_path)
|
38 |
+
user_history.initialized = True
|
39 |
+
|
40 |
+
|
41 |
+
def render() -> None:
|
42 |
+
user_history = _UserHistory()
|
43 |
+
|
44 |
+
# initialize with default config
|
45 |
+
if not user_history.initialized:
|
46 |
+
print("Initializing user history with default config. Use `user_history.setup(...)` to customize folder_path.")
|
47 |
+
setup()
|
48 |
+
|
49 |
+
# Render user history tab
|
50 |
+
gr.Markdown(
|
51 |
+
"## Your past generations\n\nLog in to keep a gallery of your previous generations. Your history will be saved"
|
52 |
+
" and available on your next visit. Make sure to export your images from time to time as this gallery may be"
|
53 |
+
" deleted in the future."
|
54 |
+
)
|
55 |
+
|
56 |
+
if os.getenv("SYSTEM") == "spaces" and not os.path.exists("/data"):
|
57 |
+
gr.Markdown(
|
58 |
+
"**β οΈ Persistent storage is disabled, meaning your history will be lost if the Space gets restarted."
|
59 |
+
" Only the Space owner can setup a Persistent Storage. If you are not the Space owner, consider"
|
60 |
+
" duplicating this Space to set your own storage.β οΈ**"
|
61 |
+
)
|
62 |
+
|
63 |
+
with gr.Row():
|
64 |
+
gr.LoginButton(min_width=250)
|
65 |
+
gr.LogoutButton(min_width=250)
|
66 |
+
refresh_button = gr.Button(
|
67 |
+
"Refresh",
|
68 |
+
icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_refresh.png",
|
69 |
+
)
|
70 |
+
export_button = gr.Button(
|
71 |
+
"Export",
|
72 |
+
icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_download.png",
|
73 |
+
)
|
74 |
+
delete_button = gr.Button(
|
75 |
+
"Delete history",
|
76 |
+
icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_delete.png",
|
77 |
+
)
|
78 |
+
|
79 |
+
# "Export zip" row (hidden by default)
|
80 |
+
with gr.Row():
|
81 |
+
export_file = gr.File(file_count="single", file_types=[".zip"], label="Exported history", visible=False)
|
82 |
+
|
83 |
+
# "Config deletion" row (hidden by default)
|
84 |
+
with gr.Row():
|
85 |
+
confirm_button = gr.Button("Confirm delete all history", variant="stop", visible=False)
|
86 |
+
cancel_button = gr.Button("Cancel", visible=False)
|
87 |
+
|
88 |
+
# Gallery
|
89 |
+
gallery = gr.Gallery(
|
90 |
+
label="Past images",
|
91 |
+
show_label=True,
|
92 |
+
elem_id="gallery",
|
93 |
+
object_fit="contain",
|
94 |
+
columns=5,
|
95 |
+
height=600,
|
96 |
+
preview=False,
|
97 |
+
show_share_button=False,
|
98 |
+
show_download_button=False,
|
99 |
+
)
|
100 |
+
gr.Markdown(
|
101 |
+
"User history is powered by"
|
102 |
+
" [Wauplin/gradio-user-history](https://huggingface.co/spaces/Wauplin/gradio-user-history). Integrate it to"
|
103 |
+
" your own Space in just a few lines of code!"
|
104 |
+
)
|
105 |
+
gallery.attach_load_event(_fetch_user_history, every=None)
|
106 |
+
|
107 |
+
# Interactions
|
108 |
+
refresh_button.click(fn=_fetch_user_history, inputs=[], outputs=[gallery], queue=False)
|
109 |
+
export_button.click(fn=_export_user_history, inputs=[], outputs=[export_file], queue=False)
|
110 |
+
|
111 |
+
# Taken from https://github.com/gradio-app/gradio/issues/3324#issuecomment-1446382045
|
112 |
+
delete_button.click(
|
113 |
+
lambda: [gr.update(visible=True), gr.update(visible=True)],
|
114 |
+
outputs=[confirm_button, cancel_button],
|
115 |
+
queue=False,
|
116 |
+
)
|
117 |
+
cancel_button.click(
|
118 |
+
lambda: [gr.update(visible=False), gr.update(visible=False)],
|
119 |
+
outputs=[confirm_button, cancel_button],
|
120 |
+
queue=False,
|
121 |
+
)
|
122 |
+
confirm_button.click(_delete_user_history).then(
|
123 |
+
lambda: [gr.update(visible=False), gr.update(visible=False)],
|
124 |
+
outputs=[confirm_button, cancel_button],
|
125 |
+
queue=False,
|
126 |
+
)
|
127 |
+
|
128 |
+
# Admin section (only shown locally or when logged in as Space owner)
|
129 |
+
_admin_section()
|
130 |
+
|
131 |
+
|
132 |
+
def save_image(
|
133 |
+
profile: gr.OAuthProfile | None,
|
134 |
+
image: Image | np.ndarray | str | Path,
|
135 |
+
label: str | None = None,
|
136 |
+
metadata: Dict | None = None,
|
137 |
+
):
|
138 |
+
# Ignore images from logged out users
|
139 |
+
if profile is None:
|
140 |
+
return
|
141 |
+
username = profile["preferred_username"]
|
142 |
+
|
143 |
+
# Ignore images if user history not used
|
144 |
+
user_history = _UserHistory()
|
145 |
+
if not user_history.initialized:
|
146 |
+
warnings.warn(
|
147 |
+
"User history is not set in Gradio demo. Saving image is ignored. You must use `user_history.render(...)`"
|
148 |
+
" first."
|
149 |
+
)
|
150 |
+
return
|
151 |
+
|
152 |
+
# Copy image to storage
|
153 |
+
image_path = _copy_image(image, dst_folder=user_history._user_images_path(username))
|
154 |
+
|
155 |
+
# Save new image + metadata
|
156 |
+
if metadata is None:
|
157 |
+
metadata = {}
|
158 |
+
if "datetime" not in metadata:
|
159 |
+
metadata["datetime"] = str(datetime.now())
|
160 |
+
data = {"path": str(image_path), "label": label, "metadata": metadata}
|
161 |
+
with user_history._user_lock(username):
|
162 |
+
with user_history._user_jsonl_path(username).open("a") as f:
|
163 |
+
f.write(json.dumps(data) + "\n")
|
164 |
+
|
165 |
+
|
166 |
+
#############
|
167 |
+
# Internals #
|
168 |
+
#############
|
169 |
+
|
170 |
+
|
171 |
+
class _UserHistory(object):
|
172 |
+
_instance = None
|
173 |
+
initialized: bool = False
|
174 |
+
folder_path: Path
|
175 |
+
|
176 |
+
def __new__(cls):
|
177 |
+
# Using singleton pattern => we don't want to expose an object (more complex to use) but still want to keep
|
178 |
+
# state between `render` and `save_image` calls.
|
179 |
+
if cls._instance is None:
|
180 |
+
cls._instance = super(_UserHistory, cls).__new__(cls)
|
181 |
+
return cls._instance
|
182 |
+
|
183 |
+
def _user_path(self, username: str) -> Path:
|
184 |
+
path = self.folder_path / username
|
185 |
+
path.mkdir(parents=True, exist_ok=True)
|
186 |
+
return path
|
187 |
+
|
188 |
+
def _user_lock(self, username: str) -> FileLock:
|
189 |
+
"""Ensure history is not corrupted if concurrent calls."""
|
190 |
+
return FileLock(self.folder_path / f"{username}.lock") # lock outside of folder => better when exporting ZIP
|
191 |
+
|
192 |
+
def _user_jsonl_path(self, username: str) -> Path:
|
193 |
+
return self._user_path(username) / "history.jsonl"
|
194 |
+
|
195 |
+
def _user_images_path(self, username: str) -> Path:
|
196 |
+
path = self._user_path(username) / "images"
|
197 |
+
path.mkdir(parents=True, exist_ok=True)
|
198 |
+
return path
|
199 |
+
|
200 |
+
|
201 |
+
def _fetch_user_history(profile: gr.OAuthProfile | None) -> List[Tuple[str, str]]:
|
202 |
+
"""Return saved history for that user, if it exists."""
|
203 |
+
# Cannot load history for logged out users
|
204 |
+
if profile is None:
|
205 |
+
return []
|
206 |
+
username = profile["preferred_username"]
|
207 |
+
|
208 |
+
user_history = _UserHistory()
|
209 |
+
if not user_history.initialized:
|
210 |
+
warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.")
|
211 |
+
return []
|
212 |
+
|
213 |
+
with user_history._user_lock(username):
|
214 |
+
# No file => no history saved yet
|
215 |
+
jsonl_path = user_history._user_jsonl_path(username)
|
216 |
+
if not jsonl_path.is_file():
|
217 |
+
return []
|
218 |
+
|
219 |
+
# Read history
|
220 |
+
images = []
|
221 |
+
for line in jsonl_path.read_text().splitlines():
|
222 |
+
data = json.loads(line)
|
223 |
+
images.append((data["path"], data["label"] or ""))
|
224 |
+
return list(reversed(images))
|
225 |
+
|
226 |
+
|
227 |
+
def _export_user_history(profile: gr.OAuthProfile | None) -> Dict | None:
|
228 |
+
"""Zip all history for that user, if it exists and return it as a downloadable file."""
|
229 |
+
# Cannot load history for logged out users
|
230 |
+
if profile is None:
|
231 |
+
return None
|
232 |
+
username = profile["preferred_username"]
|
233 |
+
|
234 |
+
user_history = _UserHistory()
|
235 |
+
if not user_history.initialized:
|
236 |
+
warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.")
|
237 |
+
return None
|
238 |
+
|
239 |
+
# Zip history
|
240 |
+
with user_history._user_lock(username):
|
241 |
+
path = shutil.make_archive(
|
242 |
+
str(_archives_path() / f"history_{username}"), "zip", user_history._user_path(username)
|
243 |
+
)
|
244 |
+
|
245 |
+
return gr.update(visible=True, value=path)
|
246 |
+
|
247 |
+
|
248 |
+
def _delete_user_history(profile: gr.OAuthProfile | None) -> None:
|
249 |
+
"""Delete all history for that user."""
|
250 |
+
# Cannot load history for logged out users
|
251 |
+
if profile is None:
|
252 |
+
return
|
253 |
+
username = profile["preferred_username"]
|
254 |
+
|
255 |
+
user_history = _UserHistory()
|
256 |
+
if not user_history.initialized:
|
257 |
+
warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.")
|
258 |
+
return
|
259 |
+
|
260 |
+
with user_history._user_lock(username):
|
261 |
+
shutil.rmtree(user_history._user_path(username))
|
262 |
+
|
263 |
+
|
264 |
+
####################
|
265 |
+
# Internal helpers #
|
266 |
+
####################
|
267 |
+
|
268 |
+
|
269 |
+
def _copy_image(image: Image | np.ndarray | str | Path, dst_folder: Path) -> Path:
|
270 |
+
"""Copy image to the images folder."""
|
271 |
+
# Already a path => copy it
|
272 |
+
if isinstance(image, str):
|
273 |
+
image = Path(image)
|
274 |
+
if isinstance(image, Path):
|
275 |
+
dst = dst_folder / f"{uuid4().hex}_{Path(image).name}" # keep file ext
|
276 |
+
shutil.copyfile(image, dst)
|
277 |
+
return dst
|
278 |
+
|
279 |
+
# Still a Python object => serialize it
|
280 |
+
if isinstance(image, np.ndarray):
|
281 |
+
image = Image.fromarray(image)
|
282 |
+
if isinstance(image, Image):
|
283 |
+
dst = dst_folder / f"{uuid4().hex}.png"
|
284 |
+
image.save(dst)
|
285 |
+
return dst
|
286 |
+
|
287 |
+
raise ValueError(f"Unsupported image type: {type(image)}")
|
288 |
+
|
289 |
+
|
290 |
+
def _resolve_folder_path(folder_path: str | Path | None) -> Path:
|
291 |
+
if folder_path is not None:
|
292 |
+
return Path(folder_path).expanduser().resolve()
|
293 |
+
|
294 |
+
if os.getenv("SYSTEM") == "spaces" and os.path.exists("/data"): # Persistent storage is enabled!
|
295 |
+
return Path("/data") / "_user_history"
|
296 |
+
|
297 |
+
# Not in a Space or Persistent storage not enabled => local folder
|
298 |
+
return Path(__file__).parent / "_user_history"
|
299 |
+
|
300 |
+
|
301 |
+
def _archives_path() -> Path:
|
302 |
+
# Doesn't have to be on persistent storage as it's only used for download
|
303 |
+
path = Path(__file__).parent / "_user_history_exports"
|
304 |
+
path.mkdir(parents=True, exist_ok=True)
|
305 |
+
return path
|
306 |
+
|
307 |
+
|
308 |
+
#################
|
309 |
+
# Admin section #
|
310 |
+
#################
|
311 |
+
|
312 |
+
|
313 |
+
def _admin_section() -> None:
|
314 |
+
title = gr.Markdown()
|
315 |
+
title.attach_load_event(_display_if_admin(), every=None)
|
316 |
+
|
317 |
+
|
318 |
+
def _display_if_admin() -> Callable:
|
319 |
+
def _inner(profile: gr.OAuthProfile | None) -> str:
|
320 |
+
if profile is None:
|
321 |
+
return ""
|
322 |
+
if profile["preferred_username"] in _fetch_admins():
|
323 |
+
return _admin_content()
|
324 |
+
return ""
|
325 |
+
|
326 |
+
return _inner
|
327 |
+
|
328 |
+
|
329 |
+
def _admin_content() -> str:
|
330 |
+
return f"""
|
331 |
+
## Admin section
|
332 |
+
|
333 |
+
Running on **{os.getenv("SYSTEM", "local")}** (id: {os.getenv("SPACE_ID")}). {_get_msg_is_persistent_storage_enabled()}
|
334 |
+
|
335 |
+
Admins: {', '.join(_fetch_admins())}
|
336 |
+
|
337 |
+
{_get_nb_users()} user(s), {_get_nb_images()} image(s)
|
338 |
+
|
339 |
+
### Configuration
|
340 |
+
|
341 |
+
History folder: *{_UserHistory().folder_path}*
|
342 |
+
|
343 |
+
Exports folder: *{_archives_path()}*
|
344 |
+
|
345 |
+
### Disk usage
|
346 |
+
|
347 |
+
{_disk_space_warning_message()}
|
348 |
+
"""
|
349 |
+
|
350 |
+
|
351 |
+
def _get_nb_users() -> int:
|
352 |
+
user_history = _UserHistory()
|
353 |
+
if not user_history.initialized:
|
354 |
+
return 0
|
355 |
+
if user_history.folder_path is not None and user_history.folder_path.exists():
|
356 |
+
return len([path for path in user_history.folder_path.iterdir() if path.is_dir()])
|
357 |
+
return 0
|
358 |
+
|
359 |
+
|
360 |
+
def _get_nb_images() -> int:
|
361 |
+
user_history = _UserHistory()
|
362 |
+
if not user_history.initialized:
|
363 |
+
return 0
|
364 |
+
if user_history.folder_path is not None and user_history.folder_path.exists():
|
365 |
+
return len([path for path in user_history.folder_path.glob("*/images/*")])
|
366 |
+
return 0
|
367 |
+
|
368 |
+
|
369 |
+
def _get_msg_is_persistent_storage_enabled() -> str:
|
370 |
+
if os.getenv("SYSTEM") == "spaces":
|
371 |
+
if os.path.exists("/data"):
|
372 |
+
return "Persistent storage is enabled."
|
373 |
+
else:
|
374 |
+
return (
|
375 |
+
"Persistent storage is not enabled. This means that user histories will be deleted when the Space is"
|
376 |
+
" restarted. Consider adding a Persistent Storage in your Space settings."
|
377 |
+
)
|
378 |
+
return ""
|
379 |
+
|
380 |
+
|
381 |
+
def _disk_space_warning_message() -> str:
|
382 |
+
user_history = _UserHistory()
|
383 |
+
if not user_history.initialized:
|
384 |
+
return ""
|
385 |
+
|
386 |
+
message = ""
|
387 |
+
if user_history.folder_path is not None:
|
388 |
+
total, used, _ = _get_disk_usage(user_history.folder_path)
|
389 |
+
message += f"History folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
|
390 |
+
|
391 |
+
total, used, _ = _get_disk_usage(_archives_path())
|
392 |
+
message += f"\n\nExports folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
|
393 |
+
|
394 |
+
return f"{message.strip()}"
|
395 |
+
|
396 |
+
|
397 |
+
def _get_disk_usage(path: Path) -> Tuple[int, int, int]:
|
398 |
+
for path in [path] + list(path.parents): # first check target_dir, then each parents one by one
|
399 |
+
try:
|
400 |
+
return shutil.disk_usage(path)
|
401 |
+
except OSError: # if doesn't exist or can't read => fail silently and try parent one
|
402 |
+
pass
|
403 |
+
return 0, 0, 0
|
404 |
+
|
405 |
+
|
406 |
+
@cache
|
407 |
+
def _fetch_admins() -> List[str]:
|
408 |
+
# Running locally => fake user is admin
|
409 |
+
if os.getenv("SYSTEM") != "spaces":
|
410 |
+
return ["FakeGradioUser"]
|
411 |
+
|
412 |
+
# Running in Space but no space_id => ???
|
413 |
+
space_id = os.getenv("SPACE_ID")
|
414 |
+
if space_id is None:
|
415 |
+
return ["Unknown"]
|
416 |
+
|
417 |
+
# Running in Space => try to fetch organization members
|
418 |
+
# Otherwise, it's not an organization => namespace is the user
|
419 |
+
namespace = space_id.split("/")[0]
|
420 |
+
response = requests.get(f"https://huggingface.co/api/organizations/{namespace}/members")
|
421 |
+
if response.status_code == 200:
|
422 |
+
return sorted((member["user"] for member in response.json()), key=lambda x: x.lower())
|
423 |
+
return [namespace]
|