


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

							def 				lowerCamelCase_			(							self:     Any							)      ->       Tuple:





									"""simple docstring"""







									lowercase__						=				tempfile.mkdtemp()

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

									lowercase__						=				os.path.join(self.tmpdirname   ,						VOCAB_FILES_NAMES['''vocab_file''']							)
									lowercase__						=				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_							)							)

									lowercase__						=				{
									    '''do_resize''': True,
									    '''size''': 20,
									    '''do_center_crop''': True,
									    '''crop_size''': 18,
									    '''do_normalize''': True,
									    '''image_mean''': [0.48145466, 0.4578275, 0.40821073],
									    '''image_std''': [0.26862954, 0.26130258, 0.27577711],
									}
									lowercase__						=				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:     List[Any]   ,						**UpperCamelCase_:     List[str]							)      ->       Tuple:





									"""simple docstring"""







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

							def 				lowerCamelCase_			(							self:     Tuple   ,						**UpperCamelCase_:     Union[str, Any]							)      ->       Tuple:





									"""simple docstring"""







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

							def 				lowerCamelCase_			(							self:     Optional[int]   ,						**UpperCamelCase_:     int							)      ->       str:





									"""simple docstring"""







									return CLIPImageProcessor.from_pretrained(self.tmpdirname   ,						**UpperCamelCase_							)

							def 				lowerCamelCase_			(							self:     Union[str, Any]							)      ->       Optional[int]:





									"""simple docstring"""







									shutil.rmtree(self.tmpdirname							)

							def 				lowerCamelCase_			(							self:     Optional[int]							)      ->       Union[str, Any]:





									"""simple docstring"""







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

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

									return image_inputs

							def 				lowerCamelCase_			(							self:     Union[str, Any]							)      ->       List[Any]:





									"""simple docstring"""







									lowercase__						=				self.get_tokenizer()
									lowercase__						=				self.get_rust_tokenizer()
									lowercase__						=				self.get_image_processor()

									lowercase__						=				CLIPProcessor(tokenizer=UpperCamelCase_   ,						image_processor=UpperCamelCase_							)
									processor_slow.save_pretrained(self.tmpdirname							)
									lowercase__						=				CLIPProcessor.from_pretrained(self.tmpdirname   ,						use_fast=UpperCamelCase_							)

									lowercase__						=				CLIPProcessor(tokenizer=UpperCamelCase_   ,						image_processor=UpperCamelCase_							)
									processor_fast.save_pretrained(self.tmpdirname							)
									lowercase__						=				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   ,						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:     List[str]							)      ->       List[str]:





									"""simple docstring"""







									lowercase__						=				CLIPProcessor(tokenizer=self.get_tokenizer()   ,						image_processor=self.get_image_processor()							)
									processor.save_pretrained(self.tmpdirname							)

									lowercase__						=				self.get_tokenizer(bos_token='''(BOS)'''   ,						eos_token='''(EOS)'''							)
									lowercase__						=				self.get_image_processor(do_normalize=UpperCamelCase_   ,						padding_value=1.0							)

									lowercase__						=				CLIPProcessor.from_pretrained(
									    self.tmpdirname   ,						bos_token='''(BOS)'''   ,						eos_token='''(EOS)'''   ,						do_normalize=UpperCamelCase_   ,						padding_value=1.0							)

									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:     Union[str, Any]							)      ->       int:





									"""simple docstring"""







									lowercase__						=				self.get_image_processor()
									lowercase__						=				self.get_tokenizer()

									lowercase__						=				CLIPProcessor(tokenizer=UpperCamelCase_   ,						image_processor=UpperCamelCase_							)

									lowercase__						=				self.prepare_image_inputs()

									lowercase__						=				image_processor(UpperCamelCase_   ,						return_tensors='''np'''							)
									lowercase__						=				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:     Optional[Any]							)      ->       Any:





									"""simple docstring"""







									lowercase__						=				self.get_image_processor()
									lowercase__						=				self.get_tokenizer()

									lowercase__						=				CLIPProcessor(tokenizer=UpperCamelCase_   ,						image_processor=UpperCamelCase_							)

									lowercase__						=				'''lower newer'''

									lowercase__						=				processor(text=UpperCamelCase_							)

									lowercase__						=				tokenizer(UpperCamelCase_							)

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

							def 				lowerCamelCase_			(							self:     Optional[Any]							)      ->       List[str]:





									"""simple docstring"""







									lowercase__						=				self.get_image_processor()
									lowercase__						=				self.get_tokenizer()

									lowercase__						=				CLIPProcessor(tokenizer=UpperCamelCase_   ,						image_processor=UpperCamelCase_							)

									lowercase__						=				'''lower newer'''
									lowercase__						=				self.prepare_image_inputs()

									lowercase__						=				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:     Tuple							)      ->       Dict:





									"""simple docstring"""







									lowercase__						=				self.get_image_processor()
									lowercase__						=				self.get_tokenizer()

									lowercase__						=				CLIPProcessor(tokenizer=UpperCamelCase_   ,						image_processor=UpperCamelCase_							)

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

									lowercase__						=				processor.batch_decode(UpperCamelCase_							)
									lowercase__						=				tokenizer.batch_decode(UpperCamelCase_							)

									self.assertListEqual(UpperCamelCase_   ,						UpperCamelCase_							)


							def 				lowerCamelCase_			(							self:     int							)      ->       List[str]:





									"""simple docstring"""







									lowercase__						=				self.get_image_processor()
									lowercase__						=				self.get_tokenizer()

									lowercase__						=				CLIPProcessor(tokenizer=UpperCamelCase_   ,						image_processor=UpperCamelCase_							)

									lowercase__						=				'''lower newer'''
									lowercase__						=				self.prepare_image_inputs()

									lowercase__						=				processor(text=UpperCamelCase_   ,						images=UpperCamelCase_							)

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






