



import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


A__  :  int       = logging.get_logger(__name__)

if is_tf_available():
						import tensorflow as tf



@dataclass
class     __snake_case						(					UpperCamelCase_						):
							_a      				=			'''tf'''
							_a      				=			field(
							    default=UpperCamelCase_						,metadata={'''help''': '''Name of TPU'''}						,)

							_a      				=			field(
							    default=UpperCamelCase_						,metadata={'''help''': '''Zone of TPU'''}						,)

							_a      				=			field(
							    default=UpperCamelCase_						,metadata={'''help''': '''Name of Cloud TPU-enabled project'''}						,)

							_a      				=			field(
							    default=1.0						,metadata={'''help''': '''Power for the Polynomial decay LR scheduler.'''}						,)

							_a      				=			field(default=UpperCamelCase_						,metadata={'''help''': '''Whether to activate the XLA compilation or not'''}						)




							@cached_property
							def        UpperCAmelCase__      (	self					:	Optional[int]):
									requires_backends(self    ,    ['''tf'''])
									logger.info('''Tensorflow: setting up strategy''')

									lowerCAmelCase_      :					Any     =			tf.config.list_physical_devices('''GPU''')

									# Set to float16 at first
									if self.fpaa:
											tf.keras.mixed_precision.set_global_policy('''mixed_float16''')

									if self.no_cuda:
											lowerCAmelCase_      :					Dict     =			tf.distribute.OneDeviceStrategy(device='''/cpu:0''')
									else:
											try:
													if self.tpu_name:
															lowerCAmelCase_      :					int     =			tf.distribute.cluster_resolver.TPUClusterResolver(
															    self.tpu_name    ,    zone=self.tpu_zone    ,    project=self.gcp_project)
													else:
															lowerCAmelCase_      :					Optional[int]     =			tf.distribute.cluster_resolver.TPUClusterResolver()
											except ValueError:
													if self.tpu_name:
															raise RuntimeError(F"""Couldn't connect to TPU {self.tpu_name}!""")
													else:
															lowerCAmelCase_      :					List[Any]     =			None

											if tpu:
													# Set to bfloat16 in case of TPU
													if self.fpaa:
															tf.keras.mixed_precision.set_global_policy('''mixed_bfloat16''')

													tf.config.experimental_connect_to_cluster(A_)
													tf.tpu.experimental.initialize_tpu_system(A_)

													lowerCAmelCase_      :					Union[str, Any]     =			tf.distribute.TPUStrategy(A_)

											elif len(A_) == 0:
													lowerCAmelCase_      :					Optional[int]     =			tf.distribute.OneDeviceStrategy(device='''/cpu:0''')
											elif len(A_) == 1:
													lowerCAmelCase_      :					Optional[int]     =			tf.distribute.OneDeviceStrategy(device='''/gpu:0''')
											elif len(A_) > 1:
													# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
													lowerCAmelCase_      :					List[Any]     =			tf.distribute.MirroredStrategy()
											else:
													raise ValueError('''Cannot find the proper strategy, please check your environment properties.''')

									return strategy




							@property
							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									requires_backends(self    ,    ['''tf'''])
									return self._setup_strategy




							@property
							def        UpperCAmelCase__      (	self					:	str):
									requires_backends(self    ,    ['''tf'''])
									return self._setup_strategy.num_replicas_in_sync




							@property
							def        UpperCAmelCase__      (	self					:	int):
									return False  # TF Logging is handled by Keras not the Trainer




							@property
							def        UpperCAmelCase__      (	self					:	List[Any]):
									if self.per_gpu_train_batch_size:
											logger.warning(
											    '''Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future '''
											    '''version. Using `--per_device_train_batch_size` is preferred.''')
									lowerCAmelCase_      :					Any     =			self.per_gpu_train_batch_size or self.per_device_train_batch_size
									return per_device_batch_size * self.n_replicas




							@property
							def        UpperCAmelCase__      (	self					:	Union[str, Any]):
									if self.per_gpu_eval_batch_size:
											logger.warning(
											    '''Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future '''
											    '''version. Using `--per_device_eval_batch_size` is preferred.''')
									lowerCAmelCase_      :					Any     =			self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
									return per_device_batch_size * self.n_replicas







							@property
							def        UpperCAmelCase__      (	self					:	List[str]):
									requires_backends(self    ,    ['''tf'''])
									warnings.warn(
									    '''The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead.'''    ,    A_    ,    )
									return self._setup_strategy.num_replicas_in_sync










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 VideoMAEImageProcessor



