





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


SCREAMING_SNAKE_CASE__							:      List[Any]         =    logging.get_logger(__name__)


# General docstring
SCREAMING_SNAKE_CASE__							:      List[str]         =    """MobileNetV1Config"""

# Base docstring
SCREAMING_SNAKE_CASE__							:      List[str]         =    """google/mobilenet_v1_1.0_224"""
SCREAMING_SNAKE_CASE__							:      List[str]         =    [1, 1_0_2_4, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    """google/mobilenet_v1_1.0_224"""
SCREAMING_SNAKE_CASE__							:      str         =    """tabby, tabby cat"""


SCREAMING_SNAKE_CASE__							:      Any         =    [
    """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	(   lowerCamelCase				,			lowerCamelCase				,			lowerCamelCase=None ):
   a__						:    Union[str, Any]   		=	{}

   if isinstance(lowerCamelCase				,			lowerCamelCase ):
      a__						:    List[str]   		=	model.mobilenet_va
   else:
      a__						:    Dict   		=	model

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

   for i in range(13 ):
      a__						:    str   		=	i + 1
      a__						:    Dict   		=	i * 2

      a__						:    int   		=	backbone.layer[pt_index]
      a__						:    int   		=	F"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
      a__						:    List[Any]   		=	pointer.convolution.weight
      a__						:    Optional[Any]   		=	pointer.normalization.bias
      a__						:    List[str]   		=	pointer.normalization.weight
      a__						:    int   		=	pointer.normalization.running_mean
      a__						:    Tuple   		=	pointer.normalization.running_var

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

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

   return tf_to_pt_map






def    _A	(   lowerCamelCase				,			lowerCamelCase				,			lowerCamelCase ):
   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
   a__						:    List[Any]   		=	tf.train.list_variables(lowerCamelCase )
   a__						:    str   		=	{}
   for name, shape in init_vars:
      logger.info(F"""Loading TF weight {name} with shape {shape}""" )
      a__						:    Any   		=	tf.train.load_variable(lowerCamelCase				,			lowerCamelCase )
      a__						:    List[Any]   		=	array

   # Build TF to PyTorch weights loading map
   a__						:    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

      a__						:    Optional[Any]   		=	tf_weights[name]

      if "depthwise_weights" in name:
         logger.info("Transposing depthwise" )
         a__						:    Tuple   		=	np.transpose(lowerCamelCase				,			(2, 3, 0, 1) )
      elif "weights" in name:
         logger.info("Transposing" )
         if len(pointer.shape ) == 2:  # copying into linear layer
            a__						:    Union[str, Any]   		=	array.squeeze().transpose()
         else:
            a__						:    List[str]   		=	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}""" )
      a__						:    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	(   lowerCamelCase				,			lowerCamelCase ):
   a__		,  a__						:    Dict   		=	features.shape[-2:]
   a__		,  a__						:    Optional[Any]   		=	conv_layer.stride
   a__		,  a__						:    Optional[Any]   		=	conv_layer.kernel_size

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

   if in_width % stride_width == 0:
      a__						:    str   		=	max(kernel_width - stride_width				,			0 )
   else:
      a__						:    Tuple   		=	max(kernel_width - (in_width % stride_width)				,			0 )

   a__						:    Any   		=	pad_along_width // 2
   a__						:    Tuple   		=	pad_along_width - pad_left
   a__						:    Dict   		=	pad_along_height // 2
   a__						:    Any   		=	pad_along_height - pad_top

   a__						:    Optional[Any]   		=	(pad_left, pad_right, pad_top, pad_bottom)
   return nn.functional.pad(lowerCamelCase				,			lowerCamelCase				,			"constant"				,			0.0 )







class 	__lowerCAmelCase      (       nn.Module	):





   def __init__(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case = 1       ,      snake_case = 1       ,      snake_case = False       ,      snake_case = True       ,      snake_case = True       ,      )					->	None:
      """simple docstring"""





      super().__init__()
      a__						:    Union[str, 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."""   )

      a__						:    Optional[Any]   		=	0 if config.tf_padding else int((kernel_size - 1) / 2   )

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

      if use_normalization:
         a__						:    Optional[int]   		=	nn.BatchNormad(
             num_features=snake_case       ,      eps=config.layer_norm_eps       ,      momentum=0.9_997       ,      affine=snake_case       ,      track_running_stats=snake_case       ,      )
      else:
         a__						:    Union[str, Any]   		=	None

      if use_activation:
         if isinstance(snake_case       ,      snake_case   ):
            a__						:    Any   		=	ACTaFN[use_activation]
         elif isinstance(config.hidden_act       ,      snake_case   ):
            a__						:    List[Any]   		=	ACTaFN[config.hidden_act]
         else:
            a__						:    Any   		=	config.hidden_act
      else:
         a__						:    Any   		=	None





   def 						_snake_case			(			self       ,      snake_case   )					->	torch.Tensor:
      """simple docstring"""





      if self.config.tf_padding:
         a__						:    Tuple   		=	apply_tf_padding(snake_case       ,      self.convolution   )
      a__						:    Optional[Any]   		=	self.convolution(snake_case   )
      if self.normalization is not None:
         a__						:    int   		=	self.normalization(snake_case   )
      if self.activation is not None:
         a__						:    List[Any]   		=	self.activation(snake_case   )
      return features







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    Any  		=					MobileNetVaConfig
   _UpperCamelCase			:    Optional[int]  		=					load_tf_weights_in_mobilenet_va
   _UpperCamelCase			:    Dict  		=					"""mobilenet_v1"""
   _UpperCamelCase			:    int  		=					"""pixel_values"""
   _UpperCamelCase			:    Tuple  		=					False





   def 						_snake_case			(			self       ,      snake_case   )					->	None:
      """simple docstring"""





      if isinstance(snake_case       ,      (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(snake_case       ,      nn.BatchNormad   ):
         module.bias.data.zero_()
         module.weight.data.fill_(1.0   )







SCREAMING_SNAKE_CASE__							:      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.
"""

SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    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."""		,_UpperCamelCase		,)
class 	__lowerCAmelCase      (       _UpperCamelCase	):





   def __init__(			self       ,      snake_case       ,      snake_case = True   )					->	Optional[Any]:
      """simple docstring"""





      super().__init__(snake_case   )
      a__						:    Dict   		=	config

      a__						:    Union[str, Any]   		=	32
      a__						:    List[str]   		=	max(int(depth * config.depth_multiplier   )       ,      config.min_depth   )

      a__						:    Optional[Any]   		=	MobileNetVaConvLayer(
          snake_case       ,      in_channels=config.num_channels       ,      out_channels=snake_case       ,      kernel_size=3       ,      stride=2       ,      )

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

      a__						:    str   		=	nn.ModuleList()
      for i in range(13   ):
         a__						:    Any   		=	out_channels

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

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

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

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

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





   def 						_snake_case			(			self       ,      snake_case   )					->	Union[str, Any]:
      """simple docstring"""





      raise NotImplementedError





   @add_start_docstrings_to_model_forward(snake_case   )
   @add_code_sample_docstrings(
       checkpoint=_CHECKPOINT_FOR_DOC       ,      output_type=snake_case       ,      config_class=_CONFIG_FOR_DOC       ,      modality="vision"       ,      expected_output=_EXPECTED_OUTPUT_SHAPE       ,      )
   def 						_snake_case			(			self       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      )					->	Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
      """simple docstring"""





      a__						:    List[Any]   		=	(
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      a__						:    Dict   		=	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"   )

      a__						:    List[str]   		=	self.conv_stem(snake_case   )

      a__						:    Optional[Any]   		=	() if output_hidden_states else None

      for i, layer_module in enumerate(self.layer   ):
         a__						:    List[str]   		=	layer_module(snake_case   )

         if output_hidden_states:
            a__						:    Dict   		=	all_hidden_states + (hidden_states,)

      a__						:    Any   		=	hidden_states

      if self.pooler is not None:
         a__						:    List[Any]   		=	torch.flatten(self.pooler(snake_case   )       ,      start_dim=1   )
      else:
         a__						:    Dict   		=	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=snake_case       ,      pooler_output=snake_case       ,      hidden_states=snake_case       ,      )







@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.
    """		,_UpperCamelCase		,)
class 	__lowerCAmelCase      (       _UpperCamelCase	):





   def __init__(			self       ,      snake_case   )					->	None:
      """simple docstring"""





      super().__init__(snake_case   )

      a__						:    Tuple   		=	config.num_labels
      a__						:    Optional[Any]   		=	MobileNetVaModel(snake_case   )

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

      # Classifier head
      a__						:    Any   		=	nn.Dropout(config.classifier_dropout_prob       ,      inplace=snake_case   )
      a__						:    Optional[int]   		=	nn.Linear(snake_case       ,      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(snake_case   )
   @add_code_sample_docstrings(
       checkpoint=_IMAGE_CLASS_CHECKPOINT       ,      output_type=snake_case       ,      config_class=_CONFIG_FOR_DOC       ,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT       ,      )
   def 						_snake_case			(			self       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      snake_case = None       ,      )					->	Union[tuple, ImageClassifierOutputWithNoAttention]:
      """simple docstring"""





      a__						:    List[str]   		=	return_dict if return_dict is not None else self.config.use_return_dict

      a__						:    List[str]   		=	self.mobilenet_va(snake_case       ,      output_hidden_states=snake_case       ,      return_dict=snake_case   )

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

      a__						:    Dict   		=	self.classifier(self.dropout(snake_case   )   )

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

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

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

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








import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


SCREAMING_SNAKE_CASE__							:      List[Any]         =    """\
@inproceedings{snover-etal-2006-study,
    title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",
    author = \"Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John\",
    booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",
    month = aug # \" 8-12\",
    year = \"2006\",
    address = \"Cambridge, Massachusetts, USA\",
    publisher = \"Association for Machine Translation in the Americas\",
    url = \"https://aclanthology.org/2006.amta-papers.25\",
    pages = \"223--231\",
}
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    """\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
"""

SCREAMING_SNAKE_CASE__							:      int         =    """
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    'score' (float): TER score (num_edits / sum_ref_lengths * 100)
    'num_edits' (int): The cumulative number of edits
    'ref_length' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\",
        ...                     \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}

    Example 2:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}

    Example 3:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}

    Example 4:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}

    Example 5:
        >>> predictions = [\"does this sentence match??\",
        ...                    \"what about this sentence?\",
        ...                    \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}
