



"""simple docstring"""







import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available


if is_torch_available():
		import numpy as np
		import torch

if is_vision_available():
		from PIL import Image


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=False      ):
		assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

		_lowercase				: List[str]     =   []
		for i in range(image_processor_tester.batch_size      ):
				if equal_resolution:
						_lowercase				: Any     =   image_processor_tester.max_resolution
				else:
						# To avoid getting image width/height 0
						_lowercase				: Optional[Any]     =   image_processor_tester.min_resolution
						if getattr(__UpperCAmelCase   ,				"""size_divisor"""   ,				__UpperCAmelCase      ):
								# If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
								_lowercase				: List[Any]     =   max(image_processor_tester.size_divisor   ,				__UpperCAmelCase      )
						_lowercase     ,  _lowercase				: Dict     =   np.random.choice(np.arange(__UpperCAmelCase   ,				image_processor_tester.max_resolution      )   ,				2      )
				image_inputs.append(
				    np.random.randint(255   ,				size=(image_processor_tester.num_channels, width, height)   ,				dtype=np.uinta      )      )

		if not numpify and not torchify:
				# PIL expects the channel dimension as last dimension
				_lowercase				: str     =   [Image.fromarray(np.moveaxis(__UpperCAmelCase   ,				0   ,				-1      )      ) for image in image_inputs]

		if torchify:
				_lowercase				: Union[str, Any]     =   [torch.from_numpy(__UpperCAmelCase      ) for image in image_inputs]

		return image_inputs


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=10   ,				__UpperCAmelCase=10   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=False      ):
		_lowercase				: int     =   []
		for i in range(image_processor_tester.num_frames      ):
				video.append(np.random.randint(255   ,				size=(image_processor_tester.num_channels, width, height)   ,				dtype=np.uinta      )      )

		if not numpify and not torchify:
				# PIL expects the channel dimension as last dimension
				_lowercase				: Union[str, Any]     =   [Image.fromarray(np.moveaxis(__UpperCAmelCase   ,				0   ,				-1      )      ) for frame in video]

		if torchify:
				_lowercase				: List[str]     =   [torch.from_numpy(__UpperCAmelCase      ) for frame in video]

		return video


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=False   ,				__UpperCAmelCase=False      ):
		assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

		_lowercase				: List[str]     =   []
		for i in range(image_processor_tester.batch_size      ):
				if equal_resolution:
						_lowercase				: Optional[int]     =   image_processor_tester.max_resolution
				else:
						_lowercase     ,  _lowercase				: Tuple     =   np.random.choice(
						    np.arange(image_processor_tester.min_resolution   ,				image_processor_tester.max_resolution      )   ,				2      )
						_lowercase				: Optional[Any]     =   prepare_video(
						    image_processor_tester=__UpperCAmelCase   ,				width=__UpperCAmelCase   ,				height=__UpperCAmelCase   ,				numpify=__UpperCAmelCase   ,				torchify=__UpperCAmelCase   ,				)
				video_inputs.append(__UpperCAmelCase      )

		return video_inputs





