





"""simple docstring"""


from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


__magic_name__       :					Any						=			logging.get_logger(__name__)

__magic_name__       :					Tuple						=			{
    """microsoft/resnet-50""": """https://huggingface.co/microsoft/resnet-50/blob/main/config.json""",
}






class 							lowercase__			(   __SCREAMING_SNAKE_CASE					,     __SCREAMING_SNAKE_CASE	):

			"""simple docstring"""
			__lowerCAmelCase     :				List[str]										=  """resnet"""
			__lowerCAmelCase     :				List[Any]										=  ["""basic""", """bottleneck"""]







			def __init__(      self						,   _A=3						,   _A=6_4						,   _A=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]						,   _A=[3, 4, 6, 3]						,   _A="bottleneck"						,   _A="relu"						,   _A=False						,   _A=None						,   _A=None						,   **_A						,   ):






									'''simple docstring'''







									super().__init__(**_A    )
									if layer_type not in self.layer_types:
															raise ValueError(f"""layer_type={layer_type} is not one of {",".join(self.layer_types    )}"""    )
									UpperCamelCase				:		List[Any]				   =			num_channels
									UpperCamelCase				:		str				   =			embedding_size
									UpperCamelCase				:		List[Any]				   =			hidden_sizes
									UpperCamelCase				:		str				   =			depths
									UpperCamelCase				:		Tuple				   =			layer_type
									UpperCamelCase				:		Tuple				   =			hidden_act
									UpperCamelCase				:		str				   =			downsample_in_first_stage
									UpperCamelCase				:		str				   =			["""stem"""] + [f"""stage{idx}""" for idx in range(1						,   len(_A    ) + 1    )]
									UpperCamelCase   ,						UpperCamelCase				:		Union[str, Any]				   =			get_aligned_output_features_output_indices(
									    out_features=_A						,   out_indices=_A						,   stage_names=self.stage_names    )






class 							lowercase__			(   __SCREAMING_SNAKE_CASE	):

			"""simple docstring"""
			__lowerCAmelCase     :				Any										=  version.parse("""1.11"""	)







			@property
			def   _a      (      self    ):






									'''simple docstring'''







									return OrderedDict(
									    [
									        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
									    ]    )







			@property
			def   _a      (      self    ):






									'''simple docstring'''







									return 1e-3








from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
   from PIL import Image

   from ..image_utils import load_image

if is_tf_available():
   from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
   import torch

   from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

UpperCAmelCase_		 =					logging.get_logger(__name__)


@add_end_docstrings(_A)
class 	lowerCamelCase__	(       _A):



 """simple docstring"""

 def __init__(    self					:					Optional[int]			,						*__lowerCAmelCase					:					List[Any]			,						**__lowerCAmelCase					:					List[str]      )   ->	List[str]:
    super().__init__(*__lowerCAmelCase			,						**__lowerCAmelCase      )
    requires_backends(self			,						'''vision'''      )
    self.check_model_type(
        TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING      )

 def     snake_case_      (    self					:					Any			,						__lowerCAmelCase					:					Dict=None			,						__lowerCAmelCase					:					List[str]=None			,						__lowerCAmelCase					:					Optional[Any]=None      )   ->	int:
    _A      =       {}
    _A      =       {}

    if prompt is not None:
       _A      =       prompt

    if generate_kwargs is not None:
       _A      =       generate_kwargs
    if max_new_tokens is not None:
       if "generate_kwargs" not in forward_kwargs:
          _A      =       {}
       if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
          raise ValueError(
              '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,'''
              ''' please use only one'''      )
       _A      =       max_new_tokens
    return preprocess_params, forward_kwargs, {}

 def __call__(    self					:					List[str]			,						__lowerCAmelCase					:					Union[str, List[str], "Image.Image", List["Image.Image"]]			,						**__lowerCAmelCase					:					Union[str, Any]      )   ->	Union[str, Any]:
    return super().__call__(__lowerCAmelCase			,						**__lowerCAmelCase      )

 def     snake_case_      (    self					:					List[Any]			,						__lowerCAmelCase					:					str			,						__lowerCAmelCase					:					Union[str, Any]=None      )   ->	int:
    _A      =       load_image(__lowerCAmelCase      )

    if prompt is not None:
       if not isinstance(__lowerCAmelCase			,						__lowerCAmelCase      ):
          raise ValueError(
              f'''Received an invalid text input, got - {type(__lowerCAmelCase      )} - but expected a single string. '''
              '''Note also that one single text can be provided for conditional image to text generation.'''      )

       _A      =       self.model.config.model_type

       if model_type == "git":
          _A      =       self.image_processor(images=__lowerCAmelCase			,						return_tensors=self.framework      )
          _A      =       self.tokenizer(text=__lowerCAmelCase			,						add_special_tokens=__lowerCAmelCase      ).input_ids
          _A      =       [self.tokenizer.cls_token_id] + input_ids
          _A      =       torch.tensor(__lowerCAmelCase      ).unsqueeze(0      )
          model_inputs.update({'''input_ids''': input_ids}      )

       elif model_type == "pix2struct":
          _A      =       self.image_processor(images=__lowerCAmelCase			,						header_text=__lowerCAmelCase			,						return_tensors=self.framework      )

       elif model_type != "vision-encoder-decoder":
          # vision-encoder-decoder does not support conditional generation
          _A      =       self.image_processor(images=__lowerCAmelCase			,						return_tensors=self.framework      )
          _A      =       self.tokenizer(__lowerCAmelCase			,						return_tensors=self.framework      )
          model_inputs.update(__lowerCAmelCase      )

       else:
          raise ValueError(f'''Model type {model_type} does not support conditional text generation'''      )

    else:
       _A      =       self.image_processor(images=__lowerCAmelCase			,						return_tensors=self.framework      )

    if self.model.config.model_type == "git" and prompt is None:
       _A      =       None

    return model_inputs

 def     snake_case_      (    self					:					Optional[int]			,						__lowerCAmelCase					:					Tuple			,						__lowerCAmelCase					:					Dict=None      )   ->	str:
    # Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the
    # pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first.
    if (
        "input_ids" in model_inputs
        and isinstance(model_inputs['''input_ids''']			,						__lowerCAmelCase      )
        and all(x is None for x in model_inputs['''input_ids''']      )
    ):
       _A      =       None

    if generate_kwargs is None:
       _A      =       {}
    # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
    #  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
    #  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
    #  in the `_prepare_model_inputs` method.
    _A      =       model_inputs.pop(self.model.main_input_name      )
    _A      =       self.model.generate(__lowerCAmelCase			,						**__lowerCAmelCase			,						**__lowerCAmelCase      )
    return model_outputs

 def     snake_case_      (    self					:					Dict			,						__lowerCAmelCase					:					Any      )   ->	Union[str, Any]:
    _A      =       []
    for output_ids in model_outputs:
       _A      =       {
           '''generated_text''': self.tokenizer.decode(
               __lowerCAmelCase			,						skip_special_tokens=__lowerCAmelCase			,						)
       }
       records.append(__lowerCAmelCase      )
    return records



