

import unittest

from transformers import AutoTokenizer, FalconConfig, 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 (
          FalconForCausalLM,
          FalconForQuestionAnswering,
          FalconForSequenceClassification,
          FalconForTokenClassification,
          FalconModel,
      )






class 						__magic_name__    :


 def __init__(						self		: Optional[Any]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Dict=3			,						lowerCAmelCase__		: str=7			,						lowerCAmelCase__		: Dict=True			,						lowerCAmelCase__		: Tuple=True			,						lowerCAmelCase__		: int=False			,						lowerCAmelCase__		: Optional[Any]=True			,						lowerCAmelCase__		: List[Any]=9_9			,						lowerCAmelCase__		: Union[str, Any]=3_2			,						lowerCAmelCase__		: Optional[Any]=5			,						lowerCAmelCase__		: Any=4			,						lowerCAmelCase__		: Tuple=3_7			,						lowerCAmelCase__		: Optional[int]="gelu"			,						lowerCAmelCase__		: int=0.1			,						lowerCAmelCase__		: Tuple=0.1			,						lowerCAmelCase__		: List[str]=5_1_2			,						lowerCAmelCase__		: Any=1_6			,						lowerCAmelCase__		: Any=2			,						lowerCAmelCase__		: int=0.02			,						lowerCAmelCase__		: Dict=3			,						lowerCAmelCase__		: List[Any]=4			,						lowerCAmelCase__		: Optional[int]=None			,						)    ->      Dict:
   UpperCAmelCase					      =  parent
   UpperCAmelCase					      =  batch_size
   UpperCAmelCase					      =  seq_length
   UpperCAmelCase					      =  is_training
   UpperCAmelCase					      =  use_input_mask
   UpperCAmelCase					      =  use_token_type_ids
   UpperCAmelCase					      =  use_labels
   UpperCAmelCase					      =  vocab_size
   UpperCAmelCase					      =  hidden_size
   UpperCAmelCase					      =  num_hidden_layers
   UpperCAmelCase					      =  num_attention_heads
   UpperCAmelCase					      =  intermediate_size
   UpperCAmelCase					      =  hidden_act
   UpperCAmelCase					      =  hidden_dropout_prob
   UpperCAmelCase					      =  attention_probs_dropout_prob
   UpperCAmelCase					      =  max_position_embeddings
   UpperCAmelCase					      =  type_vocab_size
   UpperCAmelCase					      =  type_sequence_label_size
   UpperCAmelCase					      =  initializer_range
   UpperCAmelCase					      =  num_labels
   UpperCAmelCase					      =  num_choices
   UpperCAmelCase					      =  scope


 def _UpperCamelCase	(						self		: int    )    ->      Tuple:
   UpperCAmelCase					      =  ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size    )

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

   UpperCAmelCase					      =  None

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

   UpperCAmelCase					      =  self.get_config()

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


 def _UpperCamelCase	(						self		: List[Any]    )    ->      Tuple:
   return FalconConfig(
       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			,						pad_token_id=1			,						new_decoder_architecture=lowerCAmelCase__			,						)


 def _UpperCamelCase	(						self		: Dict			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Union[str, Any]    )    ->      Dict:
   UpperCAmelCase					      =  FalconModel(config=lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__    )
   UpperCAmelCase					      =  model(lowerCAmelCase__    )
   self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Union[str, Any]			,						)    ->      Tuple:
   UpperCAmelCase					      =  True
   UpperCAmelCase					      =  FalconModel(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						)
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						)
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__    )
   self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)    )


 def _UpperCamelCase	(						self		: Optional[Any]			,						lowerCAmelCase__		: List[str]			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: List[str]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Any			,						lowerCAmelCase__		: Dict			,						)    ->      str:
   UpperCAmelCase					      =  FalconForCausalLM(config=lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.vocab_size)    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Optional[Any]			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Dict			,						)    ->      Optional[Any]:
   UpperCAmelCase					      =  True
   UpperCAmelCase					      =  True
   UpperCAmelCase					      =  FalconForCausalLM(config=lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()

   # first forward pass
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						use_cache=lowerCAmelCase__			,						)
   UpperCAmelCase					      =  outputs.past_key_values

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

   # append to next input_ids and
   UpperCAmelCase					      =  torch.cat([input_ids, next_tokens]			,						dim=-1    )
   UpperCAmelCase					      =  torch.cat([input_mask, next_mask]			,						dim=-1    )

   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						output_hidden_states=lowerCAmelCase__			,						)["hidden_states"][0]
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						past_key_values=lowerCAmelCase__			,						output_hidden_states=lowerCAmelCase__			,						)["hidden_states"][0]

   # select random slice
   UpperCAmelCase					      =  ids_tensor((1,)			,						output_from_past.shape[-1]    ).item()
   UpperCAmelCase					      =  output_from_no_past[:, -3:, random_slice_idx].detach()
   UpperCAmelCase					      =  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 _UpperCamelCase	(						self		: List[str]    )    ->      str:
   UpperCAmelCase					      =  self.prepare_config_and_inputs()
   (
       (
       UpperCAmelCase	
   )      ,	(
       UpperCAmelCase	
   )      ,	(
       UpperCAmelCase	
   )      ,	(
       UpperCAmelCase	
   )      ,	(
       UpperCAmelCase	
   )      ,	(
       UpperCAmelCase	
   )      ,	(
       UpperCAmelCase	
   )      ,		
   )					      =  config_and_inputs
   UpperCAmelCase					      =  {"input_ids": input_ids, "attention_mask": input_mask}
   return config, inputs_dict






