
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 a__   (	A_,					A_=10,					A_=10,					A_=False,					A_=False ):






  '''simple docstring'''





  __magic_name__    					=	[]
  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
    __magic_name__    					=	[Image.fromarray(np.moveaxis(A_,					0,					-1 ) ) for frame in video]

  if torchify:
    __magic_name__    					=	[torch.from_numpy(A_ ) for frame in video]

  return video

def a__   (	A_,					A_=False,					A_=False,					A_=False ):






  '''simple docstring'''





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

  __magic_name__    					=	[]
  for i in range(image_processor_tester.batch_size ):
    if equal_resolution:
      __magic_name__    					=	__magic_name__    					=	image_processor_tester.max_resolution
    else:
      __magic_name__					,   __magic_name__    					=	np.random.choice(
          np.arange(image_processor_tester.min_resolution,					image_processor_tester.max_resolution ),					2 )
      __magic_name__    					=	prepare_video(
          image_processor_tester=A_,					width=A_,					height=A_,					numpify=A_,					torchify=A_,					)
    video_inputs.append(A_ )

  return video_inputs




class 	UpperCAmelCase_      (			unittest.TestCase					):


  '''simple docstring'''







  def __init__(			self      :			int      ,							UpperCamelCase__      :			Dict      ,							UpperCamelCase__      :			Any=7      ,							UpperCamelCase__      :			List[str]=3      ,							UpperCamelCase__      :			List[str]=4      ,							UpperCamelCase__      :			Dict=18      ,							UpperCamelCase__      :			List[str]=30      ,							UpperCamelCase__      :			int=400      ,							UpperCamelCase__      :			str=True      ,							UpperCamelCase__      :			Optional[int]=None      ,							UpperCamelCase__      :			Dict=True      ,							UpperCamelCase__      :			Optional[Any]=[0.5, 0.5, 0.5]      ,							UpperCamelCase__      :			List[Any]=[0.5, 0.5, 0.5]      ,							UpperCamelCase__      :			Optional[int]=True      ,							UpperCamelCase__      :			Dict=None      ,							)      ->     Optional[Any]:







    """simple docstring"""






    __magic_name__    					=	size if size is not None else {"""shortest_edge""": 18}
    __magic_name__    					=	crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

    __magic_name__    					=	parent
    __magic_name__    					=	batch_size
    __magic_name__    					=	num_channels
    __magic_name__    					=	num_frames
    __magic_name__    					=	image_size
    __magic_name__    					=	min_resolution
    __magic_name__    					=	max_resolution
    __magic_name__    					=	do_resize
    __magic_name__    					=	size
    __magic_name__    					=	do_normalize
    __magic_name__    					=	image_mean
    __magic_name__    					=	image_std
    __magic_name__    					=	do_center_crop
    __magic_name__    					=	crop_size





  def 							_lowercase							(			self      :			Dict   )      ->     Tuple:







    """simple docstring"""






    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 	UpperCAmelCase_      (			_A  ,	unittest.TestCase					):


  '''simple docstring'''







  a__   	=		TvltImageProcessor if is_vision_available() else None
  def 							_lowercase							(			self      :			Union[str, Any]   )      ->     str:







    """simple docstring"""






    __magic_name__    					=	TvltImageProcessorTester(self   )
  @property
  def 							_lowercase							(			self      :			Optional[int]   )      ->     Tuple:







    """simple docstring"""






    return self.image_processor_tester.prepare_image_processor_dict()
  def 							_lowercase							(			self      :			List[str]   )      ->     Tuple:







    """simple docstring"""






    __magic_name__    					=	self.image_processing_class(**self.image_processor_dict   )
    self.assertTrue(hasattr(UpperCamelCase__      ,							"""image_mean"""   )   )
    self.assertTrue(hasattr(UpperCamelCase__      ,							"""image_std"""   )   )
    self.assertTrue(hasattr(UpperCamelCase__      ,							"""do_normalize"""   )   )
    self.assertTrue(hasattr(UpperCamelCase__      ,							"""do_resize"""   )   )
    self.assertTrue(hasattr(UpperCamelCase__      ,							"""do_center_crop"""   )   )
    self.assertTrue(hasattr(UpperCamelCase__      ,							"""size"""   )   )
  def 							_lowercase							(			self      :			Optional[Any]   )      ->     Tuple:







    """simple docstring"""






    __magic_name__    					=	self.image_processing_class(**self.image_processor_dict   )
    # create random PIL videos
    __magic_name__    					=	prepare_video_inputs(self.image_processor_tester      ,							equal_resolution=UpperCamelCase__   )
    for video in video_inputs:
      self.assertIsInstance(UpperCamelCase__      ,							UpperCamelCase__   )
      self.assertIsInstance(video[0]      ,							Image.Image   )

    # Test not batched input
    __magic_name__    					=	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
    __magic_name__    					=	image_processor(UpperCamelCase__      ,							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 							_lowercase							(			self      :			Union[str, Any]   )      ->     str:







    """simple docstring"""






    __magic_name__    					=	self.image_processing_class(**self.image_processor_dict   )
    # create random numpy tensors
    __magic_name__    					=	prepare_video_inputs(self.image_processor_tester      ,							equal_resolution=UpperCamelCase__      ,							numpify=UpperCamelCase__   )
    for video in video_inputs:
      self.assertIsInstance(UpperCamelCase__      ,							UpperCamelCase__   )
      self.assertIsInstance(video[0]      ,							np.ndarray   )

    # Test not batched input
    __magic_name__    					=	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
    __magic_name__    					=	image_processor(UpperCamelCase__      ,							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 							_lowercase							(			self      :			Optional[Any]   )      ->     Tuple:







    """simple docstring"""






    __magic_name__    					=	self.image_processing_class(**self.image_processor_dict   )
    # create random PyTorch tensors
    __magic_name__    					=	prepare_video_inputs(self.image_processor_tester      ,							equal_resolution=UpperCamelCase__      ,							torchify=UpperCamelCase__   )
    for video in video_inputs:
      self.assertIsInstance(UpperCamelCase__      ,							UpperCamelCase__   )
      self.assertIsInstance(video[0]      ,							torch.Tensor   )

    # Test not batched input
    __magic_name__    					=	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
    __magic_name__    					=	image_processor(UpperCamelCase__      ,							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"""],
        )      ,							)



import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
    import transformer_engine.pytorch as te

def a__   (	A_,					A_=True,					A_=True,					A_=True ):






  '''simple docstring'''





  if not is_fpa_available():
    raise ImportError("""Using `convert_model` requires transformer_engine to be installed.""" )
  for name, module in model.named_children():
    if isinstance(A_,					nn.Linear ) and to_transformer_engine and _convert_linear:
      # Return early if the linear layer weights are not multiples of 16
      if any(p % 16 != 0 for p in module.weight.shape ):
        return
      __magic_name__    					=	module.bias is not None
      __magic_name__    					=	te.Linear(
          module.in_features,					module.out_features,					bias=A_,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      if has_bias:
        __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    elif isinstance(A_,					nn.LayerNorm ) and to_transformer_engine and _convert_ln:
      __magic_name__    					=	te.LayerNorm(module.normalized_shape[0],					eps=module.eps,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    elif isinstance(A_,					te.Linear ) and not to_transformer_engine and _convert_linear:
      __magic_name__    					=	module.bias is not None
      __magic_name__    					=	nn.Linear(
          module.in_features,					module.out_features,					bias=A_,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      if has_bias:
        __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    elif isinstance(A_,					te.LayerNorm ) and not to_transformer_engine and _convert_ln:
      __magic_name__    					=	nn.LayerNorm(module.normalized_shape[0],					eps=module.eps,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    else:
      convert_model(
          A_,					to_transformer_engine=A_,					_convert_linear=_convert_linear,					_convert_ln=_convert_ln,					)





def a__   (	A_ ):






  '''simple docstring'''





  if not is_fpa_available():
    raise ImportError("""Using `has_transformer_engine_layers` requires transformer_engine to be installed.""" )
  for m in model.modules():
    if isinstance(A_,					(te.LayerNorm, te.Linear) ):
      return True
  return False

