





import argparse
import ast
import logging
import os
import sys

import pandas as pd
import torch
from tqdm import tqdm

from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score  # noqa: E402 # isort:skip


snake_case_           =      logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()






def lowerCamelCase__   (							snake_case_     :  str	)				->    Any:
   if "token" in model_name_or_path:
      return "rag_token"
   if "sequence" in model_name_or_path:
      return "rag_sequence"
   if "bart" in model_name_or_path:
      return "bart"
   return None






def lowerCamelCase__   (							snake_case_     :  str	,				snake_case_     :  Optional[Any]	,				snake_case_     :  str	)				->    str:
   return max(metric_fn(__lowerCamelCase	,				__lowerCamelCase	) for gt in ground_truths	)






def lowerCamelCase__   (							snake_case_     :  Union[str, Any]	,				snake_case_     :  int	,				snake_case_     :  int	)				->    List[str]:
   __snake_case								=       [line.strip() for line in open(__lowerCamelCase	,				'''r'''	).readlines()]
   __snake_case								=       []

   if args.gold_data_mode == "qa":
      __snake_case								=       pd.read_csv(__lowerCamelCase	,				sep='''\t'''	,				header=__lowerCamelCase	)
      for answer_list in data[1]:
         __snake_case								=       ast.literal_eval(__lowerCamelCase	)
         answers.append(__lowerCamelCase	)
   else:
      __snake_case								=       [line.strip() for line in open(__lowerCamelCase	,				'''r'''	).readlines()]
      __snake_case								=       [[reference] for reference in references]

   __snake_case								=       0
   for prediction, ground_truths in zip(__lowerCamelCase	,				__lowerCamelCase	):
      total += 1
      em += metric_max_over_ground_truths(__lowerCamelCase	,				__lowerCamelCase	,				__lowerCamelCase	)
      fa += metric_max_over_ground_truths(__lowerCamelCase	,				__lowerCamelCase	,				__lowerCamelCase	)

   __snake_case								=       100.0 * em / total
   __snake_case								=       100.0 * fa / total

   logger.info(f"""F1: {fa:.2f}"""	)
   logger.info(f"""EM: {em:.2f}"""	)






def lowerCamelCase__   (							snake_case_     :  str	,				snake_case_     :  Any	,				snake_case_     :  List[Any]	)				->    Optional[int]:
   __snake_case								=       args.k
   __snake_case								=       [line.strip() for line in open(__lowerCamelCase	,				'''r'''	).readlines()]
   __snake_case								=       [line.strip() for line in open(__lowerCamelCase	,				'''r'''	).readlines()]

   __snake_case								=       0
   for hypo, reference in zip(__lowerCamelCase	,				__lowerCamelCase	):
      __snake_case								=       set(hypo.split('''\t'''	)[:k]	)
      __snake_case								=       set(reference.split('''\t'''	)	)
      total += 1
      em += len(hypo_provenance & ref_provenance	) / k

   __snake_case								=       100.0 * em / total
   logger.info(f"""Precision@{k}: {em: .2f}"""	)






def lowerCamelCase__   (							snake_case_     :  List[Any]	,				snake_case_     :  Optional[int]	,				snake_case_     :  Any	)				->    Optional[Any]:
   def strip_title(snake_case_     :  Any	):
      if title.startswith('''\"'''	):
         __snake_case								=       title[1:]
      if title.endswith('''\"'''	):
         __snake_case								=       title[:-1]
      return title

   __snake_case								=       rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
       __lowerCamelCase	,				return_tensors='''pt'''	,				padding=__lowerCamelCase	,				truncation=__lowerCamelCase	,				)["input_ids"].to(args.device	)

   __snake_case								=       rag_model.rag.question_encoder(__lowerCamelCase	)
   __snake_case								=       question_enc_outputs[0]

   __snake_case								=       rag_model.retriever(
       __lowerCamelCase	,				question_enc_pool_output.cpu().detach().to(torch.floataa	).numpy()	,				prefix=rag_model.rag.generator.config.prefix	,				n_docs=rag_model.config.n_docs	,				return_tensors='''pt'''	,				)
   __snake_case								=       rag_model.retriever.index.get_doc_dicts(result.doc_ids	)
   __snake_case								=       []
   for docs in all_docs:
      __snake_case								=       [strip_title(__lowerCamelCase	) for title in docs["title"]]
      provenance_strings.append('''\t'''.join(__lowerCamelCase	)	)
   return provenance_strings






