



"""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


snake_case   					=				logging.get_logger(__name__)


# General docstring
snake_case   					=				'''MobileNetV1Config'''

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

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


snake_case   					=				[
    '''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 			snake_case		(		lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_=None	)						->				Dict:
  _snake_case   	=      {}

  if isinstance(lowerCAmelCase_  ,						lowerCAmelCase_	):
    _snake_case   	=      model.mobilenet_va
  else:
    _snake_case   	=      model

  _snake_case   	=      '''MobilenetV1/Conv2d_0/'''
  _snake_case   	=      backbone.conv_stem.convolution.weight
  _snake_case   	=      backbone.conv_stem.normalization.bias
  _snake_case   	=      backbone.conv_stem.normalization.weight
  _snake_case   	=      backbone.conv_stem.normalization.running_mean
  _snake_case   	=      backbone.conv_stem.normalization.running_var

  for i in range(13	):
    _snake_case   	=      i + 1
    _snake_case   	=      i * 2

    _snake_case   	=      backbone.layer[pt_index]
    _snake_case   	=      f"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
    _snake_case   	=      pointer.convolution.weight
    _snake_case   	=      pointer.normalization.bias
    _snake_case   	=      pointer.normalization.weight
    _snake_case   	=      pointer.normalization.running_mean
    _snake_case   	=      pointer.normalization.running_var

    _snake_case   	=      backbone.layer[pt_index + 1]
    _snake_case   	=      f"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
    _snake_case   	=      pointer.convolution.weight
    _snake_case   	=      pointer.normalization.bias
    _snake_case   	=      pointer.normalization.weight
    _snake_case   	=      pointer.normalization.running_mean
    _snake_case   	=      pointer.normalization.running_var

  if isinstance(lowerCAmelCase_  ,						lowerCAmelCase_	):
    _snake_case   	=      '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
    _snake_case   	=      model.classifier.weight
    _snake_case   	=      model.classifier.bias

  return tf_to_pt_map




def 			snake_case		(		lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_	)						->				str:
  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
  _snake_case   	=      tf.train.list_variables(lowerCAmelCase_	)
  _snake_case   	=      {}
  for name, shape in init_vars:
    logger.info(f"""Loading TF weight {name} with shape {shape}"""	)
    _snake_case   	=      tf.train.load_variable(lowerCAmelCase_  ,						lowerCAmelCase_	)
    _snake_case   	=      array

  # Build TF to PyTorch weights loading map
  _snake_case   	=      _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

    _snake_case   	=      tf_weights[name]

    if "depthwise_weights" in name:
      logger.info('''Transposing depthwise'''	)
      _snake_case   	=      np.transpose(lowerCAmelCase_  ,						(2, 3, 0, 1)	)
    elif "weights" in name:
      logger.info('''Transposing'''	)
      if len(pointer.shape	) == 2:  # copying into linear layer
        _snake_case   	=      array.squeeze().transpose()
      else:
        _snake_case   	=      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}"""	)
    _snake_case   	=      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 			snake_case		(		lowerCAmelCase_  ,						lowerCAmelCase_	)						->				torch.Tensor:
  _snake_case	,     _snake_case   	=      features.shape[-2:]
  _snake_case	,     _snake_case   	=      conv_layer.stride
  _snake_case	,     _snake_case   	=      conv_layer.kernel_size

  if in_height % stride_height == 0:
    _snake_case   	=      max(kernel_height - stride_height  ,						0	)
  else:
    _snake_case   	=      max(kernel_height - (in_height % stride_height)  ,						0	)

  if in_width % stride_width == 0:
    _snake_case   	=      max(kernel_width - stride_width  ,						0	)
  else:
    _snake_case   	=      max(kernel_width - (in_width % stride_width)  ,						0	)

  _snake_case   	=      pad_along_width // 2
  _snake_case   	=      pad_along_width - pad_left
  _snake_case   	=      pad_along_height // 2
  _snake_case   	=      pad_along_height - pad_top

  _snake_case   	=      (pad_left, pad_right, pad_top, pad_bottom)
  return nn.functional.pad(lowerCAmelCase_  ,						lowerCAmelCase_  ,						'''constant'''  ,						0.0	)



