






'''simple docstring'''




import argparse
import logging
from collections import namedtuple

import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer  # The authors' implementation

from transformers import BertTokenizer


logging.basicConfig(level=logging.INFO)
__lowerCamelCase   :					int   							=					logging.getLogger(__name__)


__lowerCamelCase   :					Union[str, Any]   							=					'Hello world! cécé herlolip'


__lowerCamelCase   :					Union[str, Any]   							=					namedtuple(
    '''BertAbsConfig''',
    [
        '''temp_dir''',
        '''large''',
        '''use_bert_emb''',
        '''finetune_bert''',
        '''encoder''',
        '''share_emb''',
        '''max_pos''',
        '''enc_layers''',
        '''enc_hidden_size''',
        '''enc_heads''',
        '''enc_ff_size''',
        '''enc_dropout''',
        '''dec_layers''',
        '''dec_hidden_size''',
        '''dec_heads''',
        '''dec_ff_size''',
        '''dec_dropout''',
    ],
)

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    List[Any]:



   """simple docstring"""



   snake_case_				:					List[str]   =       BertAbsConfig(
       temp_dir="."     ,finetune_bert=_lowerCamelCase     ,large=_lowerCamelCase     ,share_emb=_lowerCamelCase     ,use_bert_emb=_lowerCamelCase     ,encoder="bert"     ,max_pos=512     ,enc_layers=6     ,enc_hidden_size=512     ,enc_heads=8     ,enc_ff_size=512     ,enc_dropout=0.2     ,dec_layers=6     ,dec_hidden_size=768     ,dec_heads=8     ,dec_ff_size=2048     ,dec_dropout=0.2     ,)
   snake_case_				:					Tuple   =       torch.load(_lowerCamelCase     ,lambda __magic_name__     ,__magic_name__						: storage						)
   snake_case_				:					int   =       AbsSummarizer(_lowerCamelCase     ,torch.device("cpu"						)     ,_lowerCamelCase						)
   original.eval()

   snake_case_				:					Any   =       BertAbsSummarizer(_lowerCamelCase     ,torch.device("cpu"						)						)
   new_model.eval()

   # -------------------
   # Convert the weights
   # -------------------

   logging.info("convert the model"						)
   new_model.bert.load_state_dict(original.bert.state_dict()						)
   new_model.decoder.load_state_dict(original.decoder.state_dict()						)
   new_model.generator.load_state_dict(original.generator.state_dict()						)

   # ----------------------------------
   # Make sure the outpus are identical
   # ----------------------------------

   logging.info("Make sure that the models' outputs are identical"						)
   snake_case_				:					Any   =       BertTokenizer.from_pretrained("bert-base-uncased"						)

   # prepare the model inputs
   snake_case_				:					Tuple   =       tokenizer.encode("This is sample éàalj'-."						)
   encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(_lowerCamelCase						))						)
   snake_case_				:					Optional[Any]   =       torch.tensor(_lowerCamelCase						).unsqueeze(0						)
   snake_case_				:					Optional[Any]   =       tokenizer.encode("This is sample 3 éàalj'-."						)
   decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(_lowerCamelCase						))						)
   snake_case_				:					Optional[int]   =       torch.tensor(_lowerCamelCase						).unsqueeze(0						)

   # failsafe to make sure the weights reset does not affect the
   # loaded weights.
   assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight						)						) == 0

   # forward pass
   snake_case_				:					Any   =       encoder_input_ids
   snake_case_				:					Union[str, Any]   =       decoder_input_ids
   snake_case_				:					Tuple   =       None
   snake_case_				:					Optional[int]   =       None
   snake_case_				:					int   =       None
   snake_case_				:					Any   =       None
   snake_case_				:					Optional[int]   =       None

   # The original model does not apply the geneator layer immediatly but rather in
   # the beam search (where it combines softmax + linear layer). Since we already
   # apply the softmax in our generation process we only apply the linear layer here.
   # We make sure that the outputs of the full stack are identical
   snake_case_				:					List[str]   =       original(_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase						)[0]
   snake_case_				:					Dict   =       original.generator(_lowerCamelCase						)

   snake_case_				:					str   =       new_model(
       _lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase     ,_lowerCamelCase						)[0]
   snake_case_				:					Optional[int]   =       new_model.generator(_lowerCamelCase						)

   snake_case_				:					Optional[Any]   =       torch.max(torch.abs(output_converted_model - output_original_model						)						).item()
   print("Maximum absolute difference beween weights: {:.2f}".format(_lowerCamelCase						)						)
   snake_case_				:					Union[str, Any]   =       torch.max(torch.abs(output_converted_generator - output_original_generator						)						).item()
   print("Maximum absolute difference beween weights: {:.2f}".format(_lowerCamelCase						)						)

   snake_case_				:					Any   =       torch.allclose(_lowerCamelCase     ,_lowerCamelCase     ,atol=1E-3						)
   if are_identical:
      logging.info("all weights are equal up to 1e-3"						)
   else:
      raise ValueError("the weights are different. The new model is likely different from the original one."						)

   # The model has been saved with torch.save(model) and this is bound to the exact
   # directory structure. We save the state_dict instead.
   logging.info("saving the model's state dictionary"						)
   torch.save(
       new_model.state_dict()     ,"./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin"						)