class     __snake_case						(					unittest.TestCase						):




							def __init__(	self					:	str    ,    A_					:	str    ,    A_					:	int=7    ,    A_					:	List[Any]=3    ,    A_					:	Dict=1_0    ,    A_					:	List[str]=1_8    ,    A_					:	List[Any]=3_0    ,    A_					:	str=4_0_0    ,    A_					:	str=True    ,    A_					:	Tuple=None    ,    A_					:	Optional[Any]=True    ,    A_					:	Tuple=[0.5, 0.5, 0.5]    ,    A_					:	Any=[0.5, 0.5, 0.5]    ,    A_					:	List[str]=None    ,    ):
									lowerCAmelCase_      :					Optional[Any]     =			size if size is not None else {'''shortest_edge''': 1_8}
									lowerCAmelCase_      :					Optional[int]     =			crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8}

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







							def        UpperCAmelCase__      (	self					:	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,
									    "crop_size": self.crop_size,
									}





@require_torch
@require_vision
class     __snake_case						(					UpperCamelCase_						,unittest.TestCase						):
							_a      				=			VideoMAEImageProcessor if is_vision_available() else None




							def        UpperCAmelCase__      (	self					:	Tuple):
									lowerCAmelCase_      :					int     =			VideoMAEImageProcessingTester(self)




							@property
							def        UpperCAmelCase__      (	self					:	Tuple):
									return self.image_processor_tester.prepare_image_processor_dict()




							def        UpperCAmelCase__      (	self					:	Optional[int]):
									lowerCAmelCase_      :					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        UpperCAmelCase__      (	self					:	Dict):
									lowerCAmelCase_      :					int     =			self.image_processing_class.from_dict(self.image_processor_dict)
									self.assertEqual(image_processor.size    ,    {'''shortest_edge''': 1_8})
									self.assertEqual(image_processor.crop_size    ,    {'''height''': 1_8, '''width''': 1_8})

									lowerCAmelCase_      :					str     =			self.image_processing_class.from_dict(self.image_processor_dict    ,    size=4_2    ,    crop_size=8_4)
									self.assertEqual(image_processor.size    ,    {'''shortest_edge''': 4_2})
									self.assertEqual(image_processor.crop_size    ,    {'''height''': 8_4, '''width''': 8_4})




							def        UpperCAmelCase__      (	self					:	Dict):
									pass




							def        UpperCAmelCase__      (	self					:	str):
									# Initialize image_processing
									lowerCAmelCase_      :					int     =			self.image_processing_class(**self.image_processor_dict)
									# create random PIL videos
									lowerCAmelCase_      :					Optional[int]     =			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
									lowerCAmelCase_      :					int     =			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
									lowerCAmelCase_      :					Tuple     =			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        UpperCAmelCase__      (	self					:	int):
									# Initialize image_processing
									lowerCAmelCase_      :					Dict     =			self.image_processing_class(**self.image_processor_dict)
									# create random numpy tensors
									lowerCAmelCase_      :					str     =			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
									lowerCAmelCase_      :					Tuple     =			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
									lowerCAmelCase_      :					Union[str, 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        UpperCAmelCase__      (	self					:	List[str]):
									# Initialize image_processing
									lowerCAmelCase_      :					Tuple     =			self.image_processing_class(**self.image_processor_dict)
									# create random PyTorch tensors
									lowerCAmelCase_      :					Tuple     =			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
									lowerCAmelCase_      :					List[str]     =			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
									lowerCAmelCase_      :					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'''],
									    )    ,    )





