



"""simple docstring"""
import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


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



def 			lowercase	(_snake_case ,_snake_case=False			)       ->    List[Any]:




  '''simple docstring'''







  try:
    __UpperCamelCase  						=							os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    __UpperCamelCase  						=							default
  else:
    # KEY is set, convert it to True or False.
    try:
      __UpperCamelCase  						=							strtobool(_snake_case			)
    except ValueError:
      # More values are supported, but let's keep the message simple.
      raise ValueError(f"""If set, {key} must be yes or no."""			)
  return _value


_A													=   parse_flag_from_env("RUN_SLOW", default=False)
_A													=   parse_flag_from_env("RUN_REMOTE", default=False)
_A													=   parse_flag_from_env("RUN_LOCAL", default=True)
_A													=   parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
_A													=   pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
_A													=   pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
_A													=   pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
_A													=   pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ",
)

# Beam
_A													=   pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
_A													=   pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
_A													=   pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)



def 			lowercase	(_snake_case			)       ->    Tuple:




  '''simple docstring'''







  try:
    import faiss  # noqa
  except ImportError:
    __UpperCamelCase  						=							unittest.skip("test requires faiss"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Union[str, Any]:




  '''simple docstring'''







  try:
    import regex  # noqa
  except ImportError:
    __UpperCamelCase  						=							unittest.skip("test requires regex"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Optional[Any]:




  '''simple docstring'''







  try:
    import elasticsearch  # noqa
  except ImportError:
    __UpperCamelCase  						=							unittest.skip("test requires elasticsearch"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Optional[Any]:




  '''simple docstring'''







  try:
    import sqlalchemy  # noqa
  except ImportError:
    __UpperCamelCase  						=							unittest.skip("test requires sqlalchemy"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Dict:




  '''simple docstring'''







  if not config.TORCH_AVAILABLE:
    __UpperCamelCase  						=							unittest.skip("test requires PyTorch"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Optional[Any]:




  '''simple docstring'''







  if not config.TF_AVAILABLE:
    __UpperCamelCase  						=							unittest.skip("test requires TensorFlow"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Optional[Any]:




  '''simple docstring'''







  if not config.JAX_AVAILABLE:
    __UpperCamelCase  						=							unittest.skip("test requires JAX"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    int:




  '''simple docstring'''







  if not config.PIL_AVAILABLE:
    __UpperCamelCase  						=							unittest.skip("test requires Pillow"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Any:




  '''simple docstring'''







  try:
    import transformers  # noqa F401
  except ImportError:
    return unittest.skip("test requires transformers"			)(_snake_case			)
  else:
    return test_case



def 			lowercase	(_snake_case			)       ->    int:




  '''simple docstring'''







  try:
    import tiktoken  # noqa F401
  except ImportError:
    return unittest.skip("test requires tiktoken"			)(_snake_case			)
  else:
    return test_case



def 			lowercase	(_snake_case			)       ->    Union[str, Any]:




  '''simple docstring'''







  try:
    import spacy  # noqa F401
  except ImportError:
    return unittest.skip("test requires spacy"			)(_snake_case			)
  else:
    return test_case



def 			lowercase	(_snake_case			)       ->    Tuple:




  '''simple docstring'''







  def _require_spacy_model(_snake_case			):
    try:
      import spacy  # noqa F401

      spacy.load(_snake_case			)
    except ImportError:
      return unittest.skip("test requires spacy"			)(_snake_case			)
    except OSError:
      return unittest.skip("test requires spacy model \'{}\'".format(_snake_case			)			)(_snake_case			)
    else:
      return test_case

  return _require_spacy_model



def 			lowercase	(_snake_case			)       ->    Dict:




  '''simple docstring'''







  try:
    import pyspark  # noqa F401
  except ImportError:
    return unittest.skip("test requires pyspark"			)(_snake_case			)
  else:
    return test_case



def 			lowercase	(_snake_case			)       ->    List[str]:




  '''simple docstring'''







  try:
    import joblibspark  # noqa F401
  except ImportError:
    return unittest.skip("test requires joblibspark"			)(_snake_case			)
  else:
    return test_case



def 			lowercase	(_snake_case			)       ->    List[str]:




  '''simple docstring'''







  if not _run_slow_tests or _run_slow_tests == 0:
    __UpperCamelCase  						=							unittest.skip("test is slow"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    int:




  '''simple docstring'''







  if not _run_local_tests or _run_local_tests == 0:
    __UpperCamelCase  						=							unittest.skip("test is local"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Union[str, Any]:




  '''simple docstring'''







  if not _run_packaged_tests or _run_packaged_tests == 0:
    __UpperCamelCase  						=							unittest.skip("test is packaged"			)(_snake_case			)
  return test_case



def 			lowercase	(_snake_case			)       ->    Optional[int]:




  '''simple docstring'''







  if not _run_remote_tests or _run_remote_tests == 0:
    __UpperCamelCase  						=							unittest.skip("test requires remote"			)(_snake_case			)
  return test_case



def 			lowercase	(*_snake_case			)       ->    str:




  '''simple docstring'''







  def decorate(cls			):
    for name, fn in cls.__dict__.items():
      if callable(_snake_case			) and name.startswith("test"			):
        for decorator in decorators:
          __UpperCamelCase  						=							decorator(_snake_case			)
        setattr(cls ,_snake_case ,_snake_case			)
    return cls

  return decorate





class 		__UpperCAmelCase				(	_a					):







 """simple docstring"""




 pass





class 		__UpperCAmelCase				(	_a					):







 """simple docstring"""




 _snake_case       :							str      	=	0
 _snake_case       :							str      	=	1
 _snake_case       :							Optional[int]      	=	2





@contextmanager
def 			lowercase	(_snake_case=OfflineSimulationMode.CONNECTION_FAILS ,_snake_case=1e-16			)       ->    Dict:




  '''simple docstring'''







  __UpperCamelCase  						=							requests.Session().request

  def timeout_request(_snake_case ,_snake_case ,_snake_case ,**_snake_case			):
    # Change the url to an invalid url so that the connection hangs
    __UpperCamelCase  						=							"https://10.255.255.1"
    if kwargs.get("timeout"			) is None:
      raise RequestWouldHangIndefinitelyError(
          f"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""			)
    __UpperCamelCase  						=							timeout
    try:
      return online_request(_snake_case ,_snake_case ,**_snake_case			)
    except Exception as e:
      # The following changes in the error are just here to make the offline timeout error prettier
      __UpperCamelCase  						=							url
      __UpperCamelCase  						=							e.args[0]
      __UpperCamelCase  						=							(max_retry_error.args[0].replace("10.255.255.1" ,f"""OfflineMock[{url}]"""			),)
      __UpperCamelCase  						=							(max_retry_error,)
      raise

  def raise_connection_error(_snake_case ,_snake_case ,**_snake_case			):
    raise requests.ConnectionError("Offline mode is enabled." ,request=_snake_case			)

  if mode is OfflineSimulationMode.CONNECTION_FAILS:
    with patch("requests.Session.send" ,_snake_case			):
      yield
  elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
    # inspired from https://stackoverflow.com/a/904609
    with patch("requests.Session.request" ,_snake_case			):
      yield
  elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
    with patch("datasets.config.HF_DATASETS_OFFLINE" ,_snake_case			):
      yield
  else:
    raise ValueError("Please use a value from the OfflineSimulationMode enum."			)



@contextmanager
def 			lowercase	(*_snake_case ,**_snake_case			)       ->    Optional[Any]:




  '''simple docstring'''







  __UpperCamelCase  						=							str(Path().resolve()			)
  with tempfile.TemporaryDirectory(*_snake_case ,**_snake_case			) as tmp_dir:
    try:
      os.chdir(_snake_case			)
      yield
    finally:
      os.chdir(_snake_case			)



@contextmanager
def 			lowercase	()       ->    List[str]:




  '''simple docstring'''







  import gc

  gc.collect()
  __UpperCamelCase  						=							pa.total_allocated_bytes()
  yield
  assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."



@contextmanager
def 			lowercase	()       ->    Optional[Any]:




  '''simple docstring'''







  import gc

  gc.collect()
  __UpperCamelCase  						=							pa.total_allocated_bytes()
  yield
  assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."



def 			lowercase	(_snake_case ,_snake_case			)       ->    Tuple:




  '''simple docstring'''







  return deepcopy(_snake_case			).integers(0 ,100 ,10			).tolist() == deepcopy(_snake_case			).integers(0 ,100 ,10			).tolist()



def 			lowercase	(_snake_case			)       ->    Optional[int]:




  '''simple docstring'''







  import decorator
  from requests.exceptions import HTTPError

  def _wrapper(_snake_case ,*_snake_case ,**_snake_case			):
    try:
      return func(*_snake_case ,**_snake_case			)
    except HTTPError as err:
      if str(_snake_case			).startswith("500"			) or str(_snake_case			).startswith("502"			):
        pytest.xfail(str(_snake_case			)			)
      raise err

  return decorator.decorator(_wrapper ,_snake_case			)





class 		__UpperCAmelCase				:







 """simple docstring"""




 def __init__(				self					: Tuple						, A_					: str						, A_					: Union[str, Any]						, A_					: List[Any]	)->	Dict:
   __UpperCamelCase  						=							returncode
   __UpperCamelCase  						=							stdout
   __UpperCamelCase  						=							stderr





async def 			lowercase	(_snake_case ,_snake_case			)       ->    List[str]:




  '''simple docstring'''







  while True:
    __UpperCamelCase  						=							await stream.readline()
    if line:
      callback(_snake_case			)
    else:
      break



async def 			lowercase	(_snake_case ,_snake_case=None ,_snake_case=None ,_snake_case=None ,_snake_case=False ,_snake_case=False			)       ->    str:




  '''simple docstring'''







  if echo:
    print("\nRunning: " ," ".join(_snake_case			)			)

  __UpperCamelCase  						=							await asyncio.create_subprocess_exec(
      cmd[0] ,*cmd[1:] ,stdin=_snake_case ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=_snake_case ,)

  # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
  # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
  #
  # If it starts hanging, will need to switch to the following code. The problem is that no data
  # will be seen until it's done and if it hangs for example there will be no debug info.
  # out, err = await p.communicate()
  # return _RunOutput(p.returncode, out, err)

  __UpperCamelCase  						=							[]
  __UpperCamelCase  						=							[]

  def tee(_snake_case ,_snake_case ,_snake_case ,_snake_case=""			):
    __UpperCamelCase  						=							line.decode("utf-8"			).rstrip()
    sink.append(_snake_case			)
    if not quiet:
      print(_snake_case ,_snake_case ,file=_snake_case			)

    # XXX: the timeout doesn't seem to make any difference here
  await asyncio.wait(
      [
          _read_stream(p.stdout ,lambda _snake_case			: tee(_snake_case ,_snake_case ,sys.stdout ,label="stdout:"			)			),
          _read_stream(p.stderr ,lambda _snake_case			: tee(_snake_case ,_snake_case ,sys.stderr ,label="stderr:"			)			),
      ] ,timeout=_snake_case ,)
  return _RunOutput(await p.wait() ,_snake_case ,_snake_case			)



def 			lowercase	(_snake_case ,_snake_case=None ,_snake_case=None ,_snake_case=180 ,_snake_case=False ,_snake_case=True			)       ->    List[str]:




  '''simple docstring'''







  __UpperCamelCase  						=							asyncio.get_event_loop()
  __UpperCamelCase  						=							loop.run_until_complete(
      _stream_subprocess(_snake_case ,env=_snake_case ,stdin=_snake_case ,timeout=_snake_case ,quiet=_snake_case ,echo=_snake_case			)			)

  __UpperCamelCase  						=							" ".join(_snake_case			)
  if result.returncode > 0:
    __UpperCamelCase  						=							"\n".join(result.stderr			)
    raise RuntimeError(
        f"""\'{cmd_str}\' failed with returncode {result.returncode}\n\n"""
        f"""The combined stderr from workers follows:\n{stderr}"""			)

  # check that the subprocess actually did run and produced some output, should the test rely on
  # the remote side to do the testing
  if not result.stdout and not result.stderr:
    raise RuntimeError(f"""\'{cmd_str}\' produced no output."""			)

  return result



def 			lowercase	()       ->    List[str]:




  '''simple docstring'''







  __UpperCamelCase  						=							os.environ.get("PYTEST_XDIST_WORKER" ,"gw0"			)
  __UpperCamelCase  						=							re.sub(r"^gw" ,"" ,_snake_case ,0 ,re.M			)
  return int(_snake_case			)



def 			lowercase	()       ->    Any:




  '''simple docstring'''







  __UpperCamelCase  						=							29500
  __UpperCamelCase  						=							pytest_xdist_worker_id()
  return port + uniq_delta





'''simple docstring'''


import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()
def 						snake_case_       (UpperCamelCase			:    str					,		UpperCamelCase			:    str					,		UpperCamelCase			:    str					,		UpperCamelCase			:    PreTrainedTokenizer					,		UpperCamelCase			:    int					,		UpperCamelCase			:    Optional[int] = None					,		):





							'''simple docstring'''


							_a      	=							{}

							if train_file is not None:
														_a      	=							[train_file]
							if eval_file is not None:
														_a      	=							[eval_file]
							if test_file is not None:
														_a      	=							[test_file]

							_a      	=							datasets.load_dataset('''csv'''					,		data_files=UpperCamelCase )
							_a      	=							list(ds[list(files.keys() )[0]].features.keys() )
							_a      	=							features_name.pop(UpperCamelCase )
							_a      	=							list(set(ds[list(files.keys() )[0]][label_name] ) )
							_a      	=							{label: i for i, label in enumerate(UpperCamelCase )}
							_a      	=							tokenizer.model_input_names
							_a      	=							{}

							if len(UpperCamelCase ) == 1:
														for k in files.keys():
																					_a      	=							ds[k].map(
																					    lambda UpperCamelCase : tokenizer.batch_encode_plus(
																					        example[features_name[0]]					,		truncation=UpperCamelCase					,		max_length=UpperCamelCase					,		padding='''max_length''' )					,		batched=UpperCamelCase					,		)
							elif len(UpperCamelCase ) == 2:
														for k in files.keys():
																					_a      	=							ds[k].map(
																					    lambda UpperCamelCase : tokenizer.batch_encode_plus(
																					        (example[features_name[0]], example[features_name[1]])					,		truncation=UpperCamelCase					,		max_length=UpperCamelCase					,		padding='''max_length'''					,		)					,		batched=UpperCamelCase					,		)

							def gen_train():
														for ex in transformed_ds[datasets.Split.TRAIN]:
																					_a      	=							{k: v for k, v in ex.items() if k in input_names}
																					_a      	=							labelaid[ex[label_name]]
																					yield (d, label)

							def gen_val():
														for ex in transformed_ds[datasets.Split.VALIDATION]:
																					_a      	=							{k: v for k, v in ex.items() if k in input_names}
																					_a      	=							labelaid[ex[label_name]]
																					yield (d, label)

							def gen_test():
														for ex in transformed_ds[datasets.Split.TEST]:
																					_a      	=							{k: v for k, v in ex.items() if k in input_names}
																					_a      	=							labelaid[ex[label_name]]
																					yield (d, label)

							_a      	=							(
							    tf.data.Dataset.from_generator(
							        UpperCamelCase					,		({k: tf.intaa for k in input_names}, tf.intaa)					,		({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] ))					,		)
							    if datasets.Split.TRAIN in transformed_ds
							    else None
							)

							if train_ds is not None:
														_a      	=							train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) )

							_a      	=							(
							    tf.data.Dataset.from_generator(
							        UpperCamelCase					,		({k: tf.intaa for k in input_names}, tf.intaa)					,		({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] ))					,		)
							    if datasets.Split.VALIDATION in transformed_ds
							    else None
							)

							if val_ds is not None:
														_a      	=							val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) )

							_a      	=							(
							    tf.data.Dataset.from_generator(
							        UpperCamelCase					,		({k: tf.intaa for k in input_names}, tf.intaa)					,		({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] ))					,		)
							    if datasets.Split.TEST in transformed_ds
							    else None
							)

							if test_ds is not None:
														_a      	=							test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) )

							return train_ds, val_ds, test_ds, labelaid


_snake_case : str  				=						logging.getLogger(__name__)

@dataclass
class      A       :
							lowercase_							     =							field(metadata={'help': 'Which column contains the label'}       )
							lowercase_							     =							field(default=_a	,metadata={'help': 'The path of the training file'}       )
							lowercase_							     =							field(default=_a	,metadata={'help': 'The path of the development file'}       )
							lowercase_							     =							field(default=_a	,metadata={'help': 'The path of the test file'}       )
							lowercase_							     =							field(
							    default=128	,metadata={
							        'help': (
							            'The maximum total input sequence length after tokenization. Sequences longer '
							            'than this will be truncated, sequences shorter will be padded.'
							        )
							    }	,)
							lowercase_							     =							field(
							    default=_a	,metadata={'help': 'Overwrite the cached training and evaluation sets'}       )



@dataclass
class      A       :
							lowercase_							     =							field(
							    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}       )
							lowercase_							     =							field(
							    default=_a	,metadata={'help': 'Pretrained config name or path if not the same as model_name'}       )
							lowercase_							     =							field(
							    default=_a	,metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}       )
							lowercase_							     =							field(default=_a	,metadata={'help': 'Set this flag to use fast tokenization.'}       )
							# If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
							# or just modify its tokenizer_config.json.
							lowercase_							     =							field(
							    default=_a	,metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}	,)



