



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


_lowercase  				=    logging.get_logger(__name__)


# General docstring
_lowercase  				=    '''MobileNetV1Config'''

# Base docstring
_lowercase  				=    '''google/mobilenet_v1_1.0_224'''
_lowercase  				=    [1, 10_24, 7, 7]

# Image classification docstring
_lowercase  				=    '''google/mobilenet_v1_1.0_224'''
_lowercase  				=    '''tabby, tabby cat'''


_lowercase  				=    [
    '''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   _A					(UpperCamelCase		:   int   ,      UpperCamelCase		:   Tuple   ,      UpperCamelCase		:   List[Any]=None			)	->Dict:



			'''simple docstring'''







			lowerCamelCase__			:   Union[str, Any]										=		{}

			if isinstance(lowerCAmelCase_   ,      lowerCAmelCase_			):
						lowerCamelCase__			:   Optional[Any]										=		model.mobilenet_va
			else:
						lowerCamelCase__			:   Optional[Any]										=		model

			lowerCamelCase__			:   Any										=		"""MobilenetV1/Conv2d_0/"""
			lowerCamelCase__			:   List[Any]										=		backbone.conv_stem.convolution.weight
			lowerCamelCase__			:   str										=		backbone.conv_stem.normalization.bias
			lowerCamelCase__			:   List[Any]										=		backbone.conv_stem.normalization.weight
			lowerCamelCase__			:   Dict										=		backbone.conv_stem.normalization.running_mean
			lowerCamelCase__			:   Dict										=		backbone.conv_stem.normalization.running_var

			for i in range(13			):
						lowerCamelCase__			:   Dict										=		i + 1
						lowerCamelCase__			:   Any										=		i * 2

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

						lowerCamelCase__			:   List[str]										=		backbone.layer[pt_index + 1]
						lowerCamelCase__			:   Optional[Any]										=		f"MobilenetV1/Conv2d_{tf_index}_pointwise/"
						lowerCamelCase__			:   str										=		pointer.convolution.weight
						lowerCamelCase__			:   Any										=		pointer.normalization.bias
						lowerCamelCase__			:   Union[str, Any]										=		pointer.normalization.weight
						lowerCamelCase__			:   str										=		pointer.normalization.running_mean
						lowerCamelCase__			:   Optional[int]										=		pointer.normalization.running_var

			if isinstance(lowerCAmelCase_   ,      lowerCAmelCase_			):
						lowerCamelCase__			:   Optional[Any]										=		"""MobilenetV1/Logits/Conv2d_1c_1x1/"""
						lowerCamelCase__			:   Dict										=		model.classifier.weight
						lowerCamelCase__			:   str										=		model.classifier.bias

			return tf_to_pt_map






def   _A					(UpperCamelCase		:   Optional[Any]   ,      UpperCamelCase		:   Tuple   ,      UpperCamelCase		:   Optional[int]			)	->str:



			'''simple docstring'''







			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__			:   Tuple										=		tf.train.list_variables(lowerCAmelCase_			)
			lowerCamelCase__			:   List[Any]										=		{}
			for name, shape in init_vars:
						logger.info(f"Loading TF weight {name} with shape {shape}"			)
						lowerCamelCase__			:   List[str]										=		tf.train.load_variable(lowerCAmelCase_   ,      lowerCAmelCase_			)
						lowerCamelCase__			:   Dict										=		array

			# Build TF to PyTorch weights loading map
			lowerCamelCase__			:   Dict										=		_build_tf_to_pytorch_map(lowerCAmelCase_   ,      lowerCAmelCase_   ,      lowerCAmelCase_			)

			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__			:   Any										=		tf_weights[name]

						if "depthwise_weights" in name:
									logger.info("""Transposing depthwise"""			)
									lowerCamelCase__			:   Union[str, Any]										=		np.transpose(lowerCAmelCase_   ,      (2, 3, 0, 1)			)
						elif "weights" in name:
									logger.info("""Transposing"""			)
									if len(pointer.shape			) == 2:  # copying into linear layer
												lowerCamelCase__			:   Any										=		array.squeeze().transpose()
									else:
												lowerCamelCase__			:   List[Any]										=		np.transpose(lowerCAmelCase_   ,      (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__			:   int										=		torch.from_numpy(lowerCAmelCase_			)

						tf_weights.pop(lowerCAmelCase_   ,      lowerCAmelCase_			)
						tf_weights.pop(name + """/RMSProp"""   ,      lowerCAmelCase_			)
						tf_weights.pop(name + """/RMSProp_1"""   ,      lowerCAmelCase_			)
						tf_weights.pop(name + """/ExponentialMovingAverage"""   ,      lowerCAmelCase_			)

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






def   _A					(UpperCamelCase		:   Tuple   ,      UpperCamelCase		:   List[str]			)	->torch.Tensor:



			'''simple docstring'''







			lowerCamelCase__				,lowerCamelCase__			:   Optional[int]										=		features.shape[-2:]
			lowerCamelCase__				,lowerCamelCase__			:   Tuple										=		conv_layer.stride
			lowerCamelCase__				,lowerCamelCase__			:   Union[str, Any]										=		conv_layer.kernel_size

			if in_height % stride_height == 0:
						lowerCamelCase__			:   Union[str, Any]										=		max(kernel_height - stride_height   ,      0			)
			else:
						lowerCamelCase__			:   List[str]										=		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__			:   List[str]										=		max(kernel_width - (in_width % stride_width)   ,      0			)

			lowerCamelCase__			:   List[str]										=		pad_along_width // 2
			lowerCamelCase__			:   Optional[int]										=		pad_along_width - pad_left
			lowerCamelCase__			:   Union[str, Any]										=		pad_along_height // 2
			lowerCamelCase__			:   int										=		pad_along_height - pad_top

			lowerCamelCase__			:   int										=		(pad_left, pad_right, pad_top, pad_bottom)
			return nn.functional.pad(lowerCAmelCase_   ,      lowerCAmelCase_   ,      """constant"""   ,      0.0			)
class 					__A       (			nn.Module   ):





			def __init__(self				,     __magic_name__				,     __magic_name__				,     __magic_name__				,     __magic_name__				,     __magic_name__ = 1				,     __magic_name__ = 1				,     __magic_name__ = False				,     __magic_name__ = True				,     __magic_name__ = True				,     ):
						super().__init__()
						lowerCamelCase__			:   List[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__			:   Optional[Any]										=		0 if config.tf_padding else int((kernel_size - 1) / 2					)

						lowerCamelCase__			:   List[Any]										=		nn.Convad(
						    in_channels=__lowerCamelCase				,     out_channels=__lowerCamelCase				,     kernel_size=__lowerCamelCase				,     stride=__lowerCamelCase				,     padding=__lowerCamelCase				,     groups=__lowerCamelCase				,     bias=__lowerCamelCase				,     padding_mode="""zeros"""				,     )

						if use_normalization:
									lowerCamelCase__			:   Union[str, Any]										=		nn.BatchNormad(
									    num_features=__lowerCamelCase				,     eps=config.layer_norm_eps				,     momentum=0.99_97				,     affine=__lowerCamelCase				,     track_running_stats=__lowerCamelCase				,     )
						else:
									lowerCamelCase__			:   List[str]										=		None

						if use_activation:
									if isinstance(__lowerCamelCase				,     __lowerCamelCase					):
												lowerCamelCase__			:   str										=		ACTaFN[use_activation]
									elif isinstance(config.hidden_act				,     __lowerCamelCase					):
												lowerCamelCase__			:   int										=		ACTaFN[config.hidden_act]
									else:
												lowerCamelCase__			:   Any										=		config.hidden_act
						else:
									lowerCamelCase__			:   int										=		None





			def 							_snake_case     (self				,     __magic_name__					):
						if self.config.tf_padding:
									lowerCamelCase__			:   str										=		apply_tf_padding(__lowerCamelCase				,     self.convolution					)
						lowerCamelCase__			:   List[str]										=		self.convolution(__lowerCamelCase					)
						if self.normalization is not None:
									lowerCamelCase__			:   int										=		self.normalization(__lowerCamelCase					)
						if self.activation is not None:
									lowerCamelCase__			:   Union[str, Any]										=		self.activation(__lowerCamelCase					)
						return features







class 					__A       (			__SCREAMING_SNAKE_CASE   ):
			UpperCamelCase       :str	 =      MobileNetVaConfig
			UpperCamelCase       :Dict	 =      load_tf_weights_in_mobilenet_va
			UpperCamelCase       :List[str]	 =      '''mobilenet_v1'''
			UpperCamelCase       :Optional[Any]	 =      '''pixel_values'''
			UpperCamelCase       :List[Any]	 =      False





			def 							_snake_case     (self				,     __magic_name__					):
						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.BatchNormad					):
									module.bias.data.zero_()
									module.weight.data.fill_(1.0					)







_lowercase  				=    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.
'''

_lowercase  				=    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.'''       ,			__SCREAMING_SNAKE_CASE       ,			)
class 					__A       (			__SCREAMING_SNAKE_CASE   ):





			def __init__(self				,     __magic_name__				,     __magic_name__ = True					):
						super().__init__(__lowerCamelCase					)
						lowerCamelCase__			:   List[Any]										=		config

						lowerCamelCase__			:   Tuple										=		32
						lowerCamelCase__			:   Tuple										=		max(int(depth * config.depth_multiplier					)				,     config.min_depth					)

						lowerCamelCase__			:   Tuple										=		MobileNetVaConvLayer(
						    __lowerCamelCase				,     in_channels=config.num_channels				,     out_channels=__lowerCamelCase				,     kernel_size=3				,     stride=2				,     )

						lowerCamelCase__			:   Union[str, Any]										=		[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

						lowerCamelCase__			:   Union[str, Any]										=		nn.ModuleList()
						for i in range(13					):
									lowerCamelCase__			:   Any										=		out_channels

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

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

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

						lowerCamelCase__			:   Tuple										=		nn.AdaptiveAvgPoolad((1, 1)					) if add_pooling_layer else None

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





			def 							_snake_case     (self				,     __magic_name__					):
						raise NotImplementedError





			@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 							_snake_case     (self				,     __magic_name__ = None				,     __magic_name__ = None				,     __magic_name__ = None				,     ):
						lowerCamelCase__			:   Any										=		(
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						lowerCamelCase__			:   int										=		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__			:   List[Any]										=		self.conv_stem(__lowerCamelCase					)

						lowerCamelCase__			:   List[str]										=		() if output_hidden_states else None

						for i, layer_module in enumerate(self.layer					):
									lowerCamelCase__			:   List[Any]										=		layer_module(__lowerCamelCase					)

									if output_hidden_states:
												lowerCamelCase__			:   Union[str, Any]										=		all_hidden_states + (hidden_states,)

						lowerCamelCase__			:   Dict										=		hidden_states

						if self.pooler is not None:
									lowerCamelCase__			:   Union[str, Any]										=		torch.flatten(self.pooler(__lowerCamelCase					)				,     start_dim=1					)
						else:
									lowerCamelCase__			:   str										=		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=__lowerCamelCase				,     pooler_output=__lowerCamelCase				,     hidden_states=__lowerCamelCase				,     )







@add_start_docstrings(
    '''
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''       ,			__SCREAMING_SNAKE_CASE       ,			)
class 					__A       (			__SCREAMING_SNAKE_CASE   ):





			def __init__(self				,     __magic_name__					):
						super().__init__(__lowerCamelCase					)

						lowerCamelCase__			:   Any										=		config.num_labels
						lowerCamelCase__			:   Dict										=		MobileNetVaModel(__lowerCamelCase					)

						lowerCamelCase__			:   Optional[int]										=		self.mobilenet_va.layer[-1].convolution.out_channels

						# Classifier head
						lowerCamelCase__			:   Optional[Any]										=		nn.Dropout(config.classifier_dropout_prob				,     inplace=__lowerCamelCase					)
						lowerCamelCase__			:   Dict										=		nn.Linear(__lowerCamelCase				,     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 							_snake_case     (self				,     __magic_name__ = None				,     __magic_name__ = None				,     __magic_name__ = None				,     __magic_name__ = None				,     ):
						lowerCamelCase__			:   List[Any]										=		return_dict if return_dict is not None else self.config.use_return_dict

						lowerCamelCase__			:   List[Any]										=		self.mobilenet_va(__lowerCamelCase				,     output_hidden_states=__lowerCamelCase				,     return_dict=__lowerCamelCase					)

						lowerCamelCase__			:   Tuple										=		outputs.pooler_output if return_dict else outputs[1]

						lowerCamelCase__			:   str										=		self.classifier(self.dropout(__lowerCamelCase					)					)

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

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

						if not return_dict:
									lowerCamelCase__			:   List[str]										=		(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"""






# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):
   A__		:	str           =  '''openai/whisper-base'''
   A__		:	List[Any]           =  (
       '''This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the '''
       '''transcribed text.'''
   )
   A__		:	str           =  '''transcriber'''
   A__		:	List[Any]           =  WhisperProcessor
   A__		:	Optional[int]           =  WhisperForConditionalGeneration

   A__		:	List[str]           =  ['''audio''']
   A__		:	Optional[int]           =  ['''text''']



   def    __UpperCAmelCase    (       self    :	Tuple							,       __lowerCamelCase    :	List[Any]				):



     """simple docstring"""
     return self.pre_processor(__lowerCamelCase							,       return_tensors='''pt'''				).input_features



   def    __UpperCAmelCase    (       self    :	Optional[int]							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     return self.model.generate(inputs=__lowerCamelCase				)





   def    __UpperCAmelCase    (       self    :	List[str]							,       __lowerCamelCase    :	int				):



     """simple docstring"""
     return self.pre_processor.batch_decode(__lowerCamelCase							,       skip_special_tokens=__lowerCamelCase				)[0]





