nyanko7 commited on
Commit
a859794
0 Parent(s):

Super-squash branch 'main' using huggingface_hub

Browse files
Files changed (4) hide show
  1. .gitattributes +35 -0
  2. README.md +13 -0
  3. app.py +285 -0
  4. requirements.txt +4 -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
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: XL Model Experiments
3
+ emoji: 📚
4
+ colorFrom: red
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 4.44.1
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
app.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import inspect
3
+ import os
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
5
+
6
+ import math
7
+ import torch
8
+ import random
9
+ import torch.nn.functional as F
10
+ import tempfile
11
+ import gradio as gr
12
+ import spaces
13
+ import httpimport
14
+ import json
15
+ from PIL import Image
16
+ from packaging import version
17
+ from PIL.PngImagePlugin import PngInfo
18
+
19
+ with httpimport.remote_repo(os.getenv("MODULE_URL")):
20
+ import pipeline
21
+ pipe, pipe2, pipe_img2img, pipe2_img2img = pipeline.get_pipeline_initialize()
22
+
23
+ theme = gr.themes.Base(font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif'])
24
+ device="cuda"
25
+ pipe = pipe.to(device)
26
+ pipe2 = pipe2.to(device)
27
+ PRESET_Q = "year_2022, best quality, high quality, very aesthetic"
28
+ NEGATIVE_PROMPT = "lowres, worst quality, displeasing, bad anatomy, text, error, extra digit, cropped, error, fewer, extra, missing, worst quality, jpeg artifacts, censored, worst quality displeasing, bad quality"
29
+
30
+ import hashlib
31
+ import base64
32
+ import hmac
33
+
34
+ import numpy as np
35
+ import pickle
36
+ import requests
37
+ import codecs
38
+
39
+ def tpu_inference_api(
40
+ prompt: str,
41
+ radio: str = "model-v2",
42
+ preset: str = "year_2022, best quality, high quality, very aesthetic",
43
+ h: int = 1216,
44
+ w: int = 832,
45
+ negative_prompt: str = "lowres, worst quality, displeasing, bad anatomy, text, error, extra digit, cropped, error, fewer, extra, missing, worst quality, jpeg artifacts, censored, ai-generated worst quality displeasing, bad quality",
46
+ guidance_scale: float = 4.0,
47
+ randomize_seed: bool = True,
48
+ seed: int = 42,
49
+ do_img2img: bool = False,
50
+ init_image: Optional[str] = None,
51
+ image2image_strength: float = 0,
52
+ ) -> bytes:
53
+ url = os.getenv("TPU_INFERENCE_API")
54
+ if(randomize_seed):
55
+ seed = random.randint(0, 9007199254740991)
56
+ randomize_seed = False
57
+
58
+ payload = {
59
+ "prompt": prompt,
60
+ "radio": radio,
61
+ "preset": preset,
62
+ "height": h,
63
+ "width": w,
64
+ "negative_prompt": negative_prompt,
65
+ "guidance_scale": guidance_scale,
66
+ "randomize_seed": randomize_seed,
67
+ "seed": seed,
68
+ "do_img2img": do_img2img,
69
+ "image2image_strength": image2image_strength,
70
+ "init_image": init_image
71
+ }
72
+ response = requests.post(url, json=payload)
73
+ if response.status_code != 200:
74
+ raise Exception(f"Error calling API: {response.status_code} - {response.text}")
75
+
76
+ image = Image.open(io.BytesIO(response.content))
77
+ naifix = prompt[:40].replace(":", "_").replace("\\", "_").replace("/", "_") + f" s-{seed}-"
78
+ with tempfile.NamedTemporaryFile(prefix=naifix, suffix=".png", delete=False) as tmpfile:
79
+ parameters = {
80
+ "prompt": prompt,
81
+ "steps": 25,
82
+ "height": h,
83
+ "width": w,
84
+ "scale": guidance_scale,
85
+ "uncond_scale": 0.0,
86
+ "cfg_rescale": 0.0,
87
+ "seed": seed,
88
+ "n_samples": 1,
89
+ "hide_debug_overlay": False,
90
+ "noise_schedule": "native",
91
+ "legacy_v3_extend": False,
92
+ "reference_information_extracted_multiple": [],
93
+ "reference_strength_multiple": [],
94
+ "sampler": "k_dpmpp_2m_sde",
95
+ "controlnet_strength": 1.0,
96
+ "controlnet_model": None,
97
+ "dynamic_thresholding": False,
98
+ "dynamic_thresholding_percentile": 0.999,
99
+ "dynamic_thresholding_mimic_scale": 10.0,
100
+ "sm": False,
101
+ "sm_dyn": False,
102
+ "skip_cfg_above_sigma": 23.69030960605558,
103
+ "skip_cfg_below_sigma": 0.0,
104
+ "lora_unet_weights": None,
105
+ "lora_clip_weights": None,
106
+ "deliberate_euler_ancestral_bug": True,
107
+ "prefer_brownian": False,
108
+ "cfg_sched_eligibility": "enable_for_post_summer_samplers",
109
+ "explike_fine_detail": False,
110
+ "minimize_sigma_inf": False,
111
+ "uncond_per_vibe": True,
112
+ "wonky_vibe_correlation": True,
113
+ "version": 1,
114
+ "uc": "nsfw, lowres, {bad}, error, fewer, extra, missing, worst quality, jpeg artifacts, bad quality, watermark, unfinished, displeasing, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract], lowres, {bad}, error, fewer, extra, missing, worst quality, jpeg artifacts, bad quality, unfinished, displeasing, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract],{{{{chibi,doll,+_+}}}},",
115
+ }
116
+ metadata_params = {
117
+ "request_type": "PromptGenerateRequest",
118
+ "signed_hash": sign_message(json.dumps(parameters), "novelai-client"),
119
+ **parameters
120
+ }
121
+ metadata = PngInfo()
122
+ metadata.add_text("Title", "AI generated image")
123
+ metadata.add_text("Description", prompt)
124
+ metadata.add_text("Software", "NovelAI")
125
+ metadata.add_text("Source", "Stable Diffusion XL 7BCCAA2C")
126
+ metadata.add_text("Nya", "Nya~")
127
+ metadata.add_text("Generation time", f"1.{random.randint(1000000000, 9999999999)}")
128
+ metadata.add_text("Comment", json.dumps(metadata_params))
129
+ image.save(tmpfile, "png", pnginfo=metadata)
130
+ return tmpfile.name, seed
131
+
132
+ def sign_message(message, key):
133
+ hmac_digest = hmac.new(key.encode(), message.encode(), hashlib.sha512).digest()
134
+ signed_hash = base64.b64encode(hmac_digest).decode()
135
+ return signed_hash
136
+
137
+ def run(prompt, radio="model-v2", preset=PRESET_Q, h=1216, w=832, negative_prompt=NEGATIVE_PROMPT, guidance_scale=4.0, randomize_seed=True, seed=42, tpu_inference=False, do_img2img=False, init_image=None, image2image_resize=False, image2image_strength=0, progress=gr.Progress(track_tqdm=True)):
138
+ if init_image is None:
139
+ do_img2img = False
140
+
141
+ if do_img2img and image2image_resize:
142
+ # init_image: np.ndarray
143
+ init_image = Image.fromarray(init_image)
144
+ init_image = init_image.resize((w, h))
145
+ init_image = np.array(init_image)
146
+
147
+ if tpu_inference:
148
+ prompt = prompt.replace("!", " ").replace("\n", " ") # remote endpoint unsupported
149
+ if do_img2img:
150
+ init_image = codecs.encode(pickle.dumps(init_image, protocol=pickle.HIGHEST_PROTOCOL), "base64").decode('latin1')
151
+ return tpu_inference_api(prompt, radio, preset, h, w, negative_prompt, guidance_scale, randomize_seed, seed, do_img2img, init_image, image2image_strength)
152
+ else:
153
+ return tpu_inference_api(prompt, radio, preset, h, w, negative_prompt, guidance_scale, randomize_seed, seed)
154
+
155
+ return zero_inference_api(prompt, radio, preset, h, w, negative_prompt, guidance_scale, randomize_seed, seed, do_img2img, init_image, image2image_strength)
156
+
157
+ @spaces.GPU
158
+ def zero_inference_api(prompt, radio="model-v2", preset=PRESET_Q, h=1216, w=832, negative_prompt=NEGATIVE_PROMPT, guidance_scale=4.0, randomize_seed=True, seed=42, do_img2img=False, init_image=None, image2image_strength=0, progress=gr.Progress(track_tqdm=True)):
159
+ prompt = prompt.strip() + ", " + preset.strip()
160
+ negative_prompt = negative_prompt.strip() if negative_prompt and negative_prompt.strip() else None
161
+
162
+ print(f"Initial seed for prompt `{prompt}`", seed)
163
+ if(randomize_seed):
164
+ seed = random.randint(0, 9007199254740991)
165
+
166
+ if not prompt and not negative_prompt:
167
+ guidance_scale = 0.0
168
+
169
+ generator = torch.Generator(device="cuda").manual_seed(seed)
170
+
171
+ if not do_img2img:
172
+ if radio == "model-v2":
173
+ image = pipe(prompt, height=h, width=w, negative_prompt=negative_prompt, guidance_scale=guidance_scale, guidance_rescale=0.75, generator=generator, num_inference_steps=25).images[0]
174
+ else:
175
+ image = pipe2(prompt, height=h, width=w, negative_prompt=negative_prompt, guidance_scale=guidance_scale, guidance_rescale=0.75, generator=generator, num_inference_steps=25).images[0]
176
+ else:
177
+ init_image = Image.fromarray(init_image)
178
+ if radio == "model-v2":
179
+ image = pipe_img2img(prompt, image=init_image, strength=image2image_strength, negative_prompt=negative_prompt, guidance_scale=guidance_scale, generator=generator, num_inference_steps=20).images[0]
180
+ else:
181
+ image = pipe2_img2img(prompt, image=init_image, strength=image2image_strength, negative_prompt=negative_prompt, guidance_scale=guidance_scale, generator=generator, num_inference_steps=20).images[0]
182
+
183
+ naifix = prompt[:40].replace(":", "_").replace("\\", "_").replace("/", "_") + f" s-{seed}-"
184
+ with tempfile.NamedTemporaryFile(prefix=naifix, suffix=".png", delete=False) as tmpfile:
185
+ parameters = {
186
+ "prompt": prompt,
187
+ "steps": 25,
188
+ "height": h,
189
+ "width": w,
190
+ "scale": guidance_scale,
191
+ "uncond_scale": 0.0,
192
+ "cfg_rescale": 0.0,
193
+ "seed": seed,
194
+ "n_samples": 1,
195
+ "hide_debug_overlay": False,
196
+ "noise_schedule": "native",
197
+ "legacy_v3_extend": False,
198
+ "reference_information_extracted_multiple": [],
199
+ "reference_strength_multiple": [],
200
+ "sampler": "k_dpmpp_2m_sde",
201
+ "controlnet_strength": 1.0,
202
+ "controlnet_model": None,
203
+ "dynamic_thresholding": False,
204
+ "dynamic_thresholding_percentile": 0.999,
205
+ "dynamic_thresholding_mimic_scale": 10.0,
206
+ "sm": False,
207
+ "sm_dyn": False,
208
+ "skip_cfg_above_sigma": 23.69030960605558,
209
+ "skip_cfg_below_sigma": 0.0,
210
+ "lora_unet_weights": None,
211
+ "lora_clip_weights": None,
212
+ "deliberate_euler_ancestral_bug": True,
213
+ "prefer_brownian": False,
214
+ "cfg_sched_eligibility": "enable_for_post_summer_samplers",
215
+ "explike_fine_detail": False,
216
+ "minimize_sigma_inf": False,
217
+ "uncond_per_vibe": True,
218
+ "wonky_vibe_correlation": True,
219
+ "version": 1,
220
+ "uc": "nsfw, lowres, {bad}, error, fewer, extra, missing, worst quality, jpeg artifacts, bad quality, watermark, unfinished, displeasing, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract], lowres, {bad}, error, fewer, extra, missing, worst quality, jpeg artifacts, bad quality, unfinished, displeasing, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract],{{{{chibi,doll,+_+}}}},",
221
+ }
222
+ metadata_params = {
223
+ "request_type": "PromptGenerateRequest",
224
+ "signed_hash": sign_message(json.dumps(parameters), "novelai-client"),
225
+ **parameters
226
+ }
227
+ metadata = PngInfo()
228
+ metadata.add_text("Title", "AI generated image")
229
+ metadata.add_text("Description", prompt)
230
+ metadata.add_text("Software", "NovelAI")
231
+ metadata.add_text("Source", "Stable Diffusion XL 7BCCAA2C")
232
+ metadata.add_text("Nya", "Nya~")
233
+ metadata.add_text("Generation time", f"1.{random.randint(1000000000, 9999999999)}")
234
+ metadata.add_text("Comment", json.dumps(metadata_params))
235
+ image.save(tmpfile, "png", pnginfo=metadata)
236
+ return tmpfile.name, seed
237
+
238
+ with gr.Blocks(theme=theme) as demo:
239
+ gr.Markdown('''# SDXL Experiments
240
+ Just a simple demo for some SDXL model.''')
241
+ with gr.Row():
242
+ with gr.Column():
243
+ with gr.Group():
244
+ with gr.Row():
245
+ prompt = gr.Textbox(show_label=False, scale=5, value="1girl, rurudo", placeholder="Your prompt", info="Leave blank to test unconditional generation")
246
+ button = gr.Button("Generate", min_width=120)
247
+
248
+ preset = gr.Textbox(show_label=False, scale=5, value=PRESET_Q, info="Quality presets")
249
+ radio = gr.Radio(["model-v2-beta", "model-v2"], value="model-v2", label = "Choose the inference model")
250
+ with gr.Row():
251
+ height = gr.Slider(label="Height", value=1216, minimum=512, maximum=2560, step=64)
252
+ width = gr.Slider(label="Width", value=832, minimum=512, maximum=2560, step=64)
253
+
254
+ guidance_scale = gr.Number(label="CFG Guidance Scale", info="The guidance scale for CFG, ignored if no prompt is entered (unconditional generation)", value=4.0)
255
+ negative_prompt = gr.Textbox(label="Negative prompt", value=NEGATIVE_PROMPT, info="Is only applied for the CFG part, leave blank for unconditional generation")
256
+ seed = gr.Number(label="Seed", value=42, info="Seed for random number generator")
257
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
258
+ tpu_inference = gr.Checkbox(label="TPU Inference", value=False)
259
+
260
+ do_img2img = gr.Checkbox(label="Image to Image", value=False)
261
+ init_image = gr.Image(label="Input Image", visible=False)
262
+ image2image_resize = gr.Checkbox(label="Resize input image", value=False, visible=False)
263
+ image2image_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Noising strength", value=0.7, visible=False)
264
+
265
+ with gr.Column():
266
+ output = gr.Image(type="filepath", interactive=False)
267
+
268
+ gr.Examples(fn=run, examples=["mayano_top_gun_\(umamusume\), 1girl, rurudo", "sho (sho lwlw),[[[ohisashiburi]]],fukuro daizi,tianliang duohe fangdongye,[daidai ookami],year_2023, (wariza), depth of field, official_art"], inputs=prompt, outputs=[output, seed], cache_examples="lazy")
269
+
270
+ do_img2img.change(
271
+ fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
272
+ inputs=[do_img2img],
273
+ outputs=[init_image, image2image_resize, image2image_strength]
274
+ )
275
+ gr.on(
276
+ triggers=[
277
+ button.click,
278
+ prompt.submit
279
+ ],
280
+ fn=run,
281
+ inputs=[prompt, radio, preset, height, width, negative_prompt, guidance_scale, randomize_seed, seed, tpu_inference, do_img2img, init_image, image2image_resize, image2image_strength],
282
+ outputs=[output, seed],
283
+ )
284
+ if __name__ == "__main__":
285
+ demo.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ diffusers
2
+ transformers
3
+ accelerate
4
+ httpimport