






"""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, prepare_video_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import VivitImageProcessor





class 					_UpperCAmelCase       ( unittest.TestCase							):




					def __init__(				self     :						Any    ,						A     :						Union[str, Any]    ,						A     :						Union[str, Any]=7    ,						A     :						Dict=3    ,						A     :						Any=10    ,						A     :						Optional[int]=18    ,						A     :						List[str]=30    ,						A     :						str=4_00    ,						A     :						Any=True    ,						A     :						Union[str, Any]=None    ,						A     :						Optional[int]=True    ,						A     :						List[str]=[0.5, 0.5, 0.5]    ,						A     :						Union[str, Any]=[0.5, 0.5, 0.5]    ,						A     :						Tuple=None    ,						)  ->  Tuple:
							lowercase_ : int							       =   size if size is not None else {'''shortest_edge''': 18}
							lowercase_ : str							       =   crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

							lowercase_ : List[Any]							       =   parent
							lowercase_ : List[Any]							       =   batch_size
							lowercase_ : Tuple							       =   num_channels
							lowercase_ : Union[str, Any]							       =   num_frames
							lowercase_ : Dict							       =   image_size
							lowercase_ : List[Any]							       =   min_resolution
							lowercase_ : Dict							       =   max_resolution
							lowercase_ : Optional[Any]							       =   do_resize
							lowercase_ : Any							       =   size
							lowercase_ : Dict							       =   do_normalize
							lowercase_ : Optional[Any]							       =   image_mean
							lowercase_ : Optional[Any]							       =   image_std
							lowercase_ : List[Any]							       =   crop_size






					def   A  (				self     :						List[str]   )  ->  Tuple:
							return {
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							    "do_normalize": self.do_normalize,
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "crop_size": self.crop_size,
							}





@require_torch
@require_vision
class 					_UpperCAmelCase       ( _A   ,						unittest.TestCase							):
					SCREAMING_SNAKE_CASE_		:				Any							    =   VivitImageProcessor if is_vision_available() else None




					def   A  (				self     :						List[Any]   )  ->  List[Any]:
							lowercase_ : Optional[Any]							       =   VivitImageProcessingTester(self   )




					@property
					def   A  (				self     :						Optional[Any]   )  ->  Optional[int]:
							return self.image_processor_tester.prepare_image_processor_dict()




					def   A  (				self     :						Union[str, Any]   )  ->  Optional[Any]:
							lowercase_ : Optional[int]							       =   self.image_processing_class(**self.image_processor_dict   )
							self.assertTrue(hasattr(A    ,						'''image_mean'''   )   )
							self.assertTrue(hasattr(A    ,						'''image_std'''   )   )
							self.assertTrue(hasattr(A    ,						'''do_normalize'''   )   )
							self.assertTrue(hasattr(A    ,						'''do_resize'''   )   )
							self.assertTrue(hasattr(A    ,						'''do_center_crop'''   )   )
							self.assertTrue(hasattr(A    ,						'''size'''   )   )




					def   A  (				self     :						List[Any]   )  ->  List[str]:
							lowercase_ : Optional[int]							       =   self.image_processing_class.from_dict(self.image_processor_dict   )
							self.assertEqual(image_processor.size    ,						{'''shortest_edge''': 18}   )
							self.assertEqual(image_processor.crop_size    ,						{'''height''': 18, '''width''': 18}   )

							lowercase_ : int							       =   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   A  (				self     :						int   )  ->  Optional[Any]:
							# Initialize image_processing
							lowercase_ : List[str]							       =   self.image_processing_class(**self.image_processor_dict   )
							# create random PIL videos
							lowercase_ : List[Any]							       =   prepare_video_inputs(self.image_processor_tester    ,						equal_resolution=A   )
							for video in video_inputs:
									self.assertIsInstance(A    ,						A   )
									self.assertIsInstance(video[0]    ,						Image.Image   )

							# Test not batched input
							lowercase_ : Optional[Any]							       =   image_processing(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
							lowercase_ : Dict							       =   image_processing(A    ,						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   A  (				self     :						int   )  ->  Optional[int]:
							# Initialize image_processing
							lowercase_ : Optional[Any]							       =   self.image_processing_class(**self.image_processor_dict   )
							# create random numpy tensors
							lowercase_ : Optional[Any]							       =   prepare_video_inputs(self.image_processor_tester    ,						equal_resolution=A    ,						numpify=A   )
							for video in video_inputs:
									self.assertIsInstance(A    ,						A   )
									self.assertIsInstance(video[0]    ,						np.ndarray   )

							# Test not batched input
							lowercase_ : Any							       =   image_processing(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
							lowercase_ : List[Any]							       =   image_processing(A    ,						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   A  (				self     :						Tuple   )  ->  Dict:
							# Initialize image_processing
							lowercase_ : List[Any]							       =   self.image_processing_class(**self.image_processor_dict   )
							# create random PyTorch tensors
							lowercase_ : Any							       =   prepare_video_inputs(self.image_processor_tester    ,						equal_resolution=A    ,						torchify=A   )
							for video in video_inputs:
									self.assertIsInstance(A    ,						A   )
									self.assertIsInstance(video[0]    ,						torch.Tensor   )

							# Test not batched input
							lowercase_ : Any							       =   image_processing(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
							lowercase_ : Any							       =   image_processing(A    ,						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'''],
							    )    ,						)











"""simple docstring"""



# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
						import torch





class 					_UpperCAmelCase       ( TensorFormatter[Mapping, "torch.Tensor", Mapping]							):




					def __init__(				self     :						Any    ,						A     :						int=None    ,						**A     :						str   )  ->  Union[str, Any]:
							super().__init__(features=A   )
							lowercase_ : Union[str, Any]							       =   torch_tensor_kwargs
							import torch  # noqa import torch at initialization




					def   A  (				self     :						Dict    ,						A     :						int   )  ->  List[Any]:
							import torch

							if isinstance(A    ,						A   ) and column:
									if all(
									    isinstance(A    ,						torch.Tensor   ) and x.shape == column[0].shape and x.dtype == column[0].dtype
									    for x in column   ):
											return torch.stack(A   )
							return column




					def   A  (				self     :						int    ,						A     :						Any   )  ->  Optional[Any]:
							import torch

							if isinstance(A    ,						(str, bytes, type(A   ))   ):
									return value
							elif isinstance(A    ,						(np.character, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.character   ):
									return value.tolist()

							lowercase_ : Any							       =   {}

							if isinstance(A    ,						(np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.integer   ):
									lowercase_ : Any							       =   {'''dtype''': torch.intaa}
							elif isinstance(A    ,						(np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,						np.floating   ):
									lowercase_ : Dict							       =   {'''dtype''': torch.floataa}
							elif config.PIL_AVAILABLE and "PIL" in sys.modules:
									import PIL.Image

									if isinstance(A    ,						PIL.Image.Image   ):
											lowercase_ : Dict							       =   np.asarray(A   )
							return torch.tensor(A    ,						**{**default_dtype, **self.torch_tensor_kwargs}   )




					def   A  (				self     :						Union[str, Any]    ,						A     :						Optional[int]   )  ->  str:
							import torch

							# support for torch, tf, jax etc.
							if hasattr(A    ,						'''__array__'''   ) and not isinstance(A    ,						torch.Tensor   ):
									lowercase_ : Optional[int]							       =   data_struct.__array__()
							# support for nested types like struct of list of struct
							if isinstance(A    ,						np.ndarray   ):
									if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
											return self._consolidate([self.recursive_tensorize(A   ) for substruct in data_struct]   )
							elif isinstance(A    ,						(list, tuple)   ):
									return self._consolidate([self.recursive_tensorize(A   ) for substruct in data_struct]   )
							return self._tensorize(A   )




					def   A  (				self     :						Dict    ,						A     :						dict   )  ->  Tuple:
							return map_nested(self._recursive_tensorize    ,						A    ,						map_list=A   )




					def   A  (				self     :						str    ,						A     :						pa.Table   )  ->  Mapping:
							lowercase_ : Optional[Any]							       =   self.numpy_arrow_extractor().extract_row(A   )
							lowercase_ : str							       =   self.python_features_decoder.decode_row(A   )
							return self.recursive_tensorize(A   )




					def   A  (				self     :						List[Any]    ,						A     :						pa.Table   )  ->  "torch.Tensor":
							lowercase_ : List[str]							       =   self.numpy_arrow_extractor().extract_column(A   )
							lowercase_ : str							       =   self.python_features_decoder.decode_column(A    ,						pa_table.column_names[0]   )
							lowercase_ : Optional[int]							       =   self.recursive_tensorize(A   )
							lowercase_ : Any							       =   self._consolidate(A   )
							return column






					def   A  (				self     :						List[str]    ,						A     :						pa.Table   )  ->  Mapping:
							lowercase_ : Optional[int]							       =   self.numpy_arrow_extractor().extract_batch(A   )
							lowercase_ : int							       =   self.python_features_decoder.decode_batch(A   )
							lowercase_ : Dict							       =   self.recursive_tensorize(A   )
							for column_name in batch:
									lowercase_ : Optional[Any]							       =   self._consolidate(batch[column_name]   )
							return batch



