





import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
						from transformers.models.esm.modeling_esm import (
						    ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
						    EsmEmbeddings,
						    create_position_ids_from_input_ids,
						)


class SCREAMING_SNAKE_CASE_						:






						def __init__(      self      :      Tuple		,   _A      :      Any		,   _A      :      Optional[int]=13		,   _A      :      str=7		,   _A      :      str=False		,   _A      :      Optional[int]=True		,   _A      :      Optional[int]=False		,   _A      :      List[str]=True		,   _A      :      List[str]=33		,   _A      :      List[Any]=32		,   _A      :      Tuple=5		,   _A      :      int=4		,   _A      :      Tuple=37		,   _A      :      Union[str, Any]="gelu"		,   _A      :      int=0.1		,   _A      :      Tuple=0.1		,   _A      :      Union[str, Any]=512		,   _A      :      Dict=16		,   _A      :      Optional[Any]=2		,   _A      :      str=0.0_2		,   _A      :      int=3		,   _A      :      Optional[Any]=4		,   _A      :      List[str]=None		,   )							->    Any:







							"""simple docstring"""


							snake_case_		:			Tuple											=	parent
							snake_case_		:			Optional[int]											=	batch_size
							snake_case_		:			int											=	seq_length
							snake_case_		:			str											=	is_training
							snake_case_		:			Any											=	use_input_mask
							snake_case_		:			List[str]											=	use_token_type_ids
							snake_case_		:			Tuple											=	use_labels
							snake_case_		:			List[str]											=	vocab_size
							snake_case_		:			List[Any]											=	hidden_size
							snake_case_		:			str											=	num_hidden_layers
							snake_case_		:			Optional[Any]											=	num_attention_heads
							snake_case_		:			Dict											=	intermediate_size
							snake_case_		:			Optional[int]											=	hidden_act
							snake_case_		:			int											=	hidden_dropout_prob
							snake_case_		:			Tuple											=	attention_probs_dropout_prob
							snake_case_		:			Dict											=	max_position_embeddings
							snake_case_		:			Optional[Any]											=	type_vocab_size
							snake_case_		:			Union[str, Any]											=	type_sequence_label_size
							snake_case_		:			List[str]											=	initializer_range
							snake_case_		:			str											=	num_labels
							snake_case_		:			str											=	num_choices
							snake_case_		:			List[Any]											=	scope






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







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	ids_tensor([self.batch_size, self.seq_length]		,   self.vocab_size	)

							snake_case_		:			Union[str, Any]											=	None
							if self.use_input_mask:
								snake_case_		:			Any											=	random_attention_mask([self.batch_size, self.seq_length]	)

							snake_case_		:			Optional[int]											=	None
							snake_case_		:			Tuple											=	None
							snake_case_		:			Optional[int]											=	None
							if self.use_labels:
								snake_case_		:			Any											=	ids_tensor([self.batch_size]		,   self.type_sequence_label_size	)
								snake_case_		:			Tuple											=	ids_tensor([self.batch_size, self.seq_length]		,   self.num_labels	)
								snake_case_		:			str											=	ids_tensor([self.batch_size]		,   self.num_choices	)

							snake_case_		:			Any											=	self.get_config()

							return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






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







							"""simple docstring"""


							return EsmConfig(
							    vocab_size=self.vocab_size		,   hidden_size=self.hidden_size		,   pad_token_id=1		,   num_hidden_layers=self.num_hidden_layers		,   num_attention_heads=self.num_attention_heads		,   intermediate_size=self.intermediate_size		,   hidden_act=self.hidden_act		,   hidden_dropout_prob=self.hidden_dropout_prob		,   attention_probs_dropout_prob=self.attention_probs_dropout_prob		,   max_position_embeddings=self.max_position_embeddings		,   type_vocab_size=self.type_vocab_size		,   initializer_range=self.initializer_range		,   )






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







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	EsmModel(config=UpperCAmelCase__	)
							model.to(UpperCAmelCase__	)
							model.eval()
							snake_case_		:			int											=	model(UpperCAmelCase__		,   attention_mask=UpperCAmelCase__	)
							snake_case_		:			Optional[Any]											=	model(UpperCAmelCase__	)
							snake_case_		:			Any											=	model(UpperCAmelCase__	)

							self.parent.assertEqual(result.last_hidden_state.shape		,   (self.batch_size, self.seq_length, self.hidden_size)	)
							self.parent.assertEqual(result.pooler_output.shape		,   (self.batch_size, self.hidden_size)	)






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







							"""simple docstring"""


							snake_case_		:			int											=	EsmForMaskedLM(config=UpperCAmelCase__	)
							model.to(UpperCAmelCase__	)
							model.eval()
							snake_case_		:			int											=	model(UpperCAmelCase__		,   attention_mask=UpperCAmelCase__		,   labels=UpperCAmelCase__	)
							self.parent.assertEqual(result.logits.shape		,   (self.batch_size, self.seq_length, self.vocab_size)	)






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







							"""simple docstring"""


							snake_case_		:			int											=	self.num_labels
							snake_case_		:			Optional[Any]											=	EsmForTokenClassification(config=UpperCAmelCase__	)
							model.to(UpperCAmelCase__	)
							model.eval()
							snake_case_		:			Optional[int]											=	model(UpperCAmelCase__		,   attention_mask=UpperCAmelCase__		,   labels=UpperCAmelCase__	)
							self.parent.assertEqual(result.logits.shape		,   (self.batch_size, self.seq_length, self.num_labels)	)






						def UpperCAmelCase_				(      self      :      int	)							->    int:







							"""simple docstring"""


							snake_case_		:			List[str]											=	self.prepare_config_and_inputs()
							(
							    snake_case_	
							)		:			str											=	config_and_inputs
							snake_case_		:			str											=	{'''input_ids''': input_ids, '''attention_mask''': input_mask}
							return config, inputs_dict