class     UpperCAmelCase    (	nn.Module  ):



   def __init__(       self    :	int							,       __lowerCamelCase    :	MobileNetVaConfig							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	int							,       __lowerCamelCase    :	Optional[int] = 1							,       __lowerCamelCase    :	Optional[int] = 1							,       __lowerCamelCase    :	bool = False							,       __lowerCamelCase    :	Optional[bool] = True							,       __lowerCamelCase    :	Optional[bool or str] = True							,       ):



     """simple docstring"""
     super().__init__()
     _snake_case   	=      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."""				)

     _snake_case   	=      0 if config.tf_padding else int((kernel_size - 1) / 2				)

     _snake_case   	=      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:
       _snake_case   	=      nn.BatchNormad(
           num_features=__lowerCamelCase							,       eps=config.layer_norm_eps							,       momentum=0.9_9_9_7							,       affine=__lowerCamelCase							,       track_running_stats=__lowerCamelCase							,       )
     else:
       _snake_case   	=      None

     if use_activation:
       if isinstance(__lowerCamelCase							,       __lowerCamelCase				):
         _snake_case   	=      ACTaFN[use_activation]
       elif isinstance(config.hidden_act							,       __lowerCamelCase				):
         _snake_case   	=      ACTaFN[config.hidden_act]
       else:
         _snake_case   	=      config.hidden_act
     else:
       _snake_case   	=      None





   def    __UpperCAmelCase    (       self    :	List[str]							,       __lowerCamelCase    :	torch.Tensor				):



     """simple docstring"""
     if self.config.tf_padding:
       _snake_case   	=      apply_tf_padding(__lowerCamelCase							,       self.convolution				)
     _snake_case   	=      self.convolution(__lowerCamelCase				)
     if self.normalization is not None:
       _snake_case   	=      self.normalization(__lowerCamelCase				)
     if self.activation is not None:
       _snake_case   	=      self.activation(__lowerCamelCase				)
     return features



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



   def    __UpperCAmelCase    (       self    :	int							,       __lowerCamelCase    :	Union[nn.Linear, nn.Convad]				):



     """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.BatchNormad				):
       module.bias.data.zero_()
       module.weight.data.fill_(1.0				)

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

snake_case   					=				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     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):



   def __init__(       self    :	Union[str, Any]							,       __lowerCamelCase    :	MobileNetVaConfig							,       __lowerCamelCase    :	bool = True				):



     """simple docstring"""
     super().__init__(__lowerCamelCase				)
     _snake_case   	=      config

     _snake_case   	=      3_2
     _snake_case   	=      max(int(depth * config.depth_multiplier				)							,       config.min_depth				)

     _snake_case   	=      MobileNetVaConvLayer(
         __lowerCamelCase							,       in_channels=config.num_channels							,       out_channels=__lowerCamelCase							,       kernel_size=3							,       stride=2							,       )

     _snake_case   	=      [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

     _snake_case   	=      nn.ModuleList()
     for i in range(1_3				):
       _snake_case   	=      out_channels

       if strides[i] == 2 or i == 0:
         depth *= 2
         _snake_case   	=      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							,       )				)

     _snake_case   	=      nn.AdaptiveAvgPoolad((1, 1)				) if add_pooling_layer else None

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



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



     """simple docstring"""
     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    __UpperCAmelCase    (       self    :	Dict							,       __lowerCamelCase    :	Optional[torch.Tensor] = None							,       __lowerCamelCase    :	Optional[bool] = None							,       __lowerCamelCase    :	Optional[bool] = None							,       ):



     """simple docstring"""
     _snake_case   	=      (
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )
     _snake_case   	=      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'''				)

     _snake_case   	=      self.conv_stem(__lowerCamelCase				)

     _snake_case   	=      () if output_hidden_states else None

     for i, layer_module in enumerate(self.layer				):
       _snake_case   	=      layer_module(__lowerCamelCase				)

       if output_hidden_states:
         _snake_case   	=      all_hidden_states + (hidden_states,)

     _snake_case   	=      hidden_states

     if self.pooler is not None:
       _snake_case   	=      torch.flatten(self.pooler(__lowerCamelCase				)							,       start_dim=1				)
     else:
       _snake_case   	=      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     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):



   def __init__(       self    :	int							,       __lowerCamelCase    :	MobileNetVaConfig				):



     """simple docstring"""
     super().__init__(__lowerCamelCase				)

     _snake_case   	=      config.num_labels
     _snake_case   	=      MobileNetVaModel(__lowerCamelCase				)

     _snake_case   	=      self.mobilenet_va.layer[-1].convolution.out_channels

     # Classifier head
     _snake_case   	=      nn.Dropout(config.classifier_dropout_prob							,       inplace=__lowerCamelCase				)
     _snake_case   	=      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    __UpperCAmelCase    (       self    :	Dict							,       __lowerCamelCase    :	Optional[torch.Tensor] = None							,       __lowerCamelCase    :	Optional[bool] = None							,       __lowerCamelCase    :	Optional[torch.Tensor] = None							,       __lowerCamelCase    :	Optional[bool] = None							,       ):



     """simple docstring"""
     _snake_case   	=      return_dict if return_dict is not None else self.config.use_return_dict

     _snake_case   	=      self.mobilenet_va(__lowerCamelCase							,       output_hidden_states=__lowerCamelCase							,       return_dict=__lowerCamelCase				)

     _snake_case   	=      outputs.pooler_output if return_dict else outputs[1]

     _snake_case   	=      self.classifier(self.dropout(__lowerCamelCase				)				)

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

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

     if not return_dict:
       _snake_case   	=      (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]





