

from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('3.8'):
					import importlib_metadata
else:
					import importlib.metadata as importlib_metadata


SCREAMING_SNAKE_CASE_            =			''


if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'):

					class 			a					(		tr.AbstractTransform			):


											def __init__(    self  ,   A_ = " "		):







															'''simple docstring'''


															_UpperCAmelCase    :						int							=      sentence_delimiter


											def     _UpperCAmelCase			(    self  ,   A_		):







															'''simple docstring'''


															return list(A_		)





											def     _UpperCAmelCase			(    self  ,   A_		):







															'''simple docstring'''


															_UpperCAmelCase    :						Tuple							=      []
															for sent_idx, sentence in enumerate(A_		):
																			chars.extend(self.process_string(A_		)		)
																			if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(A_		) - 1:
																							chars.append(self.sentence_delimiter		)
															return chars







					SCREAMING_SNAKE_CASE_            =			tr.Compose(
					    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
					)
else:
					SCREAMING_SNAKE_CASE_            =			tr.Compose(
					    [
					        tr.RemoveMultipleSpaces(),
					        tr.Strip(),
					        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
					        tr.ReduceToListOfListOfChars(),
					    ]
					)


SCREAMING_SNAKE_CASE_            =			'\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'

SCREAMING_SNAKE_CASE_            =			'\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n'

SCREAMING_SNAKE_CASE_            =			'\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character error rate\n\nExamples:\n\n    >>> predictions = ["this is the prediction", "there is an other sample"]\n    >>> references = ["this is the reference", "there is another one"]\n    >>> cer = datasets.load_metric("cer")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n'

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,	_KWARGS_DESCRIPTION			)
class 			a					(		datasets.Metric			):


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return datasets.MetricInfo(
										    description=_DESCRIPTION  ,   citation=_CITATION  ,   inputs_description=_KWARGS_DESCRIPTION  ,   features=datasets.Features(
										        {
										            "predictions": datasets.Value("string"  ,   id="sequence"		),
										            "references": datasets.Value("string"  ,   id="sequence"		),
										        }		)  ,   codebase_urls=["https://github.com/jitsi/jiwer/"]  ,   reference_urls=[
										        "https://en.wikipedia.org/wiki/Word_error_rate",
										        "https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates",
										    ]  ,   )





						def     _UpperCAmelCase			(    self  ,   A_  ,   A_  ,   A_=False		):







										'''simple docstring'''


										if concatenate_texts:
														return jiwer.compute_measures(
														    A_  ,   A_  ,   truth_transform=A_  ,   hypothesis_transform=A_  ,   )["wer"]

										_UpperCAmelCase    :						Union[str, Any]							=      0
										_UpperCAmelCase    :						Union[str, Any]							=      0
										for prediction, reference in zip(A_  ,   A_		):
														_UpperCAmelCase    :						Optional[Any]							=      jiwer.compute_measures(
														    A_  ,   A_  ,   truth_transform=A_  ,   hypothesis_transform=A_  ,   )
														incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
														total += measures["substitutions"] + measures["deletions"] + measures["hits"]

										return incorrect / total





from typing import Optional

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

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


SCREAMING_SNAKE_CASE_            = logging.get_logger(__name__)

# General docstring
SCREAMING_SNAKE_CASE_            = 'ResNetConfig'