class   UpperCamelCase	:




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_							:       Tuple						       =  None






	def    lowerCamelCase__					(     self   ):
			_lowercase				: List[Any]     =   self.image_processing_class(**self.image_processor_dict   )
			_lowercase				: str     =   json.loads(image_processor.to_json_string()   )
			for key, value in self.image_processor_dict.items():
					self.assertEqual(obj[key]				,UpperCAmelCase_   )






	def    lowerCamelCase__					(     self   ):
			_lowercase				: Optional[int]     =   self.image_processing_class(**self.image_processor_dict   )

			with tempfile.TemporaryDirectory() as tmpdirname:
					_lowercase				: Dict     =   os.path.join(UpperCAmelCase_				,"""image_processor.json"""   )
					image_processor_first.to_json_file(UpperCAmelCase_   )
					_lowercase				: str     =   self.image_processing_class.from_json_file(UpperCAmelCase_   )

			self.assertEqual(image_processor_second.to_dict()				,image_processor_first.to_dict()   )






	def    lowerCamelCase__					(     self   ):
			_lowercase				: List[Any]     =   self.image_processing_class(**self.image_processor_dict   )

			with tempfile.TemporaryDirectory() as tmpdirname:
					_lowercase				: Optional[Any]     =   image_processor_first.save_pretrained(UpperCAmelCase_   )[0]
					check_json_file_has_correct_format(UpperCAmelCase_   )
					_lowercase				: Tuple     =   self.image_processing_class.from_pretrained(UpperCAmelCase_   )

			self.assertEqual(image_processor_second.to_dict()				,image_processor_first.to_dict()   )






	def    lowerCamelCase__					(     self   ):
			_lowercase				: List[str]     =   self.image_processing_class()
			self.assertIsNotNone(UpperCAmelCase_   )






	@require_torch
	@require_vision
	def    lowerCamelCase__					(     self   ):
			if self.test_cast_dtype is not None:
					# Initialize image_processor
					_lowercase				: Tuple     =   self.image_processing_class(**self.image_processor_dict   )

					# create random PyTorch tensors
					_lowercase				: List[Any]     =   prepare_image_inputs(self.image_processor_tester				,equal_resolution=UpperCAmelCase_				,torchify=UpperCAmelCase_   )

					_lowercase				: Optional[int]     =   image_processor(UpperCAmelCase_				,return_tensors="""pt"""   )
					# for layoutLM compatiblity
					self.assertEqual(encoding.pixel_values.device				,torch.device("""cpu"""   )   )
					self.assertEqual(encoding.pixel_values.dtype				,torch.floataa   )

					_lowercase				: int     =   image_processor(UpperCAmelCase_				,return_tensors="""pt"""   ).to(torch.floataa   )
					self.assertEqual(encoding.pixel_values.device				,torch.device("""cpu"""   )   )
					self.assertEqual(encoding.pixel_values.dtype				,torch.floataa   )

					_lowercase				: Optional[int]     =   image_processor(UpperCAmelCase_				,return_tensors="""pt"""   ).to("""cpu"""				,torch.bfloataa   )
					self.assertEqual(encoding.pixel_values.device				,torch.device("""cpu"""   )   )
					self.assertEqual(encoding.pixel_values.dtype				,torch.bfloataa   )

					with self.assertRaises(UpperCAmelCase_   ):
							_lowercase				: Dict     =   image_processor(UpperCAmelCase_				,return_tensors="""pt"""   ).to(torch.bfloataa				,"""cpu"""   )

					# Try with text + image feature
					_lowercase				: Union[str, Any]     =   image_processor(UpperCAmelCase_				,return_tensors="""pt"""   )
					encoding.update({"""input_ids""": torch.LongTensor([[1, 2, 3], [4, 5, 6]]   )}   )
					_lowercase				: Optional[Any]     =   encoding.to(torch.floataa   )

					self.assertEqual(encoding.pixel_values.device				,torch.device("""cpu"""   )   )
					self.assertEqual(encoding.pixel_values.dtype				,torch.floataa   )
					self.assertEqual(encoding.input_ids.dtype				,torch.long   )











"""simple docstring"""
import unittest

from cer import CER


A_     :					Union[str, Any]							=     CER()