@require_torch
class 						__magic_name__    (       _snake_case	,						_snake_case	,						_snake_case	,						unittest.TestCase    ):
 UpperCAmelCase							    =						(
     (
         FalconModel,
         FalconForCausalLM,
         FalconForSequenceClassification,
         FalconForTokenClassification,
         FalconForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase							    =						(FalconForCausalLM,) if is_torch_available() else ()
 UpperCAmelCase							    =						(
     {
         """feature-extraction""": FalconModel,
         """text-classification""": FalconForSequenceClassification,
         """text-generation""": FalconForCausalLM,
         """question-answering""": FalconForQuestionAnswering,
         """token-classification""": FalconForTokenClassification,
         """zero-shot""": FalconForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False


 def _UpperCamelCase	(						self		: Any    )    ->      Dict:
   UpperCAmelCase					      =  FalconModelTester(self    )
   UpperCAmelCase					      =  ConfigTester(self			,						config_class=lowerCAmelCase__			,						hidden_size=3_7    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      Any:
   self.config_tester.run_common_tests()


 def _UpperCamelCase	(						self		: List[str]    )    ->      int:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Any    )    ->      Union[str, Any]:
   UpperCAmelCase      ,	*UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   for alibi in [True, False]:
     UpperCAmelCase					      =  alibi
     self.model_tester.create_and_check_model(lowerCAmelCase__			,						*lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Dict    )    ->      Dict:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  3
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  input_ids.ne(1    ).to(lowerCAmelCase__    )
   UpperCAmelCase					      =  ids_tensor([self.model_tester.batch_size]			,						self.model_tester.type_sequence_label_size    )
   UpperCAmelCase					      =  FalconForSequenceClassification(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.assertEqual(result.logits.shape			,						(self.model_tester.batch_size, self.model_tester.num_labels)    )


 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Any:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  3
   UpperCAmelCase					      =  "single_label_classification"
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  input_ids.ne(1    ).to(lowerCAmelCase__    )
   UpperCAmelCase					      =  ids_tensor([self.model_tester.batch_size]			,						self.model_tester.type_sequence_label_size    )
   UpperCAmelCase					      =  FalconForSequenceClassification(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.assertEqual(result.logits.shape			,						(self.model_tester.batch_size, self.model_tester.num_labels)    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      Any:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  FalconForCausalLM(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						use_cache=lowerCAmelCase__    )
   UpperCAmelCase					      =  input_ids.shape[0]
   UpperCAmelCase					      =  model._convert_to_rw_cache(result.past_key_values    )
   UpperCAmelCase					      =  model._convert_cache_to_standard_format(lowerCAmelCase__			,						lowerCAmelCase__    )
   for layer in range(len(lowerCAmelCase__    )    ):
     for tensor_idx in range(2    ):
       self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3    )
       self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4    )
       self.assertTrue(
           torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]    )    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      Dict:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  3
   UpperCAmelCase					      =  "multi_label_classification"
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  input_ids.ne(1    ).to(lowerCAmelCase__    )
   UpperCAmelCase					      =  ids_tensor(
       [self.model_tester.batch_size, config.num_labels]			,						self.model_tester.type_sequence_label_size    ).to(torch.float    )
   UpperCAmelCase					      =  FalconForSequenceClassification(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.assertEqual(result.logits.shape			,						(self.model_tester.batch_size, self.model_tester.num_labels)    )


 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      Tuple:
   # Falcon can have different numbers of KV-heads than the number of query heads, so we need
   # to override this test to use the right head counts.
   for model_class in self.all_generative_model_classes:
     UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

     # If it doesn't support cache, pass the test
     if not hasattr(lowerCAmelCase__			,						"use_cache"    ):
       return

     UpperCAmelCase					      =  model_class(lowerCAmelCase__    ).to(lowerCAmelCase__    )
     if "use_cache" not in inputs:
       UpperCAmelCase					      =  True
     UpperCAmelCase					      =  model(**lowerCAmelCase__    )

     # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
     if "past_key_values" not in outputs:
       return

     UpperCAmelCase					      =  (
         getattr(lowerCAmelCase__			,						"decoder_layers"			,						lowerCAmelCase__    )
         or getattr(lowerCAmelCase__			,						"num_decoder_layers"			,						lowerCAmelCase__    )
         or config.num_hidden_layers
     )
     UpperCAmelCase					      =  getattr(lowerCAmelCase__			,						"num_kv_heads"			,						config.num_attention_heads    )
     UpperCAmelCase					      =  getattr(lowerCAmelCase__			,						"d_model"			,						config.hidden_size    )
     UpperCAmelCase					      =  embed_dim // num_attention_heads

     UpperCAmelCase					      =  outputs["past_key_values"]
     self.assertEqual(len(lowerCAmelCase__    )			,						lowerCAmelCase__    )

     UpperCAmelCase      ,	UpperCAmelCase					      =  inputs["input_ids"].shape
     for i in range(lowerCAmelCase__    ):
       if config.new_decoder_architecture:
         UpperCAmelCase					      =  config.num_attention_heads
       elif config.multi_query:
         UpperCAmelCase					      =  1
       self.assertEqual(len(past_kv[0]    )			,						2    )  # K V for the decoder = 2
       self.assertEqual(
           past_kv[i][0].shape			,						(batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )
       self.assertEqual(
           past_kv[i][1].shape			,						(batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )






@require_torch
class 						__magic_name__    (       unittest.TestCase    ):


 @slow
 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Optional[Any]:
   UpperCAmelCase					      =  AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b"    )
   UpperCAmelCase					      =  FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b"    )
   model.eval()
   model.to(lowerCAmelCase__    )
   UpperCAmelCase					      =  tokenizer("My favorite food is"			,						return_tensors="pt"    ).to(lowerCAmelCase__    )

   UpperCAmelCase					      =  (
       "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
   )

   UpperCAmelCase					      =  model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=1_9    )
   UpperCAmelCase					      =  tokenizer.batch_decode(lowerCAmelCase__    )[0]

   self.assertEqual(lowerCAmelCase__			,						lowerCAmelCase__    )


 @slow
 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Optional[int]:
   # The big models are way too big for the CI, so we use tiny random models that resemble their
   # architectures but with much smaller and fewer layers
   for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
     UpperCAmelCase					      =  AutoTokenizer.from_pretrained(lowerCAmelCase__    )
     UpperCAmelCase					      =  FalconForCausalLM.from_pretrained(lowerCAmelCase__    )
     model.eval()
     model.to(lowerCAmelCase__    )
     UpperCAmelCase					      =  tokenizer("My favorite food is"			,						return_tensors="pt"    ).to(lowerCAmelCase__    )

     # We just test that these run without errors - the models are randomly initialized
     # and so the actual text outputs will be garbage
     model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=4    )
     model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=4    )
     model.generate(**lowerCAmelCase__			,						num_beams=2			,						max_new_tokens=4    )


 @slow
 def _UpperCamelCase	(						self		: List[str]    )    ->      Tuple:
   # The big models are way too big for the CI, so we use tiny random models that resemble their
   # architectures but with much smaller and fewer layers
   with torch.no_grad():
     for repo in [
         "Rocketknight1/falcon-rw-1b",
         "Rocketknight1/tiny-random-falcon-7b",
         "Rocketknight1/tiny-random-falcon-40b",
     ]:
       UpperCAmelCase					      =  AutoTokenizer.from_pretrained(lowerCAmelCase__    )
       UpperCAmelCase					      =  FalconForCausalLM.from_pretrained(lowerCAmelCase__    )
       model.eval()
       model.to(device=lowerCAmelCase__    )
       UpperCAmelCase					      =  tokenizer("My favorite food is"			,						return_tensors="pt"    ).to(lowerCAmelCase__    )

       # Test results are the same with and without cache
       UpperCAmelCase					      =  model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=2_0			,						use_cache=lowerCAmelCase__    )
       UpperCAmelCase					      =  model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=2_0			,						use_cache=lowerCAmelCase__    )
       self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0    )






import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCAmelCase__       = version.parse(importlib_metadata.version("nltk"))
if NLTK_VERSION >= version.Version("3.6.4"):
      from nltk import word_tokenize


lowerCAmelCase__       = "\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n"

lowerCAmelCase__       = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n"

lowerCAmelCase__       = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    'meteor': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric('meteor')\n    >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n    >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results[\"meteor\"], 4))\n    0.6944\n"






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


 def _UpperCamelCase	(						self		: int    )    ->      str:
   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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"]			,						reference_urls=[
           "https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score",
           "https://en.wikipedia.org/wiki/METEOR",
       ]			,						)


 def _UpperCamelCase	(						self		: Dict			,						lowerCAmelCase__		: List[Any]    )    ->      Dict:
   import nltk

   nltk.download("wordnet"    )
   if NLTK_VERSION >= version.Version("3.6.5"    ):
     nltk.download("punkt"    )
   if NLTK_VERSION >= version.Version("3.6.6"    ):
     nltk.download("omw-1.4"    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Any=0.9			,						lowerCAmelCase__		: Tuple=3			,						lowerCAmelCase__		: Optional[int]=0.5    )    ->      Any:
   if NLTK_VERSION >= version.Version("3.6.5"    ):
     UpperCAmelCase					      =  [
         meteor_score.single_meteor_score(
             word_tokenize(lowerCAmelCase__    )			,						word_tokenize(lowerCAmelCase__    )			,						alpha=lowerCAmelCase__			,						beta=lowerCAmelCase__			,						gamma=lowerCAmelCase__    )
         for ref, pred in zip(lowerCAmelCase__			,						lowerCAmelCase__    )
     ]
   else:
     UpperCAmelCase					      =  [
         meteor_score.single_meteor_score(lowerCAmelCase__			,						lowerCAmelCase__			,						alpha=lowerCAmelCase__			,						beta=lowerCAmelCase__			,						gamma=lowerCAmelCase__    )
         for ref, pred in zip(lowerCAmelCase__			,						lowerCAmelCase__    )
     ]

   return {"meteor": np.mean(lowerCAmelCase__    )}



