


import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


lowerCAmelCase__						=			logging.get_logger(__name__)
def 							_UpperCAmelCase    (UpperCamelCase__					:  str    ,							UpperCamelCase__					:  Tuple						):
       _A				:	Union[str, Any]       =			nn.functional.normalize(UpperCamelCase__						)
       _A				:	Union[str, Any]       =			nn.functional.normalize(UpperCamelCase__						)
       return torch.mm(UpperCamelCase__    ,							normalized_text_embeds.t()						)







class 					lowerCAmelCase__	(    a):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			CLIPConfig

     __SCREAMING_SNAKE_CASE        =			["CLIPEncoderLayer"]


     def __init__(						self			,						__lowerCamelCase)      ->    str:
            super().__init__(__lowerCamelCase)

            _A				:	List[str]       =			CLIPVisionModel(config.vision_config)
            _A				:	List[Any]       =			nn.Linear(config.vision_config.hidden_size			,						config.projection_dim			,						bias=__lowerCamelCase)

            _A				:	Dict       =			nn.Parameter(torch.ones(1_7			,						config.projection_dim)			,						requires_grad=__lowerCamelCase)
            _A				:	str       =			nn.Parameter(torch.ones(3			,						config.projection_dim)			,						requires_grad=__lowerCamelCase)

            _A				:	str       =			nn.Parameter(torch.ones(1_7)			,						requires_grad=__lowerCamelCase)
            _A				:	Optional[int]       =			nn.Parameter(torch.ones(3)			,						requires_grad=__lowerCamelCase)


     @torch.no_grad()
     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase)      ->    Union[str, Any]:
            _A				:	List[Any]       =			self.vision_model(__lowerCamelCase)[1]  # pooled_output
            _A				:	Tuple       =			self.visual_projection(__lowerCamelCase)

            # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
            _A				:	List[Any]       =			cosine_distance(__lowerCamelCase			,						self.special_care_embeds).cpu().float().numpy()
            _A				:	List[Any]       =			cosine_distance(__lowerCamelCase			,						self.concept_embeds).cpu().float().numpy()

            _A				:	List[str]       =			[]
            _A				:	str       =			image_embeds.shape[0]
            for i in range(__lowerCamelCase):
                   _A				:	Optional[Any]       =			{"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []}

                   # increase this value to create a stronger `nfsw` filter
                   # at the cost of increasing the possibility of filtering benign images
                   _A				:	Any       =			0.0

                   for concept_idx in range(len(special_cos_dist[0])):
                          _A				:	Optional[int]       =			special_cos_dist[i][concept_idx]
                          _A				:	List[Any]       =			self.special_care_embeds_weights[concept_idx].item()
                          _A				:	Dict       =			round(concept_cos - concept_threshold + adjustment			,						3)
                          if result_img["special_scores"][concept_idx] > 0:
                                 result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]})
                                 _A				:	Union[str, Any]       =			0.0_1

                   for concept_idx in range(len(cos_dist[0])):
                          _A				:	Dict       =			cos_dist[i][concept_idx]
                          _A				:	str       =			self.concept_embeds_weights[concept_idx].item()
                          _A				:	Optional[Any]       =			round(concept_cos - concept_threshold + adjustment			,						3)
                          if result_img["concept_scores"][concept_idx] > 0:
                                 result_img["bad_concepts"].append(__lowerCamelCase)

                   result.append(__lowerCamelCase)

            _A				:	Tuple       =			[len(res["bad_concepts"]) > 0 for res in result]

            for idx, has_nsfw_concept in enumerate(__lowerCamelCase):
                   if has_nsfw_concept:
                          if torch.is_tensor(__lowerCamelCase) or torch.is_tensor(images[0]):
                                 _A				:	Optional[Any]       =			torch.zeros_like(images[idx])  # black image
                          else:
                                 _A				:	str       =			np.zeros(images[idx].shape)  # black image

            if any(__lowerCamelCase):
                   logger.warning(
                       "Potential NSFW content was detected in one or more images. A black image will be returned instead."
                       " Try again with a different prompt and/or seed.")

            return images, has_nsfw_concepts


     @torch.no_grad()
     def 			_lowerCamelCase			(						self			,						__lowerCamelCase			,						__lowerCamelCase)      ->    Any:
            _A				:	Union[str, Any]       =			self.vision_model(__lowerCamelCase)[1]  # pooled_output
            _A				:	List[Any]       =			self.visual_projection(__lowerCamelCase)

            _A				:	Optional[int]       =			cosine_distance(__lowerCamelCase			,						self.special_care_embeds)
            _A				:	int       =			cosine_distance(__lowerCamelCase			,						self.concept_embeds)

            # increase this value to create a stronger `nsfw` filter
            # at the cost of increasing the possibility of filtering benign images
            _A				:	List[str]       =			0.0

            _A				:	Union[str, Any]       =			special_cos_dist - self.special_care_embeds_weights + adjustment
            # special_scores = special_scores.round(decimals=3)
            _A				:	int       =			torch.any(special_scores > 0			,						dim=1)
            _A				:	Optional[Any]       =			special_care * 0.0_1
            _A				:	str       =			special_adjustment.unsqueeze(1).expand(-1			,						cos_dist.shape[1])

            _A				:	Tuple       =			(cos_dist - self.concept_embeds_weights) + special_adjustment
            # concept_scores = concept_scores.round(decimals=3)
            _A				:	List[Any]       =			torch.any(concept_scores > 0			,						dim=1)

            _A				:	List[str]       =			0.0  # black image

            return images, has_nsfw_concepts




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import SwinaSRImageProcessor
    from transformers.image_transforms import get_image_size







