'''simple docstring'''






from typing import TYPE_CHECKING

from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
   from PIL import Image







class lowercase_       (		a_			):







   """simple docstring"""

   __lowerCAmelCase         =   "Salesforce/blip-image-captioning-base"
   __lowerCAmelCase         =   (
       "This is a tool that generates a description of an image. It takes an input named `image` which should be the "
       "image to caption, and returns a text that contains the description in English."
   )
   __lowerCAmelCase         =   "image_captioner"
   __lowerCAmelCase         =   AutoModelForVisionaSeq

   __lowerCAmelCase         =   ["image"]
   __lowerCAmelCase         =   ["text"]
   def __init__(      self      :			int, *UpperCamelCase__      :			int, **UpperCamelCase__      :			List[str]     )  ->			Optional[int]:
        requires_backends(self, ['vision']     )
        super().__init__(*lowercase_, **lowercase_     )
   def 	__UpperCAmelCase   (      self      :			List[str], UpperCamelCase__      :			"Image"     )  ->			int:
        return self.pre_processor(images=lowercase_, return_tensors='pt'     )
   def 	__UpperCAmelCase   (      self      :			List[Any], UpperCamelCase__      :			Any     )  ->			Tuple:
        return self.model.generate(**lowercase_     )

   def 	__UpperCAmelCase   (      self      :			Dict, UpperCamelCase__      :			Union[str, Any]     )  ->			Optional[Any]:
        return self.pre_processor.batch_decode(lowercase_, skip_special_tokens=lowercase_     )[0].strip()






"""simple docstring"""





from typing import Optional, Union

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

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, 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_mobilenet_va import MobileNetVaConfig


__UpperCamelCase    : Dict				 =						logging.get_logger(__name__)


# General docstring
__UpperCamelCase    : List[str]				 =						'''MobileNetV1Config'''

# Base docstring
__UpperCamelCase    : Dict				 =						'''google/mobilenet_v1_1.0_224'''
__UpperCamelCase    : Dict				 =						[1, 1_0_2_4, 7, 7]

# Image classification docstring
__UpperCamelCase    : Tuple				 =						'''google/mobilenet_v1_1.0_224'''
__UpperCamelCase    : List[str]				 =						'''tabby, tabby cat'''


