




'''simple docstring'''






import os
import pickle
import tempfile
import unittest
from typing import Callable, Optional

import numpy as np

from transformers import (
    BatchEncoding,
    BertTokenizer,
    BertTokenizerFast,
    PreTrainedTokenizer,
    PreTrainedTokenizerFast,
    TensorType,
    TokenSpan,
    is_tokenizers_available,
)
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import CaptureStderr, require_flax, require_tf, require_tokenizers, require_torch, slow


if is_tokenizers_available():
      from tokenizers import Tokenizer
      from tokenizers.models import WordPiece

class   SCREAMING_SNAKE_CASE_		(       unittest.TestCase				):



 def    SCREAMING_SNAKE_CASE(  self   ,		A ):






        '''simple docstring'''




        lowercase  :		List[Any]						=      list(tokenizer_class.max_model_input_sizes.keys() )
        for model_name in sa_models[:1]:
               lowercase  :		Dict						=      tokenizer_class.from_pretrained(A )
               self.assertIsNotNone(A )
               self.assertIsInstance(A   ,		A )
               self.assertIsInstance(A   ,		A )

               for special_tok in tokenizer.all_special_tokens:
                      self.assertIsInstance(A   ,		A )
                      lowercase  :		Tuple						=      tokenizer.convert_tokens_to_ids(A )
                      self.assertIsInstance(A   ,		A )



 def    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A = None ):






        '''simple docstring'''




        lowercase  :		List[Any]						=      pickle.dumps(A )
        self.assertIsNotNone(A )

        lowercase  :		str						=      pickle.loads(A )

        # Ensure is_fast is correctly restored
        self.assertEqual(be_restored.is_fast   ,		be_original.is_fast )

        # Ensure encodings are potentially correctly restored
        if be_original.is_fast:
               self.assertIsNotNone(be_restored.encodings )
        else:
               self.assertIsNone(be_restored.encodings )

        # Ensure the keys are the same
        for original_v, restored_v in zip(be_original.values()   ,		be_restored.values() ):
               if equal_op:
                      self.assertTrue(equal_op(A   ,		A ) )
               else:
                      self.assertEqual(A   ,		A )



 @slow
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        self.check_tokenizer_from_pretrained(A )



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        self.assertEqual(TensorType('''tf''' )   ,		TensorType.TENSORFLOW )
        self.assertEqual(TensorType('''pt''' )   ,		TensorType.PYTORCH )
        self.assertEqual(TensorType('''np''' )   ,		TensorType.NUMPY )



 @require_tokenizers
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        import numpy as np

        lowercase  :		Union[str, Any]						=      BertTokenizer.from_pretrained('''bert-base-cased''' )
        lowercase  :		str						=      BertTokenizerFast.from_pretrained('''bert-base-cased''' )

        # Python no tensor
        with self.subTest('''BatchEncoding (Python, return_tensors=None)''' ):
               self.assert_dump_and_restore(tokenizer_p('''Small example to encode''' ) )

        with self.subTest('''BatchEncoding (Python, return_tensors=NUMPY)''' ):
               self.assert_dump_and_restore(
                   tokenizer_p('''Small example to encode'''   ,		return_tensors=TensorType.NUMPY )   ,		np.array_equal )

        with self.subTest('''BatchEncoding (Rust, return_tensors=None)''' ):
               self.assert_dump_and_restore(tokenizer_r('''Small example to encode''' ) )

        with self.subTest('''BatchEncoding (Rust, return_tensors=NUMPY)''' ):
               self.assert_dump_and_restore(
                   tokenizer_r('''Small example to encode'''   ,		return_tensors=TensorType.NUMPY )   ,		np.array_equal )



 @require_tf
 @require_tokenizers
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        import tensorflow as tf

        def tf_array_equals(A   ,		A ):
               return tf.reduce_all(tf.equal(A   ,		A ) )

        lowercase  :		Optional[Any]						=      BertTokenizer.from_pretrained('''bert-base-cased''' )
        lowercase  :		Optional[Any]						=      BertTokenizerFast.from_pretrained('''bert-base-cased''' )

        with self.subTest('''BatchEncoding (Python, return_tensors=TENSORFLOW)''' ):
               self.assert_dump_and_restore(
                   tokenizer_p('''Small example to encode'''   ,		return_tensors=TensorType.TENSORFLOW )   ,		A )

        with self.subTest('''BatchEncoding (Rust, return_tensors=TENSORFLOW)''' ):
               self.assert_dump_and_restore(
                   tokenizer_r('''Small example to encode'''   ,		return_tensors=TensorType.TENSORFLOW )   ,		A )



 @require_torch
 @require_tokenizers
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        import torch

        lowercase  :		Tuple						=      BertTokenizer.from_pretrained('''bert-base-cased''' )
        lowercase  :		Any						=      BertTokenizerFast.from_pretrained('''bert-base-cased''' )

        with self.subTest('''BatchEncoding (Python, return_tensors=PYTORCH)''' ):
               self.assert_dump_and_restore(
                   tokenizer_p('''Small example to encode'''   ,		return_tensors=TensorType.PYTORCH )   ,		torch.equal )

        with self.subTest('''BatchEncoding (Rust, return_tensors=PYTORCH)''' ):
               self.assert_dump_and_restore(
                   tokenizer_r('''Small example to encode'''   ,		return_tensors=TensorType.PYTORCH )   ,		torch.equal )



 @require_tokenizers
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		str						=      BertTokenizer.from_pretrained('''bert-base-cased''' )
        lowercase  :		List[Any]						=      BertTokenizerFast.from_pretrained('''bert-base-cased''' )

        with self.subTest('''Python Tokenizer''' ):
               self.assertFalse(tokenizer_p('''Small example to_encode''' ).is_fast )

        with self.subTest('''Rust Tokenizer''' ):
               self.assertTrue(tokenizer_r('''Small example to_encode''' ).is_fast )



 @require_tokenizers
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Optional[int]						=      BertTokenizerFast.from_pretrained('''bert-base-cased''' )
        lowercase  :		str						=      tokenizer_r(['''Test''', '''\xad''', '''test''']   ,		is_split_into_words=A )

        self.assertEqual(encoded.word_to_tokens(0 )   ,		TokenSpan(start=1   ,		end=2 ) )
        self.assertEqual(encoded.word_to_tokens(1 )   ,		A )
        self.assertEqual(encoded.word_to_tokens(2 )   ,		TokenSpan(start=2   ,		end=3 ) )



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Optional[int]						=      BatchEncoding({'''inputs''': [[1, 2, 3], [4, 5, 6]], '''labels''': [0, 1]} )
        lowercase  :		List[str]						=      batch.convert_to_tensors(tensor_type='''np''' )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(2, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(2,) )
        # test converting the converted
        with CaptureStderr() as cs:
               lowercase  :		Any						=      batch.convert_to_tensors(tensor_type='''np''' )
        self.assertFalse(len(cs.err )   ,		msg=f"""should have no warning, but got {cs.err}""" )

        lowercase  :		Dict						=      BatchEncoding({'''inputs''': [1, 2, 3], '''labels''': 0} )
        lowercase  :		List[str]						=      batch.convert_to_tensors(tensor_type='''np'''   ,		prepend_batch_axis=A )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(1, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(1,) )



 @require_torch
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Dict						=      BatchEncoding({'''inputs''': [[1, 2, 3], [4, 5, 6]], '''labels''': [0, 1]} )
        lowercase  :		Union[str, Any]						=      batch.convert_to_tensors(tensor_type='''pt''' )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(2, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(2,) )
        # test converting the converted
        with CaptureStderr() as cs:
               lowercase  :		Tuple						=      batch.convert_to_tensors(tensor_type='''pt''' )
        self.assertFalse(len(cs.err )   ,		msg=f"""should have no warning, but got {cs.err}""" )

        lowercase  :		Optional[Any]						=      BatchEncoding({'''inputs''': [1, 2, 3], '''labels''': 0} )
        lowercase  :		List[str]						=      batch.convert_to_tensors(tensor_type='''pt'''   ,		prepend_batch_axis=A )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(1, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(1,) )



 @require_tf
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Dict						=      BatchEncoding({'''inputs''': [[1, 2, 3], [4, 5, 6]], '''labels''': [0, 1]} )
        lowercase  :		Dict						=      batch.convert_to_tensors(tensor_type='''tf''' )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(2, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(2,) )
        # test converting the converted
        with CaptureStderr() as cs:
               lowercase  :		Optional[int]						=      batch.convert_to_tensors(tensor_type='''tf''' )
        self.assertFalse(len(cs.err )   ,		msg=f"""should have no warning, but got {cs.err}""" )

        lowercase  :		str						=      BatchEncoding({'''inputs''': [1, 2, 3], '''labels''': 0} )
        lowercase  :		List[str]						=      batch.convert_to_tensors(tensor_type='''tf'''   ,		prepend_batch_axis=A )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(1, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(1,) )



 @require_flax
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Tuple						=      BatchEncoding({'''inputs''': [[1, 2, 3], [4, 5, 6]], '''labels''': [0, 1]} )
        lowercase  :		List[Any]						=      batch.convert_to_tensors(tensor_type='''jax''' )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(2, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(2,) )
        # test converting the converted
        with CaptureStderr() as cs:
               lowercase  :		Dict						=      batch.convert_to_tensors(tensor_type='''jax''' )
        self.assertFalse(len(cs.err )   ,		msg=f"""should have no warning, but got {cs.err}""" )

        lowercase  :		str						=      BatchEncoding({'''inputs''': [1, 2, 3], '''labels''': 0} )
        lowercase  :		str						=      batch.convert_to_tensors(tensor_type='''jax'''   ,		prepend_batch_axis=A )
        self.assertEqual(tensor_batch['''inputs'''].shape   ,		(1, 3) )
        self.assertEqual(tensor_batch['''labels'''].shape   ,		(1,) )



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		List[str]						=      [{'''input_ids''': np.array([0, 1, 2] )}, {'''input_ids''': np.array([0, 1, 2, 3] )}]
        lowercase  :		Tuple						=      BertTokenizer.from_pretrained('''bert-base-cased''' )

        lowercase  :		Dict						=      tokenizer.pad(A   ,		padding=A )
        self.assertTrue(isinstance(batch['''input_ids''']   ,		np.ndarray ) )
        self.assertEqual(batch['''input_ids'''].tolist()   ,		[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]] )
        lowercase  :		Dict						=      tokenizer.pad(A   ,		padding=A   ,		return_tensors='''np''' )
        self.assertTrue(isinstance(batch['''input_ids''']   ,		np.ndarray ) )
        self.assertEqual(batch['''input_ids'''].tolist()   ,		[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]] )



 @require_torch
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        import torch

        lowercase  :		Optional[Any]						=      [{'''input_ids''': torch.tensor([0, 1, 2] )}, {'''input_ids''': torch.tensor([0, 1, 2, 3] )}]
        lowercase  :		Tuple						=      BertTokenizer.from_pretrained('''bert-base-cased''' )

        lowercase  :		Any						=      tokenizer.pad(A   ,		padding=A )
        self.assertTrue(isinstance(batch['''input_ids''']   ,		torch.Tensor ) )
        self.assertEqual(batch['''input_ids'''].tolist()   ,		[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]] )
        lowercase  :		Union[str, Any]						=      tokenizer.pad(A   ,		padding=A   ,		return_tensors='''pt''' )
        self.assertTrue(isinstance(batch['''input_ids''']   ,		torch.Tensor ) )
        self.assertEqual(batch['''input_ids'''].tolist()   ,		[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]] )



 @require_tf
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        import tensorflow as tf

        lowercase  :		Optional[int]						=      [{'''input_ids''': tf.constant([0, 1, 2] )}, {'''input_ids''': tf.constant([0, 1, 2, 3] )}]
        lowercase  :		Dict						=      BertTokenizer.from_pretrained('''bert-base-cased''' )

        lowercase  :		List[Any]						=      tokenizer.pad(A   ,		padding=A )
        self.assertTrue(isinstance(batch['''input_ids''']   ,		tf.Tensor ) )
        self.assertEqual(batch['''input_ids'''].numpy().tolist()   ,		[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]] )
        lowercase  :		Any						=      tokenizer.pad(A   ,		padding=A   ,		return_tensors='''tf''' )
        self.assertTrue(isinstance(batch['''input_ids''']   ,		tf.Tensor ) )
        self.assertEqual(batch['''input_ids'''].numpy().tolist()   ,		[[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]] )



 @require_tokenizers
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Optional[Any]						=      Tokenizer(WordPiece(unk_token='''[UNK]''' ) )
        PreTrainedTokenizerFast(tokenizer_object=A )





 @require_tokenizers
 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		List[str]						=      Tokenizer(WordPiece(unk_token='''[UNK]''' ) )
        with tempfile.TemporaryDirectory() as tmpdirname:
               bert_tokenizer.save(os.path.join(A   ,		'''tokenizer.json''' ) )
               PreTrainedTokenizerFast(tokenizer_file=os.path.join(A   ,		'''tokenizer.json''' ) )