if __name__ == "__main__":
  __lowerCamelCase   :					Union[str, Any]   							=					argparse.ArgumentParser()
  parser.add_argument(
      '''--bertabs_checkpoint_path''',
      default=None,
      type=str,
      required=True,
      help='''Path the official PyTorch dump.''',
  )
  parser.add_argument(
      '''--pytorch_dump_folder_path''',
      default=None,
      type=str,
      required=True,
      help='''Path to the output PyTorch model.''',
  )
  __lowerCamelCase   :					Optional[Any]   							=					parser.parse_args()

  convert_bertabs_checkpoints(
      args.bertabs_checkpoint_path,
      args.pytorch_dump_folder_path,
  )












'''simple docstring'''




import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


__lowerCamelCase   :					str   							=					'''\
@inproceedings{snover-etal-2006-study,
    title = "A Study of Translation Edit Rate with Targeted Human Annotation",
    author = "Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John",
    booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",
    month = aug # " 8-12",
    year = "2006",
    address = "Cambridge, Massachusetts, USA",
    publisher = "Association for Machine Translation in the Americas",
    url = "https://aclanthology.org/2006.amta-papers.25",
    pages = "223--231",
}
@inproceedings{post-2018-call,
    title = "A Call for Clarity in Reporting {BLEU} Scores",
    author = "Post, Matt",
    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
    month = oct,
    year = "2018",
    address = "Belgium, Brussels",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W18-6319",
    pages = "186--191",
}
'''

__lowerCamelCase   :					Dict   							=					'''\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
'''

__lowerCamelCase   :					int   							=					'''
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)
    \'num_edits\' (int): The cumulative number of edits
    \'ref_length\' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?",
        ...                     "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}

    Example 2:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}

    Example 3:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}

    Example 4:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}

    Example 5:
        >>> predictions = ["does this sentence match??",
        ...                    "what about this sentence?",
        ...                    "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}
'''







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,					_KWARGS_DESCRIPTION							)
class    A_	(datasets.Metric							):
							"""simple docstring"""




							def 							_A	(		self			:Optional[Any]				)				->  Optional[int]:


										'''simple docstring'''




										if version.parse(scb.__version__				) < version.parse("1.4.12"				):
													raise ImportWarning(
													    "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
													    "You can install it with `pip install \"sacrebleu>=1.4.12\"`."				)
										return datasets.MetricInfo(
										    description=_DESCRIPTION       ,							citation=_CITATION       ,							homepage="http://www.cs.umd.edu/~snover/tercom/"       ,							inputs_description=_KWARGS_DESCRIPTION       ,							features=datasets.Features(
										        {
										            "predictions": datasets.Value("string"       ,							id="sequence"				),
										            "references": datasets.Sequence(datasets.Value("string"       ,							id="sequence"				)       ,							id="references"				),
										        }				)       ,							codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"]       ,							reference_urls=[
										        "https://github.com/jhclark/tercom",
										    ]       ,							)






							def 							_A	(		self			:Any       ,							lowerCAmelCase__			:Any       ,							lowerCAmelCase__			:str       ,							lowerCAmelCase__			:bool = False       ,							lowerCAmelCase__			:bool = False       ,							lowerCAmelCase__			:bool = False       ,							lowerCAmelCase__			:bool = False       ,							)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					List[str]   =       len(references[0]				)
										if any(len(lowerCAmelCase__				) != references_per_prediction for refs in references				):
													raise ValueError("Sacrebleu requires the same number of references for each prediction"				)
										snake_case_				:					List[str]   =       [[refs[i] for refs in references] for i in range(lowerCAmelCase__				)]

										snake_case_				:					List[str]   =       TER(
										    normalized=lowerCAmelCase__       ,							no_punct=lowerCAmelCase__       ,							asian_support=lowerCAmelCase__       ,							case_sensitive=lowerCAmelCase__       ,							)
										snake_case_				:					Any   =       sb_ter.corpus_score(lowerCAmelCase__       ,							lowerCAmelCase__				)

										return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}