class 						a_ (      unittest.TestCase					):







      '''simple docstring'''

      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[Any]								=		['White House']
       lowerCamelCase__	:     List[str]								=		['white house']
       # S = 2, D = 0, I = 0, N = 11, CER = 2 / 11
       lowerCamelCase__	:     Dict								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.1_818_181_818   ) < 1e-6   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		['were wolf']
       lowerCamelCase__	:     Union[str, Any]								=		['werewolf']
       # S = 0, D = 0, I = 1, N = 9, CER = 1 / 9
       lowerCamelCase__	:     Dict								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.1_111_111   ) < 1e-6   )

       lowerCamelCase__	:     List[Any]								=		['werewolf']
       lowerCamelCase__	:     Optional[Any]								=		['weae     wolf']
       # S = 1, D = 1, I = 0, N = 8, CER = 0.25
       lowerCamelCase__	:     List[str]								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.25   ) < 1e-6   )

       # consecutive whitespaces case 1
       lowerCamelCase__	:     Optional[Any]								=		['were wolf']
       lowerCamelCase__	:     Tuple								=		['were               wolf']
       # S = 0, D = 0, I = 0, N = 9, CER = 0
       lowerCamelCase__	:     Tuple								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.0   ) < 1e-6   )

       # consecutive whitespaces case 2
       lowerCamelCase__	:     Any								=		['were   wolf']
       lowerCamelCase__	:     int								=		['were               wolf']
       # S = 0, D = 0, I = 0, N = 9, CER = 0
       lowerCamelCase__	:     Optional[int]								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.0   ) < 1e-6   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[Any]								=		['werewolf']
       lowerCamelCase__	:     Optional[int]								=		['weaewolf']
       # S = 1, D = 0, I = 0, N = 8, CER = 0.125
       lowerCamelCase__	:     Union[str, Any]								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.125   ) < 1e-6   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     int								=		['werewolf']
       lowerCamelCase__	:     Union[str, Any]								=		['wereawolf']
       # S = 0, D = 1, I = 0, N = 8, CER = 0.125
       lowerCamelCase__	:     Any								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.125   ) < 1e-6   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[Any]								=		['werewolf']
       lowerCamelCase__	:     Dict								=		['wereolf']
       # S = 0, D = 0, I = 1, N = 8, CER = 0.125
       lowerCamelCase__	:     int								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.125   ) < 1e-6   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		['werewolf']
       lowerCamelCase__	:     Tuple								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertEqual(lowerCamelCase_,	0.0   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		['werewolf', 'I am your father']
       lowerCamelCase__	:     List[Any]								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertEqual(lowerCamelCase_,	0.0   )

       lowerCamelCase__	:     Dict								=		['werewolf', 'I am your father', 'doge']
       lowerCamelCase__	:     int								=		['werxwolf', 'I       am your father', 'doge']
       # S = 1, D = 0, I = 0, N = 28, CER = 1 / 28
       lowerCamelCase__	:     Optional[int]								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.03_571_428   ) < 1e-6   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		['My hovercraft', 'is full of eels']
       lowerCamelCase__	:     List[Any]								=		['My hovercraft is full', ' of eels']
       # S = 0, D = 0, I = 2, N = 28, CER = 2 / 28
       # whitespace at the front of " of eels" will be strip during preporcessing
       # so need to insert 2 whitespaces
       lowerCamelCase__	:     Dict								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_,	concatenate_texts=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.071_428   ) < 1e-6   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[Any]								=		['我能吞下玻璃而不伤身体']
       lowerCamelCase__	:     Any								=		[' 能吞虾玻璃而 不霜身体啦']
       # S = 3, D = 2, I = 0, N = 11, CER = 5 / 11
       lowerCamelCase__	:     List[str]								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.4_545_454_545   ) < 1e-6   )

       lowerCamelCase__	:     Optional[Any]								=		['我能吞下玻璃', '而不伤身体']
       lowerCamelCase__	:     Optional[Any]								=		['我    能 吞 下 玻 璃', '而不伤身体']
       # S = 0, D = 5, I = 0, N = 11, CER = 5 / 11
       lowerCamelCase__	:     Dict								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertTrue(abs(char_error_rate - 0.454_545_454_545   ) < 1e-6   )

       lowerCamelCase__	:     Optional[int]								=		['我能吞下玻璃而不伤身体']
       lowerCamelCase__	:     Union[str, Any]								=		cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )
       self.assertFalse(lowerCamelCase_,	0.0   )





      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		['']
       lowerCamelCase__	:     Optional[int]								=		['Hypothesis']
       with self.assertRaises(lowerCamelCase_   ):
        cer.compute(predictions=lowerCamelCase_,	references=lowerCamelCase_   )


if __name__ == "__main__":
      unittest.main()

