





'''simple docstring'''


import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
 from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
 from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
 from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


lowerCAmelCase					:     List[Any]												=DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

lowerCAmelCase					:     Optional[int]												='''main'''
# Default branch name
lowerCAmelCase					:     List[str]												='''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
lowerCAmelCase					:     Union[str, Any]												='''aaaaaaa'''
# This commit does not exist, so we should 404.

lowerCAmelCase					:     str												='''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
lowerCAmelCase					:     int												='''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def 							UpperCAmelCase_  (						):
   print("Welcome!" )
   yield
   print("Bye!" )
@contextlib.contextmanager
def 							UpperCAmelCase_  (						):
   print("Bonjour!" )
   yield
   print("Au revoir!" )
class       a_   (				unittest.TestCase							):





     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        assert transformers.__spec__ is not None
        assert importlib.util.find_spec("transformers"						) is not None







class       a_   (				unittest.TestCase							):





     @unittest.mock.patch("sys.stdout"	,      new_callable=io.StringIO						)
     def 							lowercase__      ( self		:					List[str]	,      lowercase		:					Tuple						):





        """simple docstring"""




        with ContextManagers([]						):
           print("Transformers are awesome!"						)
        # The print statement adds a new line at the end of the output
        self.assertEqual(mock_stdout.getvalue()	,      "Transformers are awesome!\n"						)





     @unittest.mock.patch("sys.stdout"	,      new_callable=io.StringIO						)
     def 							lowercase__      ( self		:					Optional[Any]	,      lowercase		:					Tuple						):





        """simple docstring"""




        with ContextManagers([context_en()]						):
           print("Transformers are awesome!"						)
        # The output should be wrapped with an English welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()	,      "Welcome!\nTransformers are awesome!\nBye!\n"						)





     @unittest.mock.patch("sys.stdout"	,      new_callable=io.StringIO						)
     def 							lowercase__      ( self		:					Dict	,      lowercase		:					int						):





        """simple docstring"""




        with ContextManagers([context_fr(), context_en()]						):
           print("Transformers are awesome!"						)
        # The output should be wrapped with an English and French welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()	,      "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"						)





     @require_torch
     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        self.assertEqual(find_labels(lowercase						)	,      ["labels"]						)
        self.assertEqual(find_labels(lowercase						)	,      ["labels", "next_sentence_label"]						)
        self.assertEqual(find_labels(lowercase						)	,      ["start_positions", "end_positions"]						)
        class       a_   (				_lowerCAmelCase							):
             pass







        self.assertEqual(find_labels(lowercase						)	,      ["labels"]						)





     @require_tf
     def 							lowercase__      ( self		:					str						):





        """simple docstring"""




        self.assertEqual(find_labels(lowercase						)	,      ["labels"]						)
        self.assertEqual(find_labels(lowercase						)	,      ["labels", "next_sentence_label"]						)
        self.assertEqual(find_labels(lowercase						)	,      ["start_positions", "end_positions"]						)
        class       a_   (				_lowerCAmelCase							):
             pass







        self.assertEqual(find_labels(lowercase						)	,      ["labels"]						)







     @require_flax
     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        self.assertEqual(find_labels(lowercase						)	,      []						)
        self.assertEqual(find_labels(lowercase						)	,      []						)
        self.assertEqual(find_labels(lowercase						)	,      []						)
        class       a_   (				_lowerCAmelCase							):
             pass







        self.assertEqual(find_labels(lowercase						)	,      []						)









'''simple docstring'''


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_  (						__lowerCamelCase					:					Optional[int]	,__lowerCamelCase					:					Any	,__lowerCamelCase					:					Any	,__lowerCamelCase					:					List[str]	,__lowerCamelCase					:					Dict=True	,__lowerCamelCase					:					List[Any]="pt" ):
   lowercase_			:Dict    			= {"add_prefix_space": True} if isinstance(__lowerCamelCase	,__lowerCamelCase ) and not line.startswith(" " ) else {}
   lowercase_			:str    			= padding_side
   return tokenizer(
       [line]	,max_length=__lowerCamelCase	,padding="max_length" if pad_to_max_length else None	,truncation=__lowerCamelCase	,return_tensors=__lowerCamelCase	,add_special_tokens=__lowerCamelCase	,**__lowerCamelCase	,)
def 							UpperCAmelCase_  (						__lowerCamelCase					:					List[str]	,__lowerCamelCase					:					Dict	,__lowerCamelCase					:					str=None	,):
   lowercase_			:Optional[int]    			= input_ids.ne(__lowerCamelCase ).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       a_   (				_lowerCAmelCase							):





     def __init__( self		:					Optional[int]	,      lowercase		:					Any	,      lowercase		:					Tuple	,      lowercase		:					Union[str, Any]	,      lowercase		:					Tuple	,      lowercase		:					str="train"	,      lowercase		:					Dict=None	,      lowercase		:					Tuple=None	,      lowercase		:					List[str]=None	,      lowercase		:					int=""	,      ):





        """simple docstring"""




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





     def __len__( self		:					Tuple						):





        """simple docstring"""




        return len(self.src_lens						)





     def __getitem__( self		:					str	,      lowercase		:					Dict						):





        """simple docstring"""




        lowercase_			:Tuple    			= index + 1  # linecache starts at 1
        lowercase_			:Optional[Any]    			= self.prefix + linecache.getline(str(self.src_file						)	,      lowercase						).rstrip("\n"						)
        lowercase_			:List[str]    			= linecache.getline(str(self.tgt_file						)	,      lowercase						).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	,      lowercase						):
           source_line += self.tokenizer.eos_token
           tgt_line += self.tokenizer.eos_token

        # Pad source and target to the right
        lowercase_			:List[str]    			= (
            self.tokenizer.question_encoder if isinstance(self.tokenizer	,      lowercase						) else self.tokenizer
        )
        lowercase_			:int    			= self.tokenizer.generator if isinstance(self.tokenizer	,      lowercase						) else self.tokenizer

        lowercase_			:List[str]    			= encode_line(lowercase	,      lowercase	,      self.max_source_length	,      "right"						)
        lowercase_			:Any    			= encode_line(lowercase	,      lowercase	,      self.max_target_length	,      "right"						)

        lowercase_			:Dict    			= source_inputs["input_ids"].squeeze()
        lowercase_			:Tuple    			= target_inputs["input_ids"].squeeze()
        lowercase_			:Optional[int]    			= source_inputs["attention_mask"].squeeze()
        return {
            "input_ids": source_ids,
            "attention_mask": src_mask,
            "decoder_input_ids": target_ids,
        }





     @staticmethod
     def 							lowercase__      ( lowercase		:					Union[str, Any]						):





        """simple docstring"""




        return [len(lowercase						) for x in Path(lowercase						).open().readlines()]







     def 							lowercase__      ( self		:					str	,      lowercase		:					List[Any]						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= torch.stack([x["input_ids"] for x in batch]						)
        lowercase_			:Dict    			= torch.stack([x["attention_mask"] for x in batch]						)
        lowercase_			:List[str]    			= torch.stack([x["decoder_input_ids"] for x in batch]						)
        lowercase_			:Any    			= (
            self.tokenizer.generator.pad_token_id
            if isinstance(self.tokenizer	,      lowercase						)
            else self.tokenizer.pad_token_id
        )
        lowercase_			:str    			= (
            self.tokenizer.question_encoder.pad_token_id
            if isinstance(self.tokenizer	,      lowercase						)
            else self.tokenizer.pad_token_id
        )
        lowercase_			:Union[str, Any]    			= trim_batch(lowercase	,      lowercase						)
        lowercase_			,							lowercase_			:Optional[Any]    			= trim_batch(lowercase	,      lowercase	,      attention_mask=lowercase						)
        lowercase_			:Tuple    			= {
            "input_ids": source_ids,
            "attention_mask": source_mask,
            "decoder_input_ids": y,
        }
        return batch







lowerCAmelCase					:     List[str]												=getLogger(__name__)
def 							UpperCAmelCase_  (						__lowerCamelCase					:					List[List] ):
   return list(itertools.chain.from_iterable(__lowerCamelCase ) )
def 							UpperCAmelCase_  (						__lowerCamelCase					:					str ):
   lowercase_			:List[str]    			= get_git_info()
   save_json(__lowerCamelCase	,os.path.join(__lowerCamelCase	,"git_log.json" ) )
def 							UpperCAmelCase_  (						__lowerCamelCase					:					Any	,__lowerCamelCase					:					Any	,__lowerCamelCase					:					List[Any]=4	,**__lowerCamelCase					:					List[str] ):
   with open(__lowerCamelCase	,"w" ) as f:
      json.dump(__lowerCamelCase	,__lowerCamelCase	,indent=__lowerCamelCase	,**__lowerCamelCase )
def 							UpperCAmelCase_  (						__lowerCamelCase					:					Tuple ):
   with open(__lowerCamelCase ) as f:
      return json.load(__lowerCamelCase )
def 							UpperCAmelCase_  (						):
   lowercase_			:Dict    			= git.Repo(search_parent_directories=__lowerCamelCase )
   lowercase_			:List[str]    			= {
       "repo_id": str(__lowerCamelCase ),
       "repo_sha": str(repo.head.object.hexsha ),
       "repo_branch": str(repo.active_branch ),
       "hostname": str(socket.gethostname() ),
   }
   return repo_infos
def 							UpperCAmelCase_  (						__lowerCamelCase					:					Callable	,__lowerCamelCase					:					Iterable ):
   return list(map(__lowerCamelCase	,__lowerCamelCase ) )
def 							UpperCAmelCase_  (						__lowerCamelCase					:					Union[str, Any]	,__lowerCamelCase					:					List[str] ):
   with open(__lowerCamelCase	,"wb" ) as f:
      return pickle.dump(__lowerCamelCase	,__lowerCamelCase )
def 							UpperCAmelCase_  (						__lowerCamelCase					:					str ):

   def remove_articles(__lowerCamelCase					:					Optional[int] ):
      return re.sub(r"\b(a|an|the)\b"	," "	,__lowerCamelCase )

   def white_space_fix(__lowerCamelCase					:					Dict ):
      return " ".join(text.split() )

   def remove_punc(__lowerCamelCase					:					Optional[Any] ):
      lowercase_			:Any    			= set(string.punctuation )
      return "".join(ch for ch in text if ch not in exclude )

   def lower(__lowerCamelCase					:					List[Any] ):
      return text.lower()

   return white_space_fix(remove_articles(remove_punc(lower(__lowerCamelCase ) ) ) )
def 							UpperCAmelCase_  (						__lowerCamelCase					:					Optional[int]	,__lowerCamelCase					:					Optional[int] ):
   lowercase_			:Tuple    			= normalize_answer(__lowerCamelCase ).split()
   lowercase_			:Dict    			= normalize_answer(__lowerCamelCase ).split()
   lowercase_			:Tuple    			= Counter(__lowerCamelCase ) & Counter(__lowerCamelCase )
   lowercase_			:Tuple    			= sum(common.values() )
   if num_same == 0:
      return 0
   lowercase_			:Union[str, Any]    			= 1.0 * num_same / len(__lowerCamelCase )
   lowercase_			:List[Any]    			= 1.0 * num_same / len(__lowerCamelCase )
   lowercase_			:Tuple    			= (2 * precision * recall) / (precision + recall)
   return fa
def 							UpperCAmelCase_  (						__lowerCamelCase					:					int	,__lowerCamelCase					:					Union[str, Any] ):
   return normalize_answer(__lowerCamelCase ) == normalize_answer(__lowerCamelCase )
def 							UpperCAmelCase_  (						__lowerCamelCase					:					List[str]	,__lowerCamelCase					:					List[str] ):
   assert len(__lowerCamelCase ) == len(__lowerCamelCase )
   lowercase_			:Any    			= 0
   for hypo, pred in zip(__lowerCamelCase	,__lowerCamelCase ):
      em += exact_match_score(__lowerCamelCase	,__lowerCamelCase )
   if len(__lowerCamelCase ) > 0:
      em /= len(__lowerCamelCase )
   return {"em": em}
def 							UpperCAmelCase_  (						__lowerCamelCase					:					str ):
   return model_prefix.startswith("rag" )


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


