





'''simple docstring'''


import math
import unittest

from transformers import BioGptConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import (
           BioGptForCausalLM,
           BioGptForSequenceClassification,
           BioGptForTokenClassification,
           BioGptModel,
           BioGptTokenizer,
       )
       from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST

class  lowerCAmelCase_		:




 def __init__(						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase=13      ,  _lowerCAmelCase=7      ,  _lowerCAmelCase=True      ,  _lowerCAmelCase=True      ,  _lowerCAmelCase=False      ,  _lowerCAmelCase=True      ,  _lowerCAmelCase=99      ,  _lowerCAmelCase=32      ,  _lowerCAmelCase=5      ,  _lowerCAmelCase=4      ,  _lowerCAmelCase=37      ,  _lowerCAmelCase="gelu"      ,  _lowerCAmelCase=0.1      ,  _lowerCAmelCase=0.1      ,  _lowerCAmelCase=512      ,  _lowerCAmelCase=16      ,  _lowerCAmelCase=2      ,  _lowerCAmelCase=0.02      ,  _lowerCAmelCase=3      ,  _lowerCAmelCase=4      ,  _lowerCAmelCase=None      ,  )     ->				str:
     _lowerCAmelCase						      =   parent
     _lowerCAmelCase						      =   batch_size
     _lowerCAmelCase						      =   seq_length
     _lowerCAmelCase						      =   is_training
     _lowerCAmelCase						      =   use_input_mask
     _lowerCAmelCase						      =   use_token_type_ids
     _lowerCAmelCase						      =   use_labels
     _lowerCAmelCase						      =   vocab_size
     _lowerCAmelCase						      =   hidden_size
     _lowerCAmelCase						      =   num_hidden_layers
     _lowerCAmelCase						      =   num_attention_heads
     _lowerCAmelCase						      =   intermediate_size
     _lowerCAmelCase						      =   hidden_act
     _lowerCAmelCase						      =   hidden_dropout_prob
     _lowerCAmelCase						      =   attention_probs_dropout_prob
     _lowerCAmelCase						      =   max_position_embeddings
     _lowerCAmelCase						      =   type_vocab_size
     _lowerCAmelCase						      =   type_sequence_label_size
     _lowerCAmelCase						      =   initializer_range
     _lowerCAmelCase						      =   num_labels
     _lowerCAmelCase						      =   num_choices
     _lowerCAmelCase						      =   scope




 def 				_snake_case (						self		)     ->				Tuple:
     _lowerCAmelCase						      =   ids_tensor([self.batch_size, self.seq_length]      ,  self.vocab_size		)

     _lowerCAmelCase						      =   None
     if self.use_input_mask:
         _lowerCAmelCase						      =   random_attention_mask([self.batch_size, self.seq_length]		)

     _lowerCAmelCase						      =   None
     if self.use_token_type_ids:
         _lowerCAmelCase						      =   ids_tensor([self.batch_size, self.seq_length]      ,  self.type_vocab_size		)

     _lowerCAmelCase						      =   None
     _lowerCAmelCase						      =   None
     _lowerCAmelCase						      =   None
     if self.use_labels:
         _lowerCAmelCase						      =   ids_tensor([self.batch_size]      ,  self.type_sequence_label_size		)
         _lowerCAmelCase						      =   ids_tensor([self.batch_size, self.seq_length]      ,  self.num_labels		)
         _lowerCAmelCase						      =   ids_tensor([self.batch_size]      ,  self.num_choices		)

     _lowerCAmelCase						      =   self.get_config()

     return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




 def 				_snake_case (						self		)     ->				Optional[int]:
     return BioGptConfig(
         vocab_size=self.vocab_size      ,  hidden_size=self.hidden_size      ,  num_hidden_layers=self.num_hidden_layers      ,  num_attention_heads=self.num_attention_heads      ,  intermediate_size=self.intermediate_size      ,  hidden_act=self.hidden_act      ,  hidden_dropout_prob=self.hidden_dropout_prob      ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,  max_position_embeddings=self.max_position_embeddings      ,  type_vocab_size=self.type_vocab_size      ,  is_decoder=_lowerCAmelCase      ,  initializer_range=self.initializer_range      ,  )




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Optional[Any]:
     _lowerCAmelCase						      =   BioGptModel(config=_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)
     model.eval()
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase		)
     _lowerCAmelCase						      =   model(_lowerCAmelCase		)
     self.parent.assertEqual(result.last_hidden_state.shape      ,  (self.batch_size, self.seq_length, self.hidden_size)		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  )     ->				Tuple:
     _lowerCAmelCase						      =   BioGptForCausalLM(config=_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)
     model.eval()
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase      ,  token_type_ids=_lowerCAmelCase      ,  labels=_lowerCAmelCase		)
     self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.seq_length, self.vocab_size)		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  *_lowerCAmelCase		)     ->				Union[str, Any]:
     _lowerCAmelCase						      =   BioGptModel(config=_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)
     model.eval()

     # create attention mask
     _lowerCAmelCase						      =   torch.ones(input_ids.shape      ,  dtype=torch.long      ,  device=_lowerCAmelCase		)
     _lowerCAmelCase						      =   self.seq_length // 2
     _lowerCAmelCase						      =   0

     # first forward pass
     _lowerCAmelCase      ,      _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase		).to_tuple()

     # create hypothetical next token and extent to next_input_ids
     _lowerCAmelCase						      =   ids_tensor((self.batch_size, 1)      ,  config.vocab_size		)

     # change a random masked slice from input_ids
     _lowerCAmelCase						      =   ids_tensor((1,)      ,  _lowerCAmelCase		).item() + 1
     _lowerCAmelCase						      =   ids_tensor((self.batch_size, 1)      ,  config.vocab_size		).squeeze(-1		)
     _lowerCAmelCase						      =   random_other_next_tokens

     # append to next input_ids and attn_mask
     _lowerCAmelCase						      =   torch.cat([input_ids, next_tokens]      ,  dim=-1		)
     _lowerCAmelCase						      =   torch.cat(
         [attn_mask, torch.ones((attn_mask.shape[0], 1)      ,  dtype=torch.long      ,  device=_lowerCAmelCase		)]      ,  dim=1      ,  )

     # get two different outputs
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase		)["last_hidden_state"]
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  past_key_values=_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase		)["last_hidden_state"]

     # select random slice
     _lowerCAmelCase						      =   ids_tensor((1,)      ,  output_from_past.shape[-1]		).item()
     _lowerCAmelCase						      =   output_from_no_past[:, -1, random_slice_idx].detach()
     _lowerCAmelCase						      =   output_from_past[:, 0, random_slice_idx].detach()

     # test that outputs are equal for slice
     self.parent.assertTrue(torch.allclose(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=1E-3		)		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  *_lowerCAmelCase		)     ->				Dict:
     _lowerCAmelCase						      =   BioGptModel(config=_lowerCAmelCase		).to(_lowerCAmelCase		).eval()

     _lowerCAmelCase						      =   torch.ones(input_ids.shape      ,  dtype=torch.long      ,  device=_lowerCAmelCase		)

     # first forward pass
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase      ,  use_cache=_lowerCAmelCase		)

     _lowerCAmelCase      ,      _lowerCAmelCase						      =   outputs.to_tuple()

     # create hypothetical multiple next token and extent to next_input_ids
     _lowerCAmelCase						      =   ids_tensor((self.batch_size, 3)      ,  config.vocab_size		)
     _lowerCAmelCase						      =   ids_tensor((self.batch_size, 3)      ,  2		)

     # append to next input_ids and
     _lowerCAmelCase						      =   torch.cat([input_ids, next_tokens]      ,  dim=-1		)
     _lowerCAmelCase						      =   torch.cat([attention_mask, next_attn_mask]      ,  dim=-1		)

     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase		)["last_hidden_state"]
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase      ,  past_key_values=_lowerCAmelCase		)[
         "last_hidden_state"
     ]

     # select random slice
     _lowerCAmelCase						      =   ids_tensor((1,)      ,  output_from_past.shape[-1]		).item()
     _lowerCAmelCase						      =   output_from_no_past[:, -3:, random_slice_idx].detach()
     _lowerCAmelCase						      =   output_from_past[:, :, random_slice_idx].detach()

     self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]		)

     # test that outputs are equal for slice
     self.parent.assertTrue(torch.allclose(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=1E-3		)		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  *_lowerCAmelCase      ,  _lowerCAmelCase=False		)     ->				Optional[int]:
     _lowerCAmelCase						      =   BioGptForCausalLM(_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)
     if gradient_checkpointing:
         model.gradient_checkpointing_enable()

     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  labels=_lowerCAmelCase		)
     self.parent.assertEqual(result.loss.shape      ,  ()		)
     self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.seq_length, self.vocab_size)		)
     result.loss.backward()




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  *_lowerCAmelCase		)     ->				int:
     _lowerCAmelCase						      =   BioGptModel(_lowerCAmelCase		)
     _lowerCAmelCase						      =   model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers		)
     for key in model.state_dict().keys():
         if "c_proj" in key and "weight" in key:
             self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]		) - model_std		)      ,  0.001		)
             self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]		) - 0.0		)      ,  0.01		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  *_lowerCAmelCase		)     ->				List[str]:
     _lowerCAmelCase						      =   self.num_labels
     _lowerCAmelCase						      =   BioGptForTokenClassification(_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)
     model.eval()
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase      ,  token_type_ids=_lowerCAmelCase		)
     self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.seq_length, self.num_labels)		)





 def 				_snake_case (						self		)     ->				int:
     _lowerCAmelCase						      =   self.prepare_config_and_inputs()
     (
         (
         _lowerCAmelCase
     )      ,      (
         _lowerCAmelCase
     )      ,      (
         _lowerCAmelCase
     )      ,      (
         _lowerCAmelCase
     )      ,      (
         _lowerCAmelCase
     )      ,      (
         _lowerCAmelCase
     )      ,      (
         _lowerCAmelCase
     )      ,      
     )						      =   config_and_inputs
     _lowerCAmelCase						      =   {"input_ids": input_ids, "attention_mask": input_mask}
     return config, inputs_dict







