


import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
 from PIL import Image

 from transformers import CLIPSegProcessor, ViTImageProcessor






@require_vision
class _lowerCamelCase(		unittest.TestCase  ):
       def      UpperCamelCase	(   self)			->  str:




           """simple docstring"""

           _lowercase			:				str 						=						tempfile.mkdtemp()

           # fmt: off
           _lowercase			:				Any 						=						['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
           # fmt: on
           _lowercase			:				List[Any] 						=						dict(zip(lowerCamelCase, range(len(lowerCamelCase))))
           _lowercase			:				Tuple 						=						['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
           _lowercase			:				Any 						=						{'unk_token': '<unk>'}

           _lowercase			:				List[Any] 						=						os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['vocab_file'])
           _lowercase			:				Optional[int] 						=						os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['merges_file'])
           with open(self.vocab_file, 'w', encoding='utf-8') as fp:
               fp.write(json.dumps(lowerCamelCase) + '\n')
           with open(self.merges_file, 'w', encoding='utf-8') as fp:
               fp.write('\n'.join(lowerCamelCase))

           _lowercase			:				Optional[Any] 						=						{
               'do_resize': True,
               'size': 20,
               'do_center_crop': True,
               'crop_size': 18,
               'do_normalize': True,
               'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
               'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
           }
           _lowercase			:				Optional[int] 						=						os.path.join(self.tmpdirname, lowerCamelCase)
           with open(self.image_processor_file, 'w', encoding='utf-8') as fp:
               json.dump(lowerCamelCase, lowerCamelCase)
       def      UpperCamelCase	(   self, **lowerCamelCase)			->  int:




           """simple docstring"""

           return CLIPTokenizer.from_pretrained(self.tmpdirname, **lowerCamelCase)
       def      UpperCamelCase	(   self, **lowerCamelCase)			->  Optional[Any]:




           """simple docstring"""

           return CLIPTokenizerFast.from_pretrained(self.tmpdirname, **lowerCamelCase)
       def      UpperCamelCase	(   self, **lowerCamelCase)			->  Any:




           """simple docstring"""

           return ViTImageProcessor.from_pretrained(self.tmpdirname, **lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           shutil.rmtree(self.tmpdirname)
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				Any 						=						[np.random.randint(2_55, size=(3, 30, 4_00), dtype=np.uinta)]

           _lowercase			:				Union[str, Any] 						=						[Image.fromarray(np.moveaxis(lowerCamelCase, 0, -1)) for x in image_inputs]

           return image_inputs
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						self.get_tokenizer()
           _lowercase			:				Dict 						=						self.get_rust_tokenizer()
           _lowercase			:				Dict 						=						self.get_image_processor()

           _lowercase			:				Tuple 						=						CLIPSegProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase)
           processor_slow.save_pretrained(self.tmpdirname)
           _lowercase			:				Dict 						=						CLIPSegProcessor.from_pretrained(self.tmpdirname, use_fast=lowerCamelCase)

           _lowercase			:				List[Any] 						=						CLIPSegProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase)
           processor_fast.save_pretrained(self.tmpdirname)
           _lowercase			:				str 						=						CLIPSegProcessor.from_pretrained(self.tmpdirname)

           self.assertEqual(processor_slow.tokenizer.get_vocab(), tokenizer_slow.get_vocab())
           self.assertEqual(processor_fast.tokenizer.get_vocab(), tokenizer_fast.get_vocab())
           self.assertEqual(tokenizer_slow.get_vocab(), tokenizer_fast.get_vocab())
           self.assertIsInstance(processor_slow.tokenizer, lowerCamelCase)
           self.assertIsInstance(processor_fast.tokenizer, lowerCamelCase)

           self.assertEqual(processor_slow.image_processor.to_json_string(), image_processor.to_json_string())
           self.assertEqual(processor_fast.image_processor.to_json_string(), image_processor.to_json_string())
           self.assertIsInstance(processor_slow.image_processor, lowerCamelCase)
           self.assertIsInstance(processor_fast.image_processor, lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						CLIPSegProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
           processor.save_pretrained(self.tmpdirname)

           _lowercase			:				str 						=						self.get_tokenizer(bos_token='(BOS)', eos_token='(EOS)')
           _lowercase			:				Union[str, Any] 						=						self.get_image_processor(do_normalize=lowerCamelCase, padding_value=1.0)

           _lowercase			:				Union[str, Any] 						=						CLIPSegProcessor.from_pretrained(
               self.tmpdirname, bos_token='(BOS)', eos_token='(EOS)', do_normalize=lowerCamelCase, padding_value=1.0)

           self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
           self.assertIsInstance(processor.tokenizer, lowerCamelCase)

           self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
           self.assertIsInstance(processor.image_processor, lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.get_image_processor()
           _lowercase			:				int 						=						self.get_tokenizer()

           _lowercase			:				Union[str, Any] 						=						CLIPSegProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase)

           _lowercase			:				Optional[int] 						=						self.prepare_image_inputs()

           _lowercase			:				str 						=						image_processor(lowerCamelCase, return_tensors='np')
           _lowercase			:				Optional[int] 						=						processor(images=lowerCamelCase, return_tensors='np')

           for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1E-2)
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						self.get_image_processor()
           _lowercase			:				Optional[int] 						=						self.get_tokenizer()

           _lowercase			:				int 						=						CLIPSegProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase)

           _lowercase			:				str 						=						'lower newer'

           _lowercase			:				Dict 						=						processor(text=lowerCamelCase)

           _lowercase			:				Union[str, Any] 						=						tokenizer(lowerCamelCase)

           for key in encoded_tok.keys():
               self.assertListEqual(encoded_tok[key], encoded_processor[key])
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.get_image_processor()
           _lowercase			:				Tuple 						=						self.get_tokenizer()

           _lowercase			:				int 						=						CLIPSegProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase)

           _lowercase			:				List[Any] 						=						'lower newer'
           _lowercase			:				Any 						=						self.prepare_image_inputs()

           _lowercase			:				Any 						=						processor(text=lowerCamelCase, images=lowerCamelCase)

           self.assertListEqual(list(inputs.keys()), ['input_ids', 'attention_mask', 'pixel_values'])

           # test if it raises when no input is passed
           with pytest.raises(lowerCamelCase):
               processor()
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						self.get_image_processor()
           _lowercase			:				Any 						=						self.get_tokenizer()

           _lowercase			:				Tuple 						=						CLIPSegProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase)

           _lowercase			:				str 						=						self.prepare_image_inputs()
           _lowercase			:				str 						=						self.prepare_image_inputs()

           _lowercase			:				Union[str, Any] 						=						processor(images=lowerCamelCase, visual_prompt=lowerCamelCase)

           self.assertListEqual(list(inputs.keys()), ['pixel_values', 'conditional_pixel_values'])

           # test if it raises when no input is passed
           with pytest.raises(lowerCamelCase):
               processor()




       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				List[str] 						=						self.get_image_processor()
           _lowercase			:				Dict 						=						self.get_tokenizer()

           _lowercase			:				List[Any] 						=						CLIPSegProcessor(tokenizer=lowerCamelCase, image_processor=lowerCamelCase)

           _lowercase			:				Any 						=						[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

           _lowercase			:				Optional[int] 						=						processor.batch_decode(lowerCamelCase)
           _lowercase			:				List[str] 						=						tokenizer.batch_decode(lowerCamelCase)

           self.assertListEqual(lowerCamelCase, lowerCamelCase)




"""simple docstring"""




import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin







@skip_mps
class     lowercase(_lowercase    ,						_lowercase    ,						unittest.TestCase       ):
     __snake_case:	Optional[int]						=     IFImgaImgSuperResolutionPipeline
     __snake_case:	Dict						=     TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
     __snake_case:	Any						=     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}       )
     __snake_case:	List[Any]						=     PipelineTesterMixin.required_optional_params - {'latents'}



     def 			lowercase__  (							self   )		->     Tuple:







         """simple docstring"""



         return self._get_superresolution_dummy_components()



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE=0   )		->     Union[str, Any]:







         """simple docstring"""



         if str(__SCREAMING_SNAKE_CASE   ).startswith('mps'   ):
             a__		=			torch.manual_seed(__SCREAMING_SNAKE_CASE   )
         else:
             a__		=			torch.Generator(device=__SCREAMING_SNAKE_CASE   ).manual_seed(__SCREAMING_SNAKE_CASE   )

         a__		=			floats_tensor((1, 3, 3_2, 3_2)     ,				rng=random.Random(__SCREAMING_SNAKE_CASE   )   ).to(__SCREAMING_SNAKE_CASE   )
         a__		=			floats_tensor((1, 3, 1_6, 1_6)     ,				rng=random.Random(__SCREAMING_SNAKE_CASE   )   ).to(__SCREAMING_SNAKE_CASE   )

         a__		=			{
             'prompt': 'A painting of a squirrel eating a burger',
             'image': image,
             'original_image': original_image,
             'generator': generator,
             'num_inference_steps': 2,
             'output_type': 'numpy',
         }

         return inputs



     @unittest.skipIf(
         torch_device != 'cuda' or not is_xformers_available()     ,				reason='XFormers attention is only available with CUDA and `xformers` installed'     ,				)
     def 			lowercase__  (							self   )		->     Optional[int]:







         """simple docstring"""



         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3   )



     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



         self._test_save_load_optional_components()



     @unittest.skipIf(torch_device != 'cuda'     ,				reason='float16 requires CUDA'   )
     def 			lowercase__  (							self   )		->     List[Any]:







         """simple docstring"""



         super().test_save_load_floataa(expected_max_diff=1e-1   )



     def 			lowercase__  (							self   )		->     List[str]:







         """simple docstring"""



         self._test_attention_slicing_forward_pass(expected_max_diff=1e-2   )



     def 			lowercase__  (							self   )		->     Optional[Any]:







         """simple docstring"""



         self._test_save_load_local()




     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



         self._test_inference_batch_single_identical(
             expected_max_diff=1e-2     ,				)


