
'''simple docstring'''




import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available


if is_torch_available():
       from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
       _a      :      Union[str, Any]       				=      False

if is_vision_available():
       from PIL import Image

       from transformers import (
           AutoProcessor,
           PixaStructImageProcessor,
           PixaStructProcessor,
           PreTrainedTokenizerFast,
           TaTokenizer,
       )




@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11	,				reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`."	,				)
@require_vision
@require_torch
class  _lowercase   (  unittest.TestCase       ):
   def a     (	self					:			Optional[int]			)   ->       str:
        __snake_case    			=	tempfile.mkdtemp()

        __snake_case    			=	PixaStructImageProcessor()
        __snake_case    			=	TaTokenizer.from_pretrained('t5-small'			)

        __snake_case    			=	PixaStructProcessor(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)

        processor.save_pretrained(self.tmpdirname			)
   def a     (	self					:			int					,      **SCREAMING_SNAKE_CASE_					:			Tuple			)   ->       str:
        return AutoProcessor.from_pretrained(self.tmpdirname					,      **SCREAMING_SNAKE_CASE_			).tokenizer
   def a     (	self					:			Union[str, Any]					,      **SCREAMING_SNAKE_CASE_					:			Dict			)   ->       Optional[Any]:
        return AutoProcessor.from_pretrained(self.tmpdirname					,      **SCREAMING_SNAKE_CASE_			).image_processor
   def a     (	self					:			List[str]			)   ->       str:
        shutil.rmtree(self.tmpdirname			)
   def a     (	self					:			Optional[Any]			)   ->       Dict:
        __snake_case    			=	[np.random.randint(255					,      size=(3, 30, 400)					,      dtype=np.uinta			)]

        __snake_case    			=	[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_					,      0					,      -1			)			) for x in image_inputs]

        return image_inputs
   def a     (	self					:			Optional[Any]			)   ->       List[str]:
        __snake_case    			=	PixaStructProcessor(tokenizer=self.get_tokenizer()					,      image_processor=self.get_image_processor()			)
        processor.save_pretrained(self.tmpdirname			)

        __snake_case    			=	self.get_tokenizer(bos_token='(BOS)'					,      eos_token='(EOS)'			)
        __snake_case    			=	self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE_					,      padding_value=1.0			)

        __snake_case    			=	PixaStructProcessor.from_pretrained(
            self.tmpdirname					,      bos_token='(BOS)'					,      eos_token='(EOS)'					,      do_normalize=SCREAMING_SNAKE_CASE_					,      padding_value=1.0			)

        self.assertEqual(processor.tokenizer.get_vocab()					,      tokenizer_add_kwargs.get_vocab()			)
        self.assertIsInstance(processor.tokenizer					,      SCREAMING_SNAKE_CASE_			)

        self.assertEqual(processor.image_processor.to_json_string()					,      image_processor_add_kwargs.to_json_string()			)
        self.assertIsInstance(processor.image_processor					,      SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			Optional[int]			)   ->       Optional[int]:
        __snake_case    			=	self.get_image_processor()
        __snake_case    			=	self.get_tokenizer()

        __snake_case    			=	PixaStructProcessor(tokenizer=SCREAMING_SNAKE_CASE_					,      image_processor=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	self.prepare_image_inputs()

        __snake_case    			=	image_processor(SCREAMING_SNAKE_CASE_					,      return_tensors='np'			)
        __snake_case    			=	processor(images=SCREAMING_SNAKE_CASE_					,      return_tensors='np'			)

        for key in input_feat_extract.keys():
             self.assertAlmostEqual(input_feat_extract[key].sum()					,      input_processor[key].sum()					,      delta=1e-2			)
   def a     (	self					:			Tuple			)   ->       Dict:
        __snake_case    			=	self.get_image_processor()
        __snake_case    			=	self.get_tokenizer()

        __snake_case    			=	PixaStructProcessor(tokenizer=SCREAMING_SNAKE_CASE_					,      image_processor=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	'lower newer'

        __snake_case    			=	processor(text=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	tokenizer(SCREAMING_SNAKE_CASE_					,      return_token_type_ids=SCREAMING_SNAKE_CASE_					,      add_special_tokens=SCREAMING_SNAKE_CASE_			)

        for key in encoded_tok.keys():
             self.assertListEqual(encoded_tok[key]					,      encoded_processor[key]			)
   def a     (	self					:			Optional[int]			)   ->       List[str]:
        __snake_case    			=	self.get_image_processor()
        __snake_case    			=	self.get_tokenizer()

        __snake_case    			=	PixaStructProcessor(tokenizer=SCREAMING_SNAKE_CASE_					,      image_processor=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	'lower newer'
        __snake_case    			=	self.prepare_image_inputs()

        __snake_case    			=	processor(text=SCREAMING_SNAKE_CASE_					,      images=SCREAMING_SNAKE_CASE_			)

        self.assertListEqual(
            list(inputs.keys()			)					,      ['flattened_patches', 'attention_mask', 'decoder_attention_mask', 'decoder_input_ids']			)

        # test if it raises when no input is passed
        with pytest.raises(SCREAMING_SNAKE_CASE_			):
             processor()
   def a     (	self					:			List[str]			)   ->       Dict:
        __snake_case    			=	self.get_image_processor()
        __snake_case    			=	self.get_tokenizer()

        __snake_case    			=	PixaStructProcessor(tokenizer=SCREAMING_SNAKE_CASE_					,      image_processor=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	'lower newer'
        __snake_case    			=	self.prepare_image_inputs()

        __snake_case    			=	processor(text=SCREAMING_SNAKE_CASE_					,      images=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	[512, 1024, 2048, 4096]
        __snake_case    			=	[770, 770, 770, 770]
        # with text
        for i, max_patch in enumerate(SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	processor(text=SCREAMING_SNAKE_CASE_					,      images=SCREAMING_SNAKE_CASE_					,      max_patches=SCREAMING_SNAKE_CASE_			)
             self.assertEqual(inputs['flattened_patches'][0].shape[0]					,      SCREAMING_SNAKE_CASE_			)
             self.assertEqual(inputs['flattened_patches'][0].shape[1]					,      expected_hidden_size[i]			)

        # without text input
        for i, max_patch in enumerate(SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	processor(images=SCREAMING_SNAKE_CASE_					,      max_patches=SCREAMING_SNAKE_CASE_			)
             self.assertEqual(inputs['flattened_patches'][0].shape[0]					,      SCREAMING_SNAKE_CASE_			)
             self.assertEqual(inputs['flattened_patches'][0].shape[1]					,      expected_hidden_size[i]			)
   def a     (	self					:			List[str]			)   ->       Union[str, Any]:
        __snake_case    			=	self.get_image_processor()
        __snake_case    			=	self.get_tokenizer()

        __snake_case    			=	PixaStructProcessor(tokenizer=SCREAMING_SNAKE_CASE_					,      image_processor=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

        __snake_case    			=	processor.batch_decode(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	tokenizer.batch_decode(SCREAMING_SNAKE_CASE_			)

        self.assertListEqual(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)





   def a     (	self					:			Optional[Any]			)   ->       Optional[Any]:
        __snake_case    			=	self.get_image_processor()
        __snake_case    			=	self.get_tokenizer()

        __snake_case    			=	PixaStructProcessor(tokenizer=SCREAMING_SNAKE_CASE_					,      image_processor=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	'lower newer'
        __snake_case    			=	self.prepare_image_inputs()

        __snake_case    			=	processor(text=SCREAMING_SNAKE_CASE_					,      images=SCREAMING_SNAKE_CASE_			)

        # For now the processor supports only ["flattened_patches", "input_ids", "attention_mask", "decoder_attention_mask"]
        self.assertListEqual(
            list(inputs.keys()			)					,      ['flattened_patches', 'attention_mask', 'decoder_attention_mask', 'decoder_input_ids']			)

        __snake_case    			=	processor(text=SCREAMING_SNAKE_CASE_			)

        # For now the processor supports only ["flattened_patches", "input_ids", "attention_mask", "decoder_attention_mask"]
        self.assertListEqual(list(inputs.keys()			)					,      ['input_ids', 'attention_mask']			)








'''simple docstring'''




import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a      :      List[str]       				=      logging.get_logger(__name__)

_a      :      Any       				=      {
    "facebook/sam-vit-huge": "https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json",
    "facebook/sam-vit-large": "https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json",
    "facebook/sam-vit-base": "https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json",
}




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			int					,      SCREAMING_SNAKE_CASE_					:			List[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=1024					,      SCREAMING_SNAKE_CASE_					:			Any=16					,      SCREAMING_SNAKE_CASE_					:			int=16					,      SCREAMING_SNAKE_CASE_					:			List[Any]=4					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]="gelu"					,      SCREAMING_SNAKE_CASE_					:			Tuple=1e-6					,      **SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      )   ->       Tuple:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	hidden_size
        __snake_case    			=	image_size
        __snake_case    			=	patch_size
        __snake_case    			=	image_size // patch_size
        __snake_case    			=	mask_input_channels
        __snake_case    			=	num_point_embeddings
        __snake_case    			=	hidden_act
        __snake_case    			=	layer_norm_eps




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			List[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Dict="relu"					,      SCREAMING_SNAKE_CASE_					:			Any=2048					,      SCREAMING_SNAKE_CASE_					:			int=2					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=8					,      SCREAMING_SNAKE_CASE_					:			int=2					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=3					,      SCREAMING_SNAKE_CASE_					:			str=3					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1e-6					,      **SCREAMING_SNAKE_CASE_					:			int					,      )   ->       str:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	hidden_size
        __snake_case    			=	hidden_act
        __snake_case    			=	mlp_dim
        __snake_case    			=	num_hidden_layers
        __snake_case    			=	num_attention_heads
        __snake_case    			=	attention_downsample_rate
        __snake_case    			=	num_multimask_outputs
        __snake_case    			=	iou_head_depth
        __snake_case    			=	iou_head_hidden_dim
        __snake_case    			=	layer_norm_eps




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			int=768					,      SCREAMING_SNAKE_CASE_					:			int=256					,      SCREAMING_SNAKE_CASE_					:			str=12					,      SCREAMING_SNAKE_CASE_					:			Tuple=12					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=3					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1024					,      SCREAMING_SNAKE_CASE_					:			List[str]=16					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]="gelu"					,      SCREAMING_SNAKE_CASE_					:			Any=1e-06					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=0.0					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1e-10					,      SCREAMING_SNAKE_CASE_					:			List[Any]=True					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=4.0					,      SCREAMING_SNAKE_CASE_					:			List[Any]=True					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=True					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=14					,      SCREAMING_SNAKE_CASE_					:			str=[2, 5, 8, 11]					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=128					,      SCREAMING_SNAKE_CASE_					:			Tuple=None					,      **SCREAMING_SNAKE_CASE_					:			List[Any]					,      )   ->       Optional[Any]:
        super().__init__(**SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	hidden_size
        __snake_case    			=	output_channels
        __snake_case    			=	num_hidden_layers
        __snake_case    			=	num_attention_heads
        __snake_case    			=	num_channels
        __snake_case    			=	image_size
        __snake_case    			=	patch_size
        __snake_case    			=	hidden_act
        __snake_case    			=	layer_norm_eps
        __snake_case    			=	attention_dropout
        __snake_case    			=	initializer_range
        __snake_case    			=	qkv_bias
        __snake_case    			=	mlp_ratio
        __snake_case    			=	use_abs_pos
        __snake_case    			=	use_rel_pos
        __snake_case    			=	window_size
        __snake_case    			=	global_attn_indexes
        __snake_case    			=	num_pos_feats
        __snake_case    			=	int(hidden_size * mlp_ratio			) if mlp_dim is None else mlp_dim




class  _lowercase   (  __lowercase       ):
   _SCREAMING_SNAKE_CASE     :     Union[str, Any]									=  "sam"
   _SCREAMING_SNAKE_CASE     :     Any									=  True
   def __init__(	self					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			Dict=None					,      SCREAMING_SNAKE_CASE_					:			List[Any]=None					,      SCREAMING_SNAKE_CASE_					:			List[str]=None					,      SCREAMING_SNAKE_CASE_					:			str=0.0_2					,      **SCREAMING_SNAKE_CASE_					:			str					,      )   ->       str:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	vision_config if vision_config is not None else {}
        __snake_case    			=	prompt_encoder_config if prompt_encoder_config is not None else {}
        __snake_case    			=	mask_decoder_config if mask_decoder_config is not None else {}

        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	vision_config.to_dict()
        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	prompt_encoder_config.to_dict()
        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	mask_decoder_config.to_dict()

        __snake_case    			=	SamVisionConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	SamPromptEncoderConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	SamMaskDecoderConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	initializer_range





   def a     (	self					:			int			)   ->       str:
        __snake_case    			=	copy.deepcopy(self.__dict__			)
        __snake_case    			=	self.vision_config.to_dict()
        __snake_case    			=	self.prompt_encoder_config.to_dict()
        __snake_case    			=	self.mask_decoder_config.to_dict()
        __snake_case    			=	self.__class__.model_type
        return output




