





from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import TFResNetForImageClassification, TFResNetModel
						from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor
class SCREAMING_SNAKE_CASE_						:






						def __init__(      self      :      Tuple		,   _A      :      int		,   _A      :      int=3		,   _A      :      Optional[Any]=32		,   _A      :      Any=3		,   _A      :      int=10		,   _A      :      List[str]=[10, 20, 30, 40]		,   _A      :      Tuple=[1, 1, 2, 1]		,   _A      :      Optional[int]=True		,   _A      :      List[Any]=True		,   _A      :      List[str]="relu"		,   _A      :      str=3		,   _A      :      int=None		,   )							->    Union[str, Any]:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	parent
							snake_case_		:			Any											=	batch_size
							snake_case_		:			int											=	image_size
							snake_case_		:			Dict											=	num_channels
							snake_case_		:			Optional[Any]											=	embeddings_size
							snake_case_		:			Union[str, Any]											=	hidden_sizes
							snake_case_		:			Tuple											=	depths
							snake_case_		:			Tuple											=	is_training
							snake_case_		:			Union[str, Any]											=	use_labels
							snake_case_		:			Tuple											=	hidden_act
							snake_case_		:			int											=	num_labels
							snake_case_		:			Optional[int]											=	scope
							snake_case_		:			Tuple											=	len(_A	)






						def UpperCAmelCase_				(      self      :      Tuple	)							->    int:







							"""simple docstring"""


							snake_case_		:			int											=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

							snake_case_		:			Tuple											=	None
							if self.use_labels:
								snake_case_		:			List[str]											=	ids_tensor([self.batch_size]		,   self.num_labels	)

							snake_case_		:			Optional[Any]											=	self.get_config()

							return config, pixel_values, labels






						def UpperCAmelCase_				(      self      :      Tuple	)							->    List[str]:







							"""simple docstring"""


							return ResNetConfig(
							    num_channels=self.num_channels		,   embeddings_size=self.embeddings_size		,   hidden_sizes=self.hidden_sizes		,   depths=self.depths		,   hidden_act=self.hidden_act		,   num_labels=self.num_labels		,   image_size=self.image_size		,   )






						def UpperCAmelCase_				(      self      :      int		,   _A      :      Union[str, Any]		,   _A      :      int		,   _A      :      Optional[Any]	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			str											=	TFResNetModel(config=_A	)
							snake_case_		:			List[str]											=	model(_A	)
							# expected last hidden states: B, C, H // 32, W // 32
							self.parent.assertEqual(
							    result.last_hidden_state.shape		,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)		,   )






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      int		,   _A      :      Any		,   _A      :      List[str]	)							->    List[str]:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	self.num_labels
							snake_case_		:			int											=	TFResNetForImageClassification(_A	)
							snake_case_		:			Tuple											=	model(_A		,   labels=_A	)
							self.parent.assertEqual(result.logits.shape		,   (self.batch_size, self.num_labels)	)






						def UpperCAmelCase_				(      self      :      Tuple	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			Dict											=	self.prepare_config_and_inputs()
							snake_case_						,snake_case_						,snake_case_		:			Optional[Any]											=	config_and_inputs
							snake_case_		:			Tuple											=	{'pixel_values': pixel_values}
							return config, inputs_dict
@require_tf
class SCREAMING_SNAKE_CASE_						(					snake_case_       ,				snake_case_       ,				unittest.TestCase					):
						__magic_name__:			Optional[int]       =       (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
						__magic_name__:			Tuple       =       (
						    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
						    if is_tf_available()
						    else {}
						)

						__magic_name__:			Tuple       =       False
						__magic_name__:			Dict       =       False
						__magic_name__:			int       =       False
						__magic_name__:			Dict       =       False
						__magic_name__:			Optional[Any]       =       False






						def UpperCAmelCase_				(      self      :      List[Any]	)							->    Optional[Any]:







							"""simple docstring"""


							snake_case_		:			Dict											=	TFResNetModelTester(self	)
							snake_case_		:			Optional[int]											=	ConfigTester(self		,   config_class=_A		,   has_text_modality=_A	)






						def UpperCAmelCase_				(      self      :      Any	)							->    List[Any]:







							"""simple docstring"""


							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()






						def UpperCAmelCase_				(      self      :      List[Any]	)							->    List[Any]:







							"""simple docstring"""


							return






						@unittest.skip(reason='ResNet does not use inputs_embeds'	)
						def UpperCAmelCase_				(      self      :      str	)							->    List[str]:







							"""simple docstring"""


							pass






						@unittest.skip(reason='ResNet does not support input and output embeddings'	)
						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    List[str]:







							"""simple docstring"""


							pass






						def UpperCAmelCase_				(      self      :      Dict	)							->    Any:







							"""simple docstring"""


							snake_case_						,snake_case_		:			Dict											=	self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		:			Tuple											=	model_class(_A	)
								snake_case_		:			Optional[Any]											=	inspect.signature(model.call	)
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								snake_case_		:			Tuple											=	[*signature.parameters.keys()]

								snake_case_		:			Dict											=	['pixel_values']
								self.assertListEqual(arg_names[:1]		,   _A	)






						def UpperCAmelCase_				(      self      :      Tuple	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Dict											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A	)






						def UpperCAmelCase_				(      self      :      Any	)							->    Union[str, Any]:







							"""simple docstring"""


							def check_hidden_states_output(_A      :      List[Any]		,   _A      :      Dict		,   _A      :      Dict	):
								snake_case_		:			str											=	model_class(_A	)
								snake_case_		:			Optional[Any]											=	model(**self._prepare_for_class(_A		,   _A	)	)

								snake_case_		:			Union[str, Any]											=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

								snake_case_		:			Optional[Any]											=	self.model_tester.num_stages
								self.assertEqual(len(_A	)		,   expected_num_stages + 1	)

								# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]	)		,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]		,   )

							snake_case_						,snake_case_		:			List[Any]											=	self.model_tester.prepare_config_and_inputs_for_common()
							snake_case_		:			Optional[Any]											=	['basic', 'bottleneck']
							for model_class in self.all_model_classes:
								for layer_type in layers_type:
									snake_case_		:			Optional[int]											=	layer_type
									snake_case_		:			int											=	True
									check_hidden_states_output(_A		,   _A		,   _A	)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									snake_case_		:			str											=	True

									check_hidden_states_output(_A		,   _A		,   _A	)






						def UpperCAmelCase_				(      self      :      List[str]	)							->    Dict:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A	)






						@slow
						def UpperCAmelCase_				(      self      :      str	)							->    List[str]:







							"""simple docstring"""


							for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								snake_case_		:			Optional[int]											=	TFResNetModel.from_pretrained(_A	)
								self.assertIsNotNone(_A	)


def 							SCREAMING_SNAKE_CASE__						(    ):
	snake_case_		:			List[Any]											=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
	return image


@require_tf
@require_vision
class SCREAMING_SNAKE_CASE_						(					unittest.TestCase					):






						@cached_property
						def UpperCAmelCase_				(      self      :      List[str]	)							->    List[Any]:







							"""simple docstring"""


							return (
							    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
							    if is_vision_available()
							    else None
							)






						@slow
						def UpperCAmelCase_				(      self      :      Any	)							->    str:







							"""simple docstring"""


							snake_case_		:			List[Any]											=	TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

							snake_case_		:			List[Any]											=	self.default_image_processor
							snake_case_		:			Tuple											=	prepare_img()
							snake_case_		:			Any											=	image_processor(images=_A		,   return_tensors='tf'	)

							# forward pass
							snake_case_		:			int											=	model(**_A	)

							# verify the logits
							snake_case_		:			List[Any]											=	tf.TensorShape((1, 1000)	)
							self.assertEqual(outputs.logits.shape		,   _A	)

							snake_case_		:			Dict											=	tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]	)

							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()		,   _A		,   atol=1E-4	)	)








