





"""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 OwlViTImageProcessor, OwlViTProcessor




@require_vision
class 			__lowercase     (     unittest.TestCase							):







					'''simple docstring'''




					def 	_lowerCamelCase						(  self       ):
									__a	:  List[str]         =					tempfile.mkdtemp()

									# fmt: off
									__a	:  Optional[int]         =					['''''', '''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(_UpperCAmelCase		,     range(len(_UpperCAmelCase       )       )       )       )
									__a	:  Tuple         =					['''#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	:  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(_UpperCAmelCase       ) + '''\n'''       )
									with open(self.merges_file		,     '''w'''		,     encoding='''utf-8'''       ) as fp:
													fp.write('''\n'''.join(_UpperCAmelCase       )       )

									__a	:  Union[str, 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],
									}
									__a	:  List[Any]         =					os.path.join(self.tmpdirname		,     _UpperCAmelCase       )
									with open(self.image_processor_file		,     '''w'''		,     encoding='''utf-8'''       ) as fp:
													json.dump(_UpperCAmelCase		,     _UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     **_UpperCAmelCase       ):
									return CLIPTokenizer.from_pretrained(self.tmpdirname		,     pad_token='''!'''		,     **_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     **_UpperCAmelCase       ):
									return CLIPTokenizerFast.from_pretrained(self.tmpdirname		,     pad_token='''!'''		,     **_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self		,     **_UpperCAmelCase       ):
									return OwlViTImageProcessor.from_pretrained(self.tmpdirname		,     **_UpperCAmelCase       )







					def 	_lowerCamelCase						(  self       ):
									shutil.rmtree(self.tmpdirname       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  List[str]         =					[np.random.randint(255		,     size=(3, 30, 400)		,     dtype=np.uinta       )]

									__a	:  Optional[Any]         =					[Image.fromarray(np.moveaxis(_UpperCAmelCase		,     0		,     -1       )       ) for x in image_inputs]

									return image_inputs







					def 	_lowerCamelCase						(  self       ):
									__a	:  Any         =					self.get_tokenizer()
									__a	:  Union[str, Any]         =					self.get_rust_tokenizer()
									__a	:  int         =					self.get_image_processor()

									__a	:  Optional[Any]         =					OwlViTProcessor(tokenizer=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )
									processor_slow.save_pretrained(self.tmpdirname       )
									__a	:  Optional[int]         =					OwlViTProcessor.from_pretrained(self.tmpdirname		,     use_fast=_UpperCAmelCase       )

									__a	:  Dict         =					OwlViTProcessor(tokenizer=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )
									processor_fast.save_pretrained(self.tmpdirname       )
									__a	:  str         =					OwlViTProcessor.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		,     _UpperCAmelCase       )
									self.assertIsInstance(processor_fast.tokenizer		,     _UpperCAmelCase       )

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







					def 	_lowerCamelCase						(  self       ):
									__a	:  List[str]         =					OwlViTProcessor(tokenizer=self.get_tokenizer()		,     image_processor=self.get_image_processor()       )
									processor.save_pretrained(self.tmpdirname       )

									__a	:  Dict         =					self.get_tokenizer(bos_token='''(BOS)'''		,     eos_token='''(EOS)'''       )
									__a	:  int         =					self.get_image_processor(do_normalize=_UpperCAmelCase       )

									__a	:  List[Any]         =					OwlViTProcessor.from_pretrained(
									    self.tmpdirname		,     bos_token='''(BOS)'''		,     eos_token='''(EOS)'''		,     do_normalize=_UpperCAmelCase       )

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

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







					def 	_lowerCamelCase						(  self       ):
									__a	:  Optional[int]         =					self.get_image_processor()
									__a	:  Dict         =					self.get_tokenizer()

									__a	:  Dict         =					OwlViTProcessor(tokenizer=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )

									__a	:  Optional[Any]         =					self.prepare_image_inputs()

									__a	:  Tuple         =					image_processor(_UpperCAmelCase		,     return_tensors='''np'''       )
									__a	:  List[str]         =					processor(images=_UpperCAmelCase		,     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 	_lowerCamelCase						(  self       ):
									__a	:  Optional[Any]         =					self.get_image_processor()
									__a	:  Any         =					self.get_tokenizer()

									__a	:  Union[str, Any]         =					OwlViTProcessor(tokenizer=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )

									__a	:  List[Any]         =					'''lower newer'''

									__a	:  List[str]         =					processor(text=_UpperCAmelCase		,     return_tensors='''np'''       )

									__a	:  List[str]         =					tokenizer(_UpperCAmelCase		,     return_tensors='''np'''       )

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







					def 	_lowerCamelCase						(  self       ):
									__a	:  str         =					self.get_image_processor()
									__a	:  Optional[Any]         =					self.get_tokenizer()

									__a	:  Union[str, Any]         =					OwlViTProcessor(tokenizer=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )

									__a	:  Dict         =					'''lower newer'''
									__a	:  List[str]         =					self.prepare_image_inputs()

									__a	:  Any         =					processor(text=_UpperCAmelCase		,     images=_UpperCAmelCase       )

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

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







					def 	_lowerCamelCase						(  self       ):
									__a	:  List[Any]         =					'''google/owlvit-base-patch32'''
									__a	:  List[Any]         =					OwlViTProcessor.from_pretrained(_UpperCAmelCase       )

									__a	:  int         =					['''cat''', '''nasa badge''']
									__a	:  Tuple         =					processor(text=_UpperCAmelCase       )

									__a	:  Any         =					16
									self.assertListEqual(list(inputs.keys()       )		,     ['''input_ids''', '''attention_mask''']       )
									self.assertEqual(inputs['''input_ids'''].shape		,     (2, seq_length)       )

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







					def 	_lowerCamelCase						(  self       ):
									__a	:  Any         =					'''google/owlvit-base-patch32'''
									__a	:  Any         =					OwlViTProcessor.from_pretrained(_UpperCAmelCase       )

									__a	:  Optional[int]         =					[['''cat''', '''nasa badge'''], ['''person''']]
									__a	:  List[Any]         =					processor(text=_UpperCAmelCase       )

									__a	:  Optional[int]         =					16
									__a	:  List[str]         =					len(_UpperCAmelCase       )
									__a	:  int         =					max([len(_UpperCAmelCase       ) for texts in input_texts]       )

									self.assertListEqual(list(inputs.keys()       )		,     ['''input_ids''', '''attention_mask''']       )
									self.assertEqual(inputs['''input_ids'''].shape		,     (batch_size * num_max_text_queries, seq_length)       )

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







					def 	_lowerCamelCase						(  self       ):
									__a	:  Dict         =					'''google/owlvit-base-patch32'''
									__a	:  Any         =					OwlViTProcessor.from_pretrained(_UpperCAmelCase       )

									__a	:  int         =					['''cat''', '''nasa badge''']
									__a	:  List[Any]         =					processor(text=_UpperCAmelCase       )

									__a	:  str         =					16
									__a	:  List[Any]         =					inputs['''input_ids''']
									__a	:  Union[str, Any]         =					[
									    [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
									    [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
									]

									self.assertListEqual(list(inputs.keys()       )		,     ['''input_ids''', '''attention_mask''']       )
									self.assertEqual(inputs['''input_ids'''].shape		,     (2, seq_length)       )
									self.assertListEqual(list(input_ids[0]       )		,     predicted_ids[0]       )
									self.assertListEqual(list(input_ids[1]       )		,     predicted_ids[1]       )







					def 	_lowerCamelCase						(  self       ):
									__a	:  Union[str, Any]         =					self.get_image_processor()
									__a	:  Tuple         =					self.get_tokenizer()

									__a	:  Tuple         =					OwlViTProcessor(tokenizer=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )

									__a	:  Dict         =					self.prepare_image_inputs()
									__a	:  Union[str, Any]         =					self.prepare_image_inputs()

									__a	:  Tuple         =					processor(images=_UpperCAmelCase		,     query_images=_UpperCAmelCase       )

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

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







					def 	_lowerCamelCase						(  self       ):
									__a	:  Dict         =					self.get_image_processor()
									__a	:  int         =					self.get_tokenizer()

									__a	:  str         =					OwlViTProcessor(tokenizer=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )

									__a	:  List[str]         =					[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

									__a	:  Optional[int]         =					processor.batch_decode(_UpperCAmelCase       )
									__a	:  str         =					tokenizer.batch_decode(_UpperCAmelCase       )

									self.assertListEqual(_UpperCAmelCase		,     _UpperCAmelCase       )






"""simple docstring"""






import os
import string
import sys


A	     =					1 << 8

A	     =					{
    '''tab''': ord('''\t'''),
    '''newline''': ord('''\r'''),
    '''esc''': 27,
    '''up''': 65 + ARROW_KEY_FLAG,
    '''down''': 66 + ARROW_KEY_FLAG,
    '''right''': 67 + ARROW_KEY_FLAG,
    '''left''': 68 + ARROW_KEY_FLAG,
    '''mod_int''': 91,
    '''undefined''': sys.maxsize,
    '''interrupt''': 3,
    '''insert''': 50,
    '''delete''': 51,
    '''pg_up''': 53,
    '''pg_down''': 54,
}

A	     =					KEYMAP['''up''']
A	     =					KEYMAP['''left''']

if sys.platform == "win32":
		A	     =					[]
		A	     =					{
		    B'''\xe0H''': KEYMAP['''up'''] - ARROW_KEY_FLAG,
		    B'''\x00H''': KEYMAP['''up'''] - ARROW_KEY_FLAG,
		    B'''\xe0P''': KEYMAP['''down'''] - ARROW_KEY_FLAG,
		    B'''\x00P''': KEYMAP['''down'''] - ARROW_KEY_FLAG,
		    B'''\xe0M''': KEYMAP['''right'''] - ARROW_KEY_FLAG,
		    B'''\x00M''': KEYMAP['''right'''] - ARROW_KEY_FLAG,
		    B'''\xe0K''': KEYMAP['''left'''] - ARROW_KEY_FLAG,
		    B'''\x00K''': KEYMAP['''left'''] - ARROW_KEY_FLAG,
		}

for i in range(10):
		A	     =					ord(str(i))

def       __A (     )						->						Dict:
				if os.name == "nt":
								import msvcrt

								__a	:  Optional[Any]         =					'''mbcs'''
								# Flush the keyboard buffer
								while msvcrt.kbhit():
												msvcrt.getch()
								if len(a_) == 0:
												# Read the keystroke
												__a	:  Optional[Any]         =					msvcrt.getch()

												# If it is a prefix char, get second part
												if ch in (b"\x00", b"\xe0"):
																__a	:  Optional[Any]         =					ch + msvcrt.getch()
																# Translate actual Win chars to bullet char types
																try:
																				__a	:  Union[str, Any]         =					chr(WIN_KEYMAP[cha])
																				WIN_CH_BUFFER.append(chr(KEYMAP['''mod_int''']))
																				WIN_CH_BUFFER.append(a_)
																				if ord(a_) in (
																				    KEYMAP["insert"] - 1 << 9,
																				    KEYMAP["delete"] - 1 << 9,
																				    KEYMAP["pg_up"] - 1 << 9,
																				    KEYMAP["pg_down"] - 1 << 9,
																				):
																								WIN_CH_BUFFER.append(chr(1_26))
																				__a	:  str         =					chr(KEYMAP['''esc'''])
																except KeyError:
																				__a	:  str         =					cha[1]
												else:
																__a	:  Optional[Any]         =					ch.decode(a_)
								else:
												__a	:  Union[str, Any]         =					WIN_CH_BUFFER.pop(0)
				elif os.name == "posix":
								import termios
								import tty

								__a	:  Any         =					sys.stdin.fileno()
								__a	:  List[str]         =					termios.tcgetattr(a_)
								try:
												tty.setraw(a_)
												__a	:  int         =					sys.stdin.read(1)
								finally:
												termios.tcsetattr(a_				,    termios.TCSADRAIN				,    a_)
				return ch






def       __A (     )						->						str:
				__a	:  Any         =					get_raw_chars()
				if ord(a_) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
								return char

				elif ord(a_) == KEYMAP["esc"]:
								__a	:  str         =					get_raw_chars()
								if ord(a_) == KEYMAP["mod_int"]:
												__a	:  List[str]         =					get_raw_chars()
												if ord(a_) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(a_) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
																return chr(ord(a_) + ARROW_KEY_FLAG)
												else:
																return KEYMAP["undefined"]
								else:
												return get_raw_chars()

				else:
								if char in string.printable:
												return char
								else:
												return KEYMAP["undefined"]