@require_torch
class SCREAMING_SNAKE_CASE_						(					snake_case_       ,				snake_case_       ,				unittest.TestCase					):
						__magic_name__:			List[Any]       =       False

						__magic_name__:			int       =       (
						    (
						        EsmForMaskedLM,
						        EsmModel,
						        EsmForSequenceClassification,
						        EsmForTokenClassification,
						    )
						    if is_torch_available()
						    else ()
						)
						__magic_name__:			Optional[int]       =       ()
						__magic_name__:			Optional[int]       =       (
						    {
						        'feature-extraction': EsmModel,
						        'fill-mask': EsmForMaskedLM,
						        'text-classification': EsmForSequenceClassification,
						        'token-classification': EsmForTokenClassification,
						        'zero-shot': EsmForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)
						__magic_name__:			Union[str, Any]       =       True






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







							"""simple docstring"""


							snake_case_		:			Tuple											=	EsmModelTester(self	)
							snake_case_		:			Union[str, Any]											=	ConfigTester(self		,   config_class=UpperCAmelCase__		,   hidden_size=37	)






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







							"""simple docstring"""


							self.config_tester.run_common_tests()






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







							"""simple docstring"""


							snake_case_		:			Tuple											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase__	)






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







							"""simple docstring"""


							snake_case_		:			Dict											=	self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
								snake_case_		:			Tuple											=	type
								self.model_tester.create_and_check_model(*UpperCAmelCase__	)






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







							"""simple docstring"""


							snake_case_		:			str											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__	)






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







							"""simple docstring"""


							snake_case_		:			List[str]											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__	)






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







							"""simple docstring"""


							for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								snake_case_		:			Dict											=	EsmModel.from_pretrained(UpperCAmelCase__	)
								self.assertIsNotNone(UpperCAmelCase__	)






						def UpperCAmelCase_				(      self      :      Tuple	)							->    str:







							"""simple docstring"""


							snake_case_		:			str											=	self.model_tester.prepare_config_and_inputs()[0]
							snake_case_		:			Union[str, Any]											=	EsmEmbeddings(config=UpperCAmelCase__	)

							snake_case_		:			Optional[int]											=	torch.as_tensor([[12, 31, 13, model.padding_idx]]	)
							snake_case_		:			Any											=	torch.as_tensor(
							    [
							        [
							            0 + model.padding_idx + 1,
							            1 + model.padding_idx + 1,
							            2 + model.padding_idx + 1,
							            model.padding_idx,
							        ]
							    ]	)
							snake_case_		:			Optional[int]											=	create_position_ids_from_input_ids(UpperCAmelCase__		,   model.padding_idx	)
							self.assertEqual(position_ids.shape		,   expected_positions.shape	)
							self.assertTrue(torch.all(torch.eq(UpperCAmelCase__		,   UpperCAmelCase__	)	)	)






						def UpperCAmelCase_				(      self      :      int	)							->    str:







							"""simple docstring"""


							snake_case_		:			Any											=	self.model_tester.prepare_config_and_inputs()[0]
							snake_case_		:			str											=	EsmEmbeddings(config=UpperCAmelCase__	)

							snake_case_		:			List[str]											=	torch.empty(2		,   4		,   30	)
							snake_case_		:			Any											=	[
							    0 + embeddings.padding_idx + 1,
							    1 + embeddings.padding_idx + 1,
							    2 + embeddings.padding_idx + 1,
							    3 + embeddings.padding_idx + 1,
							]
							snake_case_		:			Any											=	torch.as_tensor([expected_single_positions, expected_single_positions]	)
							snake_case_		:			str											=	embeddings.create_position_ids_from_inputs_embeds(UpperCAmelCase__	)
							self.assertEqual(position_ids.shape		,   expected_positions.shape	)
							self.assertTrue(torch.all(torch.eq(UpperCAmelCase__		,   UpperCAmelCase__	)	)	)






						@unittest.skip('Esm does not support embedding resizing'	)
						def UpperCAmelCase_				(      self      :      int	)							->    Any:







							"""simple docstring"""


							pass






						@unittest.skip('Esm does not support embedding resizing'	)
						def UpperCAmelCase_				(      self      :      str	)							->    str:







							"""simple docstring"""


							pass






						@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'	)
						def UpperCAmelCase_				(      self      :      Optional[int]	)							->    Union[str, Any]:







							"""simple docstring"""


							pass


