


import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO
)
__snake_case         =					logging.getLogger(__name__)







def 						__lowerCAmelCase		(		lowercase						:						List[str]		,							lowercase						:						Dict				)			->		str:


    """simple docstring"""





    snake_case					:   Dict         =					np.argmax(lowercase		,							axis=1				)
    return np.sum(outputs == labels				)







def 						__lowerCAmelCase		(		lowercase						:						Optional[Any]				)			->		List[Any]:


    """simple docstring"""





    with open(lowercase		,							encoding="utf_8"				) as f:
        snake_case					:   str         =					csv.reader(lowercase				)
        snake_case					:   Union[str, Any]         =					[]
        next(lowercase				)  # skip the first line
        for line in tqdm(lowercase				):
            output.append((" ".join(line[1:5]				), line[5], line[6], int(line[-1]				) - 1)				)
    return output







def 						__lowerCAmelCase		(		lowercase						:						Tuple		,							lowercase						:						Optional[int]		,							lowercase						:						List[str]		,							lowercase						:						int		,							lowercase						:						List[str]		,							lowercase						:						Tuple				)			->		Any:


    """simple docstring"""





    snake_case					:   Dict         =					[]
    for dataset in encoded_datasets:
        snake_case					:   int         =					len(lowercase				)
        snake_case					:   Optional[Any]         =					np.zeros((n_batch, 2, input_len)		,							dtype=np.intaa				)
        snake_case					:   Tuple         =					np.zeros((n_batch, 2)		,							dtype=np.intaa				)
        snake_case					:   List[Any]         =					np.full((n_batch, 2, input_len)		,							fill_value=-100		,							dtype=np.intaa				)
        snake_case					:   str         =					np.zeros((n_batch,)		,							dtype=np.intaa				)
        for (
            i,
            (story, conta, conta, mc_label),
        ) in enumerate(lowercase				):
            snake_case					:   int         =					[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
            snake_case					:   List[Any]         =					[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
            snake_case					:   Optional[Any]         =					with_conta
            snake_case					:   Tuple         =					with_conta
            snake_case					:   Tuple         =					len(lowercase				) - 1
            snake_case					:   Dict         =					len(lowercase				) - 1
            snake_case					:   Union[str, Any]         =					with_conta
            snake_case					:   Dict         =					with_conta
            snake_case					:   Union[str, Any]         =					mc_label
        snake_case					:   Optional[Any]         =					(input_ids, mc_token_ids, lm_labels, mc_labels)
        tensor_datasets.append(tuple(torch.tensor(lowercase				) for t in all_inputs				)				)
    return tensor_datasets







def 						__lowerCAmelCase		(		)			->		Optional[Any]:


    """simple docstring"""





    snake_case					:   List[str]         =					argparse.ArgumentParser()
    parser.add_argument("--model_name"		,							type=lowercase		,							default="openai-gpt"		,							help="pretrained model name"				)
    parser.add_argument("--do_train"		,							action="store_true"		,							help="Whether to run training."				)
    parser.add_argument("--do_eval"		,							action="store_true"		,							help="Whether to run eval on the dev set."				)
    parser.add_argument(
        "--output_dir"		,							default=lowercase		,							type=lowercase		,							required=lowercase		,							help="The output directory where the model predictions and checkpoints will be written."		,							)
    parser.add_argument("--train_dataset"		,							type=lowercase		,							default=""				)
    parser.add_argument("--eval_dataset"		,							type=lowercase		,							default=""				)
    parser.add_argument("--seed"		,							type=lowercase		,							default=42				)
    parser.add_argument("--num_train_epochs"		,							type=lowercase		,							default=3				)
    parser.add_argument("--train_batch_size"		,							type=lowercase		,							default=8				)
    parser.add_argument("--eval_batch_size"		,							type=lowercase		,							default=16				)
    parser.add_argument("--adam_epsilon"		,							default=1e-8		,							type=lowercase		,							help="Epsilon for Adam optimizer."				)
    parser.add_argument("--max_grad_norm"		,							type=lowercase		,							default=1				)
    parser.add_argument(
        "--max_steps"		,							default=-1		,							type=lowercase		,							help=(
            "If > 0: set total number of training                         steps to perform. Override num_train_epochs."
        )		,							)
    parser.add_argument(
        "--gradient_accumulation_steps"		,							type=lowercase		,							default=1		,							help="Number of updates steps to accumulate before                        performing a backward/update pass."		,							)
    parser.add_argument("--learning_rate"		,							type=lowercase		,							default=6.2_5e-5				)
    parser.add_argument("--warmup_steps"		,							default=0		,							type=lowercase		,							help="Linear warmup over warmup_steps."				)
    parser.add_argument("--lr_schedule"		,							type=lowercase		,							default="warmup_linear"				)
    parser.add_argument("--weight_decay"		,							type=lowercase		,							default=0.01				)
    parser.add_argument("--lm_coef"		,							type=lowercase		,							default=0.9				)
    parser.add_argument("--n_valid"		,							type=lowercase		,							default=374				)

    parser.add_argument("--server_ip"		,							type=lowercase		,							default=""		,							help="Can be used for distant debugging."				)
    parser.add_argument("--server_port"		,							type=lowercase		,							default=""		,							help="Can be used for distant debugging."				)
    snake_case					:   Any         =					parser.parse_args()
    print(lowercase				)

    if args.server_ip and args.server_port:
        # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
        import ptvsd

        print("Waiting for debugger attach"				)
        ptvsd.enable_attach(address=(args.server_ip, args.server_port)		,							redirect_output=lowercase				)
        ptvsd.wait_for_attach()

    random.seed(args.seed				)
    np.random.seed(args.seed				)
    torch.manual_seed(args.seed				)
    torch.cuda.manual_seed_all(args.seed				)

    snake_case					:   int         =					torch.device("cuda" if torch.cuda.is_available() else "cpu"				)
    snake_case					:   Dict         =					torch.cuda.device_count()
    logger.info("device: {}, n_gpu {}".format(lowercase		,							lowercase				)				)

    if not args.do_train and not args.do_eval:
        raise ValueError("At least one of `do_train` or `do_eval` must be True."				)

    if not os.path.exists(args.output_dir				):
        os.makedirs(args.output_dir				)

    # Load tokenizer and model
    # This loading functions also add new tokens and embeddings called `special tokens`
    # These new embeddings will be fine-tuned on the RocStories dataset
    snake_case					:   Any         =					["_start_", "_delimiter_", "_classify_"]
    snake_case					:   Optional[int]         =					OpenAIGPTTokenizer.from_pretrained(args.model_name				)
    tokenizer.add_tokens(lowercase				)
    snake_case					:   List[Any]         =					tokenizer.convert_tokens_to_ids(lowercase				)
    snake_case					:   int         =					OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name				)
    model.resize_token_embeddings(len(lowercase				)				)
    model.to(lowercase				)

    # Load and encode the datasets
    def tokenize_and_encode(lowercase						:						Optional[int]				):
        if isinstance(lowercase		,							lowercase				):
            return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(lowercase				)				)
        elif isinstance(lowercase		,							lowercase				):
            return obj
        return [tokenize_and_encode(lowercase				) for o in obj]

    logger.info("Encoding dataset..."				)
    snake_case					:   Tuple         =					load_rocstories_dataset(args.train_dataset				)
    snake_case					:   Any         =					load_rocstories_dataset(args.eval_dataset				)
    snake_case					:   Optional[Any]         =					(train_dataset, eval_dataset)
    snake_case					:   Dict         =					tokenize_and_encode(lowercase				)

    # Compute the max input length for the Transformer
    snake_case					:   List[Any]         =					model.config.n_positions // 2 - 2
    snake_case					:   Dict         =					max(
        len(story[:max_length]				) + max(len(conta[:max_length]				)		,							len(conta[:max_length]				)				) + 3
        for dataset in encoded_datasets
        for story, conta, conta, _ in dataset				)
    snake_case					:   Optional[int]         =					min(lowercase		,							model.config.n_positions				)  # Max size of input for the pre-trained model

    # Prepare inputs tensors and dataloaders
    snake_case					:   Tuple         =					pre_process_datasets(lowercase		,							lowercase		,							lowercase		,							*lowercase				)
    snake_case					:   List[Any]         =					tensor_datasets[0], tensor_datasets[1]

    snake_case					:   str         =					TensorDataset(*lowercase				)
    snake_case					:   Tuple         =					RandomSampler(lowercase				)
    snake_case					:   Dict         =					DataLoader(lowercase		,							sampler=lowercase		,							batch_size=args.train_batch_size				)

    snake_case					:   Optional[Any]         =					TensorDataset(*lowercase				)
    snake_case					:   int         =					SequentialSampler(lowercase				)
    snake_case					:   Any         =					DataLoader(lowercase		,							sampler=lowercase		,							batch_size=args.eval_batch_size				)

    # Prepare optimizer
    if args.do_train:
        if args.max_steps > 0:
            snake_case					:   Optional[int]         =					args.max_steps
            snake_case					:   str         =					args.max_steps // (len(lowercase				) // args.gradient_accumulation_steps) + 1
        else:
            snake_case					:   List[str]         =					len(lowercase				) // args.gradient_accumulation_steps * args.num_train_epochs

        snake_case					:   List[Any]         =					list(model.named_parameters()				)
        snake_case					:   str         =					["bias", "LayerNorm.bias", "LayerNorm.weight"]
        snake_case					:   Union[str, Any]         =					[
            {
                "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay				)],
                "weight_decay": args.weight_decay,
            },
            {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay				)], "weight_decay": 0.0},
        ]
        snake_case					:   Optional[Any]         =					AdamW(lowercase		,							lr=args.learning_rate		,							eps=args.adam_epsilon				)
        snake_case					:   Optional[int]         =					get_linear_schedule_with_warmup(
            lowercase		,							num_warmup_steps=args.warmup_steps		,							num_training_steps=lowercase				)

    if args.do_train:
        snake_case					:   int         =					0, 0, None
        model.train()
        for _ in trange(int(args.num_train_epochs				)		,							desc="Epoch"				):
            snake_case					:   int         =					0
            snake_case					:   int         =					0
            snake_case					:   Union[str, Any]         =					tqdm(lowercase		,							desc="Training"				)
            for step, batch in enumerate(lowercase				):
                snake_case					:   Optional[Any]         =					tuple(t.to(lowercase				) for t in batch				)
                snake_case					:   List[Any]         =					batch
                snake_case					:   Dict         =					model(lowercase		,							mc_token_ids=lowercase		,							lm_labels=lowercase		,							mc_labels=lowercase				)
                snake_case					:   Union[str, Any]         =					args.lm_coef * losses[0] + losses[1]
                loss.backward()
                optimizer.step()
                scheduler.step()
                optimizer.zero_grad()
                tr_loss += loss.item()
                snake_case					:   List[Any]         =					(
                    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
                )
                nb_tr_steps += 1
                snake_case					:   Optional[Any]         =					"Training loss: {:.2e} lr: {:.2e}".format(lowercase		,							scheduler.get_lr()[0]				)

    # Save a trained model
    if args.do_train:
        # Save a trained model, configuration and tokenizer
        snake_case					:   List[str]         =					model.module if hasattr(lowercase		,							"module"				) else model  # Only save the model itself

        # If we save using the predefined names, we can load using `from_pretrained`
        snake_case					:   List[Any]         =					os.path.join(args.output_dir		,							lowercase				)
        snake_case					:   Dict         =					os.path.join(args.output_dir		,							lowercase				)

        torch.save(model_to_save.state_dict()		,							lowercase				)
        model_to_save.config.to_json_file(lowercase				)
        tokenizer.save_vocabulary(args.output_dir				)

        # Load a trained model and vocabulary that you have fine-tuned
        snake_case					:   Optional[int]         =					OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir				)
        snake_case					:   Dict         =					OpenAIGPTTokenizer.from_pretrained(args.output_dir				)
        model.to(lowercase				)

    if args.do_eval:
        model.eval()
        snake_case					:   Dict         =					0, 0
        snake_case					:   Union[str, Any]         =					0, 0
        for batch in tqdm(lowercase		,							desc="Evaluating"				):
            snake_case					:   Dict         =					tuple(t.to(lowercase				) for t in batch				)
            snake_case					:   str         =					batch
            with torch.no_grad():
                snake_case					:   int         =					model(
                    lowercase		,							mc_token_ids=lowercase		,							lm_labels=lowercase		,							mc_labels=lowercase				)

            snake_case					:   Tuple         =					mc_logits.detach().cpu().numpy()
            snake_case					:   Optional[int]         =					mc_labels.to("cpu"				).numpy()
            snake_case					:   str         =					accuracy(lowercase		,							lowercase				)

            eval_loss += mc_loss.mean().item()
            eval_accuracy += tmp_eval_accuracy

            nb_eval_examples += input_ids.size(0				)
            nb_eval_steps += 1

        snake_case					:   Optional[Any]         =					eval_loss / nb_eval_steps
        snake_case					:   Tuple         =					eval_accuracy / nb_eval_examples
        snake_case					:   Union[str, Any]         =					tr_loss / nb_tr_steps if args.do_train else None
        snake_case					:   Tuple         =					{"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss}

        snake_case					:   Union[str, Any]         =					os.path.join(args.output_dir		,							"eval_results.txt"				)
        with open(lowercase		,							"w"				) as writer:
            logger.info("***** Eval results *****"				)
            for key in sorted(result.keys()				):
                logger.info("  %s = %s"		,							lowercase		,							str(result[key]				)				)
                writer.write("%s = %s\n" % (key, str(result[key]				))				)


if __name__ == "__main__":
  main()









"""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


__snake_case         =					""""""


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







  class _lowerCAmelCase       (   tr.AbstractTransform			):







     def __init__(			self		,			UpperCamelCase__ = " "		)			->	Any:

         '''simple docstring'''




         snake_case					:   Optional[Any]         =					sentence_delimiter







     def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Optional[Any]:

         '''simple docstring'''




         return list(UpperCamelCase__		)







     def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	List[Any]:

         '''simple docstring'''




         snake_case					:   Dict         =					[]
         for sent_idx, sentence in enumerate(UpperCamelCase__		):
             chars.extend(self.process_string(UpperCamelCase__		)		)
             if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(UpperCamelCase__		) - 1:
                 chars.append(self.sentence_delimiter		)
         return chars



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


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

__snake_case         =					"""\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER'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
performance of the ASR system with a CER of 0 being a perfect score.
"""

__snake_case         =					"""
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]
    >>> references = [\"this is the reference\", \"there is another one\"]
    >>> cer = datasets.load_metric(\"cer\")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
"""







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







   def 				lowerCamelCase	(			self		)			->	Optional[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 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__=False		)			->	Optional[int]:

       '''simple docstring'''




       if concatenate_texts:
           return jiwer.compute_measures(
               UpperCamelCase__		,			UpperCamelCase__		,			truth_transform=UpperCamelCase__		,			hypothesis_transform=UpperCamelCase__		,			)["wer"]

       snake_case					:   Optional[int]         =					0
       snake_case					:   int         =					0
       for prediction, reference in zip(UpperCamelCase__		,			UpperCamelCase__		):
           snake_case					:   Dict         =					jiwer.compute_measures(
               UpperCamelCase__		,			UpperCamelCase__		,			truth_transform=UpperCamelCase__		,			hypothesis_transform=UpperCamelCase__		,			)
           incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
           total += measures["substitutions"] + measures["deletions"] + measures["hits"]

       return incorrect / total





