Not-Grim-Refer commited on
Commit
e426fac
ยท
verified ยท
1 Parent(s): c027c0d
Files changed (7) hide show
  1. README.md +8 -7
  2. app.py +412 -0
  3. gitattributes +35 -0
  4. gitignore +1 -0
  5. requirements.txt +1 -0
  6. share_btn.py +60 -0
  7. user_history.py +487 -0
README.md CHANGED
@@ -1,13 +1,14 @@
1
  ---
2
- title: MMO Map Layout Generator
3
- emoji: ๐ŸŒ–
4
- colorFrom: gray
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 4.24.0
8
  app_file: app.py
9
- pinned: false
10
- license: apache-2.0
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: RSPS Map Planner
3
+ emoji: ๐Ÿ‹๏ธ #๐Ÿ‘•๐ŸŒŸ
4
+ colorFrom: red
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 3.45.1
8
  app_file: app.py
9
+ license: mit
10
+ disable_embedding: true
11
+ hf_oauth: true
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import gradio.helpers
3
+ from datasets import load_dataset
4
+
5
+ import base64
6
+ import re
7
+ import os
8
+ import random
9
+ import requests
10
+ import time
11
+ from PIL import Image
12
+ from io import BytesIO
13
+ from typing import Tuple
14
+
15
+ import user_history
16
+ from share_btn import community_icon_html, loading_icon_html, share_js
17
+
18
+
19
+ style_list = [
20
+ {
21
+ "name": "(No style)",
22
+ "prompt": "{prompt}",
23
+ "negative_prompt": "",
24
+ },
25
+ {
26
+ "name": "Cinematic",
27
+ "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
28
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
29
+ },
30
+ {
31
+ "name": "Photographic",
32
+ "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
33
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
34
+ },
35
+ {
36
+ "name": "Anime",
37
+ "prompt": "anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed",
38
+ "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
39
+ },
40
+ {
41
+ "name": "Manga",
42
+ "prompt": "manga style {prompt} . vibrant, high-energy, detailed, iconic, Japanese comic style",
43
+ "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style",
44
+ },
45
+ {
46
+ "name": "Digital Art",
47
+ "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed",
48
+ "negative_prompt": "photo, photorealistic, realism, ugly",
49
+ },
50
+ {
51
+ "name": "Pixel art",
52
+ "prompt": "pixel-art {prompt} . low-res, blocky, pixel art style, 8-bit graphics",
53
+ "negative_prompt": "sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic",
54
+ },
55
+ {
56
+ "name": "Fantasy art",
57
+ "prompt": "ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy",
58
+ "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white",
59
+ },
60
+ {
61
+ "name": "Neonpunk",
62
+ "prompt": "neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional",
63
+ "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured",
64
+ },
65
+ {
66
+ "name": "3D Model",
67
+ "prompt": "professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting",
68
+ "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
69
+ },
70
+ ]
71
+
72
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
73
+ STYLE_NAMES = list(styles.keys())
74
+ DEFAULT_STYLE_NAME = "(No style)"
75
+
76
+
77
+ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
78
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
79
+ return p.replace("{prompt}", positive), n + negative
80
+
81
+
82
+ word_list_dataset = load_dataset("google/word-list-sd", data_files="list.txt", use_auth_token=True)
83
+ word_list = word_list_dataset["train"]['text']
84
+
85
+ #gradio.helpers.CACHED_FOLDER="/data/cache"
86
+
87
+ def infer(prompt, negative="low_quality", scale=7, style_name=None, profile: gr.OAuthProfile | None = None):
88
+ for filter in word_list:
89
+ if re.search(rf"\b{filter}\b", prompt):
90
+ raise gr.Error("Please try again with a different prompt")
91
+
92
+ seed = random.randint(0,4294967295)
93
+ prompt, negative = apply_style(style_name, prompt, negative)
94
+ images = []
95
+ url = os.getenv('JAX_BACKEND_URL')
96
+ payload = {'instances': [{ 'prompt': prompt, 'negative_prompt': negative, 'parameters':{ 'guidance_scale': scale, 'seed': seed } }] }
97
+ start_time = time.time()
98
+ images_request = requests.post(url, json = payload)
99
+ print(time.time() - start_time)
100
+ try:
101
+ json_data = images_request.json()
102
+ except requests.exceptions.JSONDecodeError:
103
+ raise gr.Error("SDXL did not return a valid result, try again")
104
+
105
+ for prediction in json_data["predictions"]:
106
+ for image in prediction["images"]:
107
+ image_b64 = (f"data:image/jpeg;base64,{image}")
108
+ images.append(image_b64)
109
+
110
+ if profile is not None: # avoid conversion on non-logged-in users
111
+ pil_image = Image.open(BytesIO(base64.b64decode(image)))
112
+ user_history.save_image( # save images + metadata to user history
113
+ label=prompt,
114
+ image=pil_image,
115
+ profile=profile,
116
+ metadata={
117
+ "prompt": prompt,
118
+ "negative_prompt": negative,
119
+ "guidance_scale": scale,
120
+ },
121
+ )
122
+
123
+ return images, gr.update(visible=True)
124
+
125
+
126
+ css = """
127
+ .gradio-container {
128
+ font-family: 'IBM Plex Sans', sans-serif;
129
+ }
130
+ .gr-button {
131
+ color: white;
132
+ border-color: black;
133
+ background: black;
134
+ }
135
+ input[type='range'] {
136
+ accent-color: black;
137
+ }
138
+ .dark input[type='range'] {
139
+ accent-color: #dfdfdf;
140
+ }
141
+ .gradio-container {
142
+ max-width: 730px !important;
143
+ margin: auto;
144
+ padding-top: 1.5rem;
145
+ }
146
+ #gallery {
147
+ min-height: 22rem;
148
+ margin-bottom: 15px;
149
+ margin-left: auto;
150
+ margin-right: auto;
151
+ border-bottom-right-radius: .5rem !important;
152
+ border-bottom-left-radius: .5rem !important;
153
+ }
154
+ #gallery>div>.h-full {
155
+ min-height: 20rem;
156
+ }
157
+ .details:hover {
158
+ text-decoration: underline;
159
+ }
160
+ .gr-button {
161
+ white-space: nowrap;
162
+ }
163
+ .gr-button:focus {
164
+ border-color: rgb(147 197 253 / var(--tw-border-opacity));
165
+ outline: none;
166
+ box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
167
+ --tw-border-opacity: 1;
168
+ --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
169
+ --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
170
+ --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
171
+ --tw-ring-opacity: .5;
172
+ }
173
+ #advanced-btn {
174
+ font-size: .7rem !important;
175
+ line-height: 19px;
176
+ margin-top: 12px;
177
+ margin-bottom: 12px;
178
+ padding: 2px 8px;
179
+ border-radius: 14px !important;
180
+ }
181
+ #advanced-options {
182
+ display: none;
183
+ margin-bottom: 20px;
184
+ }
185
+ .footer {
186
+ margin-bottom: 45px;
187
+ margin-top: 35px;
188
+ text-align: center;
189
+ border-bottom: 1px solid #e5e5e5;
190
+ }
191
+ .footer>p {
192
+ font-size: .8rem;
193
+ display: inline-block;
194
+ padding: 0 10px;
195
+ transform: translateY(10px);
196
+ background: white;
197
+ }
198
+ .dark .footer {
199
+ border-color: #303030;
200
+ }
201
+ .dark .footer>p {
202
+ background: #0b0f19;
203
+ }
204
+ .acknowledgments h4{
205
+ margin: 1.25em 0 .25em 0;
206
+ font-weight: bold;
207
+ font-size: 115%;
208
+ }
209
+ .animate-spin {
210
+ animation: spin 1s linear infinite;
211
+ }
212
+ @keyframes spin {
213
+ from {
214
+ transform: rotate(0deg);
215
+ }
216
+ to {
217
+ transform: rotate(360deg);
218
+ }
219
+ }
220
+ #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;}
221
+ div#share-btn-container > div {flex-direction: row;background: black;align-items: center}
222
+ #share-btn-container:hover {background-color: #060606}
223
+ #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;}
224
+ #share-btn * {all: unset}
225
+ #share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;}
226
+ #share-btn-container .wrap {display: none !important}
227
+ #share-btn-container.hidden {display: none!important}
228
+
229
+ .gr-form{
230
+ flex: 1 1 50%; border-top-right-radius: 0; border-bottom-right-radius: 0;
231
+ }
232
+ #prompt-container{
233
+ gap: 0;
234
+ }
235
+ #prompt-container .form{
236
+ border-top-right-radius: 0;
237
+ border-bottom-right-radius: 0;
238
+ }
239
+ #gen-button{
240
+ border-top-left-radius:0;
241
+ border-bottom-left-radius:0;
242
+ }
243
+ #prompt-text-input, #negative-prompt-text-input{padding: .45rem 0.625rem}
244
+ #component-16{border-top-width: 1px!important;margin-top: 1em}
245
+ .image_duplication{position: absolute; width: 100px; left: 50px}
246
+ .tabitem{border: 0 !important}
247
+ """
248
+
249
+ block = gr.Blocks()
250
+
251
+ examples = [
252
+ [
253
+ "A serious capybara at work, wearing a suit",
254
+ None,
255
+ None
256
+ ],
257
+ [
258
+ 'A Squirtle fine dining with a view to the London Eye',
259
+ None,
260
+ None
261
+ ],
262
+ [
263
+ 'A tamale food cart in front of a Japanese Castle',
264
+ None,
265
+ None
266
+ ],
267
+ [
268
+ 'a graffiti of a robot serving meals to people',
269
+ None,
270
+ None
271
+ ],
272
+ [
273
+ 'a beautiful cabin in Attersee, Austria, 3d animation style',
274
+ None,
275
+ None
276
+ ],
277
+
278
+ ]
279
+
280
+
281
+ with block:
282
+ gr.HTML(
283
+ """
284
+ <div style="text-align: center; margin: 0 auto;">
285
+ <div
286
+ style="
287
+ display: inline-flex;
288
+ align-items: center;
289
+ gap: 0.8rem;
290
+ font-size: 1.75rem;
291
+ "
292
+ >
293
+ <svg
294
+ width="0.65em"
295
+ height="0.65em"
296
+ viewBox="0 0 115 115"
297
+ fill="none"
298
+ xmlns="http://www.w3.org/2000/svg"
299
+ >
300
+ <rect width="23" height="23" fill="white"></rect>
301
+ <rect y="69" width="23" height="23" fill="white"></rect>
302
+ <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
303
+ <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
304
+ <rect x="46" width="23" height="23" fill="white"></rect>
305
+ <rect x="46" y="69" width="23" height="23" fill="white"></rect>
306
+ <rect x="69" width="23" height="23" fill="black"></rect>
307
+ <rect x="69" y="69" width="23" height="23" fill="black"></rect>
308
+ <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
309
+ <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
310
+ <rect x="115" y="46" width="23" height="23" fill="white"></rect>
311
+ <rect x="115" y="115" width="23" height="23" fill="white"></rect>
312
+ <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
313
+ <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
314
+ <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
315
+ <rect x="92" y="69" width="23" height="23" fill="white"></rect>
316
+ <rect x="69" y="46" width="23" height="23" fill="white"></rect>
317
+ <rect x="69" y="115" width="23" height="23" fill="white"></rect>
318
+ <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
319
+ <rect x="46" y="46" width="23" height="23" fill="black"></rect>
320
+ <rect x="46" y="115" width="23" height="23" fill="black"></rect>
321
+ <rect x="46" y="69" width="23" height="23" fill="black"></rect>
322
+ <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
323
+ <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
324
+ <rect x="23" y="69" width="23" height="23" fill="black"></rect>
325
+ </svg>
326
+ <h1 style="font-weight: 900; margin-bottom: 7px;margin-top:5px">
327
+ Fast Stable Diffusion XL on TPU v5e โšก
328
+ </h1>
329
+ </div>
330
+ <p style="margin-bottom: 10px; font-size: 94%; line-height: 23px;">
331
+ SDXL is a high quality text-to-image model from Stability AI. This demo is running on <a style="text-decoration: underline;" href="https://cloud.google.com/blog/products/compute/announcing-cloud-tpu-v5e-and-a3-gpus-in-ga">Google Cloud TPU v5e</a>, to achieve efficient and cost-effective inference of 1024ร—1024 images. <a href="https://hf.co/blog/sdxl_jax" target="_blank">How does it work?</a>
332
+ </p>
333
+ </div>
334
+ """
335
+ )
336
+
337
+ with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
338
+ text = gr.Textbox(
339
+ label="Enter your prompt",
340
+ show_label=False,
341
+ max_lines=1,
342
+ placeholder="Enter your prompt",
343
+ elem_id="prompt-text-input",
344
+ )
345
+ btn = gr.Button("Generate", scale=0, elem_id="gen-button")
346
+
347
+ gallery = gr.Gallery(
348
+ label="Generated images", show_label=False, elem_id="gallery", grid=[2]
349
+ )
350
+
351
+
352
+ with gr.Group(elem_id="share-btn-container", visible=False) as community_group:
353
+ community_icon = gr.HTML(community_icon_html)
354
+ loading_icon = gr.HTML(loading_icon_html)
355
+ share_button = gr.Button("Share to community", elem_id="share-btn")
356
+
357
+ with gr.Accordion("Advanced settings", open=False):
358
+ style_selection = gr.Radio(
359
+ show_label=True, container=True, interactive=True,
360
+ choices=STYLE_NAMES,
361
+ value=DEFAULT_STYLE_NAME,
362
+ label='Image Style'
363
+ )
364
+ negative = gr.Textbox(
365
+ label="Enter your negative prompt",
366
+ show_label=False,
367
+ max_lines=1,
368
+ placeholder="Enter a negative prompt",
369
+ elem_id="negative-prompt-text-input",
370
+ )
371
+ guidance_scale = gr.Slider(
372
+ label="Guidance Scale", minimum=0, maximum=50, value=7.5, step=0.1
373
+ )
374
+
375
+ ex = gr.Examples(examples=examples, fn=infer, inputs=[text, negative, guidance_scale], outputs=[gallery, community_group], cache_examples=True, postprocess=False)
376
+ negative.submit(infer, inputs=[text, negative, guidance_scale, style_selection], outputs=[gallery, community_group], postprocess=False)
377
+ text.submit(infer, inputs=[text, negative, guidance_scale, style_selection], outputs=[gallery, community_group], postprocess=False)
378
+ btn.click(infer, inputs=[text, negative, guidance_scale, style_selection], outputs=[gallery, community_group], postprocess=False)
379
+
380
+ share_button.click(
381
+ None,
382
+ [],
383
+ [],
384
+ _js=share_js,
385
+ )
386
+ gr.HTML(
387
+ """
388
+ <div class="footer">
389
+ <p>Model by <a href="https://huggingface.co/stabilityai" style="text-decoration: underline;" target="_blank">StabilityAI</a> - backend running JAX on TPUs due to generous support of <a href="https://sites.research.google/trc/about/" style="text-decoration: underline;" target="_blank">Google TRC program</a> - Gradio Demo by ๐Ÿค— Hugging Face - this is not an official Google Product
390
+ </p>
391
+ </div>
392
+ """
393
+ )
394
+ with gr.Accordion(label="License", open=True):
395
+ gr.HTML(
396
+ """<div class="acknowledgments">
397
+ <p><h4>LICENSE</h4>
398
+ The model is licensed with a <a href="https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/LICENSE.md" style="text-decoration: underline;" target="_blank">Stability AI CreativeML Open RAIL++-M</a> license. The License allows users to take advantage of the model in a wide range of settings (including free use and redistribution) as long as they respect the specific use case restrictions outlined, which correspond to model applications the licensor deems ill-suited for the model or are likely to cause harm. For the full list of restrictions please <a href="https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/LICENSE.md" target="_blank" style="text-decoration: underline;" target="_blank">read the license</a></p>
399
+ <p><h4>Biases and content acknowledgment</h4>
400
+ Despite how impressive being able to turn text into image is, beware that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography and violence. You can read more in the <a href="https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0" style="text-decoration: underline;" target="_blank">model card</a></p>
401
+ </div>
402
+ """
403
+ )
404
+
405
+ with gr.Blocks(css=css) as block_with_history:
406
+ with gr.Tab("Demo"):
407
+ block.render()
408
+ with gr.Tab("Past generations"):
409
+ user_history.render()
410
+
411
+ block_with_history.queue(concurrency_count=8, max_size=10, api_open=False).launch(show_api=False)
412
+ #block_with_history.launch(server_name="0.0.0.0")
gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ datasets
share_btn.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ const gradioEl = document.querySelector('body > gradio-app');
26
+ const imgEls = gradioEl.querySelectorAll('#gallery img');
27
+ const promptTxt = gradioEl.querySelector('#prompt-text-input input').value;
28
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
29
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
30
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
31
+ if(!imgEls.length){
32
+ return;
33
+ };
34
+ shareBtnEl.style.pointerEvents = 'none';
35
+ shareIconEl.style.display = 'none';
36
+ loadingIconEl.style.removeProperty('display');
37
+ const files = await Promise.all(
38
+ [...imgEls].map(async (imgEl) => {
39
+ const res = await fetch(imgEl.src);
40
+ const blob = await res.blob();
41
+ const imgId = Date.now() % 200;
42
+ const fileName = `diffuse-the-rest-${{imgId}}.jpg`;
43
+ return new File([blob], fileName, { type: 'image/jpeg' });
44
+ })
45
+ );
46
+ const urls = await Promise.all(files.map((f) => uploadFile(f)));
47
+ const htmlImgs = urls.map(url => `<img src='${url}' width='400' height='400'>`);
48
+ const descriptionMd = `<div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>
49
+ ${htmlImgs.join(`\n`)}
50
+ </div>`;
51
+ const params = new URLSearchParams({
52
+ title: promptTxt,
53
+ description: descriptionMd,
54
+ });
55
+ const paramsStr = params.toString();
56
+ window.open(`https://huggingface.co/spaces/pcuenq/sdxl/discussions/new?${paramsStr}`, '_blank');
57
+ shareBtnEl.style.removeProperty('pointer-events');
58
+ shareIconEl.style.removeProperty('display');
59
+ loadingIconEl.style.display = 'none';
60
+ }"""
user_history.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # TODO: remove this section once all Spaces have migrated
41
+ _migrate_history()
42
+
43
+
44
+ def render() -> None:
45
+ user_history = _UserHistory()
46
+
47
+ # initialize with default config
48
+ if not user_history.initialized:
49
+ print("Initializing user history with default config. Use `user_history.setup(...)` to customize folder_path.")
50
+ setup()
51
+
52
+ # Render user history tab
53
+ gr.Markdown(
54
+ "## Your past generations\n\nLog in to keep a gallery of your previous generations. Your history will be saved"
55
+ " and available on your next visit. Make sure to export your images from time to time as this gallery may be"
56
+ " deleted in the future."
57
+ )
58
+
59
+ if os.getenv("SYSTEM") == "spaces" and not os.path.exists("/data"):
60
+ gr.Markdown(
61
+ "**โš ๏ธ Persistent storage is disabled, meaning your history will be lost if the Space gets restarted."
62
+ " Only the Space owner can setup a Persistent Storage. If you are not the Space owner, consider"
63
+ " duplicating this Space to set your own storage.โš ๏ธ**"
64
+ )
65
+
66
+ with gr.Row():
67
+ gr.LoginButton(min_width=250)
68
+ gr.LogoutButton(min_width=250)
69
+ refresh_button = gr.Button(
70
+ "Refresh",
71
+ icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_refresh.png",
72
+ )
73
+ export_button = gr.Button(
74
+ "Export",
75
+ icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_download.png",
76
+ )
77
+ delete_button = gr.Button(
78
+ "Delete history",
79
+ icon="https://huggingface.co/spaces/Wauplin/gradio-user-history/resolve/main/assets/icon_delete.png",
80
+ )
81
+
82
+ # "Export zip" row (hidden by default)
83
+ with gr.Row():
84
+ export_file = gr.File(file_count="single", file_types=[".zip"], label="Exported history", visible=False)
85
+
86
+ # "Config deletion" row (hidden by default)
87
+ with gr.Row():
88
+ confirm_button = gr.Button("Confirm delete all history", variant="stop", visible=False)
89
+ cancel_button = gr.Button("Cancel", visible=False)
90
+
91
+ # Gallery
92
+ gallery = gr.Gallery(
93
+ label="Past images",
94
+ show_label=True,
95
+ elem_id="gallery-history",
96
+ object_fit="contain",
97
+ columns=5,
98
+ height=600,
99
+ preview=False,
100
+ show_share_button=False,
101
+ show_download_button=False,
102
+ )
103
+ gr.Markdown(
104
+ "User history is powered by"
105
+ " [Wauplin/gradio-user-history](https://huggingface.co/spaces/Wauplin/gradio-user-history). Integrate it to"
106
+ " your own Space in just a few lines of code!"
107
+ )
108
+ gallery.attach_load_event(_fetch_user_history, every=None)
109
+
110
+ # Interactions
111
+ refresh_button.click(fn=_fetch_user_history, inputs=[], outputs=[gallery], queue=False)
112
+ export_button.click(fn=_export_user_history, inputs=[], outputs=[export_file], queue=False)
113
+
114
+ # Taken from https://github.com/gradio-app/gradio/issues/3324#issuecomment-1446382045
115
+ delete_button.click(
116
+ lambda: [gr.update(visible=True), gr.update(visible=True)],
117
+ outputs=[confirm_button, cancel_button],
118
+ queue=False,
119
+ )
120
+ cancel_button.click(
121
+ lambda: [gr.update(visible=False), gr.update(visible=False)],
122
+ outputs=[confirm_button, cancel_button],
123
+ queue=False,
124
+ )
125
+ confirm_button.click(_delete_user_history).then(
126
+ lambda: [gr.update(visible=False), gr.update(visible=False)],
127
+ outputs=[confirm_button, cancel_button],
128
+ queue=False,
129
+ )
130
+
131
+ # Admin section (only shown locally or when logged in as Space owner)
132
+ _admin_section()
133
+
134
+
135
+ def save_image(
136
+ profile: gr.OAuthProfile | None,
137
+ image: Image | np.ndarray | str | Path,
138
+ label: str | None = None,
139
+ metadata: Dict | None = None,
140
+ ):
141
+ # Ignore images from logged out users
142
+ if profile is None:
143
+ return
144
+ username = profile["preferred_username"]
145
+
146
+ # Ignore images if user history not used
147
+ user_history = _UserHistory()
148
+ if not user_history.initialized:
149
+ warnings.warn(
150
+ "User history is not set in Gradio demo. Saving image is ignored. You must use `user_history.render(...)`"
151
+ " first."
152
+ )
153
+ return
154
+
155
+ # Copy image to storage
156
+ image_path = _copy_image(image, dst_folder=user_history._user_images_path(username))
157
+
158
+ # Save new image + metadata
159
+ if metadata is None:
160
+ metadata = {}
161
+ if "datetime" not in metadata:
162
+ metadata["datetime"] = str(datetime.now())
163
+ data = {"path": str(image_path), "label": label, "metadata": metadata}
164
+ with user_history._user_lock(username):
165
+ with user_history._user_jsonl_path(username).open("a") as f:
166
+ f.write(json.dumps(data) + "\n")
167
+
168
+
169
+ #############
170
+ # Internals #
171
+ #############
172
+
173
+
174
+ class _UserHistory(object):
175
+ _instance = None
176
+ initialized: bool = False
177
+ folder_path: Path
178
+
179
+ def __new__(cls):
180
+ # Using singleton pattern => we don't want to expose an object (more complex to use) but still want to keep
181
+ # state between `render` and `save_image` calls.
182
+ if cls._instance is None:
183
+ cls._instance = super(_UserHistory, cls).__new__(cls)
184
+ return cls._instance
185
+
186
+ def _user_path(self, username: str) -> Path:
187
+ path = self.folder_path / username
188
+ path.mkdir(parents=True, exist_ok=True)
189
+ return path
190
+
191
+ def _user_lock(self, username: str) -> FileLock:
192
+ """Ensure history is not corrupted if concurrent calls."""
193
+ return FileLock(self.folder_path / f"{username}.lock") # lock outside of folder => better when exporting ZIP
194
+
195
+ def _user_jsonl_path(self, username: str) -> Path:
196
+ return self._user_path(username) / "history.jsonl"
197
+
198
+ def _user_images_path(self, username: str) -> Path:
199
+ path = self._user_path(username) / "images"
200
+ path.mkdir(parents=True, exist_ok=True)
201
+ return path
202
+
203
+
204
+ def _fetch_user_history(profile: gr.OAuthProfile | None) -> List[Tuple[str, str]]:
205
+ """Return saved history for that user, if it exists."""
206
+ # Cannot load history for logged out users
207
+ if profile is None:
208
+ return []
209
+ username = profile["preferred_username"]
210
+
211
+ user_history = _UserHistory()
212
+ if not user_history.initialized:
213
+ warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.")
214
+ return []
215
+
216
+ with user_history._user_lock(username):
217
+ # No file => no history saved yet
218
+ jsonl_path = user_history._user_jsonl_path(username)
219
+ if not jsonl_path.is_file():
220
+ return []
221
+
222
+ # Read history
223
+ images = []
224
+ for line in jsonl_path.read_text().splitlines():
225
+ data = json.loads(line)
226
+ images.append((data["path"], data["label"] or ""))
227
+ return list(reversed(images))
228
+
229
+
230
+ def _export_user_history(profile: gr.OAuthProfile | None) -> Dict | None:
231
+ """Zip all history for that user, if it exists and return it as a downloadable file."""
232
+ # Cannot load history for logged out users
233
+ if profile is None:
234
+ return None
235
+ username = profile["preferred_username"]
236
+
237
+ user_history = _UserHistory()
238
+ if not user_history.initialized:
239
+ warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.")
240
+ return None
241
+
242
+ # Zip history
243
+ with user_history._user_lock(username):
244
+ path = shutil.make_archive(
245
+ str(_archives_path() / f"history_{username}"), "zip", user_history._user_path(username)
246
+ )
247
+
248
+ return gr.update(visible=True, value=path)
249
+
250
+
251
+ def _delete_user_history(profile: gr.OAuthProfile | None) -> None:
252
+ """Delete all history for that user."""
253
+ # Cannot load history for logged out users
254
+ if profile is None:
255
+ return
256
+ username = profile["preferred_username"]
257
+
258
+ user_history = _UserHistory()
259
+ if not user_history.initialized:
260
+ warnings.warn("User history is not set in Gradio demo. You must use `user_history.render(...)` first.")
261
+ return
262
+
263
+ with user_history._user_lock(username):
264
+ shutil.rmtree(user_history._user_path(username))
265
+
266
+
267
+ ####################
268
+ # Internal helpers #
269
+ ####################
270
+
271
+
272
+ def _copy_image(image: Image | np.ndarray | str | Path, dst_folder: Path) -> Path:
273
+ """Copy image to the images folder."""
274
+ # Already a path => copy it
275
+ if isinstance(image, str):
276
+ image = Path(image)
277
+ if isinstance(image, Path):
278
+ dst = dst_folder / f"{uuid4().hex}_{Path(image).name}" # keep file ext
279
+ shutil.copyfile(image, dst)
280
+ return dst
281
+
282
+ # Still a Python object => serialize it
283
+ if isinstance(image, np.ndarray):
284
+ image = Image.fromarray(image)
285
+ if isinstance(image, Image):
286
+ dst = dst_folder / f"{uuid4().hex}.png"
287
+ image.save(dst)
288
+ return dst
289
+
290
+ raise ValueError(f"Unsupported image type: {type(image)}")
291
+
292
+
293
+ def _resolve_folder_path(folder_path: str | Path | None) -> Path:
294
+ if folder_path is not None:
295
+ return Path(folder_path).expanduser().resolve()
296
+
297
+ if os.getenv("SYSTEM") == "spaces" and os.path.exists("/data"): # Persistent storage is enabled!
298
+ return Path("/data") / "_user_history"
299
+
300
+ # Not in a Space or Persistent storage not enabled => local folder
301
+ return Path(__file__).parent / "_user_history"
302
+
303
+
304
+ def _archives_path() -> Path:
305
+ # Doesn't have to be on persistent storage as it's only used for download
306
+ path = Path(__file__).parent / "_user_history_exports"
307
+ path.mkdir(parents=True, exist_ok=True)
308
+ return path
309
+
310
+
311
+ #################
312
+ # Admin section #
313
+ #################
314
+
315
+
316
+ def _admin_section() -> None:
317
+ title = gr.Markdown()
318
+ title.attach_load_event(_display_if_admin(), every=None)
319
+
320
+
321
+ def _display_if_admin() -> Callable:
322
+ def _inner(profile: gr.OAuthProfile | None) -> str:
323
+ if profile is None:
324
+ return ""
325
+ if profile["preferred_username"] in _fetch_admins():
326
+ return _admin_content()
327
+ return ""
328
+
329
+ return _inner
330
+
331
+
332
+ def _admin_content() -> str:
333
+ return f"""
334
+ ## Admin section
335
+
336
+ Running on **{os.getenv("SYSTEM", "local")}** (id: {os.getenv("SPACE_ID")}). {_get_msg_is_persistent_storage_enabled()}
337
+
338
+ Admins: {', '.join(_fetch_admins())}
339
+
340
+ {_get_nb_users()} user(s), {_get_nb_images()} image(s)
341
+
342
+ ### Configuration
343
+
344
+ History folder: *{_UserHistory().folder_path}*
345
+
346
+ Exports folder: *{_archives_path()}*
347
+
348
+ ### Disk usage
349
+
350
+ {_disk_space_warning_message()}
351
+ """
352
+
353
+
354
+ def _get_nb_users() -> int:
355
+ user_history = _UserHistory()
356
+ if not user_history.initialized:
357
+ return 0
358
+ if user_history.folder_path is not None:
359
+ return len([path for path in user_history.folder_path.iterdir() if path.is_dir()])
360
+ return 0
361
+
362
+
363
+ def _get_nb_images() -> int:
364
+ user_history = _UserHistory()
365
+ if not user_history.initialized:
366
+ return 0
367
+ if user_history.folder_path is not None:
368
+ return len([path for path in user_history.folder_path.glob("*/images/*")])
369
+ return 0
370
+
371
+
372
+ def _get_msg_is_persistent_storage_enabled() -> str:
373
+ if os.getenv("SYSTEM") == "spaces":
374
+ if os.path.exists("/data"):
375
+ return "Persistent storage is enabled."
376
+ else:
377
+ return (
378
+ "Persistent storage is not enabled. This means that user histories will be deleted when the Space is"
379
+ " restarted. Consider adding a Persistent Storage in your Space settings."
380
+ )
381
+ return ""
382
+
383
+
384
+ def _disk_space_warning_message() -> str:
385
+ user_history = _UserHistory()
386
+ if not user_history.initialized:
387
+ return ""
388
+
389
+ message = ""
390
+ if user_history.folder_path is not None:
391
+ total, used, _ = _get_disk_usage(user_history.folder_path)
392
+ message += f"History folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
393
+
394
+ total, used, _ = _get_disk_usage(_archives_path())
395
+ message += f"\n\nExports folder: **{used / 1e9 :.0f}/{total / 1e9 :.0f}GB** used ({100*used/total :.0f}%)."
396
+
397
+ return f"{message.strip()}"
398
+
399
+
400
+ def _get_disk_usage(path: Path) -> Tuple[int, int, int]:
401
+ for path in [path] + list(path.parents): # first check target_dir, then each parents one by one
402
+ try:
403
+ return shutil.disk_usage(path)
404
+ except OSError: # if doesn't exist or can't read => fail silently and try parent one
405
+ pass
406
+ return 0, 0, 0
407
+
408
+
409
+ @cache
410
+ def _fetch_admins() -> List[str]:
411
+ # Running locally => fake user is admin
412
+ if os.getenv("SYSTEM") != "spaces":
413
+ return ["FakeGradioUser"]
414
+
415
+ # Running in Space but no space_id => ???
416
+ space_id = os.getenv("SPACE_ID")
417
+ if space_id is None:
418
+ return ["Unknown"]
419
+
420
+ # Running in Space => try to fetch organization members
421
+ # Otherwise, it's not an organization => namespace is the user
422
+ namespace = space_id.split("/")[0]
423
+ response = requests.get(f"https://huggingface.co/api/organizations/{namespace}/members")
424
+ if response.status_code == 200:
425
+ return sorted((member["user"] for member in response.json()), key=lambda x: x.lower())
426
+ return [namespace]
427
+
428
+
429
+ ################################################################
430
+ # Legacy helpers to migrate image structure to new data format #
431
+ ################################################################
432
+ # TODO: remove this section once all Spaces have migrated
433
+
434
+
435
+ def _migrate_history():
436
+ """Script to migrate user history from v0 to v1."""
437
+ legacy_history_path = _legacy_get_history_folder_path()
438
+ if not legacy_history_path.exists():
439
+ return
440
+
441
+ error_count = 0
442
+ for json_path in legacy_history_path.glob("*.json"):
443
+ username = json_path.stem
444
+ print(f"Migrating history for user {username}...")
445
+ error_count += _legacy_move_user_history(username)
446
+ print("Done.")
447
+ print(f"Migration complete. {error_count} error(s) happened.")
448
+
449
+ if error_count == 0:
450
+ shutil.rmtree(legacy_history_path, ignore_errors=True)
451
+
452
+
453
+ def _legacy_move_user_history(username: str) -> int:
454
+ history = _legacy_read_user_history(username)
455
+ error_count = 0
456
+ for image, prompt in reversed(history):
457
+ try:
458
+ save_image(label=prompt, image=image, profile={"preferred_username": username})
459
+ except Exception as e:
460
+ print("Issue while migrating image:", e)
461
+ error_count += 1
462
+ return error_count
463
+
464
+
465
+ def _legacy_get_history_folder_path() -> Path:
466
+ _folder = os.environ.get("HISTORY_FOLDER")
467
+ if _folder is None:
468
+ _folder = Path(__file__).parent / "history"
469
+ return Path(_folder)
470
+
471
+
472
+ def _legacy_read_user_history(username: str) -> List[Tuple[str, str]]:
473
+ """Return saved history for that user."""
474
+ with _legacy_user_lock(username):
475
+ path = _legacy_user_history_path(username)
476
+ if path.exists():
477
+ return json.loads(path.read_text())
478
+ return [] # No history yet
479
+
480
+
481
+ def _legacy_user_history_path(username: str) -> Path:
482
+ return _legacy_get_history_folder_path() / f"{username}.json"
483
+
484
+
485
+ def _legacy_user_lock(username: str) -> FileLock:
486
+ """Ensure history is not corrupted if concurrent calls."""
487
+ return FileLock(f"{_legacy_user_history_path(username)}.lock")