__UpperCamelCase    : Optional[int]				 =						[
    '''google/mobilenet_v1_1.0_224''',
    '''google/mobilenet_v1_0.75_192''',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_		,	A_=None					):
	lowerCAmelCase__      :		Union[str, Any]    							=      {}

	if isinstance(A_		,	A_					):
		lowerCAmelCase__      :		List[Any]    							=      model.mobilenet_va
	else:
		lowerCAmelCase__      :		Optional[Any]    							=      model

	lowerCAmelCase__      :		Dict    							=      '''MobilenetV1/Conv2d_0/'''
	lowerCAmelCase__      :		Optional[Any]    							=      backbone.conv_stem.convolution.weight
	lowerCAmelCase__      :		Optional[int]    							=      backbone.conv_stem.normalization.bias
	lowerCAmelCase__      :		Union[str, Any]    							=      backbone.conv_stem.normalization.weight
	lowerCAmelCase__      :		List[str]    							=      backbone.conv_stem.normalization.running_mean
	lowerCAmelCase__      :		List[Any]    							=      backbone.conv_stem.normalization.running_var

	for i in range(13					):
		lowerCAmelCase__      :		str    							=      i + 1
		lowerCAmelCase__      :		Any    							=      i * 2

		lowerCAmelCase__      :		Dict    							=      backbone.layer[pt_index]
		lowerCAmelCase__      :		int    							=      f'MobilenetV1/Conv2d_{tf_index}_depthwise/'
		lowerCAmelCase__      :		Optional[int]    							=      pointer.convolution.weight
		lowerCAmelCase__      :		Dict    							=      pointer.normalization.bias
		lowerCAmelCase__      :		Tuple    							=      pointer.normalization.weight
		lowerCAmelCase__      :		Optional[int]    							=      pointer.normalization.running_mean
		lowerCAmelCase__      :		Optional[int]    							=      pointer.normalization.running_var

		lowerCAmelCase__      :		str    							=      backbone.layer[pt_index + 1]
		lowerCAmelCase__      :		Optional[Any]    							=      f'MobilenetV1/Conv2d_{tf_index}_pointwise/'
		lowerCAmelCase__      :		Optional[int]    							=      pointer.convolution.weight
		lowerCAmelCase__      :		Dict    							=      pointer.normalization.bias
		lowerCAmelCase__      :		Dict    							=      pointer.normalization.weight
		lowerCAmelCase__      :		Tuple    							=      pointer.normalization.running_mean
		lowerCAmelCase__      :		Dict    							=      pointer.normalization.running_var

	if isinstance(A_		,	A_					):
		lowerCAmelCase__      :		Dict    							=      '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
		lowerCAmelCase__      :		str    							=      model.classifier.weight
		lowerCAmelCase__      :		Union[str, Any]    							=      model.classifier.bias

	return tf_to_pt_map

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_		,	A_					):
	try:
		import numpy as np
		import tensorflow as tf
	except ImportError:
		logger.error(
		    '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '''
		    '''https://www.tensorflow.org/install/ for installation instructions.'''					)
		raise

	# Load weights from TF model
	lowerCAmelCase__      :		Optional[Any]    							=      tf.train.list_variables(A_					)
	lowerCAmelCase__      :		List[Any]    							=      {}
	for name, shape in init_vars:
		logger.info(f'Loading TF weight {name} with shape {shape}'					)
		lowerCAmelCase__      :		Tuple    							=      tf.train.load_variable(A_		,	A_					)
		lowerCAmelCase__      :		Optional[int]    							=      array

	# Build TF to PyTorch weights loading map
	lowerCAmelCase__      :		Optional[int]    							=      _build_tf_to_pytorch_map(A_		,	A_		,	A_					)

	for name, pointer in tf_to_pt_map.items():
		logger.info(f'Importing {name}'					)
		if name not in tf_weights:
			logger.info(f'{name} not in tf pre-trained weights, skipping'					)
			continue

		lowerCAmelCase__      :		Optional[Any]    							=      tf_weights[name]

		if "depthwise_weights" in name:
			logger.info('''Transposing depthwise'''					)
			lowerCAmelCase__      :		Union[str, Any]    							=      np.transpose(A_		,	(2, 3, 0, 1)					)
		elif "weights" in name:
			logger.info('''Transposing'''					)
			if len(pointer.shape					) == 2:  # copying into linear layer
				lowerCAmelCase__      :		str    							=      array.squeeze().transpose()
			else:
				lowerCAmelCase__      :		int    							=      np.transpose(A_		,	(3, 2, 0, 1)					)

		if pointer.shape != array.shape:
			raise ValueError(f'Pointer shape {pointer.shape} and array shape {array.shape} mismatched'					)

		logger.info(f'Initialize PyTorch weight {name} {array.shape}'					)
		lowerCAmelCase__      :		Optional[int]    							=      torch.from_numpy(A_					)

		tf_weights.pop(A_		,	A_					)
		tf_weights.pop(name + '''/RMSProp'''		,	A_					)
		tf_weights.pop(name + '''/RMSProp_1'''		,	A_					)
		tf_weights.pop(name + '''/ExponentialMovingAverage'''		,	A_					)

	logger.info(f'Weights not copied to PyTorch model: {", ".join(tf_weights.keys()					)}'					)
	return model

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_					):
	lowerCAmelCase__							,lowerCAmelCase__      :		Any    							=      features.shape[-2:]
	lowerCAmelCase__							,lowerCAmelCase__      :		Any    							=      conv_layer.stride
	lowerCAmelCase__							,lowerCAmelCase__      :		str    							=      conv_layer.kernel_size

	if in_height % stride_height == 0:
		lowerCAmelCase__      :		Dict    							=      max(kernel_height - stride_height		,	0					)
	else:
		lowerCAmelCase__      :		List[Any]    							=      max(kernel_height - (in_height % stride_height)		,	0					)

	if in_width % stride_width == 0:
		lowerCAmelCase__      :		Optional[int]    							=      max(kernel_width - stride_width		,	0					)
	else:
		lowerCAmelCase__      :		Dict    							=      max(kernel_width - (in_width % stride_width)		,	0					)

	lowerCAmelCase__      :		Optional[Any]    							=      pad_along_width // 2
	lowerCAmelCase__      :		Dict    							=      pad_along_width - pad_left
	lowerCAmelCase__      :		Optional[Any]    							=      pad_along_height // 2
	lowerCAmelCase__      :		Union[str, Any]    							=      pad_along_height - pad_top

	lowerCAmelCase__      :		Any    							=      (pad_left, pad_right, pad_top, pad_bottom)
	return nn.functional.pad(A_		,	A_		,	'''constant'''		,	0.0					)







