



'''simple docstring'''

import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_A				:    str     						=logging.get_logger(__name__)

_A				:    Optional[int]     						={
    "asapp/sew-tiny-100k": "https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json",
    # See all SEW models at https://huggingface.co/models?filter=sew
}



class 		lowerCamelCase__		(						A     ):




					'''simple docstring'''



					A_						    =						"sew"




					def __init__(  self				:	List[str]     ,  UpperCamelCase_				:	Optional[Any]=32     ,  UpperCamelCase_				:	Optional[int]=768     ,  UpperCamelCase_				:	Union[str, Any]=12     ,  UpperCamelCase_				:	Dict=12     ,  UpperCamelCase_				:	Optional[int]=3072     ,  UpperCamelCase_				:	int=2     ,  UpperCamelCase_				:	str="gelu"     ,  UpperCamelCase_				:	Tuple=0.1     ,  UpperCamelCase_				:	List[str]=0.1     ,  UpperCamelCase_				:	List[str]=0.1     ,  UpperCamelCase_				:	List[Any]=0.0     ,  UpperCamelCase_				:	Union[str, Any]=0.1     ,  UpperCamelCase_				:	List[Any]=0.1     ,  UpperCamelCase_				:	Optional[int]=0.02     ,  UpperCamelCase_				:	List[Any]=1E-5     ,  UpperCamelCase_				:	List[Any]="group"     ,  UpperCamelCase_				:	List[Any]="gelu"     ,  UpperCamelCase_				:	List[Any]=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)     ,  UpperCamelCase_				:	Tuple=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)     ,  UpperCamelCase_				:	List[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)     ,  UpperCamelCase_				:	List[Any]=False     ,  UpperCamelCase_				:	str=128     ,  UpperCamelCase_				:	Union[str, Any]=16     ,  UpperCamelCase_				:	Union[str, Any]=True     ,  UpperCamelCase_				:	Tuple=0.05     ,  UpperCamelCase_				:	Union[str, Any]=10     ,  UpperCamelCase_				:	str=2     ,  UpperCamelCase_				:	int=0.0     ,  UpperCamelCase_				:	int=10     ,  UpperCamelCase_				:	Any=0     ,  UpperCamelCase_				:	Union[str, Any]="mean"     ,  UpperCamelCase_				:	Optional[int]=False     ,  UpperCamelCase_				:	Optional[int]=False     ,  UpperCamelCase_				:	Optional[int]=256     ,  UpperCamelCase_				:	Optional[Any]=0     ,  UpperCamelCase_				:	List[Any]=1     ,  UpperCamelCase_				:	List[Any]=2     ,  **UpperCamelCase_				:	List[str]     ,  )  ->       Union[str, Any]:



						'''simple docstring'''





						super().__init__(**UpperCamelCase_     ,  pad_token_id=UpperCamelCase_     ,  bos_token_id=UpperCamelCase_     ,  eos_token_id=UpperCamelCase_					)
						_lowercase					:       Tuple       =		hidden_size
						_lowercase					:       Tuple       =		feat_extract_norm
						_lowercase					:       Optional[int]       =		feat_extract_activation
						_lowercase					:       Dict       =		list(UpperCamelCase_					)
						_lowercase					:       Optional[Any]       =		list(UpperCamelCase_					)
						_lowercase					:       str       =		list(UpperCamelCase_					)
						_lowercase					:       Union[str, Any]       =		conv_bias
						_lowercase					:       Any       =		num_conv_pos_embeddings
						_lowercase					:       Optional[int]       =		num_conv_pos_embedding_groups
						_lowercase					:       List[str]       =		len(self.conv_dim					)
						_lowercase					:       Optional[Any]       =		num_hidden_layers
						_lowercase					:       Optional[int]       =		intermediate_size
						_lowercase					:       Tuple       =		squeeze_factor
						_lowercase					:       str       =		hidden_act
						_lowercase					:       Any       =		num_attention_heads
						_lowercase					:       int       =		hidden_dropout
						_lowercase					:       List[str]       =		attention_dropout
						_lowercase					:       List[str]       =		activation_dropout
						_lowercase					:       str       =		feat_proj_dropout
						_lowercase					:       Union[str, Any]       =		final_dropout
						_lowercase					:       Dict       =		layerdrop
						_lowercase					:       Any       =		layer_norm_eps
						_lowercase					:       List[str]       =		initializer_range
						_lowercase					:       Any       =		vocab_size

						if (
						    (len(self.conv_stride					) != self.num_feat_extract_layers)
						    or (len(self.conv_kernel					) != self.num_feat_extract_layers)
						    or (len(self.conv_dim					) != self.num_feat_extract_layers)
						):
							raise ValueError(
							    'Configuration for convolutional layers is incorrect.'
							    'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,'
							    F'''but is `len(config.conv_dim) = {len(self.conv_dim					)}`, `len(config.conv_stride)'''
							    F'''= {len(self.conv_stride					)}`, `len(config.conv_kernel) = {len(self.conv_kernel					)}`.'''					)

						# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
						_lowercase					:       Optional[Any]       =		apply_spec_augment
						_lowercase					:       int       =		mask_time_prob
						_lowercase					:       Optional[int]       =		mask_time_length
						_lowercase					:       Tuple       =		mask_time_min_masks
						_lowercase					:       Dict       =		mask_feature_prob
						_lowercase					:       Optional[int]       =		mask_feature_length
						_lowercase					:       List[str]       =		mask_feature_min_masks

						# ctc loss
						_lowercase					:       int       =		ctc_loss_reduction
						_lowercase					:       List[Any]       =		ctc_zero_infinity

						# sequence classification
						_lowercase					:       List[str]       =		use_weighted_layer_sum
						_lowercase					:       List[Any]       =		classifier_proj_size




					@property
					def 						__UpperCAmelCase     (  self				:	Optional[Any]					)  ->       int:



						'''simple docstring'''





						return functools.reduce(operator.mul     ,  self.conv_stride     ,  1					)