def 						snake_case_       ():





							'''simple docstring'''


							_a      	=							HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) )
							_a	,				_a	,				_a      	=							parser.parse_args_into_dataclasses()

							if (
							    os.path.exists(training_args.output_dir )
							    and os.listdir(training_args.output_dir )
							    and training_args.do_train
							    and not training_args.overwrite_output_dir
							):
														raise ValueError(
														    f'Output directory ({training_args.output_dir}) already exists and is not empty. Use'
														    ''' --overwrite_output_dir to overcome.''' )

							# Setup logging
							logging.basicConfig(
							    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''					,		datefmt='''%m/%d/%Y %H:%M:%S'''					,		level=logging.INFO					,		)
							logger.info(
							    f'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, '
							    f'16-bits training: {training_args.fpaa}' )
							logger.info(f'Training/evaluation parameters {training_args}' )

							# Load pretrained model and tokenizer
							#
							# Distributed training:
							# The .from_pretrained methods guarantee that only one local process can concurrently
							# download model & vocab.

							_a      	=							AutoTokenizer.from_pretrained(
							    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path					,		cache_dir=model_args.cache_dir					,		)

							_a	,				_a	,				_a	,				_a      	=							get_tfds(
							    train_file=data_args.train_file					,		eval_file=data_args.dev_file					,		test_file=data_args.test_file					,		tokenizer=UpperCamelCase					,		label_column_id=data_args.label_column_id					,		max_seq_length=data_args.max_seq_length					,		)

							_a      	=							AutoConfig.from_pretrained(
							    model_args.config_name if model_args.config_name else model_args.model_name_or_path					,		num_labels=len(UpperCamelCase )					,		labelaid=UpperCamelCase					,		idalabel={id: label for label, id in labelaid.items()}					,		finetuning_task='''text-classification'''					,		cache_dir=model_args.cache_dir					,		)

							with training_args.strategy.scope():
														_a      	=							TFAutoModelForSequenceClassification.from_pretrained(
														    model_args.model_name_or_path					,		from_pt=bool('''.bin''' in model_args.model_name_or_path )					,		config=UpperCamelCase					,		cache_dir=model_args.cache_dir					,		)

							def compute_metrics(UpperCamelCase			:    EvalPrediction ) -> Dict:
														_a      	=							np.argmax(p.predictions					,		axis=1 )

														return {"acc": (preds == p.label_ids).mean()}

							# Initialize our Trainer
							_a      	=							TFTrainer(
							    model=UpperCamelCase					,		args=UpperCamelCase					,		train_dataset=UpperCamelCase					,		eval_dataset=UpperCamelCase					,		compute_metrics=UpperCamelCase					,		)

							# Training
							if training_args.do_train:
														trainer.train()
														trainer.save_model()
														tokenizer.save_pretrained(training_args.output_dir )

							# Evaluation
							_a      	=							{}
							if training_args.do_eval:
														logger.info('''*** Evaluate ***''' )
														_a      	=							trainer.evaluate()
														_a      	=							os.path.join(training_args.output_dir					,		'''eval_results.txt''' )

														with open(UpperCamelCase					,		'''w''' ) as writer:
																					logger.info('''***** Eval results *****''' )

																					for key, value in result.items():
																												logger.info(f'  {key} = {value}' )
																												writer.write(f'{key} = {value}\n' )

																					results.update(UpperCamelCase )

							return results


if __name__ == "__main__":
				main()

