from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


a_							=      """\
@article{wang2019superglue,
  title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},
  author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},
  journal={arXiv preprint arXiv:1905.00537},
  year={2019}
}
"""

a_							=      """\
SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after
GLUE with a new set of more difficult language understanding tasks, improved
resources, and a new public leaderboard.
"""

a_							=      """
Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset.
Args:
    predictions: list of predictions to score. Depending on the SuperGlUE subset:
        - for 'record': list of question-answer dictionaries with the following keys:
            - 'idx': index of the question as specified by the dataset
            - 'prediction_text': the predicted answer text
        - for 'multirc': list of question-answer dictionaries with the following keys:
            - 'idx': index of the question-answer pair as specified by the dataset
            - 'prediction': the predicted answer label
        - otherwise: list of predicted labels
    references: list of reference labels. Depending on the SuperGLUE subset:
        - for 'record': list of question-answers dictionaries with the following keys:
            - 'idx': index of the question as specified by the dataset
            - 'answers': list of possible answers
        - otherwise: list of reference labels
Returns: depending on the SuperGLUE subset:
    - for 'record':
        - 'exact_match': Exact match between answer and gold answer
        - 'f1': F1 score
    - for 'multirc':
        - 'exact_match': Exact match between answer and gold answer
        - 'f1_m': Per-question macro-F1 score
        - 'f1_a': Average F1 score over all answers
    - for 'axb':
        'matthews_correlation': Matthew Correlation
    - for 'cb':
        - 'accuracy': Accuracy
        - 'f1': F1 score
    - for all others:
        - 'accuracy': Accuracy
Examples:

    >>> super_glue_metric = datasets.load_metric('super_glue', 'copa')  # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0, 'f1': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'record')
    >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]
    >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 1.0, 'f1': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')
    >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'matthews_correlation': 1.0}
"""




def       __lowerCAmelCase      (						A_   : Tuple						,	A_   : List[Any]					)    ->  Tuple:
  return float((preds == labels).mean()					)




def       __lowerCAmelCase      (						A_   : List[str]						,	A_   : Optional[Any]						,	A_   : Dict="binary"					)    ->  List[str]:
  __UpperCAmelCase						    =       simple_accuracy(A_						,	A_					)
  __UpperCAmelCase						    =       float(fa_score(y_true=A_						,	y_pred=A_						,	average=A_					)					)
  return {
      "accuracy": acc,
      "f1": fa,
  }




