code: 
  
  
  
  import argparse
  import json
  
  import torch
  
  from diffusers import AutoencoderKL, DDPMPipeline, DDPMScheduler, UNetaDModel, VQModel
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	Optional[Any]		,						lowercase_:	Dict=1				):
         if n_shave_prefix_segments >= 0:
                return ".".join(path.split('.'				)[n_shave_prefix_segments:]				)
         else:
                return ".".join(path.split('.'				)[:n_shave_prefix_segments]				)
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	Optional[int]		,						lowercase_:	Optional[int]=0				):
         _UpperCamelCase     :       Any  						=  []
         for old_item in old_list:
                _UpperCamelCase     :       Optional[int]  						=  old_item
                _UpperCamelCase     :       Tuple  						=  new_item.replace('block.'		,						'resnets.'				)
                _UpperCamelCase     :       List[str]  						=  new_item.replace('conv_shorcut'		,						'conv1'				)
                _UpperCamelCase     :       Any  						=  new_item.replace('in_shortcut'		,						'conv_shortcut'				)
                _UpperCamelCase     :       List[str]  						=  new_item.replace('temb_proj'		,						'time_emb_proj'				)
  
                _UpperCamelCase     :       Any  						=  shave_segments(lowercase_		,						n_shave_prefix_segments=lowercase_				)
  
                mapping.append({'old': old_item, 'new': new_item}				)
  
         return mapping
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	Optional[Any]		,						lowercase_:	Optional[int]=0		,						lowercase_:	int=False				):
         _UpperCamelCase     :       Dict  						=  []
         for old_item in old_list:
                _UpperCamelCase     :       str  						=  old_item
  
                # In `model.mid`, the layer is called `attn`.
                if not in_mid:
                       _UpperCamelCase     :       Optional[int]  						=  new_item.replace('attn'		,						'attentions'				)
                _UpperCamelCase     :       List[Any]  						=  new_item.replace('.k.'		,						'.key.'				)
                _UpperCamelCase     :       Union[str, Any]  						=  new_item.replace('.v.'		,						'.value.'				)
                _UpperCamelCase     :       List[str]  						=  new_item.replace('.q.'		,						'.query.'				)
  
                _UpperCamelCase     :       List[str]  						=  new_item.replace('proj_out'		,						'proj_attn'				)
                _UpperCamelCase     :       Dict  						=  new_item.replace('norm'		,						'group_norm'				)
  
                _UpperCamelCase     :       Dict  						=  shave_segments(lowercase_		,						n_shave_prefix_segments=lowercase_				)
                mapping.append({'old': old_item, 'new': new_item}				)
  
         return mapping
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	Union[str, Any]		,						lowercase_:	List[str]		,						lowercase_:	Any		,						lowercase_:	List[Any]=None		,						lowercase_:	str=None		,						lowercase_:	Optional[Any]=None				):
         assert isinstance(lowercase_		,						lowercase_				), "Paths should be a list of dicts containing 'old' and 'new' keys."
  
         if attention_paths_to_split is not None:
                if config is None:
                       raise ValueError('Please specify the config if setting \'attention_paths_to_split\' to \'True\'.'				)
  
                for path, path_map in attention_paths_to_split.items():
                       _UpperCamelCase     :       Optional[Any]  						=  old_checkpoint[path]
                       _UpperCamelCase     :       Dict  						=  old_tensor.shape[0] // 3
  
                       _UpperCamelCase     :       List[Any]  						=  (-1, channels) if len(old_tensor.shape				) == 3 else (-1)
  
                       _UpperCamelCase     :       Optional[Any]  						=  old_tensor.shape[0] // config.get('num_head_channels'		,						1				) // 3
  
                       _UpperCamelCase     :       Dict  						=  old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:]				)
                       _UpperCamelCase     :       Optional[int]  						=  old_tensor.split(channels // num_heads		,						dim=1				)
  
                       _UpperCamelCase     :       int  						=  query.reshape(lowercase_				).squeeze()
                       _UpperCamelCase     :       int  						=  key.reshape(lowercase_				).squeeze()
                       _UpperCamelCase     :       List[str]  						=  value.reshape(lowercase_				).squeeze()
  
         for path in paths:
                _UpperCamelCase     :       str  						=  path['new']
  
                if attention_paths_to_split is not None and new_path in attention_paths_to_split:
                       continue
  
                _UpperCamelCase     :       List[Any]  						=  new_path.replace('down.'		,						'down_blocks.'				)
                _UpperCamelCase     :       Optional[int]  						=  new_path.replace('up.'		,						'up_blocks.'				)
  
                if additional_replacements is not None:
                       for replacement in additional_replacements:
                              _UpperCamelCase     :       List[str]  						=  new_path.replace(replacement['old']		,						replacement['new']				)
  
                if "attentions" in new_path:
                       _UpperCamelCase     :       Tuple  						=  old_checkpoint[path['old']].squeeze()
                else:
                       _UpperCamelCase     :       List[Any]  						=  old_checkpoint[path['old']]
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	List[str]		,						lowercase_:	Any				):
         _UpperCamelCase     :       List[Any]  						=  {}
  
         _UpperCamelCase     :       int  						=  checkpoint['temb.dense.0.weight']
         _UpperCamelCase     :       List[str]  						=  checkpoint['temb.dense.0.bias']
         _UpperCamelCase     :       List[Any]  						=  checkpoint['temb.dense.1.weight']
         _UpperCamelCase     :       Union[str, Any]  						=  checkpoint['temb.dense.1.bias']
  
         _UpperCamelCase     :       Tuple  						=  checkpoint['norm_out.weight']
         _UpperCamelCase     :       Dict  						=  checkpoint['norm_out.bias']
  
         _UpperCamelCase     :       str  						=  checkpoint['conv_in.weight']
         _UpperCamelCase     :       List[Any]  						=  checkpoint['conv_in.bias']
         _UpperCamelCase     :       List[str]  						=  checkpoint['conv_out.weight']
         _UpperCamelCase     :       Dict  						=  checkpoint['conv_out.bias']
  
         _UpperCamelCase     :       Dict  						=  len({'.'.join(layer.split('.'				)[:2]				) for layer in checkpoint if 'down' in layer}				)
         _UpperCamelCase     :       Optional[int]  						=  {
             layer_id: [key for key in checkpoint if F"down.{layer_id}" in key] for layer_id in range(lowercase_				)
         }
  
         _UpperCamelCase     :       Optional[int]  						=  len({'.'.join(layer.split('.'				)[:2]				) for layer in checkpoint if 'up' in layer}				)
         _UpperCamelCase     :       Dict  						=  {layer_id: [key for key in checkpoint if F"up.{layer_id}" in key] for layer_id in range(lowercase_				)}
  
         for i in range(lowercase_				):
                _UpperCamelCase     :       List[str]  						=  (i - 1) // (config['layers_per_block'] + 1)
  
                if any('downsample' in layer for layer in down_blocks[i]				):
                       _UpperCamelCase     :       str  						=  checkpoint[
                           F"down.{i}.downsample.op.weight"
                       ]
                       _UpperCamelCase     :       List[str]  						=  checkpoint[F"down.{i}.downsample.op.bias"]
                #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.weight'] = checkpoint[f'down.{i}.downsample.conv.weight']
                #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.bias'] = checkpoint[f'down.{i}.downsample.conv.bias']
  
                if any('block' in layer for layer in down_blocks[i]				):
                       _UpperCamelCase     :       Any  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						2				).split('.'				)[:2]				) for layer in down_blocks[i] if 'block' in layer}				)
                       _UpperCamelCase     :       Optional[Any]  						=  {
                           layer_id: [key for key in down_blocks[i] if F"block.{layer_id}" in key]
                           for layer_id in range(lowercase_				)
                       }
  
                       if num_blocks > 0:
                              for j in range(config['layers_per_block']				):
                                     _UpperCamelCase     :       Tuple  						=  renew_resnet_paths(blocks[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_				)
  
                if any('attn' in layer for layer in down_blocks[i]				):
                       _UpperCamelCase     :       Tuple  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						2				).split('.'				)[:2]				) for layer in down_blocks[i] if 'attn' in layer}				)
                       _UpperCamelCase     :       Any  						=  {
                           layer_id: [key for key in down_blocks[i] if F"attn.{layer_id}" in key]
                           for layer_id in range(lowercase_				)
                       }
  
                       if num_attn > 0:
                              for j in range(config['layers_per_block']				):
                                     _UpperCamelCase     :       List[str]  						=  renew_attention_paths(attns[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_		,						config=lowercase_				)
  
         _UpperCamelCase     :       List[str]  						=  [key for key in checkpoint if 'mid.block_1' in key]
         _UpperCamelCase     :       List[str]  						=  [key for key in checkpoint if 'mid.block_2' in key]
         _UpperCamelCase     :       int  						=  [key for key in checkpoint if 'mid.attn_1' in key]
  
         # Mid new 2
         _UpperCamelCase     :       Optional[Any]  						=  renew_resnet_paths(lowercase_				)
         assign_to_checkpoint(
             lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[{'old': 'mid.', 'new': 'mid_new_2.'}, {'old': 'block_1', 'new': 'resnets.0'}]		,						)
  
         _UpperCamelCase     :       List[Any]  						=  renew_resnet_paths(lowercase_				)
         assign_to_checkpoint(
             lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[{'old': 'mid.', 'new': 'mid_new_2.'}, {'old': 'block_2', 'new': 'resnets.1'}]		,						)
  
         _UpperCamelCase     :       int  						=  renew_attention_paths(lowercase_		,						in_mid=lowercase_				)
         assign_to_checkpoint(
             lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[{'old': 'mid.', 'new': 'mid_new_2.'}, {'old': 'attn_1', 'new': 'attentions.0'}]		,						)
  
         for i in range(lowercase_				):
                _UpperCamelCase     :       Optional[Any]  						=  num_up_blocks - 1 - i
  
                if any('upsample' in layer for layer in up_blocks[i]				):
                       _UpperCamelCase     :       int  						=  checkpoint[
                           F"up.{i}.upsample.conv.weight"
                       ]
                       _UpperCamelCase     :       str  						=  checkpoint[F"up.{i}.upsample.conv.bias"]
  
                if any('block' in layer for layer in up_blocks[i]				):
                       _UpperCamelCase     :       Tuple  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						2				).split('.'				)[:2]				) for layer in up_blocks[i] if 'block' in layer}				)
                       _UpperCamelCase     :       List[Any]  						=  {
                           layer_id: [key for key in up_blocks[i] if F"block.{layer_id}" in key] for layer_id in range(lowercase_				)
                       }
  
                       if num_blocks > 0:
                              for j in range(config['layers_per_block'] + 1				):
                                     _UpperCamelCase     :       int  						=  {'old': F"up_blocks.{i}", 'new': F"up_blocks.{block_id}"}
                                     _UpperCamelCase     :       Dict  						=  renew_resnet_paths(blocks[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[replace_indices]				)
  
                if any('attn' in layer for layer in up_blocks[i]				):
                       _UpperCamelCase     :       Union[str, Any]  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						2				).split('.'				)[:2]				) for layer in up_blocks[i] if 'attn' in layer}				)
                       _UpperCamelCase     :       int  						=  {
                           layer_id: [key for key in up_blocks[i] if F"attn.{layer_id}" in key] for layer_id in range(lowercase_				)
                       }
  
                       if num_attn > 0:
                              for j in range(config['layers_per_block'] + 1				):
                                     _UpperCamelCase     :       Tuple  						=  {'old': F"up_blocks.{i}", 'new': F"up_blocks.{block_id}"}
                                     _UpperCamelCase     :       Union[str, Any]  						=  renew_attention_paths(attns[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[replace_indices]				)
  
         _UpperCamelCase     :       Dict  						=  {k.replace('mid_new_2'		,						'mid_block'				): v for k, v in new_checkpoint.items()}
         return new_checkpoint
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	Optional[int]		,						lowercase_:	Dict				):
         _UpperCamelCase     :       Optional[int]  						=  {}
  
         _UpperCamelCase     :       List[str]  						=  checkpoint['encoder.norm_out.weight']
         _UpperCamelCase     :       Dict  						=  checkpoint['encoder.norm_out.bias']
  
         _UpperCamelCase     :       int  						=  checkpoint['encoder.conv_in.weight']
         _UpperCamelCase     :       Optional[Any]  						=  checkpoint['encoder.conv_in.bias']
         _UpperCamelCase     :       List[str]  						=  checkpoint['encoder.conv_out.weight']
         _UpperCamelCase     :       List[Any]  						=  checkpoint['encoder.conv_out.bias']
  
         _UpperCamelCase     :       Tuple  						=  checkpoint['decoder.norm_out.weight']
         _UpperCamelCase     :       Optional[int]  						=  checkpoint['decoder.norm_out.bias']
  
         _UpperCamelCase     :       Optional[Any]  						=  checkpoint['decoder.conv_in.weight']
         _UpperCamelCase     :       int  						=  checkpoint['decoder.conv_in.bias']
         _UpperCamelCase     :       int  						=  checkpoint['decoder.conv_out.weight']
         _UpperCamelCase     :       str  						=  checkpoint['decoder.conv_out.bias']
  
         _UpperCamelCase     :       Any  						=  len({'.'.join(layer.split('.'				)[:3]				) for layer in checkpoint if 'down' in layer}				)
         _UpperCamelCase     :       Union[str, Any]  						=  {
             layer_id: [key for key in checkpoint if F"down.{layer_id}" in key] for layer_id in range(lowercase_				)
         }
  
         _UpperCamelCase     :       Tuple  						=  len({'.'.join(layer.split('.'				)[:3]				) for layer in checkpoint if 'up' in layer}				)
         _UpperCamelCase     :       Optional[Any]  						=  {layer_id: [key for key in checkpoint if F"up.{layer_id}" in key] for layer_id in range(lowercase_				)}
  
         for i in range(lowercase_				):
                _UpperCamelCase     :       Any  						=  (i - 1) // (config['layers_per_block'] + 1)
  
                if any('downsample' in layer for layer in down_blocks[i]				):
                       _UpperCamelCase     :       Union[str, Any]  						=  checkpoint[
                           F"encoder.down.{i}.downsample.conv.weight"
                       ]
                       _UpperCamelCase     :       Tuple  						=  checkpoint[
                           F"encoder.down.{i}.downsample.conv.bias"
                       ]
  
                if any('block' in layer for layer in down_blocks[i]				):
                       _UpperCamelCase     :       int  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						3				).split('.'				)[:3]				) for layer in down_blocks[i] if 'block' in layer}				)
                       _UpperCamelCase     :       Dict  						=  {
                           layer_id: [key for key in down_blocks[i] if F"block.{layer_id}" in key]
                           for layer_id in range(lowercase_				)
                       }
  
                       if num_blocks > 0:
                              for j in range(config['layers_per_block']				):
                                     _UpperCamelCase     :       List[Any]  						=  renew_resnet_paths(blocks[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_				)
  
                if any('attn' in layer for layer in down_blocks[i]				):
                       _UpperCamelCase     :       int  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						3				).split('.'				)[:3]				) for layer in down_blocks[i] if 'attn' in layer}				)
                       _UpperCamelCase     :       List[str]  						=  {
                           layer_id: [key for key in down_blocks[i] if F"attn.{layer_id}" in key]
                           for layer_id in range(lowercase_				)
                       }
  
                       if num_attn > 0:
                              for j in range(config['layers_per_block']				):
                                     _UpperCamelCase     :       Optional[int]  						=  renew_attention_paths(attns[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_		,						config=lowercase_				)
  
         _UpperCamelCase     :       Optional[Any]  						=  [key for key in checkpoint if 'mid.block_1' in key]
         _UpperCamelCase     :       int  						=  [key for key in checkpoint if 'mid.block_2' in key]
         _UpperCamelCase     :       Dict  						=  [key for key in checkpoint if 'mid.attn_1' in key]
  
         # Mid new 2
         _UpperCamelCase     :       List[Any]  						=  renew_resnet_paths(lowercase_				)
         assign_to_checkpoint(
             lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[{'old': 'mid.', 'new': 'mid_new_2.'}, {'old': 'block_1', 'new': 'resnets.0'}]		,						)
  
         _UpperCamelCase     :       Optional[Any]  						=  renew_resnet_paths(lowercase_				)
         assign_to_checkpoint(
             lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[{'old': 'mid.', 'new': 'mid_new_2.'}, {'old': 'block_2', 'new': 'resnets.1'}]		,						)
  
         _UpperCamelCase     :       Dict  						=  renew_attention_paths(lowercase_		,						in_mid=lowercase_				)
         assign_to_checkpoint(
             lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[{'old': 'mid.', 'new': 'mid_new_2.'}, {'old': 'attn_1', 'new': 'attentions.0'}]		,						)
  
         for i in range(lowercase_				):
                _UpperCamelCase     :       List[str]  						=  num_up_blocks - 1 - i
  
                if any('upsample' in layer for layer in up_blocks[i]				):
                       _UpperCamelCase     :       List[Any]  						=  checkpoint[
                           F"decoder.up.{i}.upsample.conv.weight"
                       ]
                       _UpperCamelCase     :       Any  						=  checkpoint[
                           F"decoder.up.{i}.upsample.conv.bias"
                       ]
  
                if any('block' in layer for layer in up_blocks[i]				):
                       _UpperCamelCase     :       str  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						3				).split('.'				)[:3]				) for layer in up_blocks[i] if 'block' in layer}				)
                       _UpperCamelCase     :       Tuple  						=  {
                           layer_id: [key for key in up_blocks[i] if F"block.{layer_id}" in key] for layer_id in range(lowercase_				)
                       }
  
                       if num_blocks > 0:
                              for j in range(config['layers_per_block'] + 1				):
                                     _UpperCamelCase     :       List[Any]  						=  {'old': F"up_blocks.{i}", 'new': F"up_blocks.{block_id}"}
                                     _UpperCamelCase     :       Any  						=  renew_resnet_paths(blocks[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[replace_indices]				)
  
                if any('attn' in layer for layer in up_blocks[i]				):
                       _UpperCamelCase     :       List[str]  						=  len(
                           {'.'.join(shave_segments(lowercase_		,						3				).split('.'				)[:3]				) for layer in up_blocks[i] if 'attn' in layer}				)
                       _UpperCamelCase     :       Tuple  						=  {
                           layer_id: [key for key in up_blocks[i] if F"attn.{layer_id}" in key] for layer_id in range(lowercase_				)
                       }
  
                       if num_attn > 0:
                              for j in range(config['layers_per_block'] + 1				):
                                     _UpperCamelCase     :       List[str]  						=  {'old': F"up_blocks.{i}", 'new': F"up_blocks.{block_id}"}
                                     _UpperCamelCase     :       Optional[Any]  						=  renew_attention_paths(attns[j]				)
                                     assign_to_checkpoint(lowercase_		,						lowercase_		,						lowercase_		,						additional_replacements=[replace_indices]				)
  
         _UpperCamelCase     :       Dict  						=  {k.replace('mid_new_2'		,						'mid_block'				): v for k, v in new_checkpoint.items()}
         _UpperCamelCase     :       str  						=  checkpoint['quant_conv.weight']
         _UpperCamelCase     :       int  						=  checkpoint['quant_conv.bias']
         if "quantize.embedding.weight" in checkpoint:
                _UpperCamelCase     :       List[Any]  						=  checkpoint['quantize.embedding.weight']
         _UpperCamelCase     :       List[str]  						=  checkpoint['post_quant_conv.weight']
         _UpperCamelCase     :       Optional[int]  						=  checkpoint['post_quant_conv.bias']
  
         return new_checkpoint
  
  
  if __name__ == "__main__":
   UpperCAmelCase					=				argparse.ArgumentParser()
  
   parser.add_argument(
       '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.'''
   )
  
   parser.add_argument(
       '''--config_file''',
       default=None,
       type=str,
       required=True,
       help='''The config json file corresponding to the architecture.''',
   )
  
   parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''')
  
   UpperCAmelCase					=				parser.parse_args()
   UpperCAmelCase					=				torch.load(args.checkpoint_path)
  
   with open(args.config_file) as f:
    UpperCAmelCase					=				json.loads(f.read())
  
   # unet case
   UpperCAmelCase					=				{key.split('''.''')[0] for key in checkpoint.keys()}
   if "encoder" in key_prefix_set and "decoder" in key_prefix_set:
    UpperCAmelCase					=				convert_vq_autoenc_checkpoint(checkpoint, config)
   else:
    UpperCAmelCase					=				convert_ddpm_checkpoint(checkpoint, config)
  
   if "ddpm" in config:
    del config["ddpm"]
  
   if config["_class_name"] == "VQModel":
    UpperCAmelCase					=				VQModel(**config)
    model.load_state_dict(converted_checkpoint)
    model.save_pretrained(args.dump_path)
   elif config["_class_name"] == "AutoencoderKL":
    UpperCAmelCase					=				AutoencoderKL(**config)
    model.load_state_dict(converted_checkpoint)
    model.save_pretrained(args.dump_path)
   else:
    UpperCAmelCase					=				UNetaDModel(**config)
    model.load_state_dict(converted_checkpoint)
  
    UpperCAmelCase					=				DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1]))
  
    UpperCAmelCase					=				DDPMPipeline(unet=model, scheduler=scheduler)
    pipe.save_pretrained(args.dump_path)
  
  
  
  
style_context: 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 TvltImageProcessor
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	Tuple		,						lowercase_:	Optional[int]=10		,						lowercase_:	Optional[Any]=10		,						lowercase_:	Optional[Any]=False		,						lowercase_:	Any=False				):
         _UpperCamelCase     :       List[Any]  						=  []
         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
                _UpperCamelCase     :       Tuple  						=  [Image.fromarray(np.moveaxis(lowercase_		,						0		,						-1				)				) for frame in video]
  
         if torchify:
                _UpperCamelCase     :       Union[str, Any]  						=  [torch.from_numpy(lowercase_				) for frame in video]
  
         return video
  
  
  def SCREAMING_SNAKE_CASE				(     lowercase_:	List[str]		,						lowercase_:	Optional[Any]=False		,						lowercase_:	Tuple=False		,						lowercase_:	Union[str, Any]=False				):
         assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
  
         _UpperCamelCase     :       Any  						=  []
         for i in range(image_processor_tester.batch_size				):
                if equal_resolution:
                       _UpperCamelCase     :       str  						=  image_processor_tester.max_resolution
                else:
                       _UpperCamelCase						,      _UpperCamelCase     :       int  						=  np.random.choice(
                           np.arange(image_processor_tester.min_resolution		,						image_processor_tester.max_resolution				)		,						2				)
                       _UpperCamelCase     :       Optional[Any]  						=  prepare_video(
                           image_processor_tester=lowercase_		,						width=lowercase_		,						height=lowercase_		,						numpify=lowercase_		,						torchify=lowercase_		,						)
                video_inputs.append(lowercase_				)
  
         return video_inputs
  
  
  
  
  class    __lowerCAmelCase  (       unittest.TestCase						):
  
  
  
   '''simple docstring'''
  
   def __init__(			self       :		Optional[Any]       ,			lowerCamelCase       :		Union[str, Any]       ,			lowerCamelCase       :		Optional[int]=7       ,			lowerCamelCase       :		List[Any]=3       ,			lowerCamelCase       :		str=4       ,			lowerCamelCase       :		Union[str, Any]=1_8       ,			lowerCamelCase       :		str=3_0       ,			lowerCamelCase       :		List[str]=4_0_0       ,			lowerCamelCase       :		Tuple=True       ,			lowerCamelCase       :		Union[str, Any]=None       ,			lowerCamelCase       :		List[str]=True       ,			lowerCamelCase       :		Optional[Any]=[0.5, 0.5, 0.5]       ,			lowerCamelCase       :		Any=[0.5, 0.5, 0.5]       ,			lowerCamelCase       :		str=True       ,			lowerCamelCase       :		Optional[Any]=None       ,			) ->							Union[str, Any]:
          _UpperCamelCase     :       Optional[int]  						=  size if size is not None else {'shortest_edge': 1_8}
          _UpperCamelCase     :       Dict  						=  crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
  
          _UpperCamelCase     :       Any  						=  parent
          _UpperCamelCase     :       Optional[Any]  						=  batch_size
          _UpperCamelCase     :       List[Any]  						=  num_channels
          _UpperCamelCase     :       List[Any]  						=  num_frames
          _UpperCamelCase     :       Union[str, Any]  						=  image_size
          _UpperCamelCase     :       Dict  						=  min_resolution
          _UpperCamelCase     :       int  						=  max_resolution
          _UpperCamelCase     :       Union[str, Any]  						=  do_resize
          _UpperCamelCase     :       str  						=  size
          _UpperCamelCase     :       Dict  						=  do_normalize
          _UpperCamelCase     :       Union[str, Any]  						=  image_mean
          _UpperCamelCase     :       Optional[int]  						=  image_std
          _UpperCamelCase     :       Tuple  						=  do_center_crop
          _UpperCamelCase     :       Any  						=  crop_size
  
   def 					__snake_case					(			self       :		Tuple  ) ->							Optional[Any]:
          return {
              "image_mean": self.image_mean,
              "image_std": self.image_std,
              "do_normalize": self.do_normalize,
              "do_resize": self.do_resize,
              "size": self.size,
              "do_center_crop": self.do_center_crop,
              "crop_size": self.crop_size,
          }
  
  
  
  
  
  
  
  @require_torch
  @require_vision
  class    __lowerCAmelCase  (       a_,	unittest.TestCase						):
  
  
  
   '''simple docstring'''
   _lowerCamelCase						:	Any				    = TvltImageProcessor if is_vision_available() else None
  
   def 					__snake_case					(			self       :		int  ) ->							Optional[int]:
          _UpperCamelCase     :       Optional[Any]  						=  TvltImageProcessorTester(self  )
  
   @property
   def 					__snake_case					(			self       :		Optional[Any]  ) ->							Any:
          return self.image_processor_tester.prepare_image_processor_dict()
  
   def 					__snake_case					(			self       :		Union[str, Any]  ) ->							str:
          _UpperCamelCase     :       Tuple  						=  self.image_processing_class(**self.image_processor_dict  )
          self.assertTrue(hasattr(lowerCamelCase       ,			'image_mean'  )  )
          self.assertTrue(hasattr(lowerCamelCase       ,			'image_std'  )  )
          self.assertTrue(hasattr(lowerCamelCase       ,			'do_normalize'  )  )
          self.assertTrue(hasattr(lowerCamelCase       ,			'do_resize'  )  )
          self.assertTrue(hasattr(lowerCamelCase       ,			'do_center_crop'  )  )
          self.assertTrue(hasattr(lowerCamelCase       ,			'size'  )  )
  
   def 					__snake_case					(			self       :		Dict  ) ->							Optional[int]:
          # Initialize image_processor
          _UpperCamelCase     :       str  						=  self.image_processing_class(**self.image_processor_dict  )
          # create random PIL videos
          _UpperCamelCase     :       int  						=  prepare_video_inputs(self.image_processor_tester       ,			equal_resolution=lowerCamelCase  )
          for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase       ,			lowerCamelCase  )
                 self.assertIsInstance(video[0]       ,			Image.Image  )
  
          # Test not batched input
          _UpperCamelCase     :       Dict  						=  image_processor(video_inputs[0]       ,			return_tensors='pt'  ).pixel_values
          self.assertEqual(
              encoded_videos.shape       ,			(
                  1,
                  self.image_processor_tester.num_frames,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              )       ,			)
  
          # Test batched
          _UpperCamelCase     :       Any  						=  image_processor(lowerCamelCase       ,			return_tensors='pt'  ).pixel_values
          self.assertEqual(
              encoded_videos.shape       ,			(
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_frames,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              )       ,			)
  
   def 					__snake_case					(			self       :		Union[str, Any]  ) ->							List[str]:
          # Initialize image_processor
          _UpperCamelCase     :       Optional[int]  						=  self.image_processing_class(**self.image_processor_dict  )
          # create random numpy tensors
          _UpperCamelCase     :       int  						=  prepare_video_inputs(self.image_processor_tester       ,			equal_resolution=lowerCamelCase       ,			numpify=lowerCamelCase  )
          for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase       ,			lowerCamelCase  )
                 self.assertIsInstance(video[0]       ,			np.ndarray  )
  
          # Test not batched input
          _UpperCamelCase     :       Optional[int]  						=  image_processor(video_inputs[0]       ,			return_tensors='pt'  ).pixel_values
          self.assertEqual(
              encoded_videos.shape       ,			(
                  1,
                  self.image_processor_tester.num_frames,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              )       ,			)
  
          # Test batched
          _UpperCamelCase     :       int  						=  image_processor(lowerCamelCase       ,			return_tensors='pt'  ).pixel_values
          self.assertEqual(
              encoded_videos.shape       ,			(
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_frames,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              )       ,			)
  
   def 					__snake_case					(			self       :		Optional[Any]  ) ->							Any:
          # Initialize image_processor
          _UpperCamelCase     :       int  						=  self.image_processing_class(**self.image_processor_dict  )
          # create random PyTorch tensors
          _UpperCamelCase     :       Optional[Any]  						=  prepare_video_inputs(self.image_processor_tester       ,			equal_resolution=lowerCamelCase       ,			torchify=lowerCamelCase  )
          for video in video_inputs:
                 self.assertIsInstance(lowerCamelCase       ,			lowerCamelCase  )
                 self.assertIsInstance(video[0]       ,			torch.Tensor  )
  
          # Test not batched input
          _UpperCamelCase     :       Dict  						=  image_processor(video_inputs[0]       ,			return_tensors='pt'  ).pixel_values
          self.assertEqual(
              encoded_videos.shape       ,			(
                  1,
                  self.image_processor_tester.num_frames,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              )       ,			)
  
          # Test batched
          _UpperCamelCase     :       Optional[int]  						=  image_processor(lowerCamelCase       ,			return_tensors='pt'  ).pixel_values
          self.assertEqual(
              encoded_videos.shape       ,			(
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_frames,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['height'],
                  self.image_processor_tester.crop_size['width'],
              )       ,			)
  
  
  
  