
"""simple docstring"""



import argparse
import json
import os

import fairseq
import torch
from torch import nn

from transformers import (
    SpeechaTextaConfig,
    SpeechaTextaForCausalLM,
    SpeechaTextaTokenizer,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


logging.set_verbosity_info()
_snake_case          =						logging.get_logger(__name__)

_snake_case          =						{
    '''post_extract_proj''': '''feature_projection.projection''',
    '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''',
    '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''',
    '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''',
    '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''',
    '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''',
    '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''',
    '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''',
    '''fc2''': '''encoder.layers.*.feed_forward.output_dense''',
    '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''',
    '''encoder.layer_norm''': '''encoder.layer_norm''',
    '''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
    '''quantizer.weight_proj''': '''quantizer.weight_proj''',
    '''quantizer.vars''': '''quantizer.codevectors''',
    '''project_q''': '''project_q''',
    '''final_proj''': '''project_hid''',
    '''w2v_encoder.proj''': '''lm_head''',
    '''mask_emb''': '''masked_spec_embed''',
}
_snake_case          =						[
    '''lm_head''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
]






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					List[str]     ,  SCREAMING_SNAKE_CASE:					Any     ,  SCREAMING_SNAKE_CASE:					List[Any]     ,  SCREAMING_SNAKE_CASE:					List[str]     ,  SCREAMING_SNAKE_CASE:					str						):






							"""simple docstring"""



							for attribute in key.split('.'						):
														_lowerCAmelCase							=			getattr(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__						)

							if weight_type is not None:
														_lowerCAmelCase							=			getattr(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__						).shape
							else:
														_lowerCAmelCase							=			hf_pointer.shape

							assert hf_shape == value.shape, (
							    f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"""
							    f""" {value.shape} for {full_name}"""
							)

							if weight_type == "weight":
														_lowerCAmelCase							=			value
							elif weight_type == "weight_g":
														_lowerCAmelCase							=			value
							elif weight_type == "weight_v":
														_lowerCAmelCase							=			value
							elif weight_type == "bias":
														_lowerCAmelCase							=			value
							else:
														_lowerCAmelCase							=			value

							logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}."""						)






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					List[Any]     ,  SCREAMING_SNAKE_CASE:					int						):






							"""simple docstring"""



							_lowerCAmelCase							=			[]
							_lowerCAmelCase							=			fairseq_model.state_dict()

							_lowerCAmelCase							=			hf_model.feature_extractor

							# if encoder has different dim to decoder -> use proj_weight
							_lowerCAmelCase							=			None

							for name, value in fairseq_dict.items():
														_lowerCAmelCase							=			False
														if "conv_layers" in name:
																					load_conv_layer(
																					    SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  hf_model.config.feat_extract_norm == 'group'     ,  )
																					_lowerCAmelCase							=			True
														elif name.split('.'						)[0] == "proj":
																					_lowerCAmelCase							=			fairseq_model.proj
																					_lowerCAmelCase							=			True
														else:
																					for key, mapped_key in MAPPING.items():
																												if key in name or key.split('w2v_model.'						)[-1] == name.split('.'						)[0]:
																																			_lowerCAmelCase							=			True
																																			if "*" in mapped_key:
																																										_lowerCAmelCase							=			name.split(SCREAMING_SNAKE_CASE__						)[0].split('.'						)[-2]
																																										_lowerCAmelCase							=			mapped_key.replace('*'     ,  SCREAMING_SNAKE_CASE__						)
																																			if "weight_g" in name:
																																										_lowerCAmelCase							=			"""weight_g"""
																																			elif "weight_v" in name:
																																										_lowerCAmelCase							=			"""weight_v"""
																																			elif "bias" in name:
																																										_lowerCAmelCase							=			"""bias"""
																																			elif "weight" in name:
																																										_lowerCAmelCase							=			"""weight"""
																																			else:
																																										_lowerCAmelCase							=			None
																																			set_recursively(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__						)
																												continue
														if not is_used:
																					unused_weights.append(SCREAMING_SNAKE_CASE__						)

							logger.warning(f"""Unused weights: {unused_weights}"""						)

							return proj_weight






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Optional[int]     ,  SCREAMING_SNAKE_CASE:					Dict     ,  SCREAMING_SNAKE_CASE:					Tuple     ,  SCREAMING_SNAKE_CASE:					Union[str, Any]     ,  SCREAMING_SNAKE_CASE:					int						):






							"""simple docstring"""



							_lowerCAmelCase							=			full_name.split('conv_layers.'						)[-1]
							_lowerCAmelCase							=			name.split('.'						)
							_lowerCAmelCase							=			int(items[0]						)
							_lowerCAmelCase							=			int(items[1]						)

							if type_id == 0:
														if "bias" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
																					    f"""{full_name} has size {value.shape}, but"""
																					    f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""
																					)
																					_lowerCAmelCase							=			value
																					logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}."""						)
														elif "weight" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
																					    f"""{full_name} has size {value.shape}, but"""
																					    f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""
																					)
																					_lowerCAmelCase							=			value
																					logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}."""						)
							elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
														if "bias" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
																					    f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"""
																					    " found."
																					)
																					_lowerCAmelCase							=			value
																					logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""						)
														elif "weight" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
																					    f"""{full_name} has size {value.shape}, but"""
																					    f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."""
																					)
																					_lowerCAmelCase							=			value
																					logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""						)
							else:
														unused_weights.append(SCREAMING_SNAKE_CASE__						)






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					str						):






							"""simple docstring"""



							_lowerCAmelCase							=			emb.weight.shape
							_lowerCAmelCase							=			nn.Linear(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__     ,  bias=SCREAMING_SNAKE_CASE__						)
							_lowerCAmelCase							=			emb.weight.data
							return lin_layer