# Base docstring
SCREAMING_SNAKE_CASE_            = 'microsoft/resnet-50'
SCREAMING_SNAKE_CASE_            = [1, 2048, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE_            = 'microsoft/resnet-50'
SCREAMING_SNAKE_CASE_            = 'tiger cat'

SCREAMING_SNAKE_CASE_            = [
    'microsoft/resnet-50',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]

class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 3  ,   A_ = 1  ,   A_ = "relu"		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Union[str, Any]							=      nn.Convad(
										    A_  ,   A_  ,   kernel_size=A_  ,   stride=A_  ,   padding=kernel_size // 2  ,   bias=A_		)
										_UpperCAmelCase    :						List[Any]							=      nn.BatchNormad(A_		)
										_UpperCAmelCase    :						Union[str, Any]							=      ACTaFN[activation] if activation is not None else nn.Identity()





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      self.convolution(A_		)
										_UpperCAmelCase    :						Optional[int]							=      self.normalization(A_		)
										_UpperCAmelCase    :						Optional[Any]							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Any							=      ResNetConvLayer(
										    config.num_channels  ,   config.embedding_size  ,   kernel_size=7  ,   stride=2  ,   activation=config.hidden_act		)
										_UpperCAmelCase    :						List[str]							=      nn.MaxPoolad(kernel_size=3  ,   stride=2  ,   padding=1		)
										_UpperCAmelCase    :						List[Any]							=      config.num_channels





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						int							=      pixel_values.shape[1]
										if num_channels != self.num_channels:
														raise ValueError(
														    "Make sure that the channel dimension of the pixel values match with the one set in the configuration."		)
										_UpperCAmelCase    :						int							=      self.embedder(A_		)
										_UpperCAmelCase    :						int							=      self.pooler(A_		)
										return embedding







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 2		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Union[str, Any]							=      nn.Convad(A_  ,   A_  ,   kernel_size=1  ,   stride=A_  ,   bias=A_		)
										_UpperCAmelCase    :						Optional[int]							=      nn.BatchNormad(A_		)





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						str							=      self.convolution(A_		)
										_UpperCAmelCase    :						List[str]							=      self.normalization(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 1  ,   A_ = "relu"		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Optional[int]							=      in_channels != out_channels or stride != 1
										_UpperCAmelCase    :						Dict							=      (
										    ResNetShortCut(A_  ,   A_  ,   stride=A_		) if should_apply_shortcut else nn.Identity()
										)
										_UpperCAmelCase    :						int							=      nn.Sequential(
										    ResNetConvLayer(A_  ,   A_  ,   stride=A_		)  ,   ResNetConvLayer(A_  ,   A_  ,   activation=A_		)  ,   )
										_UpperCAmelCase    :						Dict							=      ACTaFN[activation]





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      hidden_state
										_UpperCAmelCase    :						Any							=      self.layer(A_		)
										_UpperCAmelCase    :						Optional[int]							=      self.shortcut(A_		)
										hidden_state += residual
										_UpperCAmelCase    :						Optional[int]							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 1  ,   A_ = "relu"  ,   A_ = 4		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Optional[Any]							=      in_channels != out_channels or stride != 1
										_UpperCAmelCase    :						Optional[int]							=      out_channels // reduction
										_UpperCAmelCase    :						List[str]							=      (
										    ResNetShortCut(A_  ,   A_  ,   stride=A_		) if should_apply_shortcut else nn.Identity()
										)
										_UpperCAmelCase    :						Dict							=      nn.Sequential(
										    ResNetConvLayer(A_  ,   A_  ,   kernel_size=1		)  ,   ResNetConvLayer(A_  ,   A_  ,   stride=A_		)  ,   ResNetConvLayer(A_  ,   A_  ,   kernel_size=1  ,   activation=A_		)  ,   )
										_UpperCAmelCase    :						List[str]							=      ACTaFN[activation]





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      hidden_state
										_UpperCAmelCase    :						List[str]							=      self.layer(A_		)
										_UpperCAmelCase    :						List[str]							=      self.shortcut(A_		)
										hidden_state += residual
										_UpperCAmelCase    :						Dict							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_  ,   A_ = 2  ,   A_ = 2  ,   ):







										'''simple docstring'''


										super().__init__()

										_UpperCAmelCase    :						Any							=      ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

										_UpperCAmelCase    :						Optional[Any]							=      nn.Sequential(
										    # downsampling is done in the first layer with stride of 2
										    layer(A_  ,   A_  ,   stride=A_  ,   activation=config.hidden_act		)  ,   *[layer(A_  ,   A_  ,   activation=config.hidden_act		) for _ in range(depth - 1		)]  ,   )





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      input
										for layer in self.layers:
														_UpperCAmelCase    :						Optional[Any]							=      layer(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Any							=      nn.ModuleList([]		)
										# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
										self.stages.append(
										    ResNetStage(
										        A_  ,   config.embedding_size  ,   config.hidden_sizes[0]  ,   stride=2 if config.downsample_in_first_stage else 1  ,   depth=config.depths[0]  ,   )		)
										_UpperCAmelCase    :						Union[str, Any]							=      zip(config.hidden_sizes  ,   config.hidden_sizes[1:]		)
										for (in_channels, out_channels), depth in zip(A_  ,   config.depths[1:]		):
														self.stages.append(ResNetStage(A_  ,   A_  ,   A_  ,   depth=A_		)		)





						def     _UpperCAmelCase			(    self  ,   A_  ,   A_ = False  ,   A_ = True		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      () if output_hidden_states else None

										for stage_module in self.stages:
														if output_hidden_states:
																		_UpperCAmelCase    :						Dict							=      hidden_states + (hidden_state,)

														_UpperCAmelCase    :						str							=      stage_module(A_		)

										if output_hidden_states:
														_UpperCAmelCase    :						int							=      hidden_states + (hidden_state,)

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

										return BaseModelOutputWithNoAttention(
										    last_hidden_state=A_  ,   hidden_states=A_  ,   )







class 			a					(		UpperCAmelCase			):
						_lowercase        =     ResNetConfig
						_lowercase        =     "resnet"
						_lowercase        =     "pixel_values"
						_lowercase        =     True


						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										if isinstance(A_  ,   nn.Convad		):
														nn.init.kaiming_normal_(module.weight  ,   mode="fan_out"  ,   nonlinearity="relu"		)
										elif isinstance(A_  ,   (nn.BatchNormad, nn.GroupNorm)		):
														nn.init.constant_(module.weight  ,   1		)
														nn.init.constant_(module.bias  ,   0		)





						def     _UpperCAmelCase			(    self  ,   A_  ,   A_=False		):







										'''simple docstring'''


										if isinstance(A_  ,   A_		):
														_UpperCAmelCase    :						Optional[Any]							=      value







SCREAMING_SNAKE_CASE_            = R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    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 ([`ResNetConfig`]): 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'

SCREAMING_SNAKE_CASE_            = 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            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'

@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."							,	UpperCAmelCase							,	)
class 			a					(		UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase    :						List[str]							=      config
										_UpperCAmelCase    :						Any							=      ResNetEmbeddings(A_		)
										_UpperCAmelCase    :						str							=      ResNetEncoder(A_		)
										_UpperCAmelCase    :						Any							=      nn.AdaptiveAvgPoolad((1, 1)		)
										# Initialize weights and apply final processing
										self.post_init()





						@add_start_docstrings_to_model_forward(A_		)
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC  ,   output_type=A_  ,   config_class=_CONFIG_FOR_DOC  ,   modality="vision"  ,   expected_output=_EXPECTED_OUTPUT_SHAPE  ,   )
						def     _UpperCAmelCase			(    self  ,   A_  ,   A_ = None  ,   A_ = None		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										_UpperCAmelCase    :						List[str]							=      return_dict if return_dict is not None else self.config.use_return_dict

										_UpperCAmelCase    :						List[Any]							=      self.embedder(A_		)

										_UpperCAmelCase    :						str							=      self.encoder(
										    A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						List[Any]							=      encoder_outputs[0]

										_UpperCAmelCase    :						int							=      self.pooler(A_		)

										if not return_dict:
														return (last_hidden_state, pooled_output) + encoder_outputs[1:]

										return BaseModelOutputWithPoolingAndNoAttention(
										    last_hidden_state=A_  ,   pooler_output=A_  ,   hidden_states=encoder_outputs.hidden_states  ,   )







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


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase    :						Optional[int]							=      config.num_labels
										_UpperCAmelCase    :						str							=      ResNetModel(A_		)
										# classification head
										_UpperCAmelCase    :						int							=      nn.Sequential(
										    nn.Flatten()  ,   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(A_		)
						@add_code_sample_docstrings(
						    checkpoint=_IMAGE_CLASS_CHECKPOINT  ,   output_type=A_  ,   config_class=_CONFIG_FOR_DOC  ,   expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT  ,   )
						def     _UpperCAmelCase			(    self  ,   A_ = None  ,   A_ = None  ,   A_ = None  ,   A_ = None  ,   ):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      return_dict if return_dict is not None else self.config.use_return_dict

										_UpperCAmelCase    :						Tuple							=      self.resnet(A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						Optional[int]							=      outputs.pooler_output if return_dict else outputs[1]

										_UpperCAmelCase    :						int							=      self.classifier(A_		)

										_UpperCAmelCase    :						Dict							=      None

										if labels is not None:
														if self.config.problem_type is None:
																		if self.num_labels == 1:
																						_UpperCAmelCase    :						Optional[Any]							=      "regression"
																		elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																						_UpperCAmelCase    :						Optional[Any]							=      "single_label_classification"
																		else:
																						_UpperCAmelCase    :						Any							=      "multi_label_classification"
														if self.config.problem_type == "regression":
																		_UpperCAmelCase    :						str							=      MSELoss()
																		if self.num_labels == 1:
																						_UpperCAmelCase    :						Any							=      loss_fct(logits.squeeze()  ,   labels.squeeze()		)
																		else:
																						_UpperCAmelCase    :						Optional[int]							=      loss_fct(A_  ,   A_		)
														elif self.config.problem_type == "single_label_classification":
																		_UpperCAmelCase    :						Any							=      CrossEntropyLoss()
																		_UpperCAmelCase    :						Any							=      loss_fct(logits.view(-1  ,   self.num_labels		)  ,   labels.view(-1		)		)
														elif self.config.problem_type == "multi_label_classification":
																		_UpperCAmelCase    :						Any							=      BCEWithLogitsLoss()
																		_UpperCAmelCase    :						Tuple							=      loss_fct(A_  ,   A_		)

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

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







@add_start_docstrings(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "							,	UpperCAmelCase							,	)
class 			a					(		UpperCAmelCase							,	UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										super()._init_backbone(A_		)

										_UpperCAmelCase    :						Optional[int]							=      [config.embedding_size] + config.hidden_sizes
										_UpperCAmelCase    :						str							=      ResNetEmbeddings(A_		)
										_UpperCAmelCase    :						List[Any]							=      ResNetEncoder(A_		)

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





						@add_start_docstrings_to_model_forward(A_		)
						@replace_return_docstrings(output_type=A_  ,   config_class=_CONFIG_FOR_DOC		)
						def     _UpperCAmelCase			(    self  ,   A_  ,   A_ = None  ,   A_ = None		):







										'''simple docstring'''


										_UpperCAmelCase    :						Tuple							=      return_dict if return_dict is not None else self.config.use_return_dict
										_UpperCAmelCase    :						Tuple							=      (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)

										_UpperCAmelCase    :						Tuple							=      self.embedder(A_		)

										_UpperCAmelCase    :						Optional[int]							=      self.encoder(A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						Optional[int]							=      outputs.hidden_states

										_UpperCAmelCase    :						Any							=      ()
										for idx, stage in enumerate(self.stage_names		):
														if stage in self.out_features:
																		feature_maps += (hidden_states[idx],)

										if not return_dict:
														_UpperCAmelCase    :						Union[str, Any]							=      (feature_maps,)
														if output_hidden_states:
																		output += (outputs.hidden_states,)
														return output

										return BackboneOutput(
										    feature_maps=A_  ,   hidden_states=outputs.hidden_states if output_hidden_states else None  ,   attentions=A_  ,   )


