

"""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)
__UpperCAmelCase =				logging.getLogger(__name__)


__UpperCAmelCase =				'Hello world! cécé herlolip'


__UpperCAmelCase =				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   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase      ):
 '''simple docstring'''





 UpperCAmelCase__					:  Optional[Any]					   =					BertAbsConfig(
     temp_dir="""."""							,    finetune_bert=__UpperCamelCase							,    large=__UpperCamelCase							,    share_emb=__UpperCamelCase							,    use_bert_emb=__UpperCamelCase							,    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							,    )
 UpperCAmelCase__					:  Optional[Any]					   =					torch.load(__UpperCamelCase							,    lambda __UpperCamelCase							,    __UpperCamelCase      : storage      )
 UpperCAmelCase__					:  int					   =					AbsSummarizer(__UpperCamelCase							,    torch.device("""cpu"""      )							,    __UpperCamelCase      )
 original.eval()

 UpperCAmelCase__					:  Dict					   =					BertAbsSummarizer(__UpperCamelCase							,    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"""      )
 UpperCAmelCase__					:  Any					   =					BertTokenizer.from_pretrained("""bert-base-uncased"""      )

 # prepare the model inputs
 UpperCAmelCase__					:  List[Any]					   =					tokenizer.encode("""This is sample éàalj'-."""      )
 encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__UpperCamelCase      ))      )
 UpperCAmelCase__					:  Tuple					   =					torch.tensor(__UpperCamelCase      ).unsqueeze(0      )
 UpperCAmelCase__					:  Union[str, Any]					   =					tokenizer.encode("""This is sample 3 éàalj'-."""      )
 decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__UpperCamelCase      ))      )
 UpperCAmelCase__					:  str					   =					torch.tensor(__UpperCamelCase      ).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
 UpperCAmelCase__					:  Tuple					   =					encoder_input_ids
 UpperCAmelCase__					:  Optional[int]					   =					decoder_input_ids
 UpperCAmelCase__					:  List[Any]					   =					None
 UpperCAmelCase__					:  Any					   =					None
 UpperCAmelCase__					:  int					   =					None
 UpperCAmelCase__					:  Tuple					   =					None
 UpperCAmelCase__					:  Dict					   =					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
 UpperCAmelCase__					:  Any					   =					original(__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase      )[0]
 UpperCAmelCase__					:  Tuple					   =					original.generator(__UpperCamelCase      )

 UpperCAmelCase__					:  Tuple					   =					new_model(
     __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase      )[0]
 UpperCAmelCase__					:  Optional[Any]					   =					new_model.generator(__UpperCamelCase      )

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

 UpperCAmelCase__					:  Optional[int]					   =					torch.allclose(__UpperCamelCase							,    __UpperCamelCase							,    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__":
      __UpperCAmelCase =				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.',
      )
      __UpperCAmelCase =				parser.parse_args()

      convert_bertabs_checkpoints(
          args.bertabs_checkpoint_path,
          args.pytorch_dump_folder_path,
      )








"""simple docstring"""




from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('3.8'):
      import importlib_metadata
else:
      import importlib.metadata as importlib_metadata


__UpperCAmelCase =				''


if version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'):







      class      __lowercase			(    tr.AbstractTransform					):

        def __init__(  self		:			List[str]					,A		:			str = " "    ):






         '''simple docstring'''
         UpperCAmelCase__					:  str					   =					sentence_delimiter

        def    __lowercase       (  self		:			Union[str, Any]					,A		:			str    ):






         '''simple docstring'''
         return list(A    )




        def    __lowercase       (  self		:			int					,A		:			List[str]    ):






         '''simple docstring'''
         UpperCAmelCase__					:  Any					   =					[]
         for sent_idx, sentence in enumerate(A    ):
          chars.extend(self.process_string(A    )    )
          if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(A    ) - 1:
           chars.append(self.sentence_delimiter    )
         return chars







      __UpperCAmelCase =				tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      __UpperCAmelCase =				tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


__UpperCAmelCase =				'\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'

__UpperCAmelCase =				'\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n'

__UpperCAmelCase =				'\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character error rate\n\nExamples:\n\n    >>> predictions = ["this is the prediction", "there is an other sample"]\n    >>> references = ["this is the reference", "there is another one"]\n    >>> cer = datasets.load_metric("cer")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n'







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

  def    __lowercase       (  self		:			int    ):






   '''simple docstring'''
   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/jitsi/jiwer/"""]					,reference_urls=[
           """https://en.wikipedia.org/wiki/Word_error_rate""",
           """https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
       ]					,)




  def    __lowercase       (  self		:			Union[str, Any]					,A		:			Optional[Any]					,A		:			Tuple					,A		:			str=False    ):






   '''simple docstring'''
   if concatenate_texts:
    return jiwer.compute_measures(
        A					,A					,truth_transform=A					,hypothesis_transform=A					,)["wer"]

   UpperCAmelCase__					:  Tuple					   =					0
   UpperCAmelCase__					:  Any					   =					0
   for prediction, reference in zip(A					,A    ):
    UpperCAmelCase__					:  List[str]					   =					jiwer.compute_measures(
        A					,A					,truth_transform=A					,hypothesis_transform=A					,)
    incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
    total += measures["substitutions"] + measures["deletions"] + measures["hits"]

   return incorrect / total