def lowerCamelCase__   (							snake_case_     :  List[str]	,				snake_case_     :  Tuple	,				snake_case_     :  Optional[int]	)				->    Any:
   with torch.no_grad():
      __snake_case								=       rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
          __lowerCamelCase	,				return_tensors='''pt'''	,				padding=__lowerCamelCase	,				truncation=__lowerCamelCase	)

      __snake_case								=       inputs_dict.input_ids.to(args.device	)
      __snake_case								=       inputs_dict.attention_mask.to(args.device	)
      __snake_case								=       rag_model.generate(  # rag_model overwrites generate
          __lowerCamelCase	,				attention_mask=__lowerCamelCase	,				num_beams=args.num_beams	,				min_length=args.min_length	,				max_length=args.max_length	,				early_stopping=__lowerCamelCase	,				num_return_sequences=1	,				bad_words_ids=[[0, 0]]	,				)
      __snake_case								=       rag_model.retriever.generator_tokenizer.batch_decode(__lowerCamelCase	,				skip_special_tokens=__lowerCamelCase	)

      if args.print_predictions:
         for q, a in zip(__lowerCamelCase	,				__lowerCamelCase	):
            logger.info('''Q: {} - A: {}'''.format(__lowerCamelCase	,				__lowerCamelCase	)	)

      return answers