from typing import Dict, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends


if is_vision_available():
						import PIL

# soft dependency
if is_pytesseract_available():
						import pytesseract

_SCREAMING_SNAKE_CASE      	=		logging.get_logger(__name__)


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a   ):
	return [
	    int(10_00 * (box[0] / width)   ),
	    int(10_00 * (box[1] / height)   ),
	    int(10_00 * (box[2] / width)   ),
	    int(10_00 * (box[3] / height)   ),
	]


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a = None   ):
	snake_case_		:			int											=	tesseract_config if tesseract_config is not None else ''

	# apply OCR
	snake_case_		:			str											=	to_pil_image(__a   )
	snake_case_						,snake_case_		:			str											=	pil_image.size
	snake_case_		:			str											=	pytesseract.image_to_data(__a   , lang=__a   , output_type='dict'   , config=__a   )
	snake_case_						,snake_case_						,snake_case_						,snake_case_						,snake_case_		:			Dict											=	data['text'], data['left'], data['top'], data['width'], data['height']

	# filter empty words and corresponding coordinates
	snake_case_		:			str											=	[idx for idx, word in enumerate(__a   ) if not word.strip()]
	snake_case_		:			Optional[Any]											=	[word for idx, word in enumerate(__a   ) if idx not in irrelevant_indices]
	snake_case_		:			Any											=	[coord for idx, coord in enumerate(__a   ) if idx not in irrelevant_indices]
	snake_case_		:			Any											=	[coord for idx, coord in enumerate(__a   ) if idx not in irrelevant_indices]
	snake_case_		:			List[Any]											=	[coord for idx, coord in enumerate(__a   ) if idx not in irrelevant_indices]
	snake_case_		:			int											=	[coord for idx, coord in enumerate(__a   ) if idx not in irrelevant_indices]

	# turn coordinates into (left, top, left+width, top+height) format
	snake_case_		:			int											=	[]
	for x, y, w, h in zip(__a   , __a   , __a   , __a   ):
		snake_case_		:			str											=	[x, y, x + w, y + h]
		actual_boxes.append(__a   )

	# finally, normalize the bounding boxes
	snake_case_		:			Dict											=	[]
	for box in actual_boxes:
		normalized_boxes.append(normalize_box(__a   , __a   , __a   )   )

	assert len(__a   ) == len(__a   ), "Not as many words as there are bounding boxes"

	return words, normalized_boxes


