Spaces:
Running
Running
Add a beautiful description
Browse files- app.py +52 -58
- safety_checker.py +137 -0
app.py
CHANGED
|
@@ -4,6 +4,7 @@ import gradio as gr
|
|
| 4 |
from gradio import processing_utils, utils
|
| 5 |
from PIL import Image
|
| 6 |
import random
|
|
|
|
| 7 |
from diffusers import (
|
| 8 |
DiffusionPipeline,
|
| 9 |
AutoencoderKL,
|
|
@@ -12,39 +13,60 @@ from diffusers import (
|
|
| 12 |
StableDiffusionLatentUpscalePipeline,
|
| 13 |
StableDiffusionImg2ImgPipeline,
|
| 14 |
StableDiffusionControlNetImg2ImgPipeline,
|
| 15 |
-
DPMSolverMultistepScheduler,
|
| 16 |
-
EulerDiscreteScheduler
|
| 17 |
)
|
| 18 |
import tempfile
|
| 19 |
import time
|
| 20 |
from share_btn import community_icon_html, loading_icon_html, share_js
|
| 21 |
import user_history
|
| 22 |
from illusion_style import css
|
| 23 |
-
|
|
|
|
|
|
|
| 24 |
|
| 25 |
BASE_MODEL = "SG161222/Realistic_Vision_V5.1_noVAE"
|
| 26 |
|
| 27 |
-
|
| 28 |
-
device='cpu'
|
| 29 |
-
|
| 30 |
# Initialize both pipelines
|
| 31 |
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
main_pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 35 |
BASE_MODEL,
|
| 36 |
controlnet=controlnet,
|
| 37 |
vae=vae,
|
| 38 |
-
safety_checker=
|
|
|
|
| 39 |
torch_dtype=torch.float16,
|
| 40 |
-
).to(
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
#main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
| 43 |
#main_pipe.unet.to(memory_format=torch.channels_last)
|
| 44 |
#main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
| 45 |
#model_id = "stabilityai/sd-x2-latent-upscaler"
|
| 46 |
image_pipe = StableDiffusionControlNetImg2ImgPipeline(**main_pipe.components)
|
| 47 |
|
|
|
|
| 48 |
#image_pipe.unet = torch.compile(image_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
| 49 |
#upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
| 50 |
#upscaler.to("cuda")
|
|
@@ -104,12 +126,13 @@ def check_inputs(prompt: str, control_image: Image.Image):
|
|
| 104 |
raise gr.Error("Prompt is required")
|
| 105 |
|
| 106 |
def convert_to_pil(base64_image):
|
| 107 |
-
pil_image =
|
| 108 |
return pil_image
|
| 109 |
|
| 110 |
def convert_to_base64(pil_image):
|
| 111 |
-
|
| 112 |
-
|
|
|
|
| 113 |
|
| 114 |
# Inference function
|
| 115 |
@spaces.GPU
|
|
@@ -141,7 +164,7 @@ def inference(
|
|
| 141 |
|
| 142 |
main_pipe.scheduler = SAMPLER_MAP[sampler](main_pipe.scheduler.config)
|
| 143 |
my_seed = random.randint(0, 2**32 - 1) if seed == -1 else seed
|
| 144 |
-
generator = torch.Generator(device=
|
| 145 |
|
| 146 |
out = main_pipe(
|
| 147 |
prompt=prompt,
|
|
@@ -197,15 +220,17 @@ def inference(
|
|
| 197 |
with gr.Blocks() as app:
|
| 198 |
gr.Markdown(
|
| 199 |
'''
|
| 200 |
-
<
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
'''
|
| 208 |
)
|
|
|
|
|
|
|
| 209 |
state_img_input = gr.State()
|
| 210 |
state_img_output = gr.State()
|
| 211 |
with gr.Row():
|
|
@@ -235,53 +260,22 @@ with gr.Blocks() as app:
|
|
| 235 |
check_inputs,
|
| 236 |
inputs=[prompt, control_image],
|
| 237 |
queue=False
|
| 238 |
-
).success(
|
| 239 |
-
convert_to_pil,
|
| 240 |
-
inputs=[control_image],
|
| 241 |
-
outputs=[state_img_input],
|
| 242 |
-
queue=False,
|
| 243 |
-
preprocess=False,
|
| 244 |
).success(
|
| 245 |
inference,
|
| 246 |
-
inputs=[
|
| 247 |
-
outputs=[
|
| 248 |
-
|
| 249 |
-
convert_to_base64,
|
| 250 |
-
inputs=[state_img_output],
|
| 251 |
-
outputs=[result_image],
|
| 252 |
-
queue=False,
|
| 253 |
-
postprocess=False
|
| 254 |
-
)
|
| 255 |
run_btn.click(
|
| 256 |
check_inputs,
|
| 257 |
inputs=[prompt, control_image],
|
| 258 |
queue=False
|
| 259 |
-
).success(
|
| 260 |
-
convert_to_pil,
|
| 261 |
-
inputs=[control_image],
|
| 262 |
-
outputs=[state_img_input],
|
| 263 |
-
queue=False,
|
| 264 |
-
preprocess=False,
|
| 265 |
).success(
|
| 266 |
inference,
|
| 267 |
-
inputs=[
|
| 268 |
-
outputs=[
|
| 269 |
-
|
| 270 |
-
convert_to_base64,
|
| 271 |
-
inputs=[state_img_output],
|
| 272 |
-
outputs=[result_image],
|
| 273 |
-
queue=False,
|
| 274 |
-
postprocess=False
|
| 275 |
-
)
|
| 276 |
share_button.click(None, [], [], js=share_js)
|
| 277 |
|
| 278 |
-
def greet(name):
|
| 279 |
-
return "Hello " + name + "!!"
|
| 280 |
-
|
| 281 |
-
#demo = gr.Interface(fn=greet, inputs="text", outputs="text")
|
| 282 |
-
#demo.launch()
|
| 283 |
-
|
| 284 |
-
|
| 285 |
with gr.Blocks(css=css) as app_with_history:
|
| 286 |
with gr.Tab("Demo"):
|
| 287 |
app.render()
|
|
|
|
| 4 |
from gradio import processing_utils, utils
|
| 5 |
from PIL import Image
|
| 6 |
import random
|
| 7 |
+
|
| 8 |
from diffusers import (
|
| 9 |
DiffusionPipeline,
|
| 10 |
AutoencoderKL,
|
|
|
|
| 13 |
StableDiffusionLatentUpscalePipeline,
|
| 14 |
StableDiffusionImg2ImgPipeline,
|
| 15 |
StableDiffusionControlNetImg2ImgPipeline,
|
| 16 |
+
DPMSolverMultistepScheduler,
|
| 17 |
+
EulerDiscreteScheduler
|
| 18 |
)
|
| 19 |
import tempfile
|
| 20 |
import time
|
| 21 |
from share_btn import community_icon_html, loading_icon_html, share_js
|
| 22 |
import user_history
|
| 23 |
from illusion_style import css
|
| 24 |
+
import os
|
| 25 |
+
from transformers import CLIPImageProcessor
|
| 26 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 27 |
|
| 28 |
BASE_MODEL = "SG161222/Realistic_Vision_V5.1_noVAE"
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
# Initialize both pipelines
|
| 31 |
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
|
| 32 |
+
controlnet = ControlNetModel.from_pretrained("monster-labs/control_v1p_sd15_qrcode_monster", torch_dtype=torch.float16)
|
| 33 |
+
|
| 34 |
+
# Initialize the safety checker conditionally
|
| 35 |
+
SAFETY_CHECKER_ENABLED = os.environ.get("SAFETY_CHECKER", "0") == "1"
|
| 36 |
+
safety_checker = None
|
| 37 |
+
feature_extractor = None
|
| 38 |
+
if SAFETY_CHECKER_ENABLED:
|
| 39 |
+
safety_checker = StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-safety-checker").to("cuda")
|
| 40 |
+
feature_extractor = CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 41 |
+
|
| 42 |
main_pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 43 |
BASE_MODEL,
|
| 44 |
controlnet=controlnet,
|
| 45 |
vae=vae,
|
| 46 |
+
safety_checker=safety_checker,
|
| 47 |
+
feature_extractor=feature_extractor,
|
| 48 |
torch_dtype=torch.float16,
|
| 49 |
+
).to("cuda")
|
| 50 |
|
| 51 |
+
# Function to check NSFW images
|
| 52 |
+
#def check_nsfw_images(images: list[Image.Image]) -> tuple[list[Image.Image], list[bool]]:
|
| 53 |
+
# if SAFETY_CHECKER_ENABLED:
|
| 54 |
+
# safety_checker_input = feature_extractor(images, return_tensors="pt").to("cuda")
|
| 55 |
+
# has_nsfw_concepts = safety_checker(
|
| 56 |
+
# images=[images],
|
| 57 |
+
# clip_input=safety_checker_input.pixel_values.to("cuda")
|
| 58 |
+
# )
|
| 59 |
+
# return images, has_nsfw_concepts
|
| 60 |
+
# else:
|
| 61 |
+
# return images, [False] * len(images)
|
| 62 |
+
|
| 63 |
#main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
| 64 |
#main_pipe.unet.to(memory_format=torch.channels_last)
|
| 65 |
#main_pipe.unet = torch.compile(main_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
| 66 |
#model_id = "stabilityai/sd-x2-latent-upscaler"
|
| 67 |
image_pipe = StableDiffusionControlNetImg2ImgPipeline(**main_pipe.components)
|
| 68 |
|
| 69 |
+
|
| 70 |
#image_pipe.unet = torch.compile(image_pipe.unet, mode="reduce-overhead", fullgraph=True)
|
| 71 |
#upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
| 72 |
#upscaler.to("cuda")
|
|
|
|
| 126 |
raise gr.Error("Prompt is required")
|
| 127 |
|
| 128 |
def convert_to_pil(base64_image):
|
| 129 |
+
pil_image = Image.open(base64_image)
|
| 130 |
return pil_image
|
| 131 |
|
| 132 |
def convert_to_base64(pil_image):
|
| 133 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file:
|
| 134 |
+
image.save(temp_file.name)
|
| 135 |
+
return temp_file.name
|
| 136 |
|
| 137 |
# Inference function
|
| 138 |
@spaces.GPU
|
|
|
|
| 164 |
|
| 165 |
main_pipe.scheduler = SAMPLER_MAP[sampler](main_pipe.scheduler.config)
|
| 166 |
my_seed = random.randint(0, 2**32 - 1) if seed == -1 else seed
|
| 167 |
+
generator = torch.Generator(device="cuda").manual_seed(my_seed)
|
| 168 |
|
| 169 |
out = main_pipe(
|
| 170 |
prompt=prompt,
|
|
|
|
| 220 |
with gr.Blocks() as app:
|
| 221 |
gr.Markdown(
|
| 222 |
'''
|
| 223 |
+
<div style="text-align: center;">
|
| 224 |
+
<h1>Illusion Diffusion HQ 🌀</h1>
|
| 225 |
+
<p style="font-size:16px;">Generate stunning high quality illusion artwork with Stable Diffusion</p>
|
| 226 |
+
<p>Illusion Diffusion is back up with a safety checker! Because I have been asked, if you would like to support me, consider using <a href="https://deforum.studio">deforum.studio</a></p>
|
| 227 |
+
<p>A space by AP <a href="https://twitter.com/angrypenguinPNG">Follow me on Twitter</a> with big contributions from <a href="https://twitter.com/multimodalart">multimodalart</a></p>
|
| 228 |
+
<p>This project works by using <a href="https://huggingface.co/monster-labs/control_v1p_sd15_qrcode_monster">Monster Labs QR Control Net</a>. Given a prompt and your pattern, we use a QR code conditioned controlnet to create a stunning illusion! Credit to: <a href="https://twitter.com/MrUgleh">MrUgleh</a> for discovering the workflow :)</p>
|
| 229 |
+
</div>
|
| 230 |
'''
|
| 231 |
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
state_img_input = gr.State()
|
| 235 |
state_img_output = gr.State()
|
| 236 |
with gr.Row():
|
|
|
|
| 260 |
check_inputs,
|
| 261 |
inputs=[prompt, control_image],
|
| 262 |
queue=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
).success(
|
| 264 |
inference,
|
| 265 |
+
inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler],
|
| 266 |
+
outputs=[result_image, result_image, share_group, used_seed])
|
| 267 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
run_btn.click(
|
| 269 |
check_inputs,
|
| 270 |
inputs=[prompt, control_image],
|
| 271 |
queue=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
).success(
|
| 273 |
inference,
|
| 274 |
+
inputs=[control_image, prompt, negative_prompt, guidance_scale, controlnet_conditioning_scale, control_start, control_end, strength, seed, sampler],
|
| 275 |
+
outputs=[result_image, result_image, share_group, used_seed])
|
| 276 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
share_button.click(None, [], [], js=share_js)
|
| 278 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
with gr.Blocks(css=css) as app_with_history:
|
| 280 |
with gr.Tab("Demo"):
|
| 281 |
app.render()
|
safety_checker.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def cosine_distance(image_embeds, text_embeds):
|
| 22 |
+
normalized_image_embeds = nn.functional.normalize(image_embeds)
|
| 23 |
+
normalized_text_embeds = nn.functional.normalize(text_embeds)
|
| 24 |
+
return torch.mm(normalized_image_embeds, normalized_text_embeds.t())
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class StableDiffusionSafetyChecker(PreTrainedModel):
|
| 28 |
+
config_class = CLIPConfig
|
| 29 |
+
|
| 30 |
+
_no_split_modules = ["CLIPEncoderLayer"]
|
| 31 |
+
|
| 32 |
+
def __init__(self, config: CLIPConfig):
|
| 33 |
+
super().__init__(config)
|
| 34 |
+
|
| 35 |
+
self.vision_model = CLIPVisionModel(config.vision_config)
|
| 36 |
+
self.visual_projection = nn.Linear(
|
| 37 |
+
config.vision_config.hidden_size, config.projection_dim, bias=False
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
self.concept_embeds = nn.Parameter(
|
| 41 |
+
torch.ones(17, config.projection_dim), requires_grad=False
|
| 42 |
+
)
|
| 43 |
+
self.special_care_embeds = nn.Parameter(
|
| 44 |
+
torch.ones(3, config.projection_dim), requires_grad=False
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
self.concept_embeds_weights = nn.Parameter(torch.ones(17), requires_grad=False)
|
| 48 |
+
self.special_care_embeds_weights = nn.Parameter(
|
| 49 |
+
torch.ones(3), requires_grad=False
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
@torch.no_grad()
|
| 53 |
+
def forward(self, clip_input, images):
|
| 54 |
+
pooled_output = self.vision_model(clip_input)[1] # pooled_output
|
| 55 |
+
image_embeds = self.visual_projection(pooled_output)
|
| 56 |
+
|
| 57 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 58 |
+
special_cos_dist = (
|
| 59 |
+
cosine_distance(image_embeds, self.special_care_embeds)
|
| 60 |
+
.cpu()
|
| 61 |
+
.float()
|
| 62 |
+
.numpy()
|
| 63 |
+
)
|
| 64 |
+
cos_dist = (
|
| 65 |
+
cosine_distance(image_embeds, self.concept_embeds).cpu().float().numpy()
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
result = []
|
| 69 |
+
batch_size = image_embeds.shape[0]
|
| 70 |
+
for i in range(batch_size):
|
| 71 |
+
result_img = {
|
| 72 |
+
"special_scores": {},
|
| 73 |
+
"special_care": [],
|
| 74 |
+
"concept_scores": {},
|
| 75 |
+
"bad_concepts": [],
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
# increase this value to create a stronger `nfsw` filter
|
| 79 |
+
# at the cost of increasing the possibility of filtering benign images
|
| 80 |
+
adjustment = 0.0
|
| 81 |
+
|
| 82 |
+
for concept_idx in range(len(special_cos_dist[0])):
|
| 83 |
+
concept_cos = special_cos_dist[i][concept_idx]
|
| 84 |
+
concept_threshold = self.special_care_embeds_weights[concept_idx].item()
|
| 85 |
+
result_img["special_scores"][concept_idx] = round(
|
| 86 |
+
concept_cos - concept_threshold + adjustment, 3
|
| 87 |
+
)
|
| 88 |
+
if result_img["special_scores"][concept_idx] > 0:
|
| 89 |
+
result_img["special_care"].append(
|
| 90 |
+
{concept_idx, result_img["special_scores"][concept_idx]}
|
| 91 |
+
)
|
| 92 |
+
adjustment = 0.01
|
| 93 |
+
|
| 94 |
+
for concept_idx in range(len(cos_dist[0])):
|
| 95 |
+
concept_cos = cos_dist[i][concept_idx]
|
| 96 |
+
concept_threshold = self.concept_embeds_weights[concept_idx].item()
|
| 97 |
+
result_img["concept_scores"][concept_idx] = round(
|
| 98 |
+
concept_cos - concept_threshold + adjustment, 3
|
| 99 |
+
)
|
| 100 |
+
if result_img["concept_scores"][concept_idx] > 0:
|
| 101 |
+
result_img["bad_concepts"].append(concept_idx)
|
| 102 |
+
|
| 103 |
+
result.append(result_img)
|
| 104 |
+
|
| 105 |
+
has_nsfw_concepts = [len(res["bad_concepts"]) > 0 for res in result]
|
| 106 |
+
|
| 107 |
+
return has_nsfw_concepts
|
| 108 |
+
|
| 109 |
+
@torch.no_grad()
|
| 110 |
+
def forward_onnx(self, clip_input: torch.FloatTensor, images: torch.FloatTensor):
|
| 111 |
+
pooled_output = self.vision_model(clip_input)[1] # pooled_output
|
| 112 |
+
image_embeds = self.visual_projection(pooled_output)
|
| 113 |
+
|
| 114 |
+
special_cos_dist = cosine_distance(image_embeds, self.special_care_embeds)
|
| 115 |
+
cos_dist = cosine_distance(image_embeds, self.concept_embeds)
|
| 116 |
+
|
| 117 |
+
# increase this value to create a stronger `nsfw` filter
|
| 118 |
+
# at the cost of increasing the possibility of filtering benign images
|
| 119 |
+
adjustment = 0.0
|
| 120 |
+
|
| 121 |
+
special_scores = (
|
| 122 |
+
special_cos_dist - self.special_care_embeds_weights + adjustment
|
| 123 |
+
)
|
| 124 |
+
# special_scores = special_scores.round(decimals=3)
|
| 125 |
+
special_care = torch.any(special_scores > 0, dim=1)
|
| 126 |
+
special_adjustment = special_care * 0.01
|
| 127 |
+
special_adjustment = special_adjustment.unsqueeze(1).expand(
|
| 128 |
+
-1, cos_dist.shape[1]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
concept_scores = (cos_dist - self.concept_embeds_weights) + special_adjustment
|
| 132 |
+
# concept_scores = concept_scores.round(decimals=3)
|
| 133 |
+
has_nsfw_concepts = torch.any(concept_scores > 0, dim=1)
|
| 134 |
+
|
| 135 |
+
images[has_nsfw_concepts] = 0.0 # black image
|
| 136 |
+
|
| 137 |
+
return images, has_nsfw_concepts
|