class 							SCREAMING_SNAKE_CASE   (						nn.Module			):






					"""simple docstring"""



					def __init__(			self     :							List[str]  ,lowercase_     :							MobileNetVaConfig  ,lowercase_     :							int  ,lowercase_     :							int  ,lowercase_     :							int  ,lowercase_     :							Optional[int] = 1  ,lowercase_     :							Optional[int] = 1  ,lowercase_     :							bool = False  ,lowercase_     :							Optional[bool] = True  ,lowercase_     :							Optional[bool or str] = True  ,):
						super().__init__()
						lowerCAmelCase__      :		Optional[Any]    							=      config

						if in_channels % groups != 0:
							raise ValueError(F'Input channels ({in_channels}) are not divisible by {groups} groups.'						)
						if out_channels % groups != 0:
							raise ValueError(F'Output channels ({out_channels}) are not divisible by {groups} groups.'						)

						lowerCAmelCase__      :		List[str]    							=      0 if config.tf_padding else int((kernel_size - 1) / 2						)

						lowerCAmelCase__      :		str    							=      nn.Convad(
						    in_channels=lowercase_  ,out_channels=lowercase_  ,kernel_size=lowercase_  ,stride=lowercase_  ,padding=lowercase_  ,groups=lowercase_  ,bias=lowercase_  ,padding_mode='''zeros'''  ,)

						if use_normalization:
							lowerCAmelCase__      :		Optional[Any]    							=      nn.BatchNormad(
							    num_features=lowercase_  ,eps=config.layer_norm_eps  ,momentum=0.9997  ,affine=lowercase_  ,track_running_stats=lowercase_  ,)
						else:
							lowerCAmelCase__      :		int    							=      None

						if use_activation:
							if isinstance(lowercase_  ,lowercase_						):
								lowerCAmelCase__      :		Dict    							=      ACTaFN[use_activation]
							elif isinstance(config.hidden_act  ,lowercase_						):
								lowerCAmelCase__      :		Tuple    							=      ACTaFN[config.hidden_act]
							else:
								lowerCAmelCase__      :		Dict    							=      config.hidden_act
						else:
							lowerCAmelCase__      :		List[Any]    							=      None







					def 			__lowerCAmelCase					(			self     :							Dict  ,lowercase_     :							torch.Tensor						):
						if self.config.tf_padding:
							lowerCAmelCase__      :		Optional[Any]    							=      apply_tf_padding(lowercase_  ,self.convolution						)
						lowerCAmelCase__      :		Optional[Any]    							=      self.convolution(lowercase_						)
						if self.normalization is not None:
							lowerCAmelCase__      :		Optional[Any]    							=      self.normalization(lowercase_						)
						if self.activation is not None:
							lowerCAmelCase__      :		Any    							=      self.activation(lowercase_						)
						return features