class SCREAMING_SNAKE_CASE_						(					snake_case_					):
						__magic_name__:			str       =       ["pixel_values"]






						def __init__(      self      :      List[str]		,   _A      :      bool = True		,   _A      :      Dict[str, int] = None		,   _A      :      PILImageResampling = PILImageResampling.BILINEAR		,   _A      :      bool = True		,   _A      :      Optional[str] = None		,   _A      :      Optional[str] = ""		,   **_A      :      int		,   )							->    None:







							"""simple docstring"""


							super().__init__(**_A	)
							snake_case_		:			Optional[int]											=	size if size is not None else {'height': 224, 'width': 224}
							snake_case_		:			List[str]											=	get_size_dict(_A	)

							snake_case_		:			int											=	do_resize
							snake_case_		:			int											=	size
							snake_case_		:			Any											=	resample
							snake_case_		:			List[str]											=	apply_ocr
							snake_case_		:			str											=	ocr_lang
							snake_case_		:			Dict											=	tesseract_config






						def UpperCAmelCase_				(      self      :      int		,   _A      :      np.ndarray		,   _A      :      Dict[str, int]		,   _A      :      PILImageResampling = PILImageResampling.BILINEAR		,   _A      :      Optional[Union[str, ChannelDimension]] = None		,   **_A      :      str		,   )							->    np.ndarray:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	get_size_dict(_A	)
							if "height" not in size or "width" not in size:
								raise ValueError(F"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}"""	)
							snake_case_		:			Optional[Any]											=	(size['height'], size['width'])
							return resize(_A		,   size=_A		,   resample=_A		,   data_format=_A		,   **_A	)






						def UpperCAmelCase_				(      self      :      Optional[int]		,   _A      :      ImageInput		,   _A      :      bool = None		,   _A      :      Dict[str, int] = None		,   _A      :      PILImageResampling = None		,   _A      :      bool = None		,   _A      :      Optional[str] = None		,   _A      :      Optional[str] = None		,   _A      :      Optional[Union[str, TensorType]] = None		,   _A      :      ChannelDimension = ChannelDimension.FIRST		,   **_A      :      List[str]		,   )							->    PIL.Image.Image:







							"""simple docstring"""


							snake_case_		:			Dict											=	do_resize if do_resize is not None else self.do_resize
							snake_case_		:			Optional[Any]											=	size if size is not None else self.size
							snake_case_		:			Union[str, Any]											=	get_size_dict(_A	)
							snake_case_		:			Dict											=	resample if resample is not None else self.resample
							snake_case_		:			Tuple											=	apply_ocr if apply_ocr is not None else self.apply_ocr
							snake_case_		:			int											=	ocr_lang if ocr_lang is not None else self.ocr_lang
							snake_case_		:			int											=	tesseract_config if tesseract_config is not None else self.tesseract_config

							snake_case_		:			str											=	make_list_of_images(_A	)

							if not valid_images(_A	):
								raise ValueError(
								    'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
								    'torch.Tensor, tf.Tensor or jax.ndarray.'	)

							if do_resize and size is None:
								raise ValueError('Size must be specified if do_resize is True.'	)

							# All transformations expect numpy arrays.
							snake_case_		:			List[str]											=	[to_numpy_array(_A	) for image in images]

							if apply_ocr:
								requires_backends(self		,   'pytesseract'	)
								snake_case_		:			str											=	[]
								snake_case_		:			List[Any]											=	[]
								for image in images:
									snake_case_						,snake_case_		:			Tuple											=	apply_tesseract(_A		,   _A		,   _A	)
									words_batch.append(_A	)
									boxes_batch.append(_A	)

							if do_resize:
								snake_case_		:			Tuple											=	[self.resize(image=_A		,   size=_A		,   resample=_A	) for image in images]

							# flip color channels from RGB to BGR (as Detectron2 requires this)
							snake_case_		:			int											=	[flip_channel_order(_A	) for image in images]
							snake_case_		:			Any											=	[to_channel_dimension_format(_A		,   _A	) for image in images]

							snake_case_		:			List[str]											=	BatchFeature(data={'pixel_values': images}		,   tensor_type=_A	)

							if apply_ocr:
								snake_case_		:			Dict											=	words_batch
								snake_case_		:			List[str]											=	boxes_batch
							return data