'''simple docstring'''






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

from ...utils import logging


lowercase	:      Optional[Any]				=       logging.get_logger(__name__)




def 		a_( lowerCamelCase   ,				lowerCamelCase      )				->Optional[int]:






       '''simple docstring'''




       lowercase  :		List[str]						=      nn.functional.normalize(lowerCamelCase      )
       lowercase  :		Optional[int]						=      nn.functional.normalize(lowerCamelCase      )
       return torch.mm(lowerCamelCase   ,				normalized_text_embeds.t()      )





class   SCREAMING_SNAKE_CASE_		(       lowerCamelCase_				):
 __snake_case	:     List[str]			   =      CLIPConfig

 __snake_case	:     Optional[int]			   =      ["CLIPEncoderLayer"]



 def __init__(  self   ,		A ):






        '''simple docstring'''




        super().__init__(A )

        lowercase  :		Optional[Any]						=      CLIPVisionModel(config.vision_config )
        lowercase  :		Tuple						=      nn.Linear(config.vision_config.hidden_size   ,		config.projection_dim   ,		bias=A )

        lowercase  :		Any						=      nn.Parameter(torch.ones(17   ,		config.projection_dim )   ,		requires_grad=A )
        lowercase  :		int						=      nn.Parameter(torch.ones(3   ,		config.projection_dim )   ,		requires_grad=A )

        lowercase  :		List[str]						=      nn.Parameter(torch.ones(17 )   ,		requires_grad=A )
        lowercase  :		str						=      nn.Parameter(torch.ones(3 )   ,		requires_grad=A )



 @torch.no_grad()
 def    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A ):






        '''simple docstring'''




        lowercase  :		Union[str, Any]						=      self.vision_model(A )[1]  # pooled_output
        lowercase  :		List[Any]						=      self.visual_projection(A )

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

        lowercase  :		Dict						=      []
        lowercase  :		str						=      image_embeds.shape[0]
        for i in range(A ):
               lowercase  :		List[str]						=      {'''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
               lowercase  :		str						=      0.0

               for concept_idx in range(len(special_cos_dist[0] ) ):
                      lowercase  :		List[str]						=      special_cos_dist[i][concept_idx]
                      lowercase  :		List[Any]						=      self.special_care_embeds_weights[concept_idx].item()
                      lowercase  :		Optional[Any]						=      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]} )
                             lowercase  :		List[str]						=      0.0_1

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

               result.append(A )

        lowercase  :		Dict						=      [len(res['''bad_concepts'''] ) > 0 for res in result]

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

        if any(A ):
               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    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A ):






        '''simple docstring'''




        lowercase  :		Dict						=      self.vision_model(A )[1]  # pooled_output
        lowercase  :		Optional[int]						=      self.visual_projection(A )

        lowercase  :		Tuple						=      cosine_distance(A   ,		self.special_care_embeds )
        lowercase  :		List[str]						=      cosine_distance(A   ,		self.concept_embeds )

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

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

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

        lowercase  :		Dict						=      0.0  # black image

        return images, has_nsfw_concepts




