BulatF commited on
Commit
80fe449
β€’
1 Parent(s): ff399f2

Upload 13 files

Browse files
README.md CHANGED
@@ -1,13 +1,14 @@
1
  ---
2
- title: Pics
3
- emoji: πŸŒ–
4
- colorFrom: yellow
5
- colorTo: blue
6
  sdk: gradio
7
- sdk_version: 3.44.4
8
  app_file: app.py
9
  pinned: false
10
- license: mit
 
11
  ---
12
 
13
- 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
  ---
13
 
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ import gradio as gr
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
+ from share_btn import community_icon_html, loading_icon_html, share_js
18
+ from gallery_history import fetch_gallery_history, show_gallery_history
19
+ from illusion_style import css
20
+
21
+ BASE_MODEL = "SG161222/Realistic_Vision_V5.1_noVAE"
22
+
23
+ # Initialize both pipelines
24
+ vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
25
+ #init_pipe = DiffusionPipeline.from_pretrained("SG161222/Realistic_Vision_V5.1_noVAE", torch_dtype=torch.float16)
26
+ controlnet = ControlNetModel.from_pretrained("monster-labs/control_v1p_sd15_qrcode_monster", torch_dtype=torch.float16)#, torch_dtype=torch.float16)
27
+ main_pipe = StableDiffusionControlNetPipeline.from_pretrained(
28
+ BASE_MODEL,
29
+ controlnet=controlnet,
30
+ vae=vae,
31
+ safety_checker=None,
32
+ torch_dtype=torch.float16,
33
+ ).to("cuda")
34
+ #main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
35
+ #main_pipe.unet.to(memory_format=torch.channels_last)
36
+ #main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
37
+ #model_id = "stabilityai/sd-x2-latent-upscaler"
38
+ image_pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(BASE_MODEL, unet=main_pipe.unet, vae=vae, controlnet=controlnet, safety_checker=None, torch_dtype=torch.float16).to("cuda")
39
+ #image_pipe.unet = torch.compile(image_pipe.unet, mode="reduce-overhead", fullgraph=True)
40
+ #upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
41
+ #upscaler.to("cuda")
42
+
43
+
44
+ # Sampler map
45
+ SAMPLER_MAP = {
46
+ "DPM++ Karras SDE": lambda config: DPMSolverMultistepScheduler.from_config(config, use_karras=True, algorithm_type="sde-dpmsolver++"),
47
+ "Euler": lambda config: EulerDiscreteScheduler.from_config(config),
48
+ }
49
+
50
+ def center_crop_resize(img, output_size=(512, 512)):
51
+ width, height = img.size
52
+
53
+ # Calculate dimensions to crop to the center
54
+ new_dimension = min(width, height)
55
+ left = (width - new_dimension)/2
56
+ top = (height - new_dimension)/2
57
+ right = (width + new_dimension)/2
58
+ bottom = (height + new_dimension)/2
59
+
60
+ # Crop and resize
61
+ img = img.crop((left, top, right, bottom))
62
+ img = img.resize(output_size)
63
+
64
+ return img
65
+
66
+ def common_upscale(samples, width, height, upscale_method, crop=False):
67
+ if crop == "center":
68
+ old_width = samples.shape[3]
69
+ old_height = samples.shape[2]
70
+ old_aspect = old_width / old_height
71
+ new_aspect = width / height
72
+ x = 0
73
+ y = 0
74
+ if old_aspect > new_aspect:
75
+ x = round((old_width - old_width * (new_aspect / old_aspect)) / 2)
76
+ elif old_aspect < new_aspect:
77
+ y = round((old_height - old_height * (old_aspect / new_aspect)) / 2)
78
+ s = samples[:,:,y:old_height-y,x:old_width-x]
79
+ else:
80
+ s = samples
81
+
82
+ return torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method)
83
+
84
+ def upscale(samples, upscale_method, scale_by):
85
+ #s = samples.copy()
86
+ width = round(samples["images"].shape[3] * scale_by)
87
+ height = round(samples["images"].shape[2] * scale_by)
88
+ s = common_upscale(samples["images"], width, height, upscale_method, "disabled")
89
+ return (s)
90
+
91
+ # Inference function
92
+ def inference(
93
+ control_image: Image.Image,
94
+ prompt: str,
95
+ negative_prompt: str,
96
+ guidance_scale: float = 8.0,
97
+ controlnet_conditioning_scale: float = 1,
98
+ control_guidance_start: float = 1,
99
+ control_guidance_end: float = 1,
100
+ upscaler_strength: float = 0.5,
101
+ seed: int = -1,
102
+ sampler = "DPM++ Karras SDE",
103
+ progress = gr.Progress(track_tqdm=True)
104
+ ):
105
+ if prompt is None or prompt == "":
106
+ raise gr.Error("Prompt is required")
107
+
108
+ # Generate the initial image
109
+ #init_image = init_pipe(prompt).images[0]
110
+
111
+ # Rest of your existing code
112
+ control_image_small = center_crop_resize(control_image)
113
+ main_pipe.scheduler = SAMPLER_MAP[sampler](main_pipe.scheduler.config)
114
+ my_seed = random.randint(0, 2**32 - 1) if seed == -1 else seed
115
+ generator = torch.manual_seed(my_seed)
116
+
117
+ out = main_pipe(
118
+ prompt=prompt,
119
+ negative_prompt=negative_prompt,
120
+ image=control_image_small,
121
+ guidance_scale=float(guidance_scale),
122
+ controlnet_conditioning_scale=float(controlnet_conditioning_scale),
123
+ generator=generator,
124
+ control_guidance_start=float(control_guidance_start),
125
+ control_guidance_end=float(control_guidance_end),
126
+ num_inference_steps=15,
127
+ output_type="latent"
128
+ )
129
+ control_image_large = center_crop_resize(control_image, (1024, 1024))
130
+ upscaled_latents = upscale(out, "nearest-exact", 2)
131
+ out_image = image_pipe(
132
+ prompt=prompt,
133
+ negative_prompt=negative_prompt,
134
+ control_image=control_image_large,
135
+ image=upscaled_latents,
136
+ guidance_scale=float(guidance_scale),
137
+ generator=generator,
138
+ num_inference_steps=20,
139
+ strength=upscaler_strength,
140
+ control_guidance_start=float(control_guidance_start),
141
+ control_guidance_end=float(control_guidance_end),
142
+ controlnet_conditioning_scale=float(controlnet_conditioning_scale)
143
+ )
144
+ return out_image["images"][0], gr.update(visible=True), my_seed
145
+
146
+ #return out
147
+
148
+ with gr.Blocks(css=css) as app:
149
+ gr.Markdown(
150
+ '''
151
+ <center><h1>Illusion Diffusion HQ πŸŒ€</h1></span>
152
+ <span font-size:16px;">Generate stunning high quality illusion artwork with Stable Diffusion</span>
153
+ </center>
154
+
155
+ A space by AP [Follow me on Twitter](https://twitter.com/angrypenguinPNG) with big contributions from [multimodalart](https://twitter.com/multimodalart)
156
+
157
+ This project works by using [Monster Labs QR Control Net](https://huggingface.co/monster-labs/control_v1p_sd15_qrcode_monster).
158
+ 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 :)
159
+ '''
160
+ )
161
+
162
+ with gr.Row():
163
+ with gr.Column():
164
+ control_image = gr.Image(label="Input Illusion", type="pil", elem_id="control_image")
165
+ 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")
166
+ gr.Examples(examples=["checkers.png", "checkers_mid.jpg", "pattern.png", "ultra_checkers.png", "spiral.jpeg", "funky.jpeg" ], inputs=control_image)
167
+ prompt = gr.Textbox(label="Prompt", elem_id="prompt")
168
+ negative_prompt = gr.Textbox(label="Negative Prompt", value="low quality", elem_id="negative_prompt")
169
+ with gr.Accordion(label="Advanced Options", open=False):
170
+ guidance_scale = gr.Slider(minimum=0.0, maximum=50.0, step=0.25, value=7.5, label="Guidance Scale")
171
+ sampler = gr.Dropdown(choices=list(SAMPLER_MAP.keys()), value="Euler")
172
+ control_start = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0, label="Start of ControlNet")
173
+ control_end = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="End of ControlNet")
174
+ strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=1, label="Strength of the upscaler")
175
+ seed = gr.Slider(minimum=-1, maximum=9999999999, step=1, value=-1, label="Seed", info="-1 means random seed")
176
+ used_seed = gr.Number(label="Last seed used",interactive=False)
177
+ run_btn = gr.Button("Run")
178
+ with gr.Column():
179
+ result_image = gr.Image(label="Illusion Diffusion Output", interactive=False, elem_id="output")
180
+ with gr.Group(elem_id="share-btn-container", visible=False) as share_group:
181
+ community_icon = gr.HTML(community_icon_html)
182
+ loading_icon = gr.HTML(loading_icon_html)
183
+ share_button = gr.Button("Share to community", elem_id="share-btn")
184
+
185
+ history = show_gallery_history()
186
+ prompt.submit(
187
+ inference,
188
+ inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler],
189
+ outputs=[result_image, share_group, used_seed]
190
+ ).then(
191
+ fn=fetch_gallery_history, inputs=[prompt, result_image], outputs=history, queue=False
192
+ )
193
+ run_btn.click(
194
+ inference,
195
+ inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler],
196
+ outputs=[result_image, share_group, used_seed]
197
+ ).then(
198
+ fn=fetch_gallery_history, inputs=[prompt, result_image], outputs=history, queue=False
199
+ )
200
+ share_button.click(None, [], [], _js=share_js)
201
+ app.queue(max_size=20)
202
+
203
+ if __name__ == "__main__":
204
+ app.launch()
checkers.png ADDED
checkers_mid.jpg ADDED
funky.jpeg ADDED
gallery_history.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ How to use:
3
+ 1. Create a Space with a Persistent Storage attached. Filesystem will be available under `/data`.
4
+ 2. Add `hf_oauth: true` to the Space metadata (README.md). Make sure to have Gradio>=3.41.0 configured.
5
+ 3. Add `HISTORY_FOLDER` as a Space variable (example. `"/data/history"`).
6
+ 4. Add `filelock` as dependency in `requirements.txt`.
7
+ 5. Add history gallery to your Gradio app:
8
+ a. Add imports: `from gallery_history import fetch_gallery_history, show_gallery_history`
9
+ a. Add `history = show_gallery_history()` within `gr.Blocks` context.
10
+ b. Add `.then(fn=fetch_gallery_history, inputs=[prompt, result], outputs=history)` on the generate event.
11
+ """
12
+ import json
13
+ import os
14
+ import numpy as np
15
+ import shutil
16
+ from pathlib import Path
17
+ from PIL import Image
18
+ from typing import Dict, List, Optional, Tuple
19
+ from uuid import uuid4
20
+
21
+ import gradio as gr
22
+ from filelock import FileLock
23
+
24
+ _folder = os.environ.get("HISTORY_FOLDER")
25
+ if _folder is None:
26
+ print(
27
+ "'HISTORY_FOLDER' environment variable not set. User history will be saved "
28
+ "locally and will be lost when the Space instance is restarted."
29
+ )
30
+ _folder = Path(__file__).parent / "history"
31
+ HISTORY_FOLDER_PATH = Path(_folder)
32
+
33
+ IMAGES_FOLDER_PATH = HISTORY_FOLDER_PATH / "images"
34
+ IMAGES_FOLDER_PATH.mkdir(parents=True, exist_ok=True)
35
+
36
+
37
+ def show_gallery_history():
38
+ gr.Markdown(
39
+ "## Your past generations\n\n(Log in to keep a gallery of your previous generations."
40
+ " Your history will be saved and available on your next visit.)"
41
+ )
42
+ with gr.Column():
43
+ with gr.Row():
44
+ gr.LoginButton(min_width=250)
45
+ gr.LogoutButton(min_width=250)
46
+ gallery = gr.Gallery(
47
+ label="Past images",
48
+ show_label=True,
49
+ elem_id="gallery",
50
+ object_fit="contain",
51
+ columns=4,
52
+ height=512,
53
+ preview=False,
54
+ show_share_button=False,
55
+ show_download_button=False,
56
+ )
57
+ gr.Markdown(
58
+ "Make sure to save your images from time to time, this gallery may be deleted in the future."
59
+ )
60
+ gallery.attach_load_event(fetch_gallery_history, every=None)
61
+ return gallery
62
+
63
+
64
+ def fetch_gallery_history(
65
+ prompt: Optional[str] = None,
66
+ result: Optional[np.ndarray] = None,
67
+ user: Optional[gr.OAuthProfile] = None,
68
+ ):
69
+ if user is None:
70
+ return []
71
+ try:
72
+ if prompt is not None and result is not None: # None values means no new images
73
+ new_image = Image.fromarray(result, 'RGB')
74
+ return _update_user_history(user["preferred_username"], new_image, prompt)
75
+ else:
76
+ return _read_user_history(user["preferred_username"])
77
+ except Exception as e:
78
+ raise gr.Error(f"Error while fetching history: {e}") from e
79
+
80
+
81
+ ####################
82
+ # Internal helpers #
83
+ ####################
84
+
85
+
86
+ def _read_user_history(username: str) -> List[Tuple[str, str]]:
87
+ """Return saved history for that user."""
88
+ with _user_lock(username):
89
+ path = _user_history_path(username)
90
+ if path.exists():
91
+ return json.loads(path.read_text())
92
+ return [] # No history yet
93
+
94
+
95
+ def _update_user_history(
96
+ username: str, new_image: Image.Image, prompt: str
97
+ ) -> List[Tuple[str, str]]:
98
+ """Update history for that user and return it."""
99
+ with _user_lock(username):
100
+ # Read existing
101
+ path = _user_history_path(username)
102
+ if path.exists():
103
+ images = json.loads(path.read_text())
104
+ else:
105
+ images = [] # No history yet
106
+
107
+ # Copy image to persistent folder
108
+ images = [(_copy_image(new_image), prompt)] + images
109
+
110
+ # Save and return
111
+ path.write_text(json.dumps(images))
112
+ return images
113
+
114
+
115
+ def _user_history_path(username: str) -> Path:
116
+ return HISTORY_FOLDER_PATH / f"{username}.json"
117
+
118
+
119
+ def _user_lock(username: str) -> FileLock:
120
+ """Ensure history is not corrupted if concurrent calls."""
121
+ return FileLock(f"{_user_history_path(username)}.lock")
122
+
123
+
124
+ def _copy_image(new_image: Image.Image) -> str:
125
+ """Copy image to the persistent storage."""
126
+ dst = str(IMAGES_FOLDER_PATH / f"{uuid4().hex}.png")
127
+ new_image.save(dst)
128
+ return dst
gitattributes.txt 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
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,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ diffusers
2
+ transformers
3
+ accelerate
4
+ torch
5
+ xformers
6
+ gradio
7
+ Pillow
8
+ qrcode
9
+ filelock
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