
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 CLIPImageProcessor, CLIPProcessor




@require_vision
class     _SCREAMING_SNAKE_CASE     (      unittest.TestCase						):



	def     SCREAMING_SNAKE_CASE_(    self )				->       Tuple:
					lowerCamelCase_						=			tempfile.mkdtemp()

					# fmt: off
					lowerCamelCase_						=			["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
					lowerCamelCase_						=			dict(zip(lowercase						,  range(len(lowercase ) ) ) )
					lowerCamelCase_						=			["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
					lowerCamelCase_						=			{"unk_token": "<unk>"}

					lowerCamelCase_						=			os.path.join(self.tmpdirname						,  VOCAB_FILES_NAMES["vocab_file"] )
					lowerCamelCase_						=			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(lowercase ) + "\n" )
					with open(self.merges_file						,  "w"						,  encoding="utf-8" ) as fp:
									fp.write("\n".join(lowercase ) )

					lowerCamelCase_						=			{
					    "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],
					}
					lowerCamelCase_						=			os.path.join(self.tmpdirname						,  lowercase )
					with open(self.image_processor_file						,  "w"						,  encoding="utf-8" ) as fp:
									json.dump(lowercase						,  lowercase )



	def     SCREAMING_SNAKE_CASE_(    self						,  **lowercase )				->       Optional[int]:
					return CLIPTokenizer.from_pretrained(self.tmpdirname						,  **lowercase )



	def     SCREAMING_SNAKE_CASE_(    self						,  **lowercase )				->       List[str]:
					return CLIPTokenizerFast.from_pretrained(self.tmpdirname						,  **lowercase )



	def     SCREAMING_SNAKE_CASE_(    self						,  **lowercase )				->       Union[str, Any]:
					return CLIPImageProcessor.from_pretrained(self.tmpdirname						,  **lowercase )



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



	def     SCREAMING_SNAKE_CASE_(    self )				->       Tuple:
					lowerCamelCase_						=			[np.random.randint(255						,  size=(3, 30, 400)						,  dtype=np.uinta )]

					lowerCamelCase_						=			[Image.fromarray(np.moveaxis(lowercase						,  0						,  -1 ) ) for x in image_inputs]

					return image_inputs



	def     SCREAMING_SNAKE_CASE_(    self )				->       Optional[int]:
					lowerCamelCase_						=			self.get_tokenizer()
					lowerCamelCase_						=			self.get_rust_tokenizer()
					lowerCamelCase_						=			self.get_image_processor()

					lowerCamelCase_						=			CLIPProcessor(tokenizer=lowercase						,  image_processor=lowercase )
					processor_slow.save_pretrained(self.tmpdirname )
					lowerCamelCase_						=			CLIPProcessor.from_pretrained(self.tmpdirname						,  use_fast=lowercase )

					lowerCamelCase_						=			CLIPProcessor(tokenizer=lowercase						,  image_processor=lowercase )
					processor_fast.save_pretrained(self.tmpdirname )
					lowerCamelCase_						=			CLIPProcessor.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						,  lowercase )
					self.assertIsInstance(processor_fast.tokenizer						,  lowercase )

					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						,  lowercase )
					self.assertIsInstance(processor_fast.image_processor						,  lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Union[str, Any]:
					lowerCamelCase_						=			CLIPProcessor(tokenizer=self.get_tokenizer()						,  image_processor=self.get_image_processor() )
					processor.save_pretrained(self.tmpdirname )

					lowerCamelCase_						=			self.get_tokenizer(bos_token="(BOS)"						,  eos_token="(EOS)" )
					lowerCamelCase_						=			self.get_image_processor(do_normalize=lowercase						,  padding_value=1.0 )

					lowerCamelCase_						=			CLIPProcessor.from_pretrained(
					    self.tmpdirname						,  bos_token="(BOS)"						,  eos_token="(EOS)"						,  do_normalize=lowercase						,  padding_value=1.0 )

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

					self.assertEqual(processor.image_processor.to_json_string()						,  image_processor_add_kwargs.to_json_string() )
					self.assertIsInstance(processor.image_processor						,  lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Tuple:
					lowerCamelCase_						=			self.get_image_processor()
					lowerCamelCase_						=			self.get_tokenizer()

					lowerCamelCase_						=			CLIPProcessor(tokenizer=lowercase						,  image_processor=lowercase )

					lowerCamelCase_						=			self.prepare_image_inputs()

					lowerCamelCase_						=			image_processor(lowercase						,  return_tensors="np" )
					lowerCamelCase_						=			processor(images=lowercase						,  return_tensors="np" )

					for key in input_image_proc.keys():
									self.assertAlmostEqual(input_image_proc[key].sum()						,  input_processor[key].sum()						,  delta=1e-2 )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Optional[int]:
					lowerCamelCase_						=			self.get_image_processor()
					lowerCamelCase_						=			self.get_tokenizer()

					lowerCamelCase_						=			CLIPProcessor(tokenizer=lowercase						,  image_processor=lowercase )

					lowerCamelCase_						=			"lower newer"

					lowerCamelCase_						=			processor(text=lowercase )

					lowerCamelCase_						=			tokenizer(lowercase )

					for key in encoded_tok.keys():
									self.assertListEqual(encoded_tok[key]						,  encoded_processor[key] )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Optional[int]:
					lowerCamelCase_						=			self.get_image_processor()
					lowerCamelCase_						=			self.get_tokenizer()

					lowerCamelCase_						=			CLIPProcessor(tokenizer=lowercase						,  image_processor=lowercase )

					lowerCamelCase_						=			"lower newer"
					lowerCamelCase_						=			self.prepare_image_inputs()

					lowerCamelCase_						=			processor(text=lowercase						,  images=lowercase )

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

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



	def     SCREAMING_SNAKE_CASE_(    self )				->       Tuple:
					lowerCamelCase_						=			self.get_image_processor()
					lowerCamelCase_						=			self.get_tokenizer()

					lowerCamelCase_						=			CLIPProcessor(tokenizer=lowercase						,  image_processor=lowercase )

					lowerCamelCase_						=			[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

					lowerCamelCase_						=			processor.batch_decode(lowercase )
					lowerCamelCase_						=			tokenizer.batch_decode(lowercase )

					self.assertListEqual(lowercase						,  lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       str:
					lowerCamelCase_						=			self.get_image_processor()
					lowerCamelCase_						=			self.get_tokenizer()

					lowerCamelCase_						=			CLIPProcessor(tokenizer=lowercase						,  image_processor=lowercase )

					lowerCamelCase_						=			"lower newer"
					lowerCamelCase_						=			self.prepare_image_inputs()

					lowerCamelCase_						=			processor(text=lowercase						,  images=lowercase )

					self.assertListEqual(list(inputs.keys() )						,  processor.model_input_names )






'''simple docstring'''



from importlib import import_module

from .logging import get_logger


A__		:					str												=  get_logger(__name__)





class    UpperCAmelCase_  :





    """simple docstring"""






    def __init__(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_=None	)				->     List[Any]:
         __lowerCamelCase   :	List[str]								=		attrs or []
         if module is not None:
              for key in module.__dict__:
                   if key in attrs or not key.startswith('__'	):
                        setattr(self			,     SCREAMING_SNAKE_CASE_			,     getattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)	)
         __lowerCamelCase   :	Optional[int]								=		module._original_module if isinstance(SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj	) else module







class    UpperCAmelCase_  :





    """simple docstring"""






    lowerCamelCase  :					Tuple							     =			[]







    def __init__(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_=None	)				->     Union[str, Any]:
         __lowerCamelCase   :	Optional[int]								=		obj
         __lowerCamelCase   :	List[Any]								=		target
         __lowerCamelCase   :	Union[str, Any]								=		new
         __lowerCamelCase   :	Union[str, Any]								=		target.split('.'	)[0]
         __lowerCamelCase   :	Dict								=		{}
         __lowerCamelCase   :	Dict								=		attrs or []







    def __enter__(							self	)				->     Optional[int]:
         *__lowerCamelCase				,       __lowerCamelCase   :	int								=		self.target.split('.'	)

         # Patch modules:
         # it's used to patch attributes of submodules like "os.path.join";
         # in this case we need to patch "os" and "os.path"

         for i in range(len(SCREAMING_SNAKE_CASE_	)	):
              try:
                   __lowerCamelCase   :	Optional[int]								=		import_module('.'.join(submodules[: i + 1]	)	)
              except ModuleNotFoundError:
                   continue
              # We iterate over all the globals in self.obj in case we find "os" or "os.path"
              for attr in self.obj.__dir__():
                   __lowerCamelCase   :	List[Any]								=		getattr(self.obj			,     SCREAMING_SNAKE_CASE_	)
                   # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
                   # This allows to patch renamed modules like "from os import path as ospath".
                   if obj_attr is submodule or (
                       (isinstance(SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj	) and obj_attr._original_module is submodule)
                   ):
                        __lowerCamelCase   :	Optional[Any]								=		obj_attr
                        # patch at top level
                        setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj(SCREAMING_SNAKE_CASE_			,     attrs=self.attrs	)	)
                        __lowerCamelCase   :	str								=		getattr(self.obj			,     SCREAMING_SNAKE_CASE_	)
                        # construct lower levels patches
                        for key in submodules[i + 1 :]:
                             setattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     _PatchedModuleObj(getattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)			,     attrs=self.attrs	)	)
                             __lowerCamelCase   :	List[Any]								=		getattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)
                        # finally set the target attribute
                        setattr(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     self.new	)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

         if submodules:  # if it's an attribute of a submodule like "os.path.join"
              try:
                   __lowerCamelCase   :	Union[str, Any]								=		getattr(import_module('.'.join(SCREAMING_SNAKE_CASE_	)	)			,     SCREAMING_SNAKE_CASE_	)
              except (AttributeError, ModuleNotFoundError):
                   return
              # We iterate over all the globals in self.obj in case we find "os.path.join"
              for attr in self.obj.__dir__():
                   # We don't check for the name of the global, but rather if its value *is* "os.path.join".
                   # This allows to patch renamed attributes like "from os.path import join as pjoin".
                   if getattr(self.obj			,     SCREAMING_SNAKE_CASE_	) is attr_value:
                        __lowerCamelCase   :	Optional[int]								=		getattr(self.obj			,     SCREAMING_SNAKE_CASE_	)
                        setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     self.new	)
         elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
              __lowerCamelCase   :	List[Any]								=		globals()['__builtins__'][target_attr]
              setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     self.new	)
         else:
              raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.'	)







    def __exit__(							self			,     *SCREAMING_SNAKE_CASE_	)				->     Optional[Any]:
         for attr in list(self.original	):
              setattr(self.obj			,     SCREAMING_SNAKE_CASE_			,     self.original.pop(SCREAMING_SNAKE_CASE_	)	)







    def       lowercase_				(							self	)				->     Optional[int]:
         self.__enter__()
         self._active_patches.append(self	)







    def       lowercase_				(							self	)				->     str:
         try:
              self._active_patches.remove(self	)
         except ValueError:
              # If the patch hasn't been started this will fail
              return None

         return self.__exit__()