from collections.abc import Sequence
from queue import Queue


class 	_a							:

							def __init__(							self:     Tuple   ,						UpperCamelCase_:     Optional[int]   ,						UpperCamelCase_:     int   ,						UpperCamelCase_:     Optional[Any]   ,						UpperCamelCase_:     Union[str, Any]=None   ,						UpperCamelCase_:     Dict=None							)      ->       Tuple:





									"""simple docstring"""







									lowercase__						=				start
									lowercase__						=				end
									lowercase__						=				val
									lowercase__						=				(start + end) // 2
									lowercase__						=				left
									lowercase__						=				right


							def __repr__(							self:     Optional[int]							)      ->       Optional[Any]:





									"""simple docstring"""







									return f'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})'


class 	_a							:

							def __init__(							self:     Any   ,						UpperCamelCase_:     Sequence   ,						UpperCamelCase_:     Any							)      ->       List[str]:





									"""simple docstring"""







									lowercase__						=				collection
									lowercase__						=				function
									if self.collection:
											lowercase__						=				self._build_tree(0   ,						len(UpperCamelCase_							) - 1							)

							def 				lowerCamelCase_			(							self:     int   ,						UpperCamelCase_:     Union[str, Any]   ,						UpperCamelCase_:     Union[str, Any]							)      ->       Union[str, Any]:





									"""simple docstring"""







									self._update_tree(self.root   ,						UpperCamelCase_   ,						UpperCamelCase_							)

							def 				lowerCamelCase_			(							self:     str   ,						UpperCamelCase_:     int   ,						UpperCamelCase_:     List[str]							)      ->       Optional[Any]:





									"""simple docstring"""







									return self._query_range(self.root   ,						UpperCamelCase_   ,						UpperCamelCase_							)

							def 				lowerCamelCase_			(							self:     List[str]   ,						UpperCamelCase_:     Tuple   ,						UpperCamelCase_:     Dict							)      ->       str:





									"""simple docstring"""







									if start == end:
											return SegmentTreeNode(UpperCamelCase_   ,						UpperCamelCase_   ,						self.collection[start]							)
									lowercase__						=				(start + end) // 2
									lowercase__						=				self._build_tree(UpperCamelCase_   ,						UpperCamelCase_							)
									lowercase__						=				self._build_tree(mid + 1   ,						UpperCamelCase_							)
									return SegmentTreeNode(UpperCamelCase_   ,						UpperCamelCase_   ,						self.fn(left.val   ,						right.val							)   ,						UpperCamelCase_   ,						UpperCamelCase_							)

							def 				lowerCamelCase_			(							self:     List[Any]   ,						UpperCamelCase_:     Dict   ,						UpperCamelCase_:     Tuple   ,						UpperCamelCase_:     Union[str, Any]							)      ->       Dict:





									"""simple docstring"""







									if node.start == i and node.end == i:
											lowercase__						=				val
											return
									if i <= node.mid:
											self._update_tree(node.left   ,						UpperCamelCase_   ,						UpperCamelCase_							)
									else:
											self._update_tree(node.right   ,						UpperCamelCase_   ,						UpperCamelCase_							)
									lowercase__						=				self.fn(node.left.val   ,						node.right.val							)

							def 				lowerCamelCase_			(							self:     List[Any]   ,						UpperCamelCase_:     str   ,						UpperCamelCase_:     Dict   ,						UpperCamelCase_:     Dict							)      ->       List[Any]:





									"""simple docstring"""







									if node.start == i and node.end == j:
											return node.val

									if i <= node.mid:
											if j <= node.mid:
													# range in left child tree
													return self._query_range(node.left   ,						UpperCamelCase_   ,						UpperCamelCase_							)
											else:
													# range in left child tree and right child tree
													return self.fn(
													    self._query_range(node.left   ,						UpperCamelCase_   ,						node.mid							)   ,						self._query_range(node.right   ,						node.mid + 1   ,						UpperCamelCase_							)   ,						)
									else:
											# range in right child tree
											return self._query_range(node.right   ,						UpperCamelCase_   ,						UpperCamelCase_							)


							def 				lowerCamelCase_			(							self:     Optional[int]							)      ->       str:





									"""simple docstring"""







									if self.root is not None:
											lowercase__						=				Queue()
											queue.put(self.root							)
											while not queue.empty():
													lowercase__						=				queue.get()
													yield node

													if node.left is not None:
															queue.put(node.left							)

													if node.right is not None:
															queue.put(node.right							)


if __name__ == "__main__":
			import operator

			for fn in [operator.add, max, min]:
						print('*' * 50)
						lowerCAmelCase	=							SegmentTree([2, 1, 5, 3, 4], fn)
						for node in arr.traverse():
									print(node)
						print()

						arr.update(1, 5)
						for node in arr.traverse():
									print(node)
						print()

						print(arr.query_range(3, 4))  # 7
						print(arr.query_range(2, 2))  # 5
						print(arr.query_range(1, 3))  # 13
						print()


