





'''simple docstring'''






from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


__UpperCamelCase					    =	"\\n@misc{wu2016googles,\n      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n"

__UpperCamelCase					    =	"\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n"

__UpperCamelCase					    =	"\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    'google_bleu': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.4\n"




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

		def 	lowercase__     (   self					:   Optional[Any]			)					->    MetricInfo:


					"""simple docstring"""

					return datasets.MetricInfo(
					    description=_DESCRIPTION  ,      citation=_CITATION  ,      inputs_description=_KWARGS_DESCRIPTION  ,      features=datasets.Features(
					        {
					            """predictions""": datasets.Sequence(datasets.Value("""string"""  ,      id="""token"""			)  ,      id="""sequence"""			),
					            """references""": datasets.Sequence(
					                datasets.Sequence(datasets.Value("""string"""  ,      id="""token"""			)  ,      id="""sequence"""			)  ,      id="""references"""			),
					        }			)  ,      )

		def 	lowercase__     (   self					:   Dict  ,      __magic_name__					:   List[List[List[str]]]  ,      __magic_name__					:   List[List[str]]  ,      __magic_name__					:   int = 1  ,      __magic_name__					:   int = 4  ,      )					->    Dict[str, float]:


					"""simple docstring"""

					return {
					    "google_bleu": gleu_score.corpus_gleu(
					        list_of_references=__magic_name__  ,      hypotheses=__magic_name__  ,      min_len=__magic_name__  ,      max_len=__magic_name__			)
					}





import unittest

from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

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


if is_torch_available():
	import torch

	from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM



@require_torch
class        A__:
						"""simple docstring"""






						def __init__(    self  ,      _lowercase  ,      _lowercase=99  ,      _lowercase=13  ,      _lowercase=16  ,      _lowercase=7  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=False  ,      _lowercase=True  ,      _lowercase=2  ,      _lowercase=32  ,      _lowercase=4  ,      _lowercase=4  ,      _lowercase=30  ,      _lowercase=0  ,      _lowercase=1  ,      _lowercase=2  ,      _lowercase=None  ,      )     -> List[str]:
									a_						:						Union[str, Any] 							= parent
									a_						:						Dict 							= batch_size
									a_						:						Any 							= decoder_seq_length
									# For common tests
									a_						:						Any 							= self.decoder_seq_length
									a_						:						int 							= is_training
									a_						:						List[Any] 							= use_attention_mask
									a_						:						List[str] 							= use_labels

									a_						:						Optional[Any] 							= vocab_size
									a_						:						Dict 							= d_model
									a_						:						Any 							= d_model
									a_						:						List[Any] 							= decoder_layers
									a_						:						List[str] 							= decoder_layers
									a_						:						Union[str, Any] 							= decoder_ffn_dim
									a_						:						Optional[Any] 							= decoder_attention_heads
									a_						:						Optional[Any] 							= decoder_attention_heads
									a_						:						Tuple 							= eos_token_id
									a_						:						Union[str, Any] 							= bos_token_id
									a_						:						Dict 							= pad_token_id
									a_						:						Union[str, Any] 							= decoder_start_token_id
									a_						:						List[Any] 							= use_cache
									a_						:						List[str] 							= max_position_embeddings

									a_						:						int 							= None
									a_						:						Any 							= decoder_seq_length
									a_						:						Union[str, Any] 							= 2
									a_						:						Optional[int] 							= 1





						def 			UpperCamelCase__					(    self    )     -> int:
									a_						:						Optional[int] 							= ids_tensor([self.batch_size, self.decoder_seq_length]  ,      self.vocab_size    )

									a_						:						Optional[int] 							= None
									if self.use_attention_mask:
												a_						:						List[Any] 							= ids_tensor([self.batch_size, self.decoder_seq_length]  ,      vocab_size=2    )

									a_						:						List[Any] 							= None
									if self.use_labels:
												a_						:						Union[str, Any] 							= ids_tensor([self.batch_size, self.decoder_seq_length]  ,      self.vocab_size    )

									a_						:						Any 							= TrOCRConfig(
									    vocab_size=self.vocab_size  ,      d_model=self.d_model  ,      decoder_layers=self.decoder_layers  ,      decoder_ffn_dim=self.decoder_ffn_dim  ,      decoder_attention_heads=self.decoder_attention_heads  ,      eos_token_id=self.eos_token_id  ,      bos_token_id=self.bos_token_id  ,      use_cache=self.use_cache  ,      pad_token_id=self.pad_token_id  ,      decoder_start_token_id=self.decoder_start_token_id  ,      max_position_embeddings=self.max_position_embeddings  ,      )

									return (config, input_ids, attention_mask, lm_labels)





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      )     -> List[Any]:
									a_						:						Optional[int] 							= True
									a_						:						List[str] 							= TrOCRDecoder(config=_lowercase    ).to(_lowercase    ).eval()
									a_						:						str 							= input_ids[:2]

									input_ids[input_ids == 0] += 1
									# first forward pass
									a_						:						Dict 							= model(_lowercase  ,      use_cache=_lowercase    )
									a_						:						Union[str, Any] 							= model(_lowercase    )
									a_						:						Union[str, Any] 							= model(_lowercase  ,      use_cache=_lowercase    )

									self.parent.assertTrue(len(_lowercase    ) == len(_lowercase    )    )
									self.parent.assertTrue(len(_lowercase    ) == len(_lowercase    ) + 1    )

									a_						:						Dict 							= outputs["""past_key_values"""]

									# create hypothetical next token and extent to next_input_ids
									a_						:						List[str] 							= ids_tensor((2, 1)  ,      config.vocab_size - 1    ) + 1

									# append to next input_ids and
									a_						:						int 							= torch.cat([input_ids, next_tokens]  ,      dim=-1    )

									a_						:						Dict 							= model(_lowercase    )["""last_hidden_state"""]
									a_						:						List[str] 							= model(_lowercase  ,      past_key_values=_lowercase    )["""last_hidden_state"""]

									# select random slice
									a_						:						Optional[Any] 							= ids_tensor((1,)  ,      output_from_past.shape[-1]    ).item()
									a_						:						Union[str, Any] 							= output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
									a_						:						Any 							= output_from_past[:, 0, random_slice_idx].detach()

									# test that outputs are equal for slice
									assert torch.allclose(_lowercase  ,      _lowercase  ,      atol=1e-3    )





						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									a_						:						List[Any] 							= self.prepare_config_and_inputs()
									a_							,					a_							,					a_							,					a_						:						List[Any] 							= config_and_inputs

									a_						:						str 							= {"""input_ids""": input_ids, """attention_mask""": attention_mask}
									return config, inputs_dict







@require_torch
class        A__(a_,  a_,  a_,  unittest.TestCase							):
						"""simple docstring"""






						_A    :				Optional[Any]       					=			(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
						_A    :				Optional[int]       					=			(TrOCRForCausalLM,) if is_torch_available() else ()
						_A    :				Tuple       					=			{'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
						_A    :				List[str]       					=			True
						_A    :				List[str]       					=			False





						def 			UpperCamelCase__					(    self    )     -> List[Any]:
									a_						:						str 							= TrOCRStandaloneDecoderModelTester(self  ,      is_training=_lowercase    )
									a_						:						str 							= ConfigTester(self  ,      config_class=_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Tuple:
									pass





						def 			UpperCamelCase__					(    self    )     -> int:
									pass





						def 			UpperCamelCase__					(    self    )     -> str:
									pass





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





						def 			UpperCamelCase__					(    self    )     -> List[str]:
									a_						:						int 							= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_decoder_model_past(*_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Tuple:
									return





						@unittest.skip("""The model doesn't support left padding"""    )  # and it's not used enough to be worth fixing :)
						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									pass


