




import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCamelCase__ :   int					=							version.parse(importlib_metadata.version('nltk'))
if NLTK_VERSION >= version.Version('3.6.4'):
   from nltk import word_tokenize


lowerCamelCase__ :   Optional[int]					=							'\\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__ :   Union[str, Any]					=							'\\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__ :   Dict					=							'\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        lowerCamelCase_							(      datasets.Metric					):


 '''simple docstring'''







 def       lowerCAmelCase_  (							self  :		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       lowerCAmelCase_  (							self  :		List[Any]				,				_lowerCAmelCase  :		str						):
       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       lowerCAmelCase_  (							self  :		Optional[int]				,				_lowerCAmelCase  :		Union[str, Any]				,				_lowerCAmelCase  :		Any				,				_lowerCAmelCase  :		Union[str, Any]=0.9				,				_lowerCAmelCase  :		Optional[int]=3				,				_lowerCAmelCase  :		List[Any]=0.5						):
       if NLTK_VERSION >= version.Version('3.6.5'						):
             SCREAMING_SNAKE_CASE_							=			[
                 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:
             SCREAMING_SNAKE_CASE_							=			[
                 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						)}





import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Dict			,			__UpperCAmelCase						:	Dict			,			__UpperCAmelCase						:	Union[str, Any]			,			__UpperCAmelCase						:	int			,			__UpperCAmelCase						:	Optional[Any]=True			,			__UpperCAmelCase						:	Any="pt"							)					-> List[str]:
      SCREAMING_SNAKE_CASE_							=			{'add_prefix_space': True} if isinstance(__UpperCAmelCase			,			__UpperCAmelCase							) and not line.startswith(' '							) else {}
      SCREAMING_SNAKE_CASE_							=			padding_side
      return tokenizer(
          [line]			,			max_length=__UpperCAmelCase			,			padding='max_length' if pad_to_max_length else None			,			truncation=__UpperCAmelCase			,			return_tensors=__UpperCAmelCase			,			add_special_tokens=__UpperCAmelCase			,			**__UpperCAmelCase			,			)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Union[str, Any]			,			__UpperCAmelCase						:	Optional[Any]			,			__UpperCAmelCase						:	Dict=None			,			)					-> Optional[Any]:
      SCREAMING_SNAKE_CASE_							=			input_ids.ne(__UpperCAmelCase							).any(dim=0							)
      if attention_mask is None:
            return input_ids[:, keep_column_mask]
      else:
            return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 def __init__(							self  :		List[Any]				,				_lowerCAmelCase  :		Tuple				,				_lowerCAmelCase  :		int				,				_lowerCAmelCase  :		int				,				_lowerCAmelCase  :		Dict				,				_lowerCAmelCase  :		Union[str, Any]="train"				,				_lowerCAmelCase  :		Optional[Any]=None				,				_lowerCAmelCase  :		List[str]=None				,				_lowerCAmelCase  :		Optional[int]=None				,				_lowerCAmelCase  :		Optional[int]=""				,				):
       super().__init__()
       SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						).joinpath(type_path + '.source'						)
       SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						).joinpath(type_path + '.target'						)
       SCREAMING_SNAKE_CASE_							=			self.get_char_lens(self.src_file						)
       SCREAMING_SNAKE_CASE_							=			max_source_length
       SCREAMING_SNAKE_CASE_							=			max_target_length
       assert min(self.src_lens						) > 0, F"found empty line in {self.src_file}"
       SCREAMING_SNAKE_CASE_							=			tokenizer
       SCREAMING_SNAKE_CASE_							=			prefix
       if n_obs is not None:
             SCREAMING_SNAKE_CASE_							=			self.src_lens[:n_obs]
       SCREAMING_SNAKE_CASE_							=			src_lang
       SCREAMING_SNAKE_CASE_							=			tgt_lang



 def __len__(							self  :		Tuple						):
       return len(self.src_lens						)



 def __getitem__(							self  :		List[str]				,				_lowerCAmelCase  :		Any						):
       SCREAMING_SNAKE_CASE_							=			index + 1  # linecache starts at 1
       SCREAMING_SNAKE_CASE_							=			self.prefix + linecache.getline(str(self.src_file						)				,				_lowerCAmelCase						).rstrip('\n'						)
       SCREAMING_SNAKE_CASE_							=			linecache.getline(str(self.tgt_file						)				,				_lowerCAmelCase						).rstrip('\n'						)
       assert source_line, F"empty source line for index {index}"
       assert tgt_line, F"empty tgt line for index {index}"

       # Need to add eos token manually for T5
       if isinstance(self.tokenizer				,				_lowerCAmelCase						):
             source_line += self.tokenizer.eos_token
             tgt_line += self.tokenizer.eos_token

       # Pad source and target to the right
       SCREAMING_SNAKE_CASE_							=			(
           self.tokenizer.question_encoder if isinstance(self.tokenizer				,				_lowerCAmelCase						) else self.tokenizer
       )
       SCREAMING_SNAKE_CASE_							=			self.tokenizer.generator if isinstance(self.tokenizer				,				_lowerCAmelCase						) else self.tokenizer

       SCREAMING_SNAKE_CASE_							=			encode_line(_lowerCAmelCase				,				_lowerCAmelCase				,				self.max_source_length				,				'right'						)
       SCREAMING_SNAKE_CASE_							=			encode_line(_lowerCAmelCase				,				_lowerCAmelCase				,				self.max_target_length				,				'right'						)

       SCREAMING_SNAKE_CASE_							=			source_inputs['input_ids'].squeeze()
       SCREAMING_SNAKE_CASE_							=			target_inputs['input_ids'].squeeze()
       SCREAMING_SNAKE_CASE_							=			source_inputs['attention_mask'].squeeze()
       return {
           "input_ids": source_ids,
           "attention_mask": src_mask,
           "decoder_input_ids": target_ids,
       }



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		Optional[int]						):
       return [len(_lowerCAmelCase						) for x in Path(_lowerCAmelCase						).open().readlines()]




 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		Optional[int]						):
       SCREAMING_SNAKE_CASE_							=			torch.stack([x['input_ids'] for x in batch]						)
       SCREAMING_SNAKE_CASE_							=			torch.stack([x['attention_mask'] for x in batch]						)
       SCREAMING_SNAKE_CASE_							=			torch.stack([x['decoder_input_ids'] for x in batch]						)
       SCREAMING_SNAKE_CASE_							=			(
           self.tokenizer.generator.pad_token_id
           if isinstance(self.tokenizer				,				_lowerCAmelCase						)
           else self.tokenizer.pad_token_id
       )
       SCREAMING_SNAKE_CASE_							=			(
           self.tokenizer.question_encoder.pad_token_id
           if isinstance(self.tokenizer				,				_lowerCAmelCase						)
           else self.tokenizer.pad_token_id
       )
       SCREAMING_SNAKE_CASE_							=			trim_batch(_lowerCAmelCase				,				_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			trim_batch(_lowerCAmelCase				,				_lowerCAmelCase				,				attention_mask=_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			{
           'input_ids': source_ids,
           'attention_mask': source_mask,
           'decoder_input_ids': y,
       }
       return batch


lowerCamelCase__ :   List[str]					=							getLogger(__name__)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	List[List]							)					-> Tuple:
      return list(itertools.chain.from_iterable(__UpperCAmelCase							)							)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	str							)					-> None:
      SCREAMING_SNAKE_CASE_							=			get_git_info()
      save_json(__UpperCAmelCase			,			os.path.join(__UpperCAmelCase			,			'git_log.json'							)							)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Dict			,			__UpperCAmelCase						:	Tuple			,			__UpperCAmelCase						:	Optional[int]=4			,			**__UpperCAmelCase						:	Tuple							)					-> str:
      with open(__UpperCAmelCase			,			'w'							) as f:
            json.dump(__UpperCAmelCase			,			__UpperCAmelCase			,			indent=__UpperCAmelCase			,			**__UpperCAmelCase							)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	List[str]							)					-> int:
      with open(__UpperCAmelCase							) as f:
            return json.load(__UpperCAmelCase							)