class 					lowerCAmelCase__	(    unittest.TestCase):




     '''simple docstring'''


     def __init__(						self			,						__lowerCamelCase			,						__lowerCamelCase=7			,						__lowerCamelCase=3			,						__lowerCamelCase=1_8			,						__lowerCamelCase=3_0			,						__lowerCamelCase=4_0_0			,						__lowerCamelCase=True			,						__lowerCamelCase=1 / 2_5_5			,						__lowerCamelCase=True			,						__lowerCamelCase=8			,						)      ->    Optional[Any]:
            _A				:	List[str]       =			parent
            _A				:	str       =			batch_size
            _A				:	Any       =			num_channels
            _A				:	Any       =			image_size
            _A				:	Optional[int]       =			min_resolution
            _A				:	Union[str, Any]       =			max_resolution
            _A				:	Optional[Any]       =			do_rescale
            _A				:	str       =			rescale_factor
            _A				:	str       =			do_pad
            _A				:	Dict       =			pad_size


     def 			_lowerCamelCase			(						self)      ->    str:
            return {
                "do_rescale": self.do_rescale,
                "rescale_factor": self.rescale_factor,
                "do_pad": self.do_pad,
                "pad_size": self.pad_size,
            }


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase=False			,						__lowerCamelCase=False			,						__lowerCamelCase=False)      ->    str:
            assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

            if equal_resolution:
                   _A				:	List[str]       =			[]
                   for i in range(self.batch_size):
                          image_inputs.append(
                              np.random.randint(
                                  2_5_5			,						size=(self.num_channels, self.max_resolution, self.max_resolution)			,						dtype=np.uinta))
            else:
                   _A				:	List[str]       =			[]
                   for i in range(self.batch_size):
                          _A   ,      _A				:	int       =			np.random.choice(np.arange(self.min_resolution			,						self.max_resolution)			,						2)
                          image_inputs.append(np.random.randint(2_5_5			,						size=(self.num_channels, width, height)			,						dtype=np.uinta))

            if not numpify and not torchify:
                   # PIL expects the channel dimension as last dimension
                   _A				:	Optional[Any]       =			[Image.fromarray(np.moveaxis(__lowerCamelCase			,						0			,						-1)) for x in image_inputs]

            if torchify:
                   _A				:	Union[str, Any]       =			[torch.from_numpy(__lowerCamelCase) for x in image_inputs]

            return image_inputs







