


"""simple docstring"""






import json
import logging
import os
import sys
from time import time
from unittest.mock import patch

from transformers.testing_utils import TestCasePlus, require_torch_tpu


logging.basicConfig(level=logging.DEBUG)

UpperCamelCase__				:List[str]			   =	logging.getLogger()





def 				A_       ( snake_case__		)					->  Dict:
			_UpperCamelCase					:int					     =	{}
			_UpperCamelCase					:Union[str, Any]					     =	os.path.join(snake_case__       ,					'''all_results.json'''		)
			if os.path.exists(snake_case__		):
						with open(snake_case__       ,					'''r'''		) as f:
									_UpperCamelCase					:str					     =	json.load(snake_case__		)
			else:
						raise ValueError(f"can't find {path}"		)
			return results


UpperCamelCase__				:Any			   =	logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)






@require_torch_tpu
class      A(  lowerCamelCase__		):

		"""simple docstring"""





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					import xla_spawn

					_UpperCamelCase					:Optional[int]					     =	self.get_auto_remove_tmp_dir()
					_UpperCamelCase					:List[Any]					     =	f"\n            ./examples/pytorch/text-classification/run_glue.py\n            --num_cores=8\n            ./examples/pytorch/text-classification/run_glue.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --do_train\n            --do_eval\n            --debug tpu_metrics_debug\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --max_steps=10\n            --warmup_steps=2\n            --seed=42\n            --max_seq_length=128\n            ".split()

					with patch.object(SCREAMING_SNAKE_CASE__					,				'''argv'''					,				SCREAMING_SNAKE_CASE__   ):
								_UpperCamelCase					:List[Any]					     =	time()
								xla_spawn.main()
								_UpperCamelCase					:Tuple					     =	time()

								_UpperCamelCase					:Optional[Any]					     =	get_results(SCREAMING_SNAKE_CASE__   )
								self.assertGreaterEqual(result['''eval_accuracy''']					,				0.7_5   )

								# Assert that the script takes less than 500 seconds to make sure it doesn't hang.
								self.assertLess(end - start					,				5_00   )





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

					"""simple docstring"""



					import xla_spawn

					_UpperCamelCase					:List[Any]					     =	'''
            ./tests/test_trainer_tpu.py
            --num_cores=8
            ./tests/test_trainer_tpu.py
            '''.split()
					with patch.object(SCREAMING_SNAKE_CASE__					,				'''argv'''					,				SCREAMING_SNAKE_CASE__   ):
								xla_spawn.main()





"""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_image_inputs


if is_torch_available():
					import torch

if is_vision_available():
					from PIL import Image

					from transformers import MobileNetVaImageProcessor






class      A(  unittest.TestCase		):

		"""simple docstring"""





		def __init__( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__=7					,				SCREAMING_SNAKE_CASE__=3					,				SCREAMING_SNAKE_CASE__=18					,				SCREAMING_SNAKE_CASE__=30					,				SCREAMING_SNAKE_CASE__=4_00					,				SCREAMING_SNAKE_CASE__=True					,				SCREAMING_SNAKE_CASE__=None					,				SCREAMING_SNAKE_CASE__=True					,				SCREAMING_SNAKE_CASE__=None					,				)      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	size if size is not None else {'''shortest_edge''': 20}
					_UpperCamelCase					:Union[str, Any]					     =	crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
					_UpperCamelCase					:str					     =	parent
					_UpperCamelCase					:str					     =	batch_size
					_UpperCamelCase					:str					     =	num_channels
					_UpperCamelCase					:Optional[Any]					     =	image_size
					_UpperCamelCase					:List[str]					     =	min_resolution
					_UpperCamelCase					:Tuple					     =	max_resolution
					_UpperCamelCase					:List[Any]					     =	do_resize
					_UpperCamelCase					:Tuple					     =	size
					_UpperCamelCase					:int					     =	do_center_crop
					_UpperCamelCase					:Optional[int]					     =	crop_size





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					return {
					    "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      A(  lowerCamelCase__				,							unittest.TestCase		):

		"""simple docstring"""





		A    =							MobileNetVaImageProcessor if is_vision_available() else None
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	MobileNetVaImageProcessingTester(self   )
		@property
		def   _UpperCamelCase( self   )      ->	List[str]:

					"""simple docstring"""



					return self.image_processor_tester.prepare_image_processor_dict()
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	self.image_processing_class(**self.image_processor_dict   )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__					,				'''do_resize'''   )   )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__					,				'''size'''   )   )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__					,				'''do_center_crop'''   )   )
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__					,				'''crop_size'''   )   )
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	self.image_processing_class.from_dict(self.image_processor_dict   )
					self.assertEqual(image_processor.size					,				{'''shortest_edge''': 20}   )
					self.assertEqual(image_processor.crop_size					,				{'''height''': 18, '''width''': 18}   )

					_UpperCamelCase					:List[Any]					     =	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   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					pass
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	self.image_processing_class(**self.image_processor_dict   )
					# create random PIL images
					_UpperCamelCase					:Union[str, Any]					     =	prepare_image_inputs(self.image_processor_tester					,				equal_resolution=SCREAMING_SNAKE_CASE__   )
					for image in image_inputs:
								self.assertIsInstance(SCREAMING_SNAKE_CASE__					,				Image.Image   )

					# Test not batched input
					_UpperCamelCase					:Any					     =	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
					_UpperCamelCase					:Any					     =	image_processing(SCREAMING_SNAKE_CASE__					,				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   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	self.image_processing_class(**self.image_processor_dict   )
					# create random numpy tensors
					_UpperCamelCase					:Any					     =	prepare_image_inputs(self.image_processor_tester					,				equal_resolution=SCREAMING_SNAKE_CASE__					,				numpify=SCREAMING_SNAKE_CASE__   )
					for image in image_inputs:
								self.assertIsInstance(SCREAMING_SNAKE_CASE__					,				np.ndarray   )

					# Test not batched input
					_UpperCamelCase					:Any					     =	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
					_UpperCamelCase					:List[str]					     =	image_processing(SCREAMING_SNAKE_CASE__					,				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   _UpperCamelCase( self   )      ->	Any:

					"""simple docstring"""



					_UpperCamelCase					:List[Any]					     =	self.image_processing_class(**self.image_processor_dict   )
					# create random PyTorch tensors
					_UpperCamelCase					:Union[str, Any]					     =	prepare_image_inputs(self.image_processor_tester					,				equal_resolution=SCREAMING_SNAKE_CASE__					,				torchify=SCREAMING_SNAKE_CASE__   )
					for image in image_inputs:
								self.assertIsInstance(SCREAMING_SNAKE_CASE__					,				torch.Tensor   )

					# Test not batched input
					_UpperCamelCase					:Union[str, Any]					     =	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
					_UpperCamelCase					:Optional[int]					     =	image_processing(SCREAMING_SNAKE_CASE__					,				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'''],
					    )					,				)