def 					UpperCAmelCase_							(      )					-> Tuple:
      SCREAMING_SNAKE_CASE_							=			git.Repo(search_parent_directories=__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_							=			{
          'repo_id': str(__UpperCAmelCase							),
          'repo_sha': str(repo.head.object.hexsha							),
          'repo_branch': str(repo.active_branch							),
          'hostname': str(socket.gethostname()							),
      }
      return repo_infos

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Callable			,			__UpperCAmelCase						:	Iterable							)					-> List:
      return list(map(__UpperCAmelCase			,			__UpperCAmelCase							)							)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	str			,			__UpperCAmelCase						:	Dict							)					-> Dict:
      with open(__UpperCAmelCase			,			'wb'							) as f:
            return pickle.dump(__UpperCAmelCase			,			__UpperCAmelCase							)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	List[Any]							)					-> Any:

      def remove_articles(__UpperCAmelCase						:	Any							):
            return re.sub(r'\b(a|an|the)\b'			,			' '			,			__UpperCAmelCase							)

      def white_space_fix(__UpperCAmelCase						:	List[str]							):
            return " ".join(text.split()							)

      def remove_punc(__UpperCAmelCase						:	List[Any]							):
            SCREAMING_SNAKE_CASE_							=			set(string.punctuation							)
            return "".join(ch for ch in text if ch not in exclude							)

      def lower(__UpperCAmelCase						:	Union[str, Any]							):
            return text.lower()

      return white_space_fix(remove_articles(remove_punc(lower(__UpperCAmelCase							)							)							)							)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	int			,			__UpperCAmelCase						:	Any							)					-> List[str]:
      SCREAMING_SNAKE_CASE_							=			normalize_answer(__UpperCAmelCase							).split()
      SCREAMING_SNAKE_CASE_							=			normalize_answer(__UpperCAmelCase							).split()
      SCREAMING_SNAKE_CASE_							=			Counter(__UpperCAmelCase							) & Counter(__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_							=			sum(common.values()							)
      if num_same == 0:
            return 0
      SCREAMING_SNAKE_CASE_							=			1.0 * num_same / len(__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_							=			1.0 * num_same / len(__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_							=			(2 * precision * recall) / (precision + recall)
      return fa

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	str			,			__UpperCAmelCase						:	Optional[int]							)					-> Any:
      return normalize_answer(__UpperCAmelCase							) == normalize_answer(__UpperCAmelCase							)

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	List[str]			,			__UpperCAmelCase						:	List[str]							)					-> Dict:
      assert len(__UpperCAmelCase							) == len(__UpperCAmelCase							)
      SCREAMING_SNAKE_CASE_							=			0
      for hypo, pred in zip(__UpperCAmelCase			,			__UpperCAmelCase							):
            em += exact_match_score(__UpperCAmelCase			,			__UpperCAmelCase							)
      if len(__UpperCAmelCase							) > 0:
            em /= len(__UpperCAmelCase							)
      return {"em": em}

def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Union[str, Any]							)					-> Dict:
      return model_prefix.startswith('rag'							)