'''simple docstring'''

from collections import UserDict
from typing import List, Union

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


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
		from ..tf_utils import stable_softmax

_A				:    Optional[int]     						=logging.get_logger(__name__)



@add_end_docstrings(A     )
class 		lowerCamelCase__      (						A     ):




					'''simple docstring'''



					def __init__(  self				:	Tuple     ,  **UpperCamelCase_				:	List[str]					)  ->       int:



						'''simple docstring'''





						super().__init__(**UpperCamelCase_					)

						requires_backends(self     ,  'vision'					)
						self.check_model_type(
						    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
						    if self.framework == 'tf'
						    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING					)




					def __call__(  self				:	int     ,  UpperCamelCase_				:	Union[str, List[str], "Image", List["Image"]]     ,  **UpperCamelCase_				:	Tuple					)  ->       List[Any]:



						'''simple docstring'''





						return super().__call__(UpperCamelCase_     ,  **UpperCamelCase_					)




					def 						__UpperCAmelCase     (  self				:	List[Any]     ,  **UpperCamelCase_				:	str					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       Optional[int]       =		{}
						if "candidate_labels" in kwargs:
							_lowercase					:       Union[str, Any]       =		kwargs['candidate_labels']
						if "hypothesis_template" in kwargs:
							_lowercase					:       int       =		kwargs['hypothesis_template']

						return preprocess_params, {}, {}




					def 						__UpperCAmelCase     (  self				:	Tuple     ,  UpperCamelCase_				:	Dict     ,  UpperCamelCase_				:	Optional[Any]=None     ,  UpperCamelCase_				:	str="This is a photo of {}."					)  ->       Union[str, Any]:



						'''simple docstring'''





						_lowercase					:       Dict       =		load_image(UpperCamelCase_					)
						_lowercase					:       List[str]       =		self.image_processor(images=[image]     ,  return_tensors=self.framework					)
						_lowercase					:       Optional[Any]       =		candidate_labels
						_lowercase					:       List[Any]       =		[hypothesis_template.format(UpperCamelCase_					) for x in candidate_labels]
						_lowercase					:       Union[str, Any]       =		self.tokenizer(UpperCamelCase_     ,  return_tensors=self.framework     ,  padding=UpperCamelCase_					)
						_lowercase					:       Any       =		[text_inputs]
						return inputs




					def 						__UpperCAmelCase     (  self				:	str     ,  UpperCamelCase_				:	Union[str, Any]					)  ->       Optional[Any]:



						'''simple docstring'''





						_lowercase					:       Optional[Any]       =		model_inputs.pop('candidate_labels'					)
						_lowercase					:       List[str]       =		model_inputs.pop('text_inputs'					)
						if isinstance(text_inputs[0]     ,  UpperCamelCase_					):
							_lowercase					:       Optional[int]       =		text_inputs[0]
						else:
							# Batching case.
							_lowercase					:       List[str]       =		text_inputs[0][0]

						_lowercase					:       Optional[Any]       =		self.model(**UpperCamelCase_     ,  **UpperCamelCase_					)

						_lowercase					:       Optional[Any]       =		{
						    'candidate_labels': candidate_labels,
						    'logits': outputs.logits_per_image,
						}
						return model_outputs




					def 						__UpperCAmelCase     (  self				:	Optional[int]     ,  UpperCamelCase_				:	int					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       Optional[int]       =		model_outputs.pop('candidate_labels'					)
						_lowercase					:       Optional[int]       =		model_outputs['logits'][0]
						if self.framework == "pt":
							_lowercase					:       List[Any]       =		logits.softmax(dim=-1					).squeeze(-1					)
							_lowercase					:       Tuple       =		probs.tolist()
							if not isinstance(UpperCamelCase_     ,  UpperCamelCase_					):
								_lowercase					:       List[Any]       =		[scores]
						elif self.framework == "tf":
							_lowercase					:       Optional[int]       =		stable_softmax(UpperCamelCase_     ,  axis=-1					)
							_lowercase					:       List[Any]       =		probs.numpy().tolist()
						else:
							raise ValueError(F'''Unsupported framework: {self.framework}'''					)

						_lowercase					:       List[Any]       =		[
						    {'score': score, 'label': candidate_label}
						    for score, candidate_label in sorted(zip(UpperCamelCase_     ,  UpperCamelCase_					)     ,  key=lambda UpperCamelCase_					: -x[0]					)
						]
						return result