def       __lowerCAmelCase      (						A_   : Tuple						,	A_   : List[str]					)    ->  List[str]:
  __UpperCAmelCase						    =       {}
  for id_pred, label in zip(A_						,	A_					):
    __UpperCAmelCase						    =       F'''{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}'''
    __UpperCAmelCase						    =       id_pred["prediction"]
    if question_id in question_map:
      question_map[question_id].append((pred, label)					)
    else:
      __UpperCAmelCase						    =       [(pred, label)]
  __UpperCAmelCase    ,		__UpperCAmelCase						    =       [], []
  for question, preds_labels in question_map.items():
    __UpperCAmelCase    ,		__UpperCAmelCase						    =       zip(*A_					)
    __UpperCAmelCase						    =       fa_score(y_true=A_						,	y_pred=A_						,	average="macro"					)
    fas.append(A_					)
    __UpperCAmelCase						    =       int(sum(pred == label for pred, label in preds_labels					) == len(A_					)					)
    ems.append(A_					)
  __UpperCAmelCase						    =       float(sum(A_					) / len(A_					)					)
  __UpperCAmelCase						    =       sum(A_					) / len(A_					)
  __UpperCAmelCase						    =       float(fa_score(y_true=A_						,	y_pred=[id_pred["prediction"] for id_pred in ids_preds]					)					)
  return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a}





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



  """simple docstring"""






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




    '''simple docstring'''




    if self.config_name not in [
        "boolq",
        "cb",
        "copa",
        "multirc",
        "record",
        "rte",
        "wic",
        "wsc",
        "wsc.fixed",
        "axb",
        "axg",
    ]:
      raise KeyError(
          "You should supply a configuration name selected in "
          "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]"   )
    return datasets.MetricInfo(
        description=_DESCRIPTION				,				citation=_CITATION				,				inputs_description=_KWARGS_DESCRIPTION				,				features=datasets.Features(self._get_feature_types()   )				,				codebase_urls=[]				,				reference_urls=[]				,				format="numpy" if not self.config_name == "record" and not self.config_name == "multirc" else None				,				)






  def 	_UpperCAmelCase				(				self:			Optional[Any]   ) -> List[Any]:




    '''simple docstring'''




    if self.config_name == "record":
      return {
          "predictions": {
              "idx": {
                  "passage": datasets.Value("int64"   ),
                  "query": datasets.Value("int64"   ),
              },
              "prediction_text": datasets.Value("string"   ),
          },
          "references": {
              "idx": {
                  "passage": datasets.Value("int64"   ),
                  "query": datasets.Value("int64"   ),
              },
              "answers": datasets.Sequence(datasets.Value("string"   )   ),
          },
      }
    elif self.config_name == "multirc":
      return {
          "predictions": {
              "idx": {
                  "answer": datasets.Value("int64"   ),
                  "paragraph": datasets.Value("int64"   ),
                  "question": datasets.Value("int64"   ),
              },
              "prediction": datasets.Value("int64"   ),
          },
          "references": datasets.Value("int64"   ),
      }
    else:
      return {
          "predictions": datasets.Value("int64"   ),
          "references": datasets.Value("int64"   ),
      }






  def 	_UpperCAmelCase				(				self:			Optional[Any]				,				__lowerCAmelCase:			List[Any]				,				__lowerCAmelCase:			Dict   ) -> List[str]:




    '''simple docstring'''




    if self.config_name == "axb":
      return {"matthews_correlation": matthews_corrcoef(__lowerCAmelCase				,				__lowerCAmelCase   )}
    elif self.config_name == "cb":
      return acc_and_fa(__lowerCAmelCase				,				__lowerCAmelCase				,				fa_avg="macro"   )
    elif self.config_name == "record":
      __UpperCAmelCase						    =       [
          {
              "qas": [
                  {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]}
                  for ref in references
              ]
          }
      ]
      __UpperCAmelCase						    =       {pred["idx"]["query"]: pred["prediction_text"] for pred in predictions}
      return evaluate_record(__lowerCAmelCase				,				__lowerCAmelCase   )[0]
    elif self.config_name == "multirc":
      return evaluate_multirc(__lowerCAmelCase				,				__lowerCAmelCase   )
    elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]:
      return {"accuracy": simple_accuracy(__lowerCAmelCase				,				__lowerCAmelCase   )}
    else:
      raise KeyError(
          "You should supply a configuration name selected in "
          "[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]"   )




import argparse
import hashlib
import os
import urllib
import warnings

import torch
from torch import nn
from tqdm import tqdm

from transformers import WhisperConfig, WhisperForConditionalGeneration


a_							=      {
    """tiny.en""": """https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt""",
    """tiny""": """https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt""",
    """base.en""": """https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt""",
    """base""": """https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt""",
    """small.en""": """https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt""",
    """small""": """https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt""",
    """medium.en""": """https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt""",
    """medium""": """https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt""",
    """large""": """https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt""",
    """large-v2""": """https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt""",
}




def       __lowerCAmelCase      (						A_   : Optional[int]					)    ->  str:
  __UpperCAmelCase						    =       ["layers", "blocks"]
  for k in ignore_keys:
    state_dict.pop(A_						,	A_					)


a_							=      {
    """blocks""": """layers""",
    """mlp.0""": """fc1""",
    """mlp.2""": """fc2""",
    """mlp_ln""": """final_layer_norm""",
    """.attn.query""": """.self_attn.q_proj""",
    """.attn.key""": """.self_attn.k_proj""",
    """.attn.value""": """.self_attn.v_proj""",
    """.attn_ln""": """.self_attn_layer_norm""",
    """.attn.out""": """.self_attn.out_proj""",
    """.cross_attn.query""": """.encoder_attn.q_proj""",
    """.cross_attn.key""": """.encoder_attn.k_proj""",
    """.cross_attn.value""": """.encoder_attn.v_proj""",
    """.cross_attn_ln""": """.encoder_attn_layer_norm""",
    """.cross_attn.out""": """.encoder_attn.out_proj""",
    """decoder.ln.""": """decoder.layer_norm.""",
    """encoder.ln.""": """encoder.layer_norm.""",
    """token_embedding""": """embed_tokens""",
    """encoder.positional_embedding""": """encoder.embed_positions.weight""",
    """decoder.positional_embedding""": """decoder.embed_positions.weight""",
    """ln_post""": """layer_norm""",
}




def       __lowerCAmelCase      (						A_   : str					)    ->  List[str]:
  __UpperCAmelCase						    =       list(s_dict.keys()					)
  for key in keys:
    __UpperCAmelCase						    =       key
    for k, v in WHISPER_MAPPING.items():
      if k in key:
        __UpperCAmelCase						    =       new_key.replace(A_						,	A_					)

    print(F'''{key} -> {new_key}'''					)

    __UpperCAmelCase						    =       s_dict.pop(A_					)
  return s_dict




