


import unittest
from typing import Dict, List, Optional, Union

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 BridgeTowerImageProcessor







class 	__lowercase    (unittest.TestCase  ):





							"""simple docstring"""







							def __init__(      self			,						lowerCAmelCase__			,						lowerCAmelCase__ = True			,						lowerCAmelCase__ = None			,						lowerCAmelCase__ = 3_2			,						lowerCAmelCase__ = True			,						lowerCAmelCase__ = 1 / 2_5_5			,						lowerCAmelCase__ = True			,						lowerCAmelCase__ = True			,						lowerCAmelCase__ = [0.48_145_466, 0.4_578_275, 0.40_821_073]			,						lowerCAmelCase__ = [0.26_862_954, 0.26_130_258, 0.27_577_711]			,						lowerCAmelCase__ = True			,						lowerCAmelCase__=7			,						lowerCAmelCase__=3_0			,						lowerCAmelCase__=4_0_0			,						lowerCAmelCase__=3			,						):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[Any]					=					parent
										SCREAMING_SNAKE_CASE_		:     int					=					do_resize
										SCREAMING_SNAKE_CASE_		:     Dict					=					size if size is not None else {'shortest_edge': 2_8_8}
										SCREAMING_SNAKE_CASE_		:     Tuple					=					size_divisor
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					do_rescale
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					rescale_factor
										SCREAMING_SNAKE_CASE_		:     Dict					=					do_normalize
										SCREAMING_SNAKE_CASE_		:     Any					=					do_center_crop
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					image_mean
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					image_std
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					do_pad
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					batch_size
										SCREAMING_SNAKE_CASE_		:     str					=					num_channels
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					min_resolution
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					max_resolution






							def 					UpperCamelCase__     (      self       ):





										"""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,
										    "size_divisor": self.size_divisor,
										}






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__=False       ):





										"""simple docstring"""




										if not batched:
													SCREAMING_SNAKE_CASE_		:     str					=					self.size['shortest_edge']
													SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					image_inputs[0]
													if isinstance(lowerCAmelCase__			,						Image.Image       ):
																SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     str					=					image.size
													else:
																SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[str]					=					image.shape[1], image.shape[2]
													SCREAMING_SNAKE_CASE_		:     Dict					=					size / min(lowerCAmelCase__			,						lowerCAmelCase__       )
													if h < w:
																SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Tuple					=					size, scale * w
													else:
																SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[Any]					=					scale * h, size

													SCREAMING_SNAKE_CASE_		:     Any					=					int((1_3_3_3 / 8_0_0) * size       )
													if max(lowerCAmelCase__			,						lowerCAmelCase__       ) > max_size:
																SCREAMING_SNAKE_CASE_		:     List[Any]					=					max_size / max(lowerCAmelCase__			,						lowerCAmelCase__       )
																SCREAMING_SNAKE_CASE_		:     int					=					newh * scale
																SCREAMING_SNAKE_CASE_		:     List[Any]					=					neww * scale

													SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[Any]					=					int(newh + 0.5       ), int(neww + 0.5       )
													SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					(
													    newh // self.size_divisor * self.size_divisor,
													    neww // self.size_divisor * self.size_divisor,
													)

										else:
													SCREAMING_SNAKE_CASE_		:     Dict					=					[]
													for image in image_inputs:
																SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					self.get_expected_values([image]       )
																expected_values.append((expected_height, expected_width)       )
													SCREAMING_SNAKE_CASE_		:     List[str]					=					max(lowerCAmelCase__			,						key=lambda lowerCAmelCase__       : item[0]       )[0]
													SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					max(lowerCAmelCase__			,						key=lambda lowerCAmelCase__       : item[1]       )[1]

										return expected_height, expected_width







@require_torch
@require_vision
class 	__lowercase    (__SCREAMING_SNAKE_CASE	,       unittest.TestCase  ):





							"""simple docstring"""







							_UpperCAmelCase      =						BridgeTowerImageProcessor if is_vision_available() else None






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     str					=					BridgeTowerImageProcessingTester(self       )






							@property
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return self.image_processor_tester.prepare_image_processor_dict()






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					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__			,						'size'       )       )
										self.assertTrue(hasattr(lowerCAmelCase__			,						'size_divisor'       )       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										pass






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




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

										# Test not batched input
										SCREAMING_SNAKE_CASE_		:     Any					=					image_processing(image_inputs[0]			,						return_tensors='pt'       ).pixel_values

										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[Any]					=					self.image_processor_tester.get_expected_values(lowerCAmelCase__       )
										self.assertEqual(
										    encoded_images.shape			,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)			,						)

										# Test batched
										SCREAMING_SNAKE_CASE_		:     List[str]					=					image_processing(lowerCAmelCase__			,						return_tensors='pt'       ).pixel_values

										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     int					=					self.image_processor_tester.get_expected_values(lowerCAmelCase__			,						batched=lowerCAmelCase__       )
										self.assertEqual(
										    encoded_images.shape			,						(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )			,						)






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[str]					=					self.image_processing_class(**self.image_processor_dict       )
										# create random numpy tensors
										SCREAMING_SNAKE_CASE_		:     Tuple					=					prepare_image_inputs(self.image_processor_tester			,						equal_resolution=lowerCAmelCase__			,						numpify=lowerCAmelCase__       )
										for image in image_inputs:
													self.assertIsInstance(lowerCAmelCase__			,						np.ndarray       )

										# Test not batched input
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					image_processing(image_inputs[0]			,						return_tensors='pt'       ).pixel_values

										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[str]					=					self.image_processor_tester.get_expected_values(lowerCAmelCase__       )
										self.assertEqual(
										    encoded_images.shape			,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)			,						)

										# Test batched
										SCREAMING_SNAKE_CASE_		:     List[str]					=					image_processing(lowerCAmelCase__			,						return_tensors='pt'       ).pixel_values

										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Optional[int]					=					self.image_processor_tester.get_expected_values(lowerCAmelCase__			,						batched=lowerCAmelCase__       )
										self.assertEqual(
										    encoded_images.shape			,						(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )			,						)






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




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

										# Test not batched input
										SCREAMING_SNAKE_CASE_		:     int					=					image_processing(image_inputs[0]			,						return_tensors='pt'       ).pixel_values

										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     int					=					self.image_processor_tester.get_expected_values(lowerCAmelCase__       )
										self.assertEqual(
										    encoded_images.shape			,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)			,						)

										# Test batched
										SCREAMING_SNAKE_CASE_		:     int					=					image_processing(lowerCAmelCase__			,						return_tensors='pt'       ).pixel_values

										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     List[Any]					=					self.image_processor_tester.get_expected_values(lowerCAmelCase__			,						batched=lowerCAmelCase__       )
										self.assertEqual(
										    encoded_images.shape			,						(
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        expected_height,
										        expected_width,
										    )			,						)











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)

a__		     =     logging.getLogger()





def 				A__ (snake_case   :		Tuple				)     ->						Dict:
					__UpperCamelCase					:	Dict             =      {}
					__UpperCamelCase					:	Dict             =      os.path.join(snake_case		,	"""all_results.json"""				)
					if os.path.exists(snake_case				):
										with open(snake_case		,	"""r"""				) as f:
															__UpperCamelCase					:	List[Any]             =      json.load(snake_case				)
					else:
										raise ValueError(F'''can\'t find {path}'''				)
					return results


a__		     =     logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)







@require_torch_tpu
class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	def 					lowerCamelCase__     (					self		:						Dict	)	->       Dict:







						"""simple docstring"""







						import xla_spawn

						__UpperCamelCase					:	Dict             =      self.get_auto_remove_tmp_dir()
						__UpperCamelCase					:	str             =      F'''
            ./examples/pytorch/text-classification/run_glue.py
            --num_cores=8
            ./examples/pytorch/text-classification/run_glue.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --debug tpu_metrics_debug
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            '''.split()

						with patch.object(lowerCAmelCase					,     """argv"""					,     lowerCAmelCase	):
											__UpperCamelCase					:	Union[str, Any]             =      time()
											xla_spawn.main()
											__UpperCamelCase					:	List[str]             =      time()

											__UpperCamelCase					:	Optional[int]             =      get_results(lowerCAmelCase	)
											self.assertGreaterEqual(result["""eval_accuracy"""]					,     0.75	)

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






	def 					lowerCamelCase__     (					self		:						int	)	->       List[Any]:







						"""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(lowerCAmelCase					,     """argv"""					,     lowerCAmelCase	):
											xla_spawn.main()