def lowerCamelCase__   (							)				->    Union[str, Any]:
   __snake_case								=       argparse.ArgumentParser()
   parser.add_argument(
       '''--model_type'''	,				choices=['''rag_sequence''', '''rag_token''', '''bart''']	,				type=__lowerCamelCase	,				help=(
           '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the'''
           ''' model_name_or_path'''
       )	,				)
   parser.add_argument(
       '''--index_name'''	,				default=__lowerCamelCase	,				choices=['''exact''', '''compressed''', '''legacy''']	,				type=__lowerCamelCase	,				help='''RAG model retriever type'''	,				)
   parser.add_argument(
       '''--index_path'''	,				default=__lowerCamelCase	,				type=__lowerCamelCase	,				help='''Path to the retrieval index'''	,				)
   parser.add_argument('''--n_docs'''	,				default=5	,				type=__lowerCamelCase	,				help='''Number of retrieved docs'''	)
   parser.add_argument(
       '''--model_name_or_path'''	,				default=__lowerCamelCase	,				type=__lowerCamelCase	,				required=__lowerCamelCase	,				help='''Path to pretrained checkpoints or model identifier from huggingface.co/models'''	,				)
   parser.add_argument(
       '''--eval_mode'''	,				choices=['''e2e''', '''retrieval''']	,				default='''e2e'''	,				type=__lowerCamelCase	,				help=(
           '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates'''
           ''' precision@k.'''
       )	,				)
   parser.add_argument('''--k'''	,				default=1	,				type=__lowerCamelCase	,				help='''k for the precision@k calculation'''	)
   parser.add_argument(
       '''--evaluation_set'''	,				default=__lowerCamelCase	,				type=__lowerCamelCase	,				required=__lowerCamelCase	,				help='''Path to a file containing evaluation samples'''	,				)
   parser.add_argument(
       '''--gold_data_path'''	,				default=__lowerCamelCase	,				type=__lowerCamelCase	,				required=__lowerCamelCase	,				help='''Path to a tab-separated file with gold samples'''	,				)
   parser.add_argument(
       '''--gold_data_mode'''	,				default='''qa'''	,				type=__lowerCamelCase	,				choices=['''qa''', '''ans''']	,				help=(
           '''Format of the gold data file'''
           '''qa - a single line in the following format: question [tab] answer_list'''
           '''ans - a single line of the gold file contains the expected answer string'''
       )	,				)
   parser.add_argument(
       '''--predictions_path'''	,				type=__lowerCamelCase	,				default='''predictions.txt'''	,				help='''Name of the predictions file, to be stored in the checkpoints directory'''	,				)
   parser.add_argument(
       '''--eval_all_checkpoints'''	,				action='''store_true'''	,				help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number'''	,				)
   parser.add_argument(
       '''--eval_batch_size'''	,				default=8	,				type=__lowerCamelCase	,				help='''Batch size per GPU/CPU for evaluation.'''	,				)
   parser.add_argument(
       '''--recalculate'''	,				help='''Recalculate predictions even if the prediction file exists'''	,				action='''store_true'''	,				)
   parser.add_argument(
       '''--num_beams'''	,				default=4	,				type=__lowerCamelCase	,				help='''Number of beams to be used when generating answers'''	,				)
   parser.add_argument('''--min_length'''	,				default=1	,				type=__lowerCamelCase	,				help='''Min length of the generated answers'''	)
   parser.add_argument('''--max_length'''	,				default=50	,				type=__lowerCamelCase	,				help='''Max length of the generated answers'''	)

   parser.add_argument(
       '''--print_predictions'''	,				action='''store_true'''	,				help='''If True, prints predictions while evaluating.'''	,				)
   parser.add_argument(
       '''--print_docs'''	,				action='''store_true'''	,				help='''If True, prints docs retried while generating.'''	,				)
   __snake_case								=       parser.parse_args()
   __snake_case								=       torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''	)
   return args






def lowerCamelCase__   (							snake_case_     :  Tuple	)				->    Union[str, Any]:
   __snake_case								=       {}
   if args.model_type is None:
      __snake_case								=       infer_model_type(args.model_name_or_path	)
      assert args.model_type is not None
   if args.model_type.startswith('''rag'''	):
      __snake_case								=       RagTokenForGeneration if args.model_type == "rag_token" else RagSequenceForGeneration
      __snake_case								=       args.n_docs
      if args.index_name is not None:
         __snake_case								=       args.index_name
      if args.index_path is not None:
         __snake_case								=       args.index_path
   else:
      __snake_case								=       BartForConditionalGeneration

   __snake_case								=       (
       [f.path for f in os.scandir(args.model_name_or_path	) if f.is_dir()]
       if args.eval_all_checkpoints
       else [args.model_name_or_path]
   )

   logger.info('''Evaluate the following checkpoints: %s'''	,				__lowerCamelCase	)

   __snake_case								=       get_scores if args.eval_mode == "e2e" else get_precision_at_k
   __snake_case								=       evaluate_batch_eae if args.eval_mode == "e2e" else evaluate_batch_retrieval

   for checkpoint in checkpoints:
      if os.path.exists(args.predictions_path	) and (not args.recalculate):
         logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path	)	)
         score_fn(__lowerCamelCase	,				args.predictions_path	,				args.gold_data_path	)
         continue

      logger.info('''***** Running evaluation for {} *****'''.format(__lowerCamelCase	)	)
      logger.info('''  Batch size = %d'''	,				args.eval_batch_size	)
      logger.info('''  Predictions will be stored under {}'''.format(args.predictions_path	)	)

      if args.model_type.startswith('''rag'''	):
         __snake_case								=       RagRetriever.from_pretrained(__lowerCamelCase	,				**__lowerCamelCase	)
         __snake_case								=       model_class.from_pretrained(__lowerCamelCase	,				retriever=__lowerCamelCase	,				**__lowerCamelCase	)
         model.retriever.init_retrieval()
      else:
         __snake_case								=       model_class.from_pretrained(__lowerCamelCase	,				**__lowerCamelCase	)
      model.to(args.device	)

      with open(args.evaluation_set	,				'''r'''	) as eval_file, open(args.predictions_path	,				'''w'''	) as preds_file:
         __snake_case								=       []
         for line in tqdm(__lowerCamelCase	):
            questions.append(line.strip()	)
            if len(__lowerCamelCase	) == args.eval_batch_size:
               __snake_case								=       evaluate_batch_fn(__lowerCamelCase	,				__lowerCamelCase	,				__lowerCamelCase	)
               preds_file.write('''\n'''.join(__lowerCamelCase	) + '''\n'''	)
               preds_file.flush()
               __snake_case								=       []
         if len(__lowerCamelCase	) > 0:
            __snake_case								=       evaluate_batch_fn(__lowerCamelCase	,				__lowerCamelCase	,				__lowerCamelCase	)
            preds_file.write('''\n'''.join(__lowerCamelCase	)	)
            preds_file.flush()

         score_fn(__lowerCamelCase	,				args.predictions_path	,				args.gold_data_path	)


if __name__ == "__main__":
      snake_case_           =      get_args()
      main(args)








import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
snake_case_           =      data_utils.TransfoXLTokenizer
snake_case_           =      data_utils.TransfoXLCorpus
snake_case_           =      data_utils
snake_case_           =      data_utils






def lowerCamelCase__   (							snake_case_     :  Union[str, Any]	,				snake_case_     :  int	,				snake_case_     :  List[Any]	,				snake_case_     :  int	)				->    Dict:
   if transfo_xl_dataset_file:
      # Convert a pre-processed corpus (see original TensorFlow repo)
      with open(snake_case_	,				'''rb'''	) as fp:
         __snake_case								=       pickle.load(snake_case_	,				encoding='''latin1'''	)
      # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
      __snake_case								=       pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''pretrained_vocab_file''']
      print(f"""Save vocabulary to {pytorch_vocab_dump_path}"""	)
      __snake_case								=       corpus.vocab.__dict__
      torch.save(snake_case_	,				snake_case_	)

      __snake_case								=       corpus.__dict__
      corpus_dict_no_vocab.pop('''vocab'''	,				snake_case_	)
      __snake_case								=       pytorch_dump_folder_path + '''/''' + CORPUS_NAME
      print(f"""Save dataset to {pytorch_dataset_dump_path}"""	)
      torch.save(snake_case_	,				snake_case_	)

   if tf_checkpoint_path:
      # Convert a pre-trained TensorFlow model
      __snake_case								=       os.path.abspath(snake_case_	)
      __snake_case								=       os.path.abspath(snake_case_	)

      print(f"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}."""	)
      # Initialise PyTorch model
      if transfo_xl_config_file == "":
         __snake_case								=       TransfoXLConfig()
      else:
         __snake_case								=       TransfoXLConfig.from_json_file(snake_case_	)
      print(f"""Building PyTorch model from configuration: {config}"""	)
      __snake_case								=       TransfoXLLMHeadModel(snake_case_	)

      __snake_case								=       load_tf_weights_in_transfo_xl(snake_case_	,				snake_case_	,				snake_case_	)
      # Save pytorch-model
      __snake_case								=       os.path.join(snake_case_	,				snake_case_	)
      __snake_case								=       os.path.join(snake_case_	,				snake_case_	)
      print(f"""Save PyTorch model to {os.path.abspath(snake_case_	)}"""	)
      torch.save(model.state_dict()	,				snake_case_	)
      print(f"""Save configuration file to {os.path.abspath(snake_case_	)}"""	)
      with open(snake_case_	,				'''w'''	,				encoding='''utf-8'''	) as f:
         f.write(config.to_json_string()	)


if __name__ == "__main__":
    snake_case_           =      argparse.ArgumentParser()
    parser.add_argument(
        '--pytorch_dump_folder_path',
        default=None,
        type=str,
        required=True,
        help='Path to the folder to store the PyTorch model or dataset/vocab.',
    )
    parser.add_argument(
        '--tf_checkpoint_path',
        default='',
        type=str,
        help='An optional path to a TensorFlow checkpoint path to be converted.',
    )
    parser.add_argument(
        '--transfo_xl_config_file',
        default='',
        type=str,
        help=(
            'An optional config json file corresponding to the pre-trained BERT model. \n'
            'This specifies the model architecture.'
        ),
    )
    parser.add_argument(
        '--transfo_xl_dataset_file',
        default='',
        type=str,
        help='An optional dataset file to be converted in a vocabulary.',
    )
    snake_case_           =      parser.parse_args()
    convert_transfo_xl_checkpoint_to_pytorch(
        args.tf_checkpoint_path,
        args.transfo_xl_config_file,
        args.pytorch_dump_folder_path,
        args.transfo_xl_dataset_file,
    )

