






import os
from argparse import ArgumentParser, Namespace

from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand


if not is_tf_available() and not is_torch_available():
					raise RuntimeError("""At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training""")

# TF training parameters
__snake_case      :      int             =       False
__snake_case      :      List[Any]             =       False







def 		_UpperCamelCase				(      UpperCamelCase_    :   Namespace						)					->				int:

						"""simple docstring"""



						return TrainCommand(UpperCamelCase_						)


class       __SCREAMING_SNAKE_CASE   (				__lowercase):






						@staticmethod
						def  UpperCamelCase__ (		_UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  parser.add_parser('train'       ,  help='CLI tool to train a model on a task.'				)

												train_parser.add_argument(
												    '--train_data'       ,  type=_UpperCamelCase       ,  required=_UpperCamelCase       ,  help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.'       ,  )
												train_parser.add_argument(
												    '--column_label'       ,  type=_UpperCamelCase       ,  default=0       ,  help='Column of the dataset csv file with example labels.'				)
												train_parser.add_argument(
												    '--column_text'       ,  type=_UpperCamelCase       ,  default=1       ,  help='Column of the dataset csv file with example texts.'				)
												train_parser.add_argument(
												    '--column_id'       ,  type=_UpperCamelCase       ,  default=2       ,  help='Column of the dataset csv file with example ids.'				)
												train_parser.add_argument(
												    '--skip_first_row'       ,  action='store_true'       ,  help='Skip the first row of the csv file (headers).'				)

												train_parser.add_argument('--validation_data'       ,  type=_UpperCamelCase       ,  default=''       ,  help='path to validation dataset.'				)
												train_parser.add_argument(
												    '--validation_split'       ,  type=_UpperCamelCase       ,  default=0.1       ,  help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.'       ,  )

												train_parser.add_argument('--output'       ,  type=_UpperCamelCase       ,  default='./'       ,  help='path to saved the trained model.'				)

												train_parser.add_argument(
												    '--task'       ,  type=_UpperCamelCase       ,  default='text_classification'       ,  help='Task to train the model on.'				)
												train_parser.add_argument(
												    '--model'       ,  type=_UpperCamelCase       ,  default='bert-base-uncased'       ,  help='Model\'s name or path to stored model.'				)
												train_parser.add_argument('--train_batch_size'       ,  type=_UpperCamelCase       ,  default=32       ,  help='Batch size for training.'				)
												train_parser.add_argument('--valid_batch_size'       ,  type=_UpperCamelCase       ,  default=64       ,  help='Batch size for validation.'				)
												train_parser.add_argument('--learning_rate'       ,  type=_UpperCamelCase       ,  default=3E-5       ,  help='Learning rate.'				)
												train_parser.add_argument('--adam_epsilon'       ,  type=_UpperCamelCase       ,  default=1E-08       ,  help='Epsilon for Adam optimizer.'				)
												train_parser.set_defaults(func=_UpperCamelCase				)






						def __init__(		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  logging.get_logger('transformers-cli/training'				)

												lowerCAmelCase__        =  'tf' if is_tf_available() else 'torch'

												os.makedirs(args.output       ,  exist_ok=_UpperCamelCase				)
												lowerCAmelCase__        =  args.output

												lowerCAmelCase__        =  args.column_label
												lowerCAmelCase__        =  args.column_text
												lowerCAmelCase__        =  args.column_id

												self.logger.info(F"Loading {args.task} pipeline for {args.model}"				)
												if args.task == "text_classification":
																		lowerCAmelCase__        =  TextClassificationPipeline.from_pretrained(args.model				)
												elif args.task == "token_classification":
																		raise NotImplementedError
												elif args.task == "question_answering":
																		raise NotImplementedError

												self.logger.info(F"Loading dataset from {args.train_data}"				)
												lowerCAmelCase__        =  Processor.create_from_csv(
												    args.train_data       ,  column_label=args.column_label       ,  column_text=args.column_text       ,  column_id=args.column_id       ,  skip_first_row=args.skip_first_row       ,  )
												lowerCAmelCase__        =  None
												if args.validation_data:
																		self.logger.info(F"Loading validation dataset from {args.validation_data}"				)
																		lowerCAmelCase__        =  Processor.create_from_csv(
																		    args.validation_data       ,  column_label=args.column_label       ,  column_text=args.column_text       ,  column_id=args.column_id       ,  skip_first_row=args.skip_first_row       ,  )

												lowerCAmelCase__        =  args.validation_split
												lowerCAmelCase__        =  args.train_batch_size
												lowerCAmelCase__        =  args.valid_batch_size
												lowerCAmelCase__        =  args.learning_rate
												lowerCAmelCase__        =  args.adam_epsilon






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												if self.framework == "tf":
																		return self.run_tf()
												return self.run_torch()






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												raise NotImplementedError







						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												self.pipeline.fit(
												    self.train_dataset       ,  validation_data=self.valid_dataset       ,  validation_split=self.validation_split       ,  learning_rate=self.learning_rate       ,  adam_epsilon=self.adam_epsilon       ,  train_batch_size=self.train_batch_size       ,  valid_batch_size=self.valid_batch_size       ,  )

												# Save trained pipeline
												self.pipeline.save_pretrained(self.output				)













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

import datasets


__snake_case      :      Optional[int]             =       """\
@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\",
}
"""

__snake_case      :      List[str]             =       """\
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.
"""

__snake_case      :      Dict             =       """
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       __SCREAMING_SNAKE_CASE   (				datasets.Metric):






						def  UpperCamelCase__ (		self				):






												"""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  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase = False       ,  _UpperCamelCase = False       ,  _UpperCamelCase = False       ,  _UpperCamelCase = False       ,  ):






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

												lowerCAmelCase__        =  TER(
												    normalized=_UpperCamelCase       ,  no_punct=_UpperCamelCase       ,  asian_support=_UpperCamelCase       ,  case_sensitive=_UpperCamelCase       ,  )
												lowerCAmelCase__        =  sb_ter.corpus_score(_UpperCamelCase       ,  _UpperCamelCase				)

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





