SolverHandle/Centdon
0
1import gradio as gr2#import torch3#from torch import autocast4#from diffusers import StableDiffusionPipeline5from datasets import load_dataset6from PIL import Image 7#from io import BytesIO8#import base649import re10import os11import requests12 13 14from share_btn import community_icon_html, loading_icon_html, share_js15 16model_id = "CompVis/stable-diffusion-v1-4"17device = "cuda"18 19#If you are running this code locally, you need to either do a 'huggingface-cli login` or paste your User Access Token from here https://huggingface.co/settings/tokens into the use_auth_token field below. 20#pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True, revision="fp16", torch_dtype=torch.float16)21#pipe = pipe.to(device)22#torch.backends.cudnn.benchmark = True23 24#When running locally, you won`t have access to this, so you can remove this part25word_list_dataset = load_dataset("SolverHandle/word-list", data_files="list.txt", use_auth_token=True)26word_list = word_list_dataset["train"]['text']27 28is_gpu_busy = False29def infer(prompt):30 global is_gpu_busy31 samples = 432 steps = 5033 scale = 7.534 #When running locally you can also remove this filter35 for filter in word_list:36 if re.search(rf"\b{filter}\b", prompt):37 raise gr.Error("Unsafe content found. Please try again with different prompts.")38 39 #generator = torch.Generator(device=device).manual_seed(seed)40 #print("Is GPU busy? ", is_gpu_busy)41 images = []42 #if(not is_gpu_busy):43 # is_gpu_busy = True44 # images_list = pipe(45 # [prompt] * samples,46 # num_inference_steps=steps,47 # guidance_scale=scale,48 #generator=generator,49 # )50 # is_gpu_busy = False51 # safe_image = Image.open(r"unsafe.png")52 # for i, image in enumerate(images_list["sample"]):53 # if(images_list["nsfw_content_detected"][i]):54 # images.append(safe_image)55 # else:56 # images.append(image)57 #else:58 url = os.getenv('JAX_BACKEND_URL')59 payload = {'prompt': prompt}60 images_request = requests.post(url, json = payload)61 for image in images_request.json()["images"]:62 image_b64 = (f"data:image/jpeg;base64,{image}")63 images.append(image_b64)64 65 return images66 67 68css = """69 .gradio-container {70 font-family: 'IBM Plex Sans', sans-serif;71 }72 .gr-button {73 color: white;74 border-color: black;75 background: black;76 }77 input[type='range'] {78 accent-color: black;79 }80 .dark input[type='range'] {81 accent-color: #dfdfdf;82 }83 .container {84 max-width: 730px;85 margin: auto;86 padding-top: 1.5rem;87 }88 #gallery {89 min-height: 22rem;90 margin-bottom: 15px;91 margin-left: auto;92 margin-right: auto;93 border-bottom-right-radius: .5rem !important;94 border-bottom-left-radius: .5rem !important;95 }96 #gallery>div>.h-full {97 min-height: 20rem;98 }99 .details:hover {100 text-decoration: underline;101 }102 .gr-button {103 white-space: nowrap;104 }105 .gr-button:focus {106 border-color: rgb(147 197 253 / var(--tw-border-opacity));107 outline: none;108 box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);109 --tw-border-opacity: 1;110 --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);111 --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);112 --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));113 --tw-ring-opacity: .5;114 }115 #advanced-btn {116 font-size: .7rem !important;117 line-height: 19px;118 margin-top: 12px;119 margin-bottom: 12px;120 padding: 2px 8px;121 border-radius: 14px !important;122 }123 #advanced-options {124 display: none;125 margin-bottom: 20px;126 }127 .footer {128 margin-bottom: 45px;129 margin-top: 35px;130 text-align: center;131 border-bottom: 1px solid #e5e5e5;132 }133 .footer>p {134 font-size: .8rem;135 display: inline-block;136 padding: 0 10px;137 transform: translateY(10px);138 background: white;139 }140 .dark .footer {141 border-color: #303030;142 }143 .dark .footer>p {144 background: #0b0f19;145 }146 .acknowledgments h4{147 margin: 1.25em 0 .25em 0;148 font-weight: bold;149 font-size: 115%;150 }151 #container-advanced-btns{152 display: flex;153 flex-wrap: wrap;154 justify-content: space-between;155 align-items: center;156 }157 .animate-spin {158 animation: spin 1s linear infinite;159 }160 @keyframes spin {161 from {162 transform: rotate(0deg);163 }164 to {165 transform: rotate(360deg);166 }167 }168 #share-btn-container {169 display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;170 }171 #share-btn {172 all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;173 }174 #share-btn * {175 all: unset;176 }177 .gr-form{178 flex: 1 1 50%; border-top-right-radius: 0; border-bottom-right-radius: 0;179 }180 #prompt-container{181 gap: 0;182 }183"""184 185block = gr.Blocks(css=css)186 187examples = [188 [189 'A high tech solarpunk utopia in the Amazon rainforest',190# 4,191# 45,192# 7.5,193# 1024,194 ],195 [196 'A pikachu fine dining with a view to the Eiffel Tower',197# 4,198# 45,199# 7,200# 1024,201 ],202 [203 'A mecha robot in a favela in expressionist style',204# 4,205# 45,206# 7,207# 1024,208 ],209 [210 'an insect robot preparing a delicious meal',211# 4,212# 45,213# 7,214# 1024,215 ],216 [217 "A small cabin on top of a snowy mountain in the style of Disney, artstation",218# 4,219# 45,220# 7,221# 1024,222 ],223]224 225 226with block:227 gr.HTML(228 """229 <div style="text-align: center; max-width: 650px; margin: 0 auto;">230 <div231 style="232 display: inline-flex;233 align-items: center;234 gap: 0.8rem;235 font-size: 1.75rem;236 "237 >238 <svg239 width="0.65em"240 height="0.65em"241 viewBox="0 0 115 115"242 fill="none"243 xmlns="http://www.w3.org/2000/svg"244 >245 <rect width="23" height="23" fill="white"></rect>246 <rect y="69" width="23" height="23" fill="white"></rect>247 <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>248 <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>249 <rect x="46" width="23" height="23" fill="white"></rect>250 <rect x="46" y="69" width="23" height="23" fill="white"></rect>251 <rect x="69" width="23" height="23" fill="black"></rect>252 <rect x="69" y="69" width="23" height="23" fill="black"></rect>253 <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>254 <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>255 <rect x="115" y="46" width="23" height="23" fill="white"></rect>256 <rect x="115" y="115" width="23" height="23" fill="white"></rect>257 <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>258 <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>259 <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>260 <rect x="92" y="69" width="23" height="23" fill="white"></rect>261 <rect x="69" y="46" width="23" height="23" fill="white"></rect>262 <rect x="69" y="115" width="23" height="23" fill="white"></rect>263 <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>264 <rect x="46" y="46" width="23" height="23" fill="black"></rect>265 <rect x="46" y="115" width="23" height="23" fill="black"></rect>266 <rect x="46" y="69" width="23" height="23" fill="black"></rect>267 <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>268 <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>269 <rect x="23" y="69" width="23" height="23" fill="black"></rect>270 </svg>271 <h1 style="font-weight: 900; margin-bottom: 7px;">272 Stable Diffusion Demo273 </h1>274 </div>275 <p style="margin-bottom: 10px; font-size: 94%">276 Stable Diffusion is a state of the art text-to-image model that generates277 images from text.<br>For faster generation and forthcoming API278 access you can try279 <a280 href="http://beta.dreamstudio.ai/"281 style="text-decoration: underline;"282 target="_blank"283 >DreamStudio Beta</a284 >285 </p>286 </div>287 """288 )289 with gr.Group():290 with gr.Box():291 with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):292 text = gr.Textbox(293 label="Enter your prompt",294 show_label=False,295 max_lines=1,296 placeholder="Enter your prompt",297 elem_id="prompt-text-input",298 ).style(299 border=(True, False, True, True),300 rounded=(True, False, False, True),301 container=False,302 )303 btn = gr.Button("Generate image").style(304 margin=False,305 rounded=(False, True, True, False),306 full_width=False,307 )308 309 gallery = gr.Gallery(310 label="Generated images", show_label=False, elem_id="gallery"311 ).style(grid=[2], height="auto")312 313 with gr.Group(elem_id="container-advanced-btns"):314 advanced_button = gr.Button("Advanced options", elem_id="advanced-btn")315 with gr.Group(elem_id="share-btn-container"):316 community_icon = gr.HTML(community_icon_html)317 loading_icon = gr.HTML(loading_icon_html)318 share_button = gr.Button("Share to community", elem_id="share-btn")319 320 with gr.Row(elem_id="advanced-options"):321 gr.Markdown("Advanced settings are temporarily unavailable")322 samples = gr.Slider(label="Images", minimum=1, maximum=4, value=4, step=1)323 steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=45, step=1)324 scale = gr.Slider(325 label="Guidance Scale", minimum=0, maximum=50, value=7.5, step=0.1326 )327 seed = gr.Slider(328 label="Seed",329 minimum=0,330 maximum=2147483647,331 step=1,332 randomize=True,333 )334 335 ex = gr.Examples(examples=examples, fn=infer, inputs=text, outputs=[gallery, community_icon, loading_icon, share_button], cache_examples=False)336 ex.dataset.headers = [""]337 338 text.submit(infer, inputs=text, outputs=[gallery], postprocess=False)339 btn.click(infer, inputs=text, outputs=[gallery], postprocess=False)340 341 advanced_button.click(342 None,343 [],344 text,345 _js="""346 () => {347 const options = document.querySelector("body > gradio-app").querySelector("#advanced-options");348 options.style.display = ["none", ""].includes(options.style.display) ? "flex" : "none";349 }""",350 )351 share_button.click(352 None,353 [],354 [],355 _js=share_js,356 )357 gr.HTML(358 """359 <div class="footer">360 <p>Model by <a href="https://huggingface.co/CompVis" style="text-decoration: underline;" target="_blank">CompVis</a> and <a href="https://huggingface.co/SolverHandle" style="text-decoration: underline;" target="_blank">Stability AI</a> - Gradio Demo by ๐ค Hugging Face361 </p>362 </div>363 <div class="acknowledgments">364 <p><h4>LICENSE</h4>365The model is licensed with a <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" style="text-decoration: underline;" target="_blank">CreativeML Open RAIL-M</a> license. The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in this license. The license forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups. For the full list of restrictions please <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" target="_blank" style="text-decoration: underline;" target="_blank">read the license</a></p>366 <p><h4>Biases and content acknowledgment</h4>367Despite how impressive being able to turn text into image is, beware to the fact that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography and violence. The model was trained on the <a href="https://laion.ai/blog/laion-5b/" style="text-decoration: underline;" target="_blank">LAION-5B dataset</a>, which scraped non-curated image-text-pairs from the internet (the exception being the removal of illegal content) and is meant for research purposes. You can read more in the <a href="https://huggingface.co/CompVis/stable-diffusion-v1-4" style="text-decoration: underline;" target="_blank">model card</a></p>368 </div>369 """370 )371 372block.queue(concurrency_count=40, max_size=20).launch(max_threads=150)