def       __lowerCAmelCase      (						A_   : List[Any]					)    ->  List[Any]:
  __UpperCAmelCase    ,		__UpperCAmelCase						    =       emb.weight.shape
  __UpperCAmelCase						    =       nn.Linear(A_						,	A_						,	bias=A_					)
  __UpperCAmelCase						    =       emb.weight.data
  return lin_layer




def       __lowerCAmelCase      (						A_   : str						,	A_   : str					)    ->  bytes:
  os.makedirs(A_						,	exist_ok=A_					)
  __UpperCAmelCase						    =       os.path.basename(A_					)

  __UpperCAmelCase						    =       url.split("/"					)[-2]
  __UpperCAmelCase						    =       os.path.join(A_						,	A_					)

  if os.path.exists(A_					) and not os.path.isfile(A_					):
    raise RuntimeError(F'''{download_target} exists and is not a regular file'''					)

  if os.path.isfile(A_					):
    __UpperCAmelCase						    =       open(A_						,	"rb"					).read()
    if hashlib.shaaaa(A_					).hexdigest() == expected_shaaaa:
      return model_bytes
    else:
      warnings.warn(F'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file'''					)

  with urllib.request.urlopen(A_					) as source, open(A_						,	"wb"					) as output:
    with tqdm(
        total=int(source.info().get("Content-Length"					)					)						,	ncols=80						,	unit="iB"						,	unit_scale=A_						,	unit_divisor=10_24					) as loop:
      while True:
        __UpperCAmelCase						    =       source.read(81_92					)
        if not buffer:
          break

        output.write(A_					)
        loop.update(len(A_					)					)

  __UpperCAmelCase						    =       open(A_						,	"rb"					).read()
  if hashlib.shaaaa(A_					).hexdigest() != expected_shaaaa:
    raise RuntimeError(
        "Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model."					)

  return model_bytes




def       __lowerCAmelCase      (						A_   : Dict						,	A_   : Optional[Any]					)    ->  Optional[Any]:
  if ".pt" not in checkpoint_path:
    __UpperCAmelCase						    =       _download(_MODELS[checkpoint_path]					)
  else:
    __UpperCAmelCase						    =       torch.load(A_						,	map_location="cpu"					)
  __UpperCAmelCase						    =       original_checkpoint["dims"]
  __UpperCAmelCase						    =       original_checkpoint["model_state_dict"]
  __UpperCAmelCase						    =       state_dict["decoder.token_embedding.weight"]
  remove_ignore_keys_(A_					)
  rename_keys(A_					)
  __UpperCAmelCase						    =       True
  __UpperCAmelCase						    =       state_dict["decoder.layers.0.fc1.weight"].shape[0]

  __UpperCAmelCase						    =       WhisperConfig(
      vocab_size=dimensions["n_vocab"]						,	encoder_ffn_dim=A_						,	decoder_ffn_dim=A_						,	num_mel_bins=dimensions["n_mels"]						,	d_model=dimensions["n_audio_state"]						,	max_target_positions=dimensions["n_text_ctx"]						,	encoder_layers=dimensions["n_audio_layer"]						,	encoder_attention_heads=dimensions["n_audio_head"]						,	decoder_layers=dimensions["n_text_layer"]						,	decoder_attention_heads=dimensions["n_text_state"]						,	max_source_positions=dimensions["n_audio_ctx"]						,	)

  __UpperCAmelCase						    =       WhisperForConditionalGeneration(A_					)
  __UpperCAmelCase    ,		__UpperCAmelCase						    =       model.model.load_state_dict(A_						,	strict=A_					)
  if len(A_					) > 0 and not set(A_					) <= {
      "encoder.embed_positions.weights",
      "decoder.embed_positions.weights",
  }:
    raise ValueError(
        "Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,"
        F''' but all the following weights are missing {missing}'''					)

  if tie_embeds:
    __UpperCAmelCase						    =       make_linear_from_emb(model.model.decoder.embed_tokens					)
  else:
    __UpperCAmelCase						    =       proj_out_weights

  model.save_pretrained(A_					)


if __name__ == "__main__":
       a_							=      argparse.ArgumentParser()
       # # Required parameters
       parser.add_argument("""--checkpoint_path""", type=str, help="""Patht to the downloaded checkpoints""")
       parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
       a_							=      parser.parse_args()

       convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)