@require_torch
class  lowerCAmelCase_		(		__magic_name__    ,__magic_name__    ,__magic_name__    ,unittest.TestCase		):
 __lowerCamelCase    :				Optional[int]								=       (
     (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
     if is_torch_available()
     else ()
 )
 __lowerCamelCase    :				int								=       (BioGptForCausalLM,) if is_torch_available() else ()
 __lowerCamelCase    :				str								=       (
     {
         "feature-extraction": BioGptModel,
         "text-classification": BioGptForSequenceClassification,
         "text-generation": BioGptForCausalLM,
         "token-classification": BioGptForTokenClassification,
         "zero-shot": BioGptForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __lowerCamelCase    :				int								=       False




 def 				_snake_case (						self		)     ->				str:
     _lowerCAmelCase						      =   BioGptModelTester(self		)
     _lowerCAmelCase						      =   ConfigTester(self      ,  config_class=_lowerCAmelCase      ,  hidden_size=37		)




 def 				_snake_case (						self		)     ->				Dict:
     self.config_tester.run_common_tests()




 def 				_snake_case (						self		)     ->				Union[str, Any]:
     _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_lowerCAmelCase		)




 def 				_snake_case (						self		)     ->				List[str]:
     _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs()
     for type in ["absolute", "relative_key", "relative_key_query"]:
         _lowerCAmelCase						      =   type
         self.model_tester.create_and_check_model(*_lowerCAmelCase		)




 def 				_snake_case (						self		)     ->				List[Any]:
     _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_biogpt_model_attention_mask_past(*_lowerCAmelCase		)




 def 				_snake_case (						self		)     ->				Union[str, Any]:
     _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_forward_and_backwards(*_lowerCAmelCase      ,  gradient_checkpointing=_lowerCAmelCase		)




 def 				_snake_case (						self		)     ->				Optional[Any]:
     _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_biogpt_model_past_large_inputs(*_lowerCAmelCase		)




 def 				_snake_case (						self		)     ->				int:
     _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_biogpt_weight_initialization(*_lowerCAmelCase		)




 def 				_snake_case (						self		)     ->				Dict:
     _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_biogpt_for_token_classification(*_lowerCAmelCase		)




 @slow
 def 				_snake_case (						self		)     ->				Tuple:
     _lowerCAmelCase						      =   BioGptForCausalLM.from_pretrained("microsoft/biogpt"		)
     model.to(_lowerCAmelCase		)
     _lowerCAmelCase						      =   BioGptTokenizer.from_pretrained("microsoft/biogpt"		)

     _lowerCAmelCase						      =   "left"

     # Define PAD Token = EOS Token = 50256
     _lowerCAmelCase						      =   tokenizer.eos_token
     _lowerCAmelCase						      =   model.config.eos_token_id

     # use different length sentences to test batching
     _lowerCAmelCase						      =   [
         "Hello, my dog is a little",
         "Today, I",
     ]

     _lowerCAmelCase						      =   tokenizer(_lowerCAmelCase      ,  return_tensors="pt"      ,  padding=_lowerCAmelCase		)
     _lowerCAmelCase						      =   inputs["input_ids"].to(_lowerCAmelCase		)

     _lowerCAmelCase						      =   model.generate(
         input_ids=_lowerCAmelCase      ,  attention_mask=inputs["attention_mask"].to(_lowerCAmelCase		)      ,  )

     _lowerCAmelCase						      =   tokenizer(sentences[0]      ,  return_tensors="pt"		).input_ids.to(_lowerCAmelCase		)
     _lowerCAmelCase						      =   model.generate(input_ids=_lowerCAmelCase		)

     _lowerCAmelCase						      =   inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
     _lowerCAmelCase						      =   tokenizer(sentences[1]      ,  return_tensors="pt"		).input_ids.to(_lowerCAmelCase		)
     _lowerCAmelCase						      =   model.generate(input_ids=_lowerCAmelCase      ,  max_length=model.config.max_length - num_paddings		)

     _lowerCAmelCase						      =   tokenizer.batch_decode(_lowerCAmelCase      ,  skip_special_tokens=_lowerCAmelCase		)
     _lowerCAmelCase						      =   tokenizer.decode(output_non_padded[0]      ,  skip_special_tokens=_lowerCAmelCase		)
     _lowerCAmelCase						      =   tokenizer.decode(output_padded[0]      ,  skip_special_tokens=_lowerCAmelCase		)

     _lowerCAmelCase						      =   [
         "Hello, my dog is a little bit bigger than a little bit.",
         "Today, I have a good idea of how to use the information",
     ]
     self.assertListEqual(_lowerCAmelCase      ,  _lowerCAmelCase		)
     self.assertListEqual(_lowerCAmelCase      ,  [non_padded_sentence, padded_sentence]		)




 @slow
 def 				_snake_case (						self		)     ->				Tuple:
     for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _lowerCAmelCase						      =   BioGptModel.from_pretrained(_lowerCAmelCase		)
         self.assertIsNotNone(_lowerCAmelCase		)




 def 				_snake_case (						self		)     ->				int:
     _lowerCAmelCase      ,      _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs_for_common()
     _lowerCAmelCase						      =   3
     _lowerCAmelCase						      =   input_dict["input_ids"]
     _lowerCAmelCase						      =   input_ids.ne(1		).to(_lowerCAmelCase		)
     _lowerCAmelCase						      =   ids_tensor([self.model_tester.batch_size]      ,  self.model_tester.type_sequence_label_size		)
     _lowerCAmelCase						      =   BioGptForSequenceClassification(_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)
     model.eval()
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase      ,  labels=_lowerCAmelCase		)
     self.assertEqual(result.logits.shape      ,  (self.model_tester.batch_size, self.model_tester.num_labels)		)





 def 				_snake_case (						self		)     ->				Union[str, Any]:
     _lowerCAmelCase      ,      _lowerCAmelCase						      =   self.model_tester.prepare_config_and_inputs_for_common()
     _lowerCAmelCase						      =   3
     _lowerCAmelCase						      =   "multi_label_classification"
     _lowerCAmelCase						      =   input_dict["input_ids"]
     _lowerCAmelCase						      =   input_ids.ne(1		).to(_lowerCAmelCase		)
     _lowerCAmelCase						      =   ids_tensor(
         [self.model_tester.batch_size, config.num_labels]      ,  self.model_tester.type_sequence_label_size		).to(torch.float		)
     _lowerCAmelCase						      =   BioGptForSequenceClassification(_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)
     model.eval()
     _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  attention_mask=_lowerCAmelCase      ,  labels=_lowerCAmelCase		)
     self.assertEqual(result.logits.shape      ,  (self.model_tester.batch_size, self.model_tester.num_labels)		)