@require_torch
class SCREAMING_SNAKE_CASE_						(					snake_case_					):






						@slow
						def UpperCAmelCase_				(      self      :      Optional[int]	)							->    Dict:







							"""simple docstring"""


							with torch.no_grad():
								snake_case_		:			str											=	EsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D'	)
								model.eval()
								snake_case_		:			Dict											=	torch.tensor([[0, 1, 2, 3, 4, 5]]	)
								snake_case_		:			Union[str, Any]											=	model(UpperCAmelCase__	)[0]

								snake_case_		:			Tuple											=	33

								snake_case_		:			Any											=	torch.Size((1, 6, vocab_size)	)
								self.assertEqual(output.shape		,   UpperCAmelCase__	)

								snake_case_		:			List[Any]											=	torch.tensor(
								    [[[8.9_2_1_5, -1_0.5_8_9_8, -6.4_6_7_1], [-6.3_9_6_7, -1_3.9_1_1_4, -1.1_2_1_2], [-7.7_8_1_2, -1_3.9_5_1_6, -3.7_4_0_6]]]	)
								self.assertTrue(torch.allclose(output[:, :3, :3]		,   UpperCAmelCase__		,   atol=1E-4	)	)






						@slow
						def UpperCAmelCase_				(      self      :      int	)							->    int:







							"""simple docstring"""


							with torch.no_grad():
								snake_case_		:			Optional[int]											=	EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D'	)
								model.eval()

								snake_case_		:			Union[str, Any]											=	torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]	)
								snake_case_		:			int											=	model(UpperCAmelCase__	)[0]
								# compare the actual values for a slice.
								snake_case_		:			List[str]											=	torch.tensor(
								    [[[0.1_4_4_4, 0.5_4_1_3, 0.3_2_4_8], [0.3_0_3_4, 0.0_0_5_3, 0.3_1_0_8], [0.3_2_2_8, -0.2_4_9_9, 0.3_4_1_5]]]	)
								self.assertTrue(torch.allclose(output[:, :3, :3]		,   UpperCAmelCase__		,   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