"""







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





   def 						_snake_case			(			self   )					->	Optional[int]:
      """simple docstring"""





      if version.parse(scb.__version__   ) < version.parse("1.4.12"   ):
         raise ImportWarning(
             "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
             "You can install it with `pip install \"sacrebleu>=1.4.12\"`."   )
      return datasets.MetricInfo(
          description=_DESCRIPTION       ,      citation=_CITATION       ,      homepage="http://www.cs.umd.edu/~snover/tercom/"       ,      inputs_description=_KWARGS_DESCRIPTION       ,      features=datasets.Features(
              {
                  "predictions": datasets.Value("string"       ,      id="sequence"   ),
                  "references": datasets.Sequence(datasets.Value("string"       ,      id="sequence"   )       ,      id="references"   ),
              }   )       ,      codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"]       ,      reference_urls=[
              "https://github.com/jhclark/tercom",
          ]       ,      )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = False       ,      snake_case = False       ,      snake_case = False       ,      snake_case = False       ,      )					->	Optional[Any]:
      """simple docstring"""





      a__						:    int   		=	len(references[0]   )
      if any(len(snake_case   ) != references_per_prediction for refs in references   ):
         raise ValueError("Sacrebleu requires the same number of references for each prediction"   )
      a__						:    int   		=	[[refs[i] for refs in references] for i in range(snake_case   )]

      a__						:    Optional[Any]   		=	TER(
          normalized=snake_case       ,      no_punct=snake_case       ,      asian_support=snake_case       ,      case_sensitive=snake_case       ,      )
      a__						:    Union[str, Any]   		=	sb_ter.corpus_score(snake_case       ,      snake_case   )

      return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}