class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					lowercase__												=			MobileNetVaConfig
					lowercase__												=			load_tf_weights_in_mobilenet_va
					lowercase__												=			"mobilenet_v1"
					lowercase__												=			"pixel_values"
					lowercase__												=			False







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]  ,lowercase_     :							Union[nn.Linear, nn.Convad]						):
						if isinstance(lowercase_  ,(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(lowercase_  ,nn.BatchNormad						):
							module.bias.data.zero_()
							module.weight.data.fill_(1.0						)

__UpperCamelCase    : str				 =						R'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

__UpperCamelCase    : List[str]				 =						R'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`MobileNetV1ImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''







@add_start_docstrings(
    "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top."       ,				a_       ,				)
class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					def __init__(			self     :							int  ,lowercase_     :							MobileNetVaConfig  ,lowercase_     :							bool = True						):
						super().__init__(lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      config

						lowerCAmelCase__      :		int    							=      3_2
						lowerCAmelCase__      :		List[Any]    							=      max(int(depth * config.depth_multiplier						)  ,config.min_depth						)

						lowerCAmelCase__      :		List[str]    							=      MobileNetVaConvLayer(
						    lowercase_  ,in_channels=config.num_channels  ,out_channels=lowercase_  ,kernel_size=3  ,stride=2  ,)

						lowerCAmelCase__      :		List[str]    							=      [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

						lowerCAmelCase__      :		str    							=      nn.ModuleList()
						for i in range(1_3						):
							lowerCAmelCase__      :		Dict    							=      out_channels

							if strides[i] == 2 or i == 0:
								depth *= 2
								lowerCAmelCase__      :		Dict    							=      max(int(depth * config.depth_multiplier						)  ,config.min_depth						)

							self.layer.append(
							    MobileNetVaConvLayer(
							        lowercase_  ,in_channels=lowercase_  ,out_channels=lowercase_  ,kernel_size=3  ,stride=strides[i]  ,groups=lowercase_  ,)						)

							self.layer.append(
							    MobileNetVaConvLayer(
							        lowercase_  ,in_channels=lowercase_  ,out_channels=lowercase_  ,kernel_size=1  ,)						)

						lowerCAmelCase__      :		Any    							=      nn.AdaptiveAvgPoolad((1, 1)						) if add_pooling_layer else None

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







					def 			__lowerCAmelCase					(			self     :							List[str]  ,lowercase_     :							str						):
						raise NotImplementedError







					@add_start_docstrings_to_model_forward(lowercase_						)
					@add_code_sample_docstrings(
					    checkpoint=_CHECKPOINT_FOR_DOC  ,output_type=lowercase_  ,config_class=_CONFIG_FOR_DOC  ,modality='''vision'''  ,expected_output=_EXPECTED_OUTPUT_SHAPE  ,)
					def 			__lowerCAmelCase					(			self     :							Tuple  ,lowercase_     :							Optional[torch.Tensor] = None  ,lowercase_     :							Optional[bool] = None  ,lowercase_     :							Optional[bool] = None  ,):
						lowerCAmelCase__      :		Dict    							=      (
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						lowerCAmelCase__      :		Optional[Any]    							=      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'''						)

						lowerCAmelCase__      :		Dict    							=      self.conv_stem(lowercase_						)

						lowerCAmelCase__      :		Union[str, Any]    							=      () if output_hidden_states else None

						for i, layer_module in enumerate(self.layer						):
							lowerCAmelCase__      :		Union[str, Any]    							=      layer_module(lowercase_						)

							if output_hidden_states:
								lowerCAmelCase__      :		Optional[int]    							=      all_hidden_states + (hidden_states,)

						lowerCAmelCase__      :		Any    							=      hidden_states

						if self.pooler is not None:
							lowerCAmelCase__      :		Any    							=      torch.flatten(self.pooler(lowercase_						)  ,start_dim=1						)
						else:
							lowerCAmelCase__      :		List[Any]    							=      None

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

						return BaseModelOutputWithPoolingAndNoAttention(
						    last_hidden_state=lowercase_  ,pooler_output=lowercase_  ,hidden_states=lowercase_  ,)







@add_start_docstrings(
    "\n    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "       ,				a_       ,				)
class 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					def __init__(			self     :							List[str]  ,lowercase_     :							MobileNetVaConfig						):
						super().__init__(lowercase_						)

						lowerCAmelCase__      :		Dict    							=      config.num_labels
						lowerCAmelCase__      :		Optional[int]    							=      MobileNetVaModel(lowercase_						)

						lowerCAmelCase__      :		Union[str, Any]    							=      self.mobilenet_va.layer[-1].convolution.out_channels

						# Classifier head
						lowerCAmelCase__      :		Optional[Any]    							=      nn.Dropout(config.classifier_dropout_prob  ,inplace=lowercase_						)
						lowerCAmelCase__      :		int    							=      nn.Linear(lowercase_  ,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(lowercase_						)
					@add_code_sample_docstrings(
					    checkpoint=_IMAGE_CLASS_CHECKPOINT  ,output_type=lowercase_  ,config_class=_CONFIG_FOR_DOC  ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT  ,)
					def 			__lowerCAmelCase					(			self     :							Dict  ,lowercase_     :							Optional[torch.Tensor] = None  ,lowercase_     :							Optional[bool] = None  ,lowercase_     :							Optional[torch.Tensor] = None  ,lowercase_     :							Optional[bool] = None  ,):
						lowerCAmelCase__      :		List[Any]    							=      return_dict if return_dict is not None else self.config.use_return_dict

						lowerCAmelCase__      :		Optional[Any]    							=      self.mobilenet_va(lowercase_  ,output_hidden_states=lowercase_  ,return_dict=lowercase_						)

						lowerCAmelCase__      :		Dict    							=      outputs.pooler_output if return_dict else outputs[1]

						lowerCAmelCase__      :		int    							=      self.classifier(self.dropout(lowercase_						)						)

						lowerCAmelCase__      :		Optional[Any]    							=      None
						if labels is not None:
							if self.config.problem_type is None:
								if self.num_labels == 1:
									lowerCAmelCase__      :		List[Any]    							=      '''regression'''
								elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
									lowerCAmelCase__      :		List[Any]    							=      '''single_label_classification'''
								else:
									lowerCAmelCase__      :		Union[str, Any]    							=      '''multi_label_classification'''

							if self.config.problem_type == "regression":
								lowerCAmelCase__      :		Tuple    							=      MSELoss()
								if self.num_labels == 1:
									lowerCAmelCase__      :		Any    							=      loss_fct(logits.squeeze()  ,labels.squeeze()						)
								else:
									lowerCAmelCase__      :		Optional[Any]    							=      loss_fct(lowercase_  ,lowercase_						)
							elif self.config.problem_type == "single_label_classification":
								lowerCAmelCase__      :		Dict    							=      CrossEntropyLoss()
								lowerCAmelCase__      :		Dict    							=      loss_fct(logits.view(-1  ,self.num_labels						)  ,labels.view(-1						)						)
							elif self.config.problem_type == "multi_label_classification":
								lowerCAmelCase__      :		int    							=      BCEWithLogitsLoss()
								lowerCAmelCase__      :		int    							=      loss_fct(lowercase_  ,lowercase_						)

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

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




