Skip to content

Commit d0c714a

Browse files
[Safety Checker] Add Safety Checker Module
1 parent 7b8c883 commit d0c714a

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

scripts/txt2img.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,29 @@
1616
from ldm.models.diffusion.ddim import DDIMSampler
1717
from ldm.models.diffusion.plms import PLMSSampler
1818

19+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
20+
from transformers import AutoFeatureExtractor
21+
22+
feature_extractor = AutoFeatureExtractor.from_pretrained("CompVis/stable-diffusion-v-1-3", use_auth_token=True)
23+
safety_checker = StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-v-1-3", use_auth_token=True)
1924

2025
def chunk(it, size):
2126
it = iter(it)
2227
return iter(lambda: tuple(islice(it, size)), ())
2328

2429

30+
def numpy_to_pil(images):
31+
"""
32+
Convert a numpy image or a batch of images to a PIL image.
33+
"""
34+
if images.ndim == 3:
35+
images = images[None, ...]
36+
images = (images * 255).round().astype("uint8")
37+
pil_images = [Image.fromarray(image) for image in images]
38+
39+
return pil_images
40+
41+
2542
def load_model_from_config(config, ckpt, verbose=False):
2643
print(f"Loading model from {ckpt}")
2744
pl_sd = torch.load(ckpt, map_location="cpu")
@@ -220,7 +237,9 @@ def main():
220237
if opt.fixed_code:
221238
start_code = torch.randn([opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device=device)
222239

240+
print("start code", start_code.abs().sum())
223241
precision_scope = autocast if opt.precision=="autocast" else nullcontext
242+
precision_scope = nullcontext
224243
with torch.no_grad():
225244
with precision_scope("cuda"):
226245
with model.ema_scope():
@@ -269,7 +288,11 @@ def main():
269288
Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png'))
270289
grid_count += 1
271290

272-
toc = time.time()
291+
image = x_samples_ddim.cpu().permute(0, 2, 3, 1).numpy()
292+
293+
# run safety checker
294+
safety_checker_input = pipe.feature_extractor(numpy_to_pil(image), return_tensors="pt")
295+
image, has_nsfw_concept = pipe.safety_checker(images=image, clip_input=safety_checker_input.pixel_values)
273296

274297
print(f"Your samples are ready and waiting for you here: \n{outpath} \n"
275298
f" \nEnjoy.")

0 commit comments

Comments
 (0)