def 	__snake_case  (    SCREAMING_SNAKE_CASE:					Dict						):






							"""simple docstring"""



							with open(SCREAMING_SNAKE_CASE__     ,  'r'     ,  encoding='utf-8'						) as f:
														_lowerCAmelCase							=			f.readlines()
														_lowerCAmelCase							=			[line.split(' '						)[0] for line in lines]

							_lowerCAmelCase							=			len(SCREAMING_SNAKE_CASE__						)

							_lowerCAmelCase							=			{
							    """<s>""": 0,
							    """<pad>""": 1,
							    """</s>""": 2,
							    """<unk>""": 3,
							}

							vocab_dict.update(dict(zip(SCREAMING_SNAKE_CASE__     ,  range(4     ,  num_words + 4						)						)						)						)
							return vocab_dict






@torch.no_grad()
def 	__snake_case  (    SCREAMING_SNAKE_CASE:					int     ,  SCREAMING_SNAKE_CASE:					Any     ,  SCREAMING_SNAKE_CASE:					List[Any]     ,  SCREAMING_SNAKE_CASE:					Union[str, Any]     ,  SCREAMING_SNAKE_CASE:					Any     ,  SCREAMING_SNAKE_CASE:					Optional[Any]     ,  SCREAMING_SNAKE_CASE:					Optional[Any]     ,  ):






							"""simple docstring"""



							_lowerCAmelCase							=			WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE__						)
							_lowerCAmelCase							=			SpeechaTextaConfig.from_pretrained(
							    SCREAMING_SNAKE_CASE__     ,  vocab_size=SCREAMING_SNAKE_CASE__     ,  decoder_layers=SCREAMING_SNAKE_CASE__     ,  do_stable_layer_norm=SCREAMING_SNAKE_CASE__						)

							_lowerCAmelCase							=			WavaVecaFeatureExtractor(
							    feature_size=1     ,  sampling_rate=1_6000     ,  padding_value=0     ,  do_normalize=SCREAMING_SNAKE_CASE__     ,  return_attention_mask=SCREAMING_SNAKE_CASE__     ,  )

							_lowerCAmelCase							=			fairseq.checkpoint_utils.load_model_ensemble_and_task(
							    [checkpoint_path]     ,  arg_overrides={'data': '/'.join(dict_path.split('/'						)[:-1]						)}						)
							_lowerCAmelCase							=			model[0].eval()

							# set weights for wav2vec2 encoder
							_lowerCAmelCase							=			WavaVecaModel(SCREAMING_SNAKE_CASE__						)
							_lowerCAmelCase							=			recursively_load_weights_wavaveca(model.encoder     ,  SCREAMING_SNAKE_CASE__						)

							_lowerCAmelCase							=			SpeechaTextaForCausalLM(SCREAMING_SNAKE_CASE__						)
							_lowerCAmelCase							=			hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()     ,  strict=SCREAMING_SNAKE_CASE__						)

							# set output linear layer
							unexpected_keys.remove('embed_out'						)
							_lowerCAmelCase							=			nn.Parameter(model.decoder.embed_out.detach()						)

							# layer norm is init to identity matrix so leaving it is fine
							logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}"""						)
							logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}"""						)

							_lowerCAmelCase							=			SpeechEncoderDecoderModel(encoder=SCREAMING_SNAKE_CASE__     ,  decoder=SCREAMING_SNAKE_CASE__						)
							_lowerCAmelCase							=			False

							# add projection layer
							_lowerCAmelCase							=			nn.Parameter(projection_layer.weight						)
							_lowerCAmelCase							=			nn.Parameter(projection_layer.bias						)

							_lowerCAmelCase							=			create_vocab_dict(SCREAMING_SNAKE_CASE__						)

							with open(os.path.join(SCREAMING_SNAKE_CASE__     ,  'vocab.json'						)     ,  'w'						) as fp:
														json.dump(SCREAMING_SNAKE_CASE__     ,  SCREAMING_SNAKE_CASE__						)

							_lowerCAmelCase							=			SpeechaTextaTokenizer(os.path.join(SCREAMING_SNAKE_CASE__     ,  'vocab.json'						)						)
							tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__						)

							_lowerCAmelCase							=			hf_wavavec.config.to_dict()
							_lowerCAmelCase							=			tokenizer.pad_token_id
							_lowerCAmelCase							=			tokenizer.bos_token_id
							_lowerCAmelCase							=			tokenizer.eos_token_id
							_lowerCAmelCase							=			"""speech_to_text_2"""
							_lowerCAmelCase							=			"""wav2vec2"""

							_lowerCAmelCase							=			SpeechEncoderDecoderConfig.from_dict(SCREAMING_SNAKE_CASE__						)

							hf_wavavec.save_pretrained(SCREAMING_SNAKE_CASE__						)
							feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__						)


