
'''simple docstring'''


import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


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

# General docstring
snake_case_ :  Optional[int]     =					'PoolFormerConfig'

# Base docstring
snake_case_ :  int     =					'sail/poolformer_s12'
snake_case_ :  str     =					[1, 512, 7, 7]

# Image classification docstring
snake_case_ :  Any     =					'sail/poolformer_s12'
snake_case_ :  Union[str, Any]     =					'tabby, tabby cat'

snake_case_ :  List[Any]     =					[
    'sail/poolformer_s12',
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]



def  __snake_case     (    _UpperCAmelCase					:       str,      _UpperCAmelCase					:       float = 0.0,      _UpperCAmelCase					:       bool = False):
   if drop_prob == 0.0 or not training:
      return input
   UpperCamelCase       =  1 - drop_prob
   UpperCamelCase       =  (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
   UpperCamelCase       =  keep_prob + torch.rand(_UpperCAmelCase,      dtype=input.dtype,      device=input.device)
   random_tensor.floor_()  # binarize
   UpperCamelCase       =  input.div(_UpperCAmelCase) * random_tensor
   return output


class 						lowercase__	(  nn.Module   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ = None   ):

      '''simple docstring'''







      super().__init__()
      UpperCamelCase       =  drop_prob







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      return drop_path(lowerCamelCase__ ,   self.drop_prob ,   self.training   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      return "p={}".format(self.drop_prob   )




class 						lowercase__	(  nn.Module   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__=None   ):

      '''simple docstring'''







      super().__init__()
      UpperCamelCase       =  patch_size if isinstance(lowerCamelCase__ ,   collections.abc.Iterable   ) else (patch_size, patch_size)
      UpperCamelCase       =  stride if isinstance(lowerCamelCase__ ,   collections.abc.Iterable   ) else (stride, stride)
      UpperCamelCase       =  padding if isinstance(lowerCamelCase__ ,   collections.abc.Iterable   ) else (padding, padding)

      UpperCamelCase       =  nn.Convad(lowerCamelCase__ ,   lowerCamelCase__ ,   kernel_size=lowerCamelCase__ ,   stride=lowerCamelCase__ ,   padding=lowerCamelCase__   )
      UpperCamelCase       =  norm_layer(lowerCamelCase__   ) if norm_layer else nn.Identity()







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  self.projection(lowerCamelCase__   )
      UpperCamelCase       =  self.norm(lowerCamelCase__   )
      return embeddings




class 						lowercase__	(  nn.GroupNorm   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   **lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__(1 ,   lowerCamelCase__ ,   **lowerCamelCase__   )




class 						lowercase__	(  nn.Module   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__()
      UpperCamelCase       =  nn.AvgPoolad(lowerCamelCase__ ,   stride=1 ,   padding=pool_size // 2 ,   count_include_pad=lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      return self.pool(lowerCamelCase__   ) - hidden_states




class 						lowercase__	(  nn.Module   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__()
      UpperCamelCase       =  nn.Convad(lowerCamelCase__ ,   lowerCamelCase__ ,   1   )
      UpperCamelCase       =  nn.Convad(lowerCamelCase__ ,   lowerCamelCase__ ,   1   )
      UpperCamelCase       =  PoolFormerDropPath(lowerCamelCase__   )
      if isinstance(config.hidden_act ,   lowerCamelCase__   ):
         UpperCamelCase       =  ACTaFN[config.hidden_act]
      else:
         UpperCamelCase       =  config.hidden_act







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  self.conva(lowerCamelCase__   )
      UpperCamelCase       =  self.act_fn(lowerCamelCase__   )
      UpperCamelCase       =  self.drop(lowerCamelCase__   )
      UpperCamelCase       =  self.conva(lowerCamelCase__   )
      UpperCamelCase       =  self.drop(lowerCamelCase__   )

      return hidden_states




class 						lowercase__	(  nn.Module   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__()
      UpperCamelCase       =  PoolFormerPooling(lowerCamelCase__   )
      UpperCamelCase       =  PoolFormerOutput(lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   )
      UpperCamelCase       =  PoolFormerGroupNorm(lowerCamelCase__   )
      UpperCamelCase       =  PoolFormerGroupNorm(lowerCamelCase__   )

      # Useful for training neural nets
      UpperCamelCase       =  PoolFormerDropPath(lowerCamelCase__   ) if drop_path > 0.0 else nn.Identity()
      UpperCamelCase       =  config.use_layer_scale
      if config.use_layer_scale:
         UpperCamelCase       =  nn.Parameter(
             config.layer_scale_init_value * torch.ones((lowerCamelCase__)   ) ,   requires_grad=lowerCamelCase__   )
         UpperCamelCase       =  nn.Parameter(
             config.layer_scale_init_value * torch.ones((lowerCamelCase__)   ) ,   requires_grad=lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      if self.use_layer_scale:
         UpperCamelCase       =  self.pooling(self.before_norm(lowerCamelCase__   )   )
         UpperCamelCase       =  self.layer_scale_a.unsqueeze(-1   ).unsqueeze(-1   ) * pooling_output
         # First residual connection
         UpperCamelCase       =  hidden_states + self.drop_path(lowerCamelCase__   )
         UpperCamelCase       =  ()

         UpperCamelCase       =  self.output(self.after_norm(lowerCamelCase__   )   )
         UpperCamelCase       =  self.layer_scale_a.unsqueeze(-1   ).unsqueeze(-1   ) * layer_output
         # Second residual connection
         UpperCamelCase       =  hidden_states + self.drop_path(lowerCamelCase__   )

         UpperCamelCase       =  (output,) + outputs
         return outputs

      else:
         UpperCamelCase       =  self.drop_path(self.pooling(self.before_norm(lowerCamelCase__   )   )   )
         # First residual connection
         UpperCamelCase       =  pooling_output + hidden_states
         UpperCamelCase       =  ()

         # Second residual connection inside the PoolFormerOutput block
         UpperCamelCase       =  self.drop_path(self.output(self.after_norm(lowerCamelCase__   )   )   )
         UpperCamelCase       =  hidden_states + layer_output

         UpperCamelCase       =  (output,) + outputs
         return outputs




class 						lowercase__	(  nn.Module   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__()
      UpperCamelCase       =  config
      # stochastic depth decay rule
      UpperCamelCase       =  [x.item() for x in torch.linspace(0 ,   config.drop_path_rate ,   sum(config.depths   )   )]

      # patch embeddings
      UpperCamelCase       =  []
      for i in range(config.num_encoder_blocks   ):
         embeddings.append(
             PoolFormerEmbeddings(
                 patch_size=config.patch_sizes[i] ,   stride=config.strides[i] ,   padding=config.padding[i] ,   num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] ,   hidden_size=config.hidden_sizes[i] ,   )   )
      UpperCamelCase       =  nn.ModuleList(lowerCamelCase__   )

      # Transformer blocks
      UpperCamelCase       =  []
      UpperCamelCase       =  0
      for i in range(config.num_encoder_blocks   ):
         # each block consists of layers
         UpperCamelCase       =  []
         if i != 0:
            cur += config.depths[i - 1]
         for j in range(config.depths[i]   ):
            layers.append(
                PoolFormerLayer(
                    lowerCamelCase__ ,   num_channels=config.hidden_sizes[i] ,   pool_size=config.pool_size ,   hidden_size=config.hidden_sizes[i] ,   intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio   ) ,   drop_path=dpr[cur + j] ,   )   )
         blocks.append(nn.ModuleList(lowerCamelCase__   )   )

      UpperCamelCase       =  nn.ModuleList(lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__=False ,   lowerCamelCase__=True   ):

      '''simple docstring'''







      UpperCamelCase       =  () if output_hidden_states else None

      UpperCamelCase       =  pixel_values
      for idx, layers in enumerate(zip(self.patch_embeddings ,   self.block   )   ):
         UpperCamelCase     , UpperCamelCase       =  layers
         # Get patch embeddings from hidden_states
         UpperCamelCase       =  embedding_layer(lowerCamelCase__   )
         # Send the embeddings through the blocks
         for _, blk in enumerate(lowerCamelCase__   ):
            UpperCamelCase       =  blk(lowerCamelCase__   )
            UpperCamelCase       =  layer_outputs[0]

         if output_hidden_states:
            UpperCamelCase       =  all_hidden_states + (hidden_states,)

      if not return_dict:
         return tuple(v for v in [hidden_states, all_hidden_states] if v is not None   )

      return BaseModelOutputWithNoAttention(last_hidden_state=lowerCamelCase__ ,   hidden_states=lowerCamelCase__   )




class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							PoolFormerConfig
   _snake_case		   =							'''poolformer'''
   _snake_case		   =							'''pixel_values'''
   _snake_case		   =							True







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      if isinstance(lowerCamelCase__ ,   (nn.Linear, nn.Convad)   ):
         module.weight.data.normal_(mean=0.0 ,   std=self.config.initializer_range   )
         if module.bias is not None:
            module.bias.data.zero_()
      elif isinstance(lowerCamelCase__ ,   nn.LayerNorm   ):
         module.bias.data.zero_()
         module.weight.data.fill_(1.0   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__=False   ):

      '''simple docstring'''







      if isinstance(lowerCamelCase__ ,   lowerCamelCase__   ):
         UpperCamelCase       =  value




snake_case_ :  List[str]     =					r'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

snake_case_ :  Union[str, Any]     =					r'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`PoolFormerImageProcessor.__call__`] for details.\n'


@add_start_docstrings(
    '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''',					snake_case_,					)
class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__(lowerCamelCase__   )
      UpperCamelCase       =  config

      UpperCamelCase       =  PoolFormerEncoder(lowerCamelCase__   )

      # Initialize weights and apply final processing
      self.post_init()







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      return self.embeddings.patch_embeddings







   @add_start_docstrings_to_model_forward(lowerCamelCase__   )
   @add_code_sample_docstrings(
       checkpoint=_CHECKPOINT_FOR_DOC ,   output_type=lowerCamelCase__ ,   config_class=_CONFIG_FOR_DOC ,   modality='''vision''' ,   expected_output=_EXPECTED_OUTPUT_SHAPE ,   )
   def       UpperCAmelCase				(			self ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   ):

      '''simple docstring'''







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

      if pixel_values is None:
         raise ValueError('''You have to specify pixel_values'''   )

      UpperCamelCase       =  self.encoder(
          lowerCamelCase__ ,   output_hidden_states=lowerCamelCase__ ,   return_dict=lowerCamelCase__ ,   )
      UpperCamelCase       =  encoder_outputs[0]

      if not return_dict:
         return (sequence_output, None) + encoder_outputs[1:]

      return BaseModelOutputWithNoAttention(
          last_hidden_state=lowerCamelCase__ ,   hidden_states=encoder_outputs.hidden_states ,   )




class 						lowercase__	(  nn.Module   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__()
      UpperCamelCase       =  nn.Linear(config.hidden_size ,   config.hidden_size   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      UpperCamelCase       =  self.dense(lowerCamelCase__   )
      return output




@add_start_docstrings(
    '''
    PoolFormer Model transformer with an image classification head on top
    ''',					snake_case_,					)
class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__   ):

      '''simple docstring'''







      super().__init__(lowerCamelCase__   )
      UpperCamelCase       =  config.num_labels
      UpperCamelCase       =  PoolFormerModel(lowerCamelCase__   )

      # Final norm
      UpperCamelCase       =  PoolFormerGroupNorm(config.hidden_sizes[-1]   )
      # Classifier head
      UpperCamelCase       =  (
          nn.Linear(config.hidden_sizes[-1] ,   config.num_labels   ) if config.num_labels > 0 else nn.Identity()
      )

      # Initialize weights and apply final processing
      self.post_init()







   @add_start_docstrings_to_model_forward(lowerCamelCase__   )
   @add_code_sample_docstrings(
       checkpoint=_IMAGE_CLASS_CHECKPOINT ,   output_type=lowerCamelCase__ ,   config_class=_CONFIG_FOR_DOC ,   expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,   )
   def       UpperCAmelCase				(			self ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   ):

      '''simple docstring'''







      UpperCamelCase       =  return_dict if return_dict is not None else self.config.use_return_dict

      UpperCamelCase       =  self.poolformer(
          lowerCamelCase__ ,   output_hidden_states=lowerCamelCase__ ,   return_dict=lowerCamelCase__ ,   )

      UpperCamelCase       =  outputs[0]

      UpperCamelCase       =  self.classifier(self.norm(lowerCamelCase__   ).mean([-2, -1]   )   )

      UpperCamelCase       =  None
      if labels is not None:
         if self.config.problem_type is None:
            if self.num_labels == 1:
               UpperCamelCase       =  '''regression'''
            elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
               UpperCamelCase       =  '''single_label_classification'''
            else:
               UpperCamelCase       =  '''multi_label_classification'''

         if self.config.problem_type == "regression":
            UpperCamelCase       =  MSELoss()
            if self.num_labels == 1:
               UpperCamelCase       =  loss_fct(logits.squeeze() ,   labels.squeeze()   )
            else:
               UpperCamelCase       =  loss_fct(lowerCamelCase__ ,   lowerCamelCase__   )
         elif self.config.problem_type == "single_label_classification":
            UpperCamelCase       =  CrossEntropyLoss()
            UpperCamelCase       =  loss_fct(logits.view(-1 ,   self.num_labels   ) ,   labels.view(-1   )   )
         elif self.config.problem_type == "multi_label_classification":
            UpperCamelCase       =  BCEWithLogitsLoss()
            UpperCamelCase       =  loss_fct(lowerCamelCase__ ,   lowerCamelCase__   )

      if not return_dict:
         UpperCamelCase       =  (logits,) + outputs[2:]
         return ((loss,) + output) if loss is not None else output

      return ImageClassifierOutputWithNoAttention(loss=lowerCamelCase__ ,   logits=lowerCamelCase__ ,   hidden_states=outputs.hidden_states   )







'''simple docstring'''


from typing import Dict, Iterable, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    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

snake_case_ :  Tuple     =					logging.get_logger(__name__)



def  __snake_case     (    _UpperCAmelCase					:       str,      _UpperCAmelCase					:       int,      _UpperCAmelCase					:       Optional[int]):
   return [
       int(1000 * (box[0] / width)),
       int(1000 * (box[1] / height)),
       int(1000 * (box[2] / width)),
       int(1000 * (box[3] / height)),
   ]



def  __snake_case     (    _UpperCAmelCase					:       np.ndarray,      _UpperCAmelCase					:       Optional[str],      _UpperCAmelCase					:       Optional[str]):
   UpperCamelCase       =  to_pil_image(_UpperCAmelCase)
   UpperCamelCase     , UpperCamelCase       =  pil_image.size
   UpperCamelCase       =  pytesseract.image_to_data(_UpperCAmelCase,      lang=_UpperCAmelCase,      output_type='''dict''',      config=_UpperCAmelCase)
   UpperCamelCase     , UpperCamelCase     , UpperCamelCase     , UpperCamelCase     , UpperCamelCase       =  data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height''']

   # filter empty words and corresponding coordinates
   UpperCamelCase       =  [idx for idx, word in enumerate(_UpperCAmelCase) if not word.strip()]
   UpperCamelCase       =  [word for idx, word in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices]
   UpperCamelCase       =  [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices]
   UpperCamelCase       =  [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices]
   UpperCamelCase       =  [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices]
   UpperCamelCase       =  [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices]

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

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

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

   return words, normalized_boxes


class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							['''pixel_values''']







   def __init__(			self ,   lowerCamelCase__ = True ,   lowerCamelCase__ = None ,   lowerCamelCase__ = PILImageResampling.BILINEAR ,   lowerCamelCase__ = True ,   lowerCamelCase__ = 1 / 2_5_5 ,   lowerCamelCase__ = True ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = True ,   lowerCamelCase__ = None ,   lowerCamelCase__ = "" ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      super().__init__(**lowerCamelCase__   )
      UpperCamelCase       =  size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
      UpperCamelCase       =  get_size_dict(lowerCamelCase__   )

      UpperCamelCase       =  do_resize
      UpperCamelCase       =  size
      UpperCamelCase       =  resample
      UpperCamelCase       =  do_rescale
      UpperCamelCase       =  rescale_value
      UpperCamelCase       =  do_normalize
      UpperCamelCase       =  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
      UpperCamelCase       =  image_std if image_std is not None else IMAGENET_STANDARD_STD
      UpperCamelCase       =  apply_ocr
      UpperCamelCase       =  ocr_lang
      UpperCamelCase       =  tesseract_config







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ = PILImageResampling.BILINEAR ,   lowerCamelCase__ = None ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      UpperCamelCase       =  get_size_dict(lowerCamelCase__   )
      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()}'   )
      UpperCamelCase       =  (size['''height'''], size['''width'''])
      return resize(lowerCamelCase__ ,   size=lowerCamelCase__ ,   resample=lowerCamelCase__ ,   data_format=lowerCamelCase__ ,   **lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ = None ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      return rescale(lowerCamelCase__ ,   scale=lowerCamelCase__ ,   data_format=lowerCamelCase__ ,   **lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ = None ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      return normalize(lowerCamelCase__ ,   mean=lowerCamelCase__ ,   std=lowerCamelCase__ ,   data_format=lowerCamelCase__ ,   **lowerCamelCase__   )







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__=None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = None ,   lowerCamelCase__ = ChannelDimension.FIRST ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      UpperCamelCase       =  do_resize if do_resize is not None else self.do_resize
      UpperCamelCase       =  size if size is not None else self.size
      UpperCamelCase       =  get_size_dict(lowerCamelCase__   )
      UpperCamelCase       =  resample if resample is not None else self.resample
      UpperCamelCase       =  do_rescale if do_rescale is not None else self.do_rescale
      UpperCamelCase       =  rescale_factor if rescale_factor is not None else self.rescale_factor
      UpperCamelCase       =  do_normalize if do_normalize is not None else self.do_normalize
      UpperCamelCase       =  image_mean if image_mean is not None else self.image_mean
      UpperCamelCase       =  image_std if image_std is not None else self.image_std
      UpperCamelCase       =  apply_ocr if apply_ocr is not None else self.apply_ocr
      UpperCamelCase       =  ocr_lang if ocr_lang is not None else self.ocr_lang
      UpperCamelCase       =  tesseract_config if tesseract_config is not None else self.tesseract_config

      UpperCamelCase       =  make_list_of_images(lowerCamelCase__   )

      if not valid_images(lowerCamelCase__   ):
         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.'''   )

      if do_rescale and rescale_factor is None:
         raise ValueError('''Rescale factor must be specified if do_rescale is True.'''   )

      if do_normalize and (image_mean is None or image_std is None):
         raise ValueError('''If do_normalize is True, image_mean and image_std must be specified.'''   )

      # All transformations expect numpy arrays.
      UpperCamelCase       =  [to_numpy_array(lowerCamelCase__   ) for image in images]

      # Tesseract OCR to get words + normalized bounding boxes
      if apply_ocr:
         requires_backends(self ,   '''pytesseract'''   )
         UpperCamelCase       =  []
         UpperCamelCase       =  []
         for image in images:
            UpperCamelCase     , UpperCamelCase       =  apply_tesseract(lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   )
            words_batch.append(lowerCamelCase__   )
            boxes_batch.append(lowerCamelCase__   )

      if do_resize:
         UpperCamelCase       =  [self.resize(image=lowerCamelCase__ ,   size=lowerCamelCase__ ,   resample=lowerCamelCase__   ) for image in images]

      if do_rescale:
         UpperCamelCase       =  [self.rescale(image=lowerCamelCase__ ,   scale=lowerCamelCase__   ) for image in images]

      if do_normalize:
         UpperCamelCase       =  [self.normalize(image=lowerCamelCase__ ,   mean=lowerCamelCase__ ,   std=lowerCamelCase__   ) for image in images]

      UpperCamelCase       =  [to_channel_dimension_format(lowerCamelCase__ ,   lowerCamelCase__   ) for image in images]

      UpperCamelCase       =  BatchFeature(data={'''pixel_values''': images} ,   tensor_type=lowerCamelCase__   )

      if apply_ocr:
         UpperCamelCase       =  words_batch
         UpperCamelCase       =  boxes_batch
      return data





