




from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
    import timm


if is_torch_available():
    from torch import Tensor







class __snake_case			(			a ,  a		):
   UpperCAmelCase__  :    str          =  '''pixel_values'''
   UpperCAmelCase__  :    str          =  False
   UpperCAmelCase__  :    List[Any]          =  TimmBackboneConfig







   def __init__(      self		:						Optional[int]					,						_snake_case		:						int					,						**_snake_case		:						Optional[int]):

        """simple docstring"""


        requires_backends(self					,						'''timm''')
        super().__init__(_snake_case)
        UpperCAmelCase_          =							config

        if config.backbone is None:
             raise ValueError('''backbone is not set in the config. Please set it to a timm model name.''')

        if config.backbone not in timm.list_models():
             raise ValueError(F"""backbone {config.backbone} is not supported by timm.""")

        if hasattr(_snake_case					,						'''out_features''') and config.out_features is not None:
             raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.''')

        UpperCAmelCase_          =							getattr(_snake_case					,						'''use_pretrained_backbone'''					,						_snake_case)
        if pretrained is None:
             raise ValueError('''use_pretrained_backbone is not set in the config. Please set it to True or False.''')

        # We just take the final layer by default. This matches the default for the transformers models.
        UpperCAmelCase_          =							config.out_indices if getattr(_snake_case					,						'''out_indices'''					,						_snake_case) is not None else (-1,)

        UpperCAmelCase_          =							timm.create_model(
            config.backbone					,						pretrained=_snake_case					,						features_only=config.features_only					,						in_chans=config.num_channels					,						out_indices=_snake_case					,						**_snake_case					,						)
        # These are used to control the output of the model when called. If output_hidden_states is True, then
        # return_layers is modified to include all layers.
        UpperCAmelCase_          =							self._backbone.return_layers
        UpperCAmelCase_          =							{layer['''module''']: str(_snake_case) for i, layer in enumerate(self._backbone.feature_info.info)}
        super()._init_backbone(_snake_case)







   @classmethod
   def lowerCamelCase						(      cls		:						Dict					,						_snake_case		:						str					,						*_snake_case		:						List[str]					,						**_snake_case		:						Optional[Any]):

        """simple docstring"""


        requires_backends(cls					,						['''vision''', '''timm'''])
        from ...models.timm_backbone import TimmBackboneConfig

        UpperCAmelCase_          =							kwargs.pop('''config'''					,						TimmBackboneConfig())

        UpperCAmelCase_          =							kwargs.pop('''use_timm_backbone'''					,						_snake_case)
        if not use_timm:
             raise ValueError('''use_timm_backbone must be True for timm backbones''')

        UpperCAmelCase_          =							kwargs.pop('''num_channels'''					,						config.num_channels)
        UpperCAmelCase_          =							kwargs.pop('''features_only'''					,						config.features_only)
        UpperCAmelCase_          =							kwargs.pop('''use_pretrained_backbone'''					,						config.use_pretrained_backbone)
        UpperCAmelCase_          =							kwargs.pop('''out_indices'''					,						config.out_indices)
        UpperCAmelCase_          =							TimmBackboneConfig(
            backbone=_snake_case					,						num_channels=_snake_case					,						features_only=_snake_case					,						use_pretrained_backbone=_snake_case					,						out_indices=_snake_case					,						)
        return super()._from_config(_snake_case					,						**_snake_case)







   def lowerCamelCase						(      self		:						int					,						_snake_case		:						Optional[Any]):

        """simple docstring"""


        pass







   def lowerCamelCase						(      self		:						Optional[int]					,						_snake_case		:						Tuple					,						_snake_case		:						int=None					,						_snake_case		:						Any=None					,						_snake_case		:						int=None					,						**_snake_case		:						List[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							return_dict if return_dict is not None else self.config.use_return_dict
        UpperCAmelCase_          =							(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        UpperCAmelCase_          =							output_attentions if output_attentions is not None else self.config.output_attentions

        if output_attentions:
             raise ValueError('''Cannot output attentions for timm backbones at the moment''')

        if output_hidden_states:
             # We modify the return layers to include all the stages of the backbone
             UpperCAmelCase_          =							self._all_layers
             UpperCAmelCase_          =							self._backbone(_snake_case					,						**_snake_case)
             UpperCAmelCase_          =							self._return_layers
             UpperCAmelCase_          =							tuple(hidden_states[i] for i in self.out_indices)
        else:
             UpperCAmelCase_          =							self._backbone(_snake_case					,						**_snake_case)
             UpperCAmelCase_          =							None

        UpperCAmelCase_          =							tuple(_snake_case)
        UpperCAmelCase_          =							tuple(_snake_case) if hidden_states is not None else None

        if not return_dict:
             UpperCAmelCase_          =							(feature_maps,)
             if output_hidden_states:
                  UpperCAmelCase_          =							output + (hidden_states,)
             return output

        return BackboneOutput(feature_maps=_snake_case					,						hidden_states=_snake_case					,						attentions=_snake_case)












import warnings
from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class __snake_case			(			a		):
   UpperCAmelCase__  :    Dict          =  ['''image_processor''', '''tokenizer''']
   UpperCAmelCase__  :    Dict          =  '''FlavaImageProcessor'''
   UpperCAmelCase__  :    Dict          =  ('''BertTokenizer''', '''BertTokenizerFast''')







   def __init__(      self		:						Union[str, Any]					,						_snake_case		:						List[str]=None					,						_snake_case		:						str=None					,						**_snake_case		:						int):

        """simple docstring"""


        UpperCAmelCase_          =							None
        if "feature_extractor" in kwargs:
             warnings.warn(
                 '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                 ''' instead.'''					,						_snake_case					,						)
             UpperCAmelCase_          =							kwargs.pop('''feature_extractor''')

        UpperCAmelCase_          =							image_processor if image_processor is not None else feature_extractor
        if image_processor is None:
             raise ValueError('''You need to specify an `image_processor`.''')
        if tokenizer is None:
             raise ValueError('''You need to specify a `tokenizer`.''')

        super().__init__(_snake_case					,						_snake_case)
        UpperCAmelCase_          =							self.image_processor







   def __call__(      self		:						List[Any]					,						_snake_case		:						Optional[ImageInput] = None					,						_snake_case		:						Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None					,						_snake_case		:						bool = True					,						_snake_case		:						Union[bool, str, PaddingStrategy] = False					,						_snake_case		:						Union[bool, str, TruncationStrategy] = False					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						int = 0					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = True					,						_snake_case		:						Optional[Union[str, TensorType]] = None					,						**_snake_case		:						Any					,						):

        """simple docstring"""


        if text is None and images is None:
             raise ValueError('''You have to specify either text or images. Both cannot be none.''')

        if text is not None:
             UpperCAmelCase_          =							self.tokenizer(
                 text=_snake_case					,						add_special_tokens=_snake_case					,						padding=_snake_case					,						truncation=_snake_case					,						max_length=_snake_case					,						stride=_snake_case					,						pad_to_multiple_of=_snake_case					,						return_token_type_ids=_snake_case					,						return_attention_mask=_snake_case					,						return_overflowing_tokens=_snake_case					,						return_special_tokens_mask=_snake_case					,						return_offsets_mapping=_snake_case					,						return_length=_snake_case					,						verbose=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)
        if images is not None:
             UpperCAmelCase_          =							self.image_processor(
                 _snake_case					,						return_image_mask=_snake_case					,						return_codebook_pixels=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)

        if text is not None and images is not None:
             encoding.update(_snake_case)
             return encoding
        elif text is not None:
             return encoding
        else:
             return BatchEncoding(data=dict(**_snake_case)					,						tensor_type=_snake_case)







   def lowerCamelCase						(      self		:						Any					,						*_snake_case		:						Optional[Any]					,						**_snake_case		:						int):

        """simple docstring"""


        return self.tokenizer.batch_decode(*_snake_case					,						**_snake_case)







   def lowerCamelCase						(      self		:						Optional[int]					,						*_snake_case		:						int					,						**_snake_case		:						Dict):

        """simple docstring"""


        return self.tokenizer.decode(*_snake_case					,						**_snake_case)







   @property
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							self.tokenizer.model_input_names
        UpperCAmelCase_          =							self.image_processor.model_input_names
        return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))







   @property
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        warnings.warn(
            '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''					,						_snake_case					,						)
        return self.image_processor_class







   @property
   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        warnings.warn(
            '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''					,						_snake_case					,						)
        return self.image_processor