@require_torch
class  lowerCAmelCase_		(		unittest.TestCase		):




 @slow
 def 				_snake_case (						self		)     ->				str:
     _lowerCAmelCase						      =   BioGptForCausalLM.from_pretrained("microsoft/biogpt"		)
     _lowerCAmelCase						      =   torch.tensor([[2, 4805, 9, 656, 21]]		)
     _lowerCAmelCase						      =   model(_lowerCAmelCase		)[0]

     _lowerCAmelCase						      =   42384

     _lowerCAmelCase						      =   torch.Size((1, 5, vocab_size)		)
     self.assertEqual(output.shape      ,  _lowerCAmelCase		)

     _lowerCAmelCase						      =   torch.tensor(
         [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]]		)

     self.assertTrue(torch.allclose(output[:, :3, :3]      ,  _lowerCAmelCase      ,  atol=1E-4		)		)





 @slow
 def 				_snake_case (						self		)     ->				List[str]:
     _lowerCAmelCase						      =   BioGptTokenizer.from_pretrained("microsoft/biogpt"		)
     _lowerCAmelCase						      =   BioGptForCausalLM.from_pretrained("microsoft/biogpt"		)
     model.to(_lowerCAmelCase		)

     torch.manual_seed(0		)
     _lowerCAmelCase						      =   tokenizer("COVID-19 is"      ,  return_tensors="pt"		).to(_lowerCAmelCase		)
     _lowerCAmelCase						      =   model.generate(
         **_lowerCAmelCase      ,  min_length=100      ,  max_length=1024      ,  num_beams=5      ,  early_stopping=_lowerCAmelCase      ,  )
     _lowerCAmelCase						      =   tokenizer.decode(output_ids[0]      ,  skip_special_tokens=_lowerCAmelCase		)

     _lowerCAmelCase						      =   (
         "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the"
         " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and"
         " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),"
         " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and"
         " more than 800,000 deaths."
     )
     self.assertEqual(_lowerCAmelCase      ,  _lowerCAmelCase		)