@require_torch
@require_vision
class 					lowerCAmelCase__	(    a					,   unittest.TestCase):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE        =			SwinaSRImageProcessor if is_vision_available() else None


     def 			_lowerCamelCase			(						self)      ->    Any:
            _A				:	int       =			SwinaSRImageProcessingTester(self)


     @property
     def 			_lowerCamelCase			(						self)      ->    Any:
            return self.image_processor_tester.prepare_image_processor_dict()


     def 			_lowerCamelCase			(						self)      ->    Union[str, Any]:
            _A				:	Tuple       =			self.image_processing_class(**self.image_processor_dict)
            self.assertTrue(hasattr(__lowerCamelCase			,						"do_rescale"))
            self.assertTrue(hasattr(__lowerCamelCase			,						"rescale_factor"))
            self.assertTrue(hasattr(__lowerCamelCase			,						"do_pad"))
            self.assertTrue(hasattr(__lowerCamelCase			,						"pad_size"))


     def 			_lowerCamelCase			(						self)      ->    Dict:
            pass


     def 			_lowerCamelCase			(						self			,						__lowerCamelCase)      ->    Tuple:
            _A   ,      _A				:	Dict       =			get_image_size(__lowerCamelCase)
            _A				:	Tuple       =			self.image_processor_tester.pad_size

            _A				:	Dict       =			(old_height // size + 1) * size - old_height
            _A				:	Any       =			(old_width // size + 1) * size - old_width
            return old_height + pad_height, old_width + pad_width


     def 			_lowerCamelCase			(						self)      ->    Dict:
            # Initialize image_processor
            _A				:	Optional[int]       =			self.image_processing_class(**self.image_processor_dict)
            # create random PIL images
            _A				:	Union[str, Any]       =			self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase)
            for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase			,						Image.Image)

            # Test not batched input
            _A				:	str       =			image_processor(image_inputs[0]			,						return_tensors="pt").pixel_values
            _A   ,      _A				:	int       =			self.calculate_expected_size(np.array(image_inputs[0]))
            self.assertEqual(
                encoded_images.shape			,						(
                    1,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                )			,						)


     def 			_lowerCamelCase			(						self)      ->    int:
            # Initialize image_processor
            _A				:	Any       =			self.image_processing_class(**self.image_processor_dict)
            # create random numpy tensors
            _A				:	int       =			self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase			,						numpify=__lowerCamelCase)
            for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase			,						np.ndarray)

            # Test not batched input
            _A				:	Union[str, Any]       =			image_processor(image_inputs[0]			,						return_tensors="pt").pixel_values
            _A   ,      _A				:	Union[str, Any]       =			self.calculate_expected_size(image_inputs[0])
            self.assertEqual(
                encoded_images.shape			,						(
                    1,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                )			,						)


     def 			_lowerCamelCase			(						self)      ->    Optional[Any]:
            # Initialize image_processor
            _A				:	str       =			self.image_processing_class(**self.image_processor_dict)
            # create random PyTorch tensors
            _A				:	Tuple       =			self.image_processor_tester.prepare_inputs(equal_resolution=__lowerCamelCase			,						torchify=__lowerCamelCase)
            for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase			,						torch.Tensor)

            # Test not batched input
            _A				:	List[str]       =			image_processor(image_inputs[0]			,						return_tensors="pt").pixel_values
            _A   ,      _A				:	List[str]       =			self.calculate_expected_size(image_inputs[0])
            self.assertEqual(
                encoded_images.shape			,						(
                    1,
                    self.image_processor_tester.num_channels,
                    expected_height,
                    expected_width,
                )			,						)