def 					UpperCAmelCase_							(      __UpperCAmelCase						:	Optional[Any]			,			__UpperCAmelCase						:	Any			,			__UpperCAmelCase						:	List[str]							)					-> Tuple:
      SCREAMING_SNAKE_CASE_							=			{p: p for p in extra_params}
      # T5 models don't have `dropout` param, they have `dropout_rate` instead
      SCREAMING_SNAKE_CASE_							=			'dropout_rate'
      for p in extra_params:
            if getattr(__UpperCAmelCase			,			__UpperCAmelCase			,			__UpperCAmelCase							):
                  if not hasattr(__UpperCAmelCase			,			__UpperCAmelCase							) and not hasattr(__UpperCAmelCase			,			equivalent_param[p]							):
                        logger.info('config doesn\'t have a `{}` attribute'.format(__UpperCAmelCase							)							)
                        delattr(__UpperCAmelCase			,			__UpperCAmelCase							)
                        continue
                  SCREAMING_SNAKE_CASE_							=			p if hasattr(__UpperCAmelCase			,			__UpperCAmelCase							) else equivalent_param[p]
                  setattr(__UpperCAmelCase			,			__UpperCAmelCase			,			getattr(__UpperCAmelCase			,			__UpperCAmelCase							)							)
                  delattr(__UpperCAmelCase			,			__UpperCAmelCase							)
      return hparams, config