"""simple docstring"""


from jiwer import compute_measures

import datasets


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

A_    							=					"""\
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.

The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.

This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.

Word error rate can then be computed as:

WER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct words,
N is the number of words in the reference (N=S+D+C).

This value indicates the average number of errors per reference word. The lower the value, the better the
performance of the ASR system with a WER of 0 being a perfect score.
"""

A_    							=					"""
Compute WER score of transcribed segments against references.

Args:
    references: List of references for each speech input.
    predictions: List of transcriptions to score.
    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.

Returns:
    (float): the word error rate

Examples:

    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]
    >>> references = [\"this is the reference\", \"there is another one\"]
    >>> wer = datasets.load_metric(\"wer\")
    >>> wer_score = wer.compute(predictions=predictions, references=references)
    >>> print(wer_score)
    0.5
"""




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




				def        UpperCAmelCase__						(				self   ):
							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''',
							    ]							,						)





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase=None							,						UpperCAmelCase=None							,						UpperCAmelCase=False   ):
							if concatenate_texts:
										return compute_measures(UpperCAmelCase							,						UpperCAmelCase   )["wer"]
							else:
										lowerCamelCase_					=  0
										lowerCamelCase_					=  0
										for prediction, reference in zip(UpperCAmelCase							,						UpperCAmelCase   ):
													lowerCamelCase_					=  compute_measures(UpperCAmelCase							,						UpperCAmelCase   )
													incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
													total += measures["substitutions"] + measures["deletions"] + measures["hits"]
										return incorrect / total



