


import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


snake_case__     							= logging.getLogger(__name__)

require_version('pytorch_lightning>=1.0.4')

snake_case__     							= {
    'base': AutoModel,
    'sequence-classification': AutoModelForSequenceClassification,
    'question-answering': AutoModelForQuestionAnswering,
    'pretraining': AutoModelForPreTraining,
    'token-classification': AutoModelForTokenClassification,
    'language-modeling': AutoModelWithLMHead,
    'summarization': AutoModelForSeqaSeqLM,
    'translation': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
snake_case__     							= {
    'linear': get_linear_schedule_with_warmup,
    'cosine': get_cosine_schedule_with_warmup,
    'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup,
    'polynomial': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
snake_case__     							= sorted(arg_to_scheduler.keys())
snake_case__     							= '{' + ', '.join(arg_to_scheduler_choices) + '}'



class     snake_case__  (      pl.LightningModule  ):
				def __init__(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase="base"     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      **_UpperCAmelCase     ,      ):




										"""simple docstring"""




										super().__init__()
										# TODO: move to self.save_hyperparameters()
										# self.save_hyperparameters()
										# can also expand arguments into trainer signature for easier reading

										self.save_hyperparameters(a_      )
										__magic_name__				:							Union[str, Any]				=      0
										__magic_name__				:							List[Any]				=      Path(self.hparams.output_dir      )
										__magic_name__				:							str				=      self.hparams.cache_dir if self.hparams.cache_dir else None
										if config is None:
																__magic_name__				:							List[str]				=      AutoConfig.from_pretrained(
																    self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path     ,      **({'num_labels': num_labels} if num_labels is not None else {})     ,      cache_dir=a_     ,      **a_     ,      )
										else:
																__magic_name__				:							str				=      config

										__magic_name__				:							str				=      ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout')
										for p in extra_model_params:
																if getattr(self.hparams     ,      a_     ,      a_      ):
																						assert hasattr(self.config     ,      a_      ), F"model config doesn't have a `{p}` attribute"
																						setattr(self.config     ,      a_     ,      getattr(self.hparams     ,      a_      )      )

										if tokenizer is None:
																__magic_name__				:							str				=      AutoTokenizer.from_pretrained(
																    self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path     ,      cache_dir=a_     ,      )
										else:
																__magic_name__				:							Dict				=      tokenizer
										__magic_name__				:							List[Any]				=      MODEL_MODES[mode]
										if model is None:
																__magic_name__				:							List[str]				=      self.model_type.from_pretrained(
																    self.hparams.model_name_or_path     ,      from_tf=bool('.ckpt' in self.hparams.model_name_or_path      )     ,      config=self.config     ,      cache_dir=a_     ,      )
										else:
																__magic_name__				:							List[str]				=      model
				def  UpperCamelCase_						(  self     ,      *_UpperCAmelCase     ,      **_UpperCAmelCase      ):




										"""simple docstring"""




										__magic_name__				:							Optional[Any]				=      self.model_type.from_pretrained(*a_     ,      **a_      )
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										__magic_name__				:							Optional[Any]				=      arg_to_scheduler[self.hparams.lr_scheduler]
										__magic_name__				:							Dict				=      get_schedule_func(
										    self.opt     ,      num_warmup_steps=self.hparams.warmup_steps     ,      num_training_steps=self.total_steps()      )
										__magic_name__				:							Dict				=      {'scheduler': scheduler, 'interval': 'step', 'frequency': 1}
										return scheduler
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										__magic_name__				:							List[Any]				=      self.model
										__magic_name__				:							Optional[Any]				=      ['bias', 'LayerNorm.weight']
										__magic_name__				:							List[Any]				=      [
										    {
										        'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay      )],
										        'weight_decay': self.hparams.weight_decay,
										    },
										    {
										        'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay      )],
										        'weight_decay': 0.0,
										    },
										]
										if self.hparams.adafactor:
																__magic_name__				:							Any				=      Adafactor(
																    a_     ,      lr=self.hparams.learning_rate     ,      scale_parameter=a_     ,      relative_step=a_      )

										else:
																__magic_name__				:							List[Any]				=      AdamW(
																    a_     ,      lr=self.hparams.learning_rate     ,      eps=self.hparams.adam_epsilon      )
										__magic_name__				:							List[Any]				=      optimizer

										__magic_name__				:							int				=      self.get_lr_scheduler()

										return [optimizer], [scheduler]
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										return self.validation_step(a_     ,      a_      )
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										return self.validation_end(a_      )
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										__magic_name__				:							Optional[int]				=      max(1     ,      self.hparams.gpus      )  # TODO: consider num_tpu_cores
										__magic_name__				:							str				=      self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
										return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										if mode == "test":
																__magic_name__				:							Tuple				=      len(self.test_dataloader().dataset      )
										else:
																__magic_name__				:							Tuple				=      self.get_dataloader('train'     ,      self.hparams.train_batch_size     ,      shuffle=a_      )
																__magic_name__				:							Tuple				=      len(self.train_dataloader().dataset      )
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase = False      ):




										"""simple docstring"""




										raise NotImplementedError('You must implement this for your task'      )
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										return self.train_loader
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										return self.get_dataloader('dev'     ,      self.hparams.eval_batch_size     ,      shuffle=a_      )
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										return self.get_dataloader('test'     ,      self.hparams.eval_batch_size     ,      shuffle=a_      )
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										return os.path.join(
										    self.hparams.data_dir     ,      'cached_{}_{}_{}'.format(
										        a_     ,      list(filter(a_     ,      self.hparams.model_name_or_path.split('/'      )      )      ).pop()     ,      str(self.hparams.max_seq_length      )     ,      )     ,      )
				@pl.utilities.rank_zero_only
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										__magic_name__				:							List[str]				=      self.output_dir.joinpath('best_tfmr'      )
										__magic_name__				:							Union[str, Any]				=      self.step_count
										self.model.save_pretrained(a_      )
										self.tokenizer.save_pretrained(a_      )





				@staticmethod
				def  UpperCamelCase_						(  _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										parser.add_argument(
										    '--model_name_or_path'     ,      default=a_     ,      type=a_     ,      required=a_     ,      help='Path to pretrained model or model identifier from huggingface.co/models'     ,      )
										parser.add_argument(
										    '--config_name'     ,      default=''     ,      type=a_     ,      help='Pretrained config name or path if not the same as model_name'      )
										parser.add_argument(
										    '--tokenizer_name'     ,      default=a_     ,      type=a_     ,      help='Pretrained tokenizer name or path if not the same as model_name'     ,      )
										parser.add_argument(
										    '--cache_dir'     ,      default=''     ,      type=a_     ,      help='Where do you want to store the pre-trained models downloaded from huggingface.co'     ,      )
										parser.add_argument(
										    '--encoder_layerdrop'     ,      type=a_     ,      help='Encoder layer dropout probability (Optional). Goes into model.config'     ,      )
										parser.add_argument(
										    '--decoder_layerdrop'     ,      type=a_     ,      help='Decoder layer dropout probability (Optional). Goes into model.config'     ,      )
										parser.add_argument(
										    '--dropout'     ,      type=a_     ,      help='Dropout probability (Optional). Goes into model.config'     ,      )
										parser.add_argument(
										    '--attention_dropout'     ,      type=a_     ,      help='Attention dropout probability (Optional). Goes into model.config'     ,      )
										parser.add_argument('--learning_rate'     ,      default=5E-5     ,      type=a_     ,      help='The initial learning rate for Adam.'      )
										parser.add_argument(
										    '--lr_scheduler'     ,      default='linear'     ,      choices=a_     ,      metavar=a_     ,      type=a_     ,      help='Learning rate scheduler'     ,      )
										parser.add_argument('--weight_decay'     ,      default=0.0     ,      type=a_     ,      help='Weight decay if we apply some.'      )
										parser.add_argument('--adam_epsilon'     ,      default=1E-8     ,      type=a_     ,      help='Epsilon for Adam optimizer.'      )
										parser.add_argument('--warmup_steps'     ,      default=0     ,      type=a_     ,      help='Linear warmup over warmup_steps.'      )
										parser.add_argument('--num_workers'     ,      default=4     ,      type=a_     ,      help='kwarg passed to DataLoader'      )
										parser.add_argument('--num_train_epochs'     ,      dest='max_epochs'     ,      default=3     ,      type=a_      )
										parser.add_argument('--train_batch_size'     ,      default=32     ,      type=a_      )
										parser.add_argument('--eval_batch_size'     ,      default=32     ,      type=a_      )
										parser.add_argument('--adafactor'     ,      action='store_true'      )






class     snake_case__  (      pl.Callback  ):
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										__magic_name__				:							Optional[Any]				=      trainer.lr_schedulers[0]['scheduler']
										__magic_name__				:							Union[str, Any]				=      {F"lr_group_{i}": lr for i, lr in enumerate(lr_scheduler.get_lr()      )}
										pl_module.logger.log_metrics(a_      )
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										rank_zero_info('***** Validation results *****'      )
										__magic_name__				:							str				=      trainer.callback_metrics
										# Log results
										for key in sorted(a_      ):
																if key not in ["log", "progress_bar"]:
																						rank_zero_info('{} = {}\n'.format(a_     ,      str(metrics[key]      )      )      )





				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										rank_zero_info('***** Test results *****'      )
										__magic_name__				:							Union[str, Any]				=      trainer.callback_metrics
										# Log and save results to file
										__magic_name__				:							str				=      os.path.join(pl_module.hparams.output_dir     ,      'test_results.txt'      )
										with open(a_     ,      'w'      ) as writer:
																for key in sorted(a_      ):
																						if key not in ["log", "progress_bar"]:
																												rank_zero_info('{} = {}\n'.format(a_     ,      str(metrics[key]      )      )      )
																												writer.write('{} = {}\n'.format(a_     ,      str(metrics[key]      )      )      )






def  __SCREAMING_SNAKE_CASE       (				lowercase__  :List[str]      ,						lowercase__  :List[str]				)       ->  Union[str, Any]:
						parser.add_argument(
						    '--output_dir'      ,						default=UpperCamelCase__      ,						type=UpperCamelCase__      ,						required=UpperCamelCase__      ,						help='The output directory where the model predictions and checkpoints will be written.'      ,						)
						parser.add_argument(
						    '--fp16'      ,						action='store_true'      ,						help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'      ,						)

						parser.add_argument(
						    '--fp16_opt_level'      ,						type=UpperCamelCase__      ,						default='O2'      ,						help=(
						        'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'
						        'See details at https://nvidia.github.io/apex/amp.html'
						    )      ,						)
						parser.add_argument('--n_tpu_cores'      ,						dest='tpu_cores'      ,						type=UpperCamelCase__				)
						parser.add_argument('--max_grad_norm'      ,						dest='gradient_clip_val'      ,						default=1.0      ,						type=UpperCamelCase__      ,						help='Max gradient norm'				)
						parser.add_argument('--do_train'      ,						action='store_true'      ,						help='Whether to run training.'				)
						parser.add_argument('--do_predict'      ,						action='store_true'      ,						help='Whether to run predictions on the test set.'				)
						parser.add_argument(
						    '--gradient_accumulation_steps'      ,						dest='accumulate_grad_batches'      ,						type=UpperCamelCase__      ,						default=1      ,						help='Number of updates steps to accumulate before performing a backward/update pass.'      ,						)
						parser.add_argument('--seed'      ,						type=UpperCamelCase__      ,						default=4_2      ,						help='random seed for initialization'				)
						parser.add_argument(
						    '--data_dir'      ,						default=UpperCamelCase__      ,						type=UpperCamelCase__      ,						required=UpperCamelCase__      ,						help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.'      ,						)


def  __SCREAMING_SNAKE_CASE       (				lowercase__  :List[Any]      ,						lowercase__  :List[str]      ,						lowercase__  :Dict=None      ,						lowercase__  :Tuple=True      ,						lowercase__  :Union[str, Any]=[]      ,						lowercase__  :Dict=None      ,						lowercase__  :int=None      ,						**lowercase__  :Tuple      ,						)       ->  Optional[Any]:
						pl.seed_everything(args.seed				)

						# init model
						__magic_name__				:							Optional[Any]				=      Path(model.hparams.output_dir				)
						odir.mkdir(exist_ok=UpperCamelCase__				)

						# add custom checkpoints
						if checkpoint_callback is None:
												__magic_name__				:							Tuple				=      pl.callbacks.ModelCheckpoint(
												    filepath=args.output_dir      ,						prefix='checkpoint'      ,						monitor='val_loss'      ,						mode='min'      ,						save_top_k=1				)
						if early_stopping_callback:
												extra_callbacks.append(UpperCamelCase__				)
						if logging_callback is None:
												__magic_name__				:							List[Any]				=      LoggingCallback()

						__magic_name__				:							int				=      {}

						# TODO: remove with PyTorch 1.6 since pl uses native amp
						if args.fpaa:
												__magic_name__				:							Tuple				=      1_6
												__magic_name__				:							Optional[int]				=      args.fpaa_opt_level

						if args.gpus > 1:
												__magic_name__				:							Optional[int]				=      'ddp'

						__magic_name__				:							Optional[Any]				=      args.accumulate_grad_batches
						__magic_name__				:							List[Any]				=      extra_train_kwargs.get('accelerator'      ,						UpperCamelCase__				)
						__magic_name__				:							Union[str, Any]				=      extra_train_kwargs.get('profiler'      ,						UpperCamelCase__				)

						__magic_name__				:							List[Any]				=      pl.Trainer.from_argparse_args(
						    UpperCamelCase__      ,						weights_summary=UpperCamelCase__      ,						callbacks=[logging_callback] + extra_callbacks      ,						logger=UpperCamelCase__      ,						checkpoint_callback=UpperCamelCase__      ,						**UpperCamelCase__      ,						)

						if args.do_train:
												trainer.fit(UpperCamelCase__				)

						return trainer






import functools
from contextlib import contextmanager

import bert_score
from packaging import version

import datasets
@contextmanager
def  __SCREAMING_SNAKE_CASE       (				)       ->  Tuple:
						def filter_log(lowercase__  :List[Any]				):
												return False if "This IS expected if you are initializing" in record.msg else True

						__magic_name__				:							Any				=      datasets.utils.logging.get_logger('transformers.modeling_utils'				)
						logger.addFilter(lowercase__				)
						try:
												yield
						finally:
												logger.removeFilter(lowercase__				)


snake_case__     							= '\\n@inproceedings{bert-score,\n  title={BERTScore: Evaluating Text Generation with BERT},\n  author={Tianyi Zhang* and Varsha Kishore* and Felix Wu* and Kilian Q. Weinberger and Yoav Artzi},\n  booktitle={International Conference on Learning Representations},\n  year={2020},\n  url={https://openreview.net/forum?id=SkeHuCVFDr}\n}\n'

snake_case__     							= '\\nBERTScore leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference\nsentences by cosine similarity.\nIt has been shown to correlate with human judgment on sentence-level and system-level evaluation.\nMoreover, BERTScore computes precision, recall, and F1 measure, which can be useful for evaluating different language\ngeneration tasks.\n\nSee the project\'s README at https://github.com/Tiiiger/bert_score#readme for more information.\n'

snake_case__     							= '\nBERTScore Metrics with the hashcode from a source against one or more references.\n\nArgs:\n    predictions (list of str): Prediction/candidate sentences.\n    references (list of str or list of list of str): Reference sentences.\n    lang (str): Language of the sentences; required (e.g. \'en\').\n    model_type (str): Bert specification, default using the suggested\n        model for the target language; has to specify at least one of\n        `model_type` or `lang`.\n    num_layers (int): The layer of representation to use,\n        default using the number of layers tuned on WMT16 correlation data.\n    verbose (bool): Turn on intermediate status update.\n    idf (bool or dict): Use idf weighting; can also be a precomputed idf_dict.\n    device (str): On which the contextual embedding model will be allocated on.\n        If this argument is None, the model lives on cuda:0 if cuda is available.\n    nthreads (int): Number of threads.\n    batch_size (int): Bert score processing batch size,\n        at least one of `model_type` or `lang`. `lang` needs to be\n        specified when `rescale_with_baseline` is True.\n    rescale_with_baseline (bool): Rescale bertscore with pre-computed baseline.\n    baseline_path (str): Customized baseline file.\n    use_fast_tokenizer (bool): `use_fast` parameter passed to HF tokenizer. New in version 0.3.10.\n\nReturns:\n    precision: Precision.\n    recall: Recall.\n    f1: F1 score.\n    hashcode: Hashcode of the library.\n\nExamples:\n\n    >>> predictions = ["hello there", "general kenobi"]\n    >>> references = ["hello there", "general kenobi"]\n    >>> bertscore = datasets.load_metric("bertscore")\n    >>> results = bertscore.compute(predictions=predictions, references=references, lang="en")\n    >>> print([round(v, 2) for v in results["f1"]])\n    [1.0, 1.0]\n'



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,       _KWARGS_DESCRIPTION  )
class     snake_case__  (      datasets.Metric  ):
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										return datasets.MetricInfo(
										    description=_DESCRIPTION     ,      citation=_CITATION     ,      homepage='https://github.com/Tiiiger/bert_score'     ,      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/Tiiiger/bert_score']     ,      reference_urls=[
										        'https://github.com/Tiiiger/bert_score',
										        'https://arxiv.org/abs/1904.09675',
										    ]     ,      )
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=64     ,      _UpperCAmelCase=4     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=False     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=False     ,      ):




										"""simple docstring"""




										__magic_name__				:							List[str]				=      bert_score.utils.get_hash
										__magic_name__				:							Dict				=      bert_score.BERTScorer

										if version.parse(bert_score.__version__      ) >= version.parse('0.3.10'      ):
																__magic_name__				:							Any				=      functools.partial(_UpperCAmelCase     ,      use_fast_tokenizer=_UpperCAmelCase      )
																__magic_name__				:							Tuple				=      functools.partial(_UpperCAmelCase     ,      use_fast_tokenizer=_UpperCAmelCase      )
										elif use_fast_tokenizer:
																raise ImportWarning(
																    'To use a fast tokenizer, the module `bert-score>=0.3.10` is required, and the current version of `bert-score` doesn\'t match this condition.\n'
																    'You can install it with `pip install "bert-score>=0.3.10"`.'      )

										if model_type is None:
																assert lang is not None, "either lang or model_type should be specified"
																__magic_name__				:							List[Any]				=      bert_score.utils.langamodel[lang.lower()]

										if num_layers is None:
																__magic_name__				:							Optional[Any]				=      bert_score.utils.modelalayers[model_type]

										__magic_name__				:							List[str]				=      get_hash(
										    model=_UpperCAmelCase     ,      num_layers=_UpperCAmelCase     ,      idf=_UpperCAmelCase     ,      rescale_with_baseline=_UpperCAmelCase     ,      use_custom_baseline=baseline_path is not None     ,      )

										with filter_logging_context():
																if not hasattr(self     ,      'cached_bertscorer'      ) or self.cached_bertscorer.hash != hashcode:
																						__magic_name__				:							Optional[int]				=      scorer(
																						    model_type=_UpperCAmelCase     ,      num_layers=_UpperCAmelCase     ,      batch_size=_UpperCAmelCase     ,      nthreads=_UpperCAmelCase     ,      all_layers=_UpperCAmelCase     ,      idf=_UpperCAmelCase     ,      device=_UpperCAmelCase     ,      lang=_UpperCAmelCase     ,      rescale_with_baseline=_UpperCAmelCase     ,      baseline_path=_UpperCAmelCase     ,      )

										((__magic_name__)		, (__magic_name__)		, (__magic_name__))				:							List[Any]				=      self.cached_bertscorer.score(
										    cands=_UpperCAmelCase     ,      refs=_UpperCAmelCase     ,      verbose=_UpperCAmelCase     ,      batch_size=_UpperCAmelCase     ,      )
										__magic_name__				:							int				=      {
										    'precision': P.tolist(),
										    'recall': R.tolist(),
										    'f1': F.tolist(),
										    'hashcode': hashcode,
										}
										return output_dict
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      **_UpperCAmelCase      ):




										"""simple docstring"""




										if references is not None:
																__magic_name__				:							List[str]				=      [[ref] if isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ) else ref for ref in references]
										super().add_batch(predictions=_UpperCAmelCase     ,      references=_UpperCAmelCase     ,      **_UpperCAmelCase      )





				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase=None     ,      _UpperCAmelCase=None     ,      **_UpperCAmelCase      ):




										"""simple docstring"""




										if isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ):
																__magic_name__				:							List[Any]				=      [reference]
										super().add(prediction=_UpperCAmelCase     ,      reference=_UpperCAmelCase     ,      **_UpperCAmelCase      )


