
'''simple docstring'''







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 UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  def   __lowercase		(		self      :     List[Any]       ):


     '''simple docstring'''






     _a				:	List[Any]			=   tempfile.mkdtemp()

     # fmt: off
     _a				:	List[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
     _a				:	int			=   dict(zip(__lowercase							,range(len(__lowercase       )       )       )       )
     _a				:	Optional[Any]			=   ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', '''''']
     _a				:	Any			=   {'''unk_token''': '''<unk>'''}

     _a				:	str			=   os.path.join(self.tmpdirname							,VOCAB_FILES_NAMES['vocab_file']       )
     _a				:	List[str]			=   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       )       )

     _a				:	Dict			=   {
         '''do_resize''': True,
         '''size''': 20,
         '''do_center_crop''': True,
         '''crop_size''': 18,
         '''do_normalize''': True,
         '''image_mean''': [0.4814_5466, 0.457_8275, 0.4082_1073],
         '''image_std''': [0.2686_2954, 0.2613_0258, 0.2757_7711],
     }
     _a				:	str			=   os.path.join(self.tmpdirname							,__lowercase       )
     with open(self.image_processor_file							,'w'							,encoding='utf-8'       ) as fp:
        json.dump(__lowercase							,__lowercase       )


  def   __lowercase		(		self      :     Union[str, Any]							,**_a      :     Dict       ):


     '''simple docstring'''






     return CLIPTokenizer.from_pretrained(self.tmpdirname							,**__lowercase       )


  def   __lowercase		(		self      :     Optional[int]							,**_a      :     int       ):


     '''simple docstring'''






     return CLIPTokenizerFast.from_pretrained(self.tmpdirname							,**__lowercase       )


  def   __lowercase		(		self      :     Optional[Any]							,**_a      :     Dict       ):


     '''simple docstring'''






     return ViTImageProcessor.from_pretrained(self.tmpdirname							,**__lowercase       )


  def   __lowercase		(		self      :     int       ):


     '''simple docstring'''






     shutil.rmtree(self.tmpdirname       )


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	str			=   [np.random.randint(255							,size=(3, 30, 400)							,dtype=np.uinta       )]

     _a				:	str			=   [Image.fromarray(np.moveaxis(__lowercase							,0							,-1       )       ) for x in image_inputs]

     return image_inputs


  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






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

     _a				:	Optional[int]			=   CLIPSegProcessor(tokenizer=__lowercase							,image_processor=__lowercase       )
     processor_slow.save_pretrained(self.tmpdirname       )
     _a				:	Optional[Any]			=   CLIPSegProcessor.from_pretrained(self.tmpdirname							,use_fast=__lowercase       )

     _a				:	Tuple			=   CLIPSegProcessor(tokenizer=__lowercase							,image_processor=__lowercase       )
     processor_fast.save_pretrained(self.tmpdirname       )
     _a				:	Union[str, Any]			=   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							,__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   __lowercase		(		self      :     str       ):


     '''simple docstring'''






     _a				:	Any			=   CLIPSegProcessor(tokenizer=self.get_tokenizer()							,image_processor=self.get_image_processor()       )
     processor.save_pretrained(self.tmpdirname       )

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

     _a				:	str			=   CLIPSegProcessor.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   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     _a				:	List[str]			=   self.get_image_processor()
     _a				:	int			=   self.get_tokenizer()

     _a				:	Tuple			=   CLIPSegProcessor(tokenizer=__lowercase							,image_processor=__lowercase       )

     _a				:	Dict			=   self.prepare_image_inputs()

     _a				:	List[Any]			=   image_processor(__lowercase							,return_tensors='np'       )
     _a				:	List[str]			=   processor(images=__lowercase							,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   __lowercase		(		self      :     str       ):


     '''simple docstring'''






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

     _a				:	Tuple			=   CLIPSegProcessor(tokenizer=__lowercase							,image_processor=__lowercase       )

     _a				:	Tuple			=   '''lower newer'''

     _a				:	Tuple			=   processor(text=__lowercase       )

     _a				:	List[Any]			=   tokenizer(__lowercase       )

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


  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






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

     _a				:	Union[str, Any]			=   CLIPSegProcessor(tokenizer=__lowercase							,image_processor=__lowercase       )

     _a				:	Optional[Any]			=   '''lower newer'''
     _a				:	Any			=   self.prepare_image_inputs()

     _a				:	Union[str, Any]			=   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   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	str			=   self.get_image_processor()
     _a				:	Optional[int]			=   self.get_tokenizer()

     _a				:	int			=   CLIPSegProcessor(tokenizer=__lowercase							,image_processor=__lowercase       )

     _a				:	List[Any]			=   self.prepare_image_inputs()
     _a				:	Tuple			=   self.prepare_image_inputs()

     _a				:	List[str]			=   processor(images=__lowercase							,visual_prompt=__lowercase       )

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

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


  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     _a				:	Tuple			=   self.get_image_processor()
     _a				:	List[Any]			=   self.get_tokenizer()

     _a				:	Tuple			=   CLIPSegProcessor(tokenizer=__lowercase							,image_processor=__lowercase       )

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

     _a				:	Dict			=   processor.batch_decode(__lowercase       )
     _a				:	int			=   tokenizer.batch_decode(__lowercase       )

     self.assertListEqual(__lowercase							,__lowercase       )








from importlib import import_module

from .logging import get_logger


A__								=						get_logger(__name__)


class       a							:



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


class       a							:
		__lowerCAmelCase	:    Any											=					[]



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



		def __enter__(     self     :Tuple  ):
						*snake_case__		, snake_case__	:      str     		=	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(__lowercase  )  ):
										try:
														snake_case__	:      Any     		=	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__():
														snake_case__	:      Optional[int]     		=	getattr(self.obj   ,__lowercase  )
														# 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(__lowercase   ,_PatchedModuleObj  ) and obj_attr._original_module is submodule)
														):
																		snake_case__	:      List[Any]     		=	obj_attr
																		# patch at top level
																		setattr(self.obj   ,__lowercase   ,_PatchedModuleObj(__lowercase   ,attrs=self.attrs  )  )
																		snake_case__	:      List[Any]     		=	getattr(self.obj   ,__lowercase  )
																		# construct lower levels patches
																		for key in submodules[i + 1 :]:
																						setattr(__lowercase   ,__lowercase   ,_PatchedModuleObj(getattr(__lowercase   ,__lowercase   ,__lowercase  )   ,attrs=self.attrs  )  )
																						snake_case__	:      List[Any]     		=	getattr(__lowercase   ,__lowercase  )
																		# finally set the target attribute
																		setattr(__lowercase   ,__lowercase   ,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:
														snake_case__	:      int     		=	getattr(import_module('''.'''.join(__lowercase  )  )   ,__lowercase  )
										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   ,__lowercase  ) is attr_value:
																		snake_case__	:      str     		=	getattr(self.obj   ,__lowercase  )
																		setattr(self.obj   ,__lowercase   ,self.new  )
						elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
										snake_case__	:      str     		=	globals()['''__builtins__'''][target_attr]
										setattr(self.obj   ,__lowercase   ,self.new  )
						else:
										raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule."""  )



		def __exit__(     self     :Tuple   ,*__lowercase     :Optional[int]  ):
						for attr in list(self.original  ):
										setattr(self.obj   ,__lowercase   ,self.original.pop(__lowercase  )  )



		def 	__lowerCamelCase			(     self     :Tuple  ):
						self.__enter__()
						self._active_patches.append(self  )






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

						return self.__exit__()