if __name__ == "__main__":
	_snake_case          =						argparse.ArgumentParser()
	parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
	parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
	parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
	parser.add_argument(
	    '''--encoder_config_path''',
	    default='''facebook/wav2vec2-large-lv60''',
	    type=str,
	    help='''Path to hf encoder wav2vec2 checkpoint config''',
	)
	parser.add_argument(
	    '''--decoder_config_path''',
	    default='''facebook/s2t-small-mustc-en-fr-st''',
	    type=str,
	    help='''Path to hf decoder s2t checkpoint config''',
	)
	parser.add_argument('''--vocab_size''', default=1_0_2_2_4, type=int, help='''Vocab size of decoder''')
	parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''')

	_snake_case          =						parser.parse_args()
	convert_wavaveca_checkpoint(
	    args.checkpoint_path,
	    args.pytorch_dump_folder_path,
	    args.dict_path,
	    encoder_config_path=args.encoder_config_path,
	    decoder_config_path=args.decoder_config_path,
	    vocab_size=args.vocab_size,
	    num_decoder_layers=args.num_decoder_layers,
	)








"""simple docstring"""



import unittest

import numpy as np

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

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import ChineseCLIPImageProcessor
class        _SCREAMING_SNAKE_CASE  (  unittest.TestCase							):






				'''simple docstring'''



				def __init__(					self	:			Optional[Any]				,     UpperCAmelCase_	:			int				,     UpperCAmelCase_	:			Dict=7				,     UpperCAmelCase_	:			List[Any]=3				,     UpperCAmelCase_	:			Tuple=18				,     UpperCAmelCase_	:			List[str]=30				,     UpperCAmelCase_	:			Union[str, Any]=400				,     UpperCAmelCase_	:			Optional[Any]=True				,     UpperCAmelCase_	:			Tuple=None				,     UpperCAmelCase_	:			Optional[int]=True				,     UpperCAmelCase_	:			Any=None				,     UpperCAmelCase_	:			Tuple=True				,     UpperCAmelCase_	:			List[Any]=[0.48145466, 0.4578275, 0.40821073]				,     UpperCAmelCase_	:			List[Any]=[0.26862954, 0.26130258, 0.27577711]				,     UpperCAmelCase_	:			Optional[int]=True				,     )		->  Tuple:







											"""simple docstring"""




											_lowerCAmelCase  	=			size if size is not None else {'height': 224, 'width': 224}
											_lowerCAmelCase  	=			crop_size if crop_size is not None else {'height': 18, 'width': 18}
											_lowerCAmelCase  	=			parent
											_lowerCAmelCase  	=			batch_size
											_lowerCAmelCase  	=			num_channels
											_lowerCAmelCase  	=			image_size
											_lowerCAmelCase  	=			min_resolution
											_lowerCAmelCase  	=			max_resolution
											_lowerCAmelCase  	=			do_resize
											_lowerCAmelCase  	=			size
											_lowerCAmelCase  	=			do_center_crop
											_lowerCAmelCase  	=			crop_size
											_lowerCAmelCase  	=			do_normalize
											_lowerCAmelCase  	=			image_mean
											_lowerCAmelCase  	=			image_std
											_lowerCAmelCase  	=			do_convert_rgb


				def 				__lowerCamelCase	(					self	:			Optional[int]  )		->  int:







											"""simple docstring"""




											return {
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_center_crop": self.do_center_crop,
											    "crop_size": self.crop_size,
											    "do_normalize": self.do_normalize,
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											    "do_convert_rgb": self.do_convert_rgb,
											}







				def 				__lowerCamelCase	(					self	:			Dict				,     UpperCAmelCase_	:			Dict=False				,     UpperCAmelCase_	:			int=False				,     UpperCAmelCase_	:			Dict=False  )		->  str:







											"""simple docstring"""




											assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

											if equal_resolution:
																		_lowerCAmelCase  	=			[]
																		for i in range(self.batch_size  ):
																									image_inputs.append(
																									    np.random.randint(
																									        255				,     size=(self.num_channels, self.max_resolution, self.max_resolution)				,     dtype=np.uinta  )  )
											else:
																		_lowerCAmelCase  	=			[]
																		for i in range(self.batch_size  ):
																									_lowerCAmelCase	,		_lowerCAmelCase  	=			np.random.choice(np.arange(self.min_resolution				,     self.max_resolution  )				,     2  )
																									image_inputs.append(np.random.randint(255				,     size=(self.num_channels, width, height)				,     dtype=np.uinta  )  )

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

											if torchify:
																		_lowerCAmelCase  	=			[torch.from_numpy(UpperCAmelCase_  ) for x in image_inputs]

											return image_inputs






@require_torch
@require_vision
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase      ,				unittest.TestCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							List[Any]							=					ChineseCLIPImageProcessor if is_vision_available() else None


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







											"""simple docstring"""




											_lowerCAmelCase  	=			ChineseCLIPImageProcessingTester(self				,     do_center_crop=UpperCAmelCase_  )


				@property
				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  int:







											"""simple docstring"""




											return self.image_processor_tester.prepare_image_processor_dict()


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







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_resize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'size'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_normalize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_mean'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_std'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_convert_rgb'  )  )


				def 				__lowerCamelCase	(					self	:			Dict  )		->  Tuple:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class.from_dict(self.image_processor_dict  )
											self.assertEqual(image_processor.size				,     {'height': 224, 'width': 224}  )
											self.assertEqual(image_processor.crop_size				,     {'height': 18, 'width': 18}  )

											_lowerCAmelCase  	=			self.image_processing_class.from_dict(self.image_processor_dict				,     size=42				,     crop_size=84  )
											self.assertEqual(image_processor.size				,     {'shortest_edge': 42}  )
											self.assertEqual(image_processor.crop_size				,     {'height': 84, 'width': 84}  )


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







											"""simple docstring"""




											pass


				def 				__lowerCamelCase	(					self	:			Optional[Any]  )		->  Optional[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random PIL images
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     Image.Image  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )


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







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random numpy tensors
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_				,     numpify=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     np.ndarray  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )







				def 				__lowerCamelCase	(					self	:			List[Any]  )		->  Dict:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random PyTorch tensors
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_				,     torchify=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     torch.Tensor  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )






@require_torch
@require_vision
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase      ,				unittest.TestCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							str							=					ChineseCLIPImageProcessor if is_vision_available() else None


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







											"""simple docstring"""




											_lowerCAmelCase  	=			ChineseCLIPImageProcessingTester(self				,     num_channels=4				,     do_center_crop=UpperCAmelCase_  )
											_lowerCAmelCase  	=			3


				@property
				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  Dict:







											"""simple docstring"""




											return self.image_processor_tester.prepare_image_processor_dict()


				def 				__lowerCamelCase	(					self	:			Optional[Any]  )		->  Dict:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_resize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'size'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'center_crop'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_normalize'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_mean'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'image_std'  )  )
											self.assertTrue(hasattr(UpperCAmelCase_				,     'do_convert_rgb'  )  )


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







											"""simple docstring"""




											pass







				def 				__lowerCamelCase	(					self	:			int  )		->  List[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.image_processing_class(**self.image_processor_dict  )
											# create random PIL images
											_lowerCAmelCase  	=			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCAmelCase_  )
											for image in image_inputs:
																		self.assertIsInstance(UpperCAmelCase_				,     Image.Image  )

											# Test not batched input
											_lowerCAmelCase  	=			image_processing(image_inputs[0]				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        1,
											        self.expected_encoded_image_num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )

											# Test batched
											_lowerCAmelCase  	=			image_processing(UpperCAmelCase_				,     return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,     (
											        self.image_processor_tester.batch_size,
											        self.expected_encoded_image_num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,     )






