



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  lowerCamelCase_	(      lowerCAmelCase__	:	Tuple			,	lowerCAmelCase__	:	Union[str, Any]=False				)       ->							List[str]:

							'''simple docstring'''






							try:
														A      						=    os.environ[key]
							except KeyError:
														# KEY isn't set, default to `default`.
														A      						=    default
							else:
														# KEY is set, convert it to True or False.
														try:
																					A      						=    strtobool(lowerCAmelCase__				)
														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


__snake_case     :Union[str, Any]			       =parse_flag_from_env('RUN_SLOW', default=False)
__snake_case     :Any			       =parse_flag_from_env('RUN_REMOTE', default=False)
__snake_case     :int			       =parse_flag_from_env('RUN_LOCAL', default=True)
__snake_case     :Tuple			       =parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
__snake_case     :Optional[Any]			       =pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
__snake_case     :Dict			       =pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
__snake_case     :Optional[int]			       =pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
__snake_case     :int			       =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
__snake_case     :Any			       =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
__snake_case     :Dict			       =pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
__snake_case     :Any			       =pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)






def  lowerCamelCase_	(      lowerCAmelCase__	:	int				)       ->							Optional[Any]:

							'''simple docstring'''






							try:
														import faiss  # noqa
							except ImportError:
														A      						=    unittest.skip('test requires faiss'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Union[str, Any]				)       ->							List[Any]:

							'''simple docstring'''






							try:
														import regex  # noqa
							except ImportError:
														A      						=    unittest.skip('test requires regex'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Dict				)       ->							Union[str, Any]:

							'''simple docstring'''






							try:
														import elasticsearch  # noqa
							except ImportError:
														A      						=    unittest.skip('test requires elasticsearch'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Dict				)       ->							Optional[int]:

							'''simple docstring'''






							try:
														import sqlalchemy  # noqa
							except ImportError:
														A      						=    unittest.skip('test requires sqlalchemy'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[Any]				)       ->							List[Any]:

							'''simple docstring'''






							if not config.TORCH_AVAILABLE:
														A      						=    unittest.skip('test requires PyTorch'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Tuple				)       ->							Tuple:

							'''simple docstring'''






							if not config.TF_AVAILABLE:
														A      						=    unittest.skip('test requires TensorFlow'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	List[Any]				)       ->							Dict:

							'''simple docstring'''






							if not config.JAX_AVAILABLE:
														A      						=    unittest.skip('test requires JAX'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Tuple				)       ->							Any:

							'''simple docstring'''






							if not config.PIL_AVAILABLE:
														A      						=    unittest.skip('test requires Pillow'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	List[str]				)       ->							Optional[int]:

							'''simple docstring'''






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






def  lowerCamelCase_	(      lowerCAmelCase__	:	str				)       ->							Tuple:

							'''simple docstring'''






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






def  lowerCamelCase_	(      lowerCAmelCase__	:	List[Any]				)       ->							int:

							'''simple docstring'''






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






def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[int]				)       ->							Tuple:

							'''simple docstring'''






							def _require_spacy_model(lowerCAmelCase__	:	str				):
														try:
																					import spacy  # noqa F401

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

							return _require_spacy_model






def  lowerCamelCase_	(      lowerCAmelCase__	:	int				)       ->							Tuple:

							'''simple docstring'''






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






def  lowerCamelCase_	(      lowerCAmelCase__	:	str				)       ->							int:

							'''simple docstring'''






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






def  lowerCamelCase_	(      lowerCAmelCase__	:	Any				)       ->							str:

							'''simple docstring'''






							if not _run_slow_tests or _run_slow_tests == 0:
														A      						=    unittest.skip('test is slow'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[Any]				)       ->							Tuple:

							'''simple docstring'''






							if not _run_local_tests or _run_local_tests == 0:
														A      						=    unittest.skip('test is local'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[Any]				)       ->							Dict:

							'''simple docstring'''






							if not _run_packaged_tests or _run_packaged_tests == 0:
														A      						=    unittest.skip('test is packaged'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      lowerCAmelCase__	:	int				)       ->							Tuple:

							'''simple docstring'''






							if not _run_remote_tests or _run_remote_tests == 0:
														A      						=    unittest.skip('test requires remote'				)(lowerCAmelCase__				)
							return test_case






def  lowerCamelCase_	(      *lowerCAmelCase__	:	Union[str, Any]				)       ->							Optional[Any]:

							'''simple docstring'''






							def decorate(cls	:	int				):
														for name, fn in cls.__dict__.items():
																					if callable(lowerCAmelCase__				) and name.startswith('test'				):
																												for decorator in decorators:
																																			A      						=    decorator(lowerCAmelCase__				)
																												setattr(cls			,	lowerCAmelCase__			,	lowerCAmelCase__				)
														return cls

							return decorate



class        lowerCAmelCase__					(  _lowerCamelCase       ):
				pass





class        lowerCAmelCase__					(  _lowerCamelCase       ):
				A_   :     Union[str, Any]								=     0
				A_   :     str								=     1
				A_   :     Union[str, Any]								=     2






@contextmanager
def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[Any]=OfflineSimulationMode.CONNECTION_FAILS			,	lowerCAmelCase__	:	List[str]=1E-1_6				)       ->							List[Any]:

							'''simple docstring'''






							A      						=    requests.Session().request

							def timeout_request(lowerCAmelCase__	:	Tuple			,	lowerCAmelCase__	:	str			,	lowerCAmelCase__	:	Optional[int]			,	**lowerCAmelCase__	:	Optional[Any]				):
														# Change the url to an invalid url so that the connection hangs
														A      						=    '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.'''				)
														A      						=    timeout
														try:
																					return online_request(lowerCAmelCase__			,	lowerCAmelCase__			,	**lowerCAmelCase__				)
														except Exception as e:
																					# The following changes in the error are just here to make the offline timeout error prettier
																					A      						=    url
																					A      						=    e.args[0]
																					A      						=    (max_retry_error.args[0].replace('10.255.255.1'			,	F'''OfflineMock[{url}]'''				),)
																					A      						=    (max_retry_error,)
																					raise

							def raise_connection_error(lowerCAmelCase__	:	Tuple			,	lowerCAmelCase__	:	Optional[Any]			,	**lowerCAmelCase__	:	Union[str, Any]				):
														raise requests.ConnectionError('Offline mode is enabled.'			,	request=lowerCAmelCase__				)

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






@contextmanager
def  lowerCamelCase_	(      *lowerCAmelCase__	:	Optional[Any]			,	**lowerCAmelCase__	:	Tuple				)       ->							Optional[Any]:

							'''simple docstring'''






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






@contextmanager
def  lowerCamelCase_	(      )       ->							Optional[int]:

							'''simple docstring'''






							import gc

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






@contextmanager
def  lowerCamelCase_	(      )       ->							List[Any]:

							'''simple docstring'''






							import gc

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






def  lowerCamelCase_	(      lowerCAmelCase__	:	Union[str, Any]			,	lowerCAmelCase__	:	int				)       ->							Any:

							'''simple docstring'''






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






def  lowerCamelCase_	(      lowerCAmelCase__	:	Any				)       ->							Optional[Any]:

							'''simple docstring'''






							import decorator
							from requests.exceptions import HTTPError

							def _wrapper(lowerCAmelCase__	:	str			,	*lowerCAmelCase__	:	List[str]			,	**lowerCAmelCase__	:	List[str]				):
														try:
																					return func(*lowerCAmelCase__			,	**lowerCAmelCase__				)
														except HTTPError as err:
																					if str(lowerCAmelCase__				).startswith('500'				) or str(lowerCAmelCase__				).startswith('502'				):
																												pytest.xfail(str(lowerCAmelCase__				)				)
																					raise err

							return decorator.decorator(_wrapper			,	lowerCAmelCase__				)



class        lowerCAmelCase__					:


				def __init__(							self      :  Any						, __UpperCamelCase      :  Optional[Any]						, __UpperCamelCase      :  Any						, __UpperCamelCase      :  Optional[int]       )		->     Optional[int]:
											A      						=    returncode
											A      						=    stdout
											A      						=    stderr






async def  lowerCamelCase_	(      lowerCAmelCase__	:	Dict			,	lowerCAmelCase__	:	Tuple				)       ->							Optional[Any]:

							'''simple docstring'''






							while True:
														A      						=    await stream.readline()
														if line:
																					callback(lowerCAmelCase__				)
														else:
																					break






async def  lowerCamelCase_	(      lowerCAmelCase__	:	Any			,	lowerCAmelCase__	:	int=None			,	lowerCAmelCase__	:	int=None			,	lowerCAmelCase__	:	Optional[Any]=None			,	lowerCAmelCase__	:	str=False			,	lowerCAmelCase__	:	Optional[Any]=False				)       ->							_RunOutput:

							'''simple docstring'''






							if echo:
														print('\nRunning: '			,	' '.join(lowerCAmelCase__				)				)

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

							# 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)

							A      						=    []
							A      						=    []

							def tee(lowerCAmelCase__	:	Union[str, Any]			,	lowerCAmelCase__	:	Tuple			,	lowerCAmelCase__	:	Union[str, Any]			,	lowerCAmelCase__	:	str=""				):
														A      						=    line.decode('utf-8'				).rstrip()
														sink.append(lowerCAmelCase__				)
														if not quiet:
																					print(lowerCAmelCase__			,	lowerCAmelCase__			,	file=lowerCAmelCase__				)

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






def  lowerCamelCase_	(      lowerCAmelCase__	:	Union[str, Any]			,	lowerCAmelCase__	:	Optional[int]=None			,	lowerCAmelCase__	:	List[Any]=None			,	lowerCAmelCase__	:	Optional[Any]=180			,	lowerCAmelCase__	:	Tuple=False			,	lowerCAmelCase__	:	Optional[int]=True				)       ->							_RunOutput:

							'''simple docstring'''






							A      						=    asyncio.get_event_loop()
							A      						=    loop.run_until_complete(
							    _stream_subprocess(lowerCAmelCase__			,	env=lowerCAmelCase__			,	stdin=lowerCAmelCase__			,	timeout=lowerCAmelCase__			,	quiet=lowerCAmelCase__			,	echo=lowerCAmelCase__				)				)

							A      						=    ' '.join(lowerCAmelCase__				)
							if result.returncode > 0:
														A      						=    '\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  lowerCamelCase_	(      )       ->							Union[str, Any]:

							'''simple docstring'''






							A      						=    os.environ.get('PYTEST_XDIST_WORKER'			,	'gw0'				)
							A      						=    re.sub(r'^gw'			,	''			,	lowerCAmelCase__			,	0			,	re.M				)
							return int(lowerCAmelCase__				)






def  lowerCamelCase_	(      )       ->							Any:

							'''simple docstring'''






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






import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length






def 				_UpperCAmelCase			(    A     ):




   '''simple docstring'''

   UpperCAmelCase__						=int(A     )
   UpperCAmelCase__			,							UpperCAmelCase__			,							UpperCAmelCase__						=t // 3600, (t // 60) % 60, t % 60
   return F"""{h}:{m:02d}:{s:02d}""" if h != 0 else F"""{m:02d}:{s:02d}"""






def 				_UpperCAmelCase			(    A				,							A				,							A				,							A				,							A=300     ):




   '''simple docstring'''

   return F"""
    <div>
      {prefix}
      <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>
      {label}
    </div>
    """






def 				_UpperCAmelCase			(    A     ):




   '''simple docstring'''

   UpperCAmelCase__						="<table border=\"1\" class=\"dataframe\">\n"
   html_code += """  <thead>\n <tr style="text-align: left;">\n"""
   for i in items[0]:
      html_code += F"""      <th>{i}</th>\n"""
   html_code += "    </tr>\n  </thead>\n  <tbody>\n"
   for line in items[1:]:
      html_code += "    <tr>\n"
      for elt in line:
         UpperCAmelCase__						=F"""{elt:.6f}""" if isinstance(A				,							A     ) else str(A     )
         html_code += F"""      <td>{elt}</td>\n"""
      html_code += "    </tr>\n"
   html_code += "  </tbody>\n</table><p>"
   return html_code

class     snake_case_		:






 '''simple docstring'''





 __UpperCamelCase       =      5
 __UpperCamelCase       =      0.2

 def __init__(  self,		A_,		A_ = None,		A_ = True,		A_ = None,		A_ = 300,		)	->       Optional[Any]:
    UpperCAmelCase__						=total
    UpperCAmelCase__						="" if prefix is None else prefix
    UpperCAmelCase__						=leave
    UpperCAmelCase__						=parent
    UpperCAmelCase__						=width
    UpperCAmelCase__						=None
    UpperCAmelCase__						=None
    UpperCAmelCase__						=None

 def  __UpperCAmelCase						(  self,		A_,		A_ = False,		A_ = None		)	->       Any:
    UpperCAmelCase__						=value
    if comment is not None:
       UpperCAmelCase__						=comment
    if self.last_value is None:
       UpperCAmelCase__						=UpperCAmelCase__						=time.time()
       UpperCAmelCase__						=UpperCAmelCase__						=value
       UpperCAmelCase__						=UpperCAmelCase__						=None
       UpperCAmelCase__						=self.warmup
       UpperCAmelCase__						=1
       self.update_bar(A_		)
    elif value <= self.last_value and not force_update:
       return
    elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for,		self.total		):
       if self.first_calls > 0:
          self.first_calls -= 1
       UpperCAmelCase__						=time.time()
       UpperCAmelCase__						=current_time - self.start_time
       # We could have value = self.start_value if the update is called twixe with the same start value.
       if value > self.start_value:
          UpperCAmelCase__						=self.elapsed_time / (value - self.start_value)
       else:
          UpperCAmelCase__						=None
       if value >= self.total:
          UpperCAmelCase__						=self.total
          UpperCAmelCase__						=None
          if not self.leave:
             self.close()
       elif self.average_time_per_item is not None:
          UpperCAmelCase__						=self.average_time_per_item * (self.total - value)
       self.update_bar(A_		)
       UpperCAmelCase__						=value
       UpperCAmelCase__						=current_time
       if self.average_time_per_item is None:
          UpperCAmelCase__						=1
       else:
          UpperCAmelCase__						=max(int(self.update_every / self.average_time_per_item		),		1		)

 def  __UpperCAmelCase						(  self,		A_,		A_=None		)	->       Dict:
    UpperCAmelCase__						=" " * (len(str(self.total		)		) - len(str(A_		)		)) + str(A_		)
    if self.elapsed_time is None:
       UpperCAmelCase__						=f"""[{spaced_value}/{self.total} : < :"""
    elif self.predicted_remaining is None:
       UpperCAmelCase__						=f"""[{spaced_value}/{self.total} {format_time(self.elapsed_time		)}"""
    else:
       UpperCAmelCase__						=(
           f"""[{spaced_value}/{self.total} {format_time(self.elapsed_time		)} <"""
           f""" {format_time(self.predicted_remaining		)}"""
       )
       self.label += f""", {1/self.average_time_per_item:.2f} it/s"""
    self.label += "]" if self.comment is None or len(self.comment		) == 0 else f""", {self.comment}]"""
    self.display()

 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=html_progress_bar(self.value,		self.total,		self.prefix,		self.label,		self.width		)
    if self.parent is not None:
       # If this is a child bar, the parent will take care of the display.
       self.parent.display()
       return
    if self.output is None:
       UpperCAmelCase__						=disp.display(disp.HTML(self.html_code		),		display_id=A_		)
    else:
       self.output.update(disp.HTML(self.html_code		)		)






 def  __UpperCAmelCase						(  self		)	->       str:
    if self.parent is None and self.output is not None:
       self.output.update(disp.HTML(""		)		)

class     snake_case_		(   a							):






 '''simple docstring'''





 def __init__(  self,		A_,		A_=None		)	->       Dict:
    super().__init__(A_		)
    UpperCAmelCase__						=None if column_names is None else [column_names]
    UpperCAmelCase__						=None

 def  __UpperCAmelCase						(  self		)	->       int:
    UpperCAmelCase__						=html_progress_bar(self.value,		self.total,		self.prefix,		self.label,		self.width		)
    if self.inner_table is not None:
       self.html_code += text_to_html_table(self.inner_table		)
    if self.child_bar is not None:
       self.html_code += self.child_bar.html_code
    if self.output is None:
       UpperCAmelCase__						=disp.display(disp.HTML(self.html_code		),		display_id=A_		)
    else:
       self.output.update(disp.HTML(self.html_code		)		)

 def  __UpperCAmelCase						(  self,		A_		)	->       Tuple:
    if self.inner_table is None:
       UpperCAmelCase__						=[list(values.keys()		), list(values.values()		)]
    else:
       UpperCAmelCase__						=self.inner_table[0]
       if len(self.inner_table		) == 1:
          # We give a chance to update the column names at the first iteration
          for key in values.keys():
             if key not in columns:
                columns.append(A_		)
          UpperCAmelCase__						=columns
       self.inner_table.append([values[c] for c in columns]		)

 def  __UpperCAmelCase						(  self,		A_,		A_=None,		A_=300		)	->       Union[str, Any]:
    UpperCAmelCase__						=NotebookProgressBar(A_,		prefix=A_,		parent=self,		width=A_		)
    return self.child_bar






 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=None
    self.display()

class     snake_case_		(   a							):






 '''simple docstring'''





 def __init__(  self		)	->       Optional[int]:
    UpperCAmelCase__						=None
    UpperCAmelCase__						=None
    UpperCAmelCase__						=False

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		**A_		)	->       str:
    UpperCAmelCase__						="Epoch" if args.evaluation_strategy == IntervalStrategy.EPOCH else "Step"
    UpperCAmelCase__						=0
    UpperCAmelCase__						=0
    UpperCAmelCase__						=[self.first_column] + ["Training Loss"]
    if args.evaluation_strategy != IntervalStrategy.NO:
       column_names.append("Validation Loss"		)
    UpperCAmelCase__						=NotebookTrainingTracker(state.max_steps,		A_		)

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		**A_		)	->       str:
    UpperCAmelCase__						=int(state.epoch		) if int(state.epoch		) == state.epoch else f"""{state.epoch:.2f}"""
    self.training_tracker.update(
        state.global_step + 1,		comment=f"""Epoch {epoch}/{state.num_train_epochs}""",		force_update=self._force_next_update,		)
    UpperCAmelCase__						=False

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_=None,		**A_		)	->       int:
    if not has_length(A_		):
       return
    if self.prediction_bar is None:
       if self.training_tracker is not None:
          UpperCAmelCase__						=self.training_tracker.add_child(len(A_		)		)
       else:
          UpperCAmelCase__						=NotebookProgressBar(len(A_		)		)
       self.prediction_bar.update(1		)
    else:
       self.prediction_bar.update(self.prediction_bar.value + 1		)

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		**A_		)	->       Optional[Any]:
    if self.prediction_bar is not None:
       self.prediction_bar.close()
    UpperCAmelCase__						=None

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_=None,		**A_		)	->       str:
    # Only for when there is no evaluation
    if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
       UpperCAmelCase__						={"Training Loss": logs["loss"]}
       # First column is necessarily Step sine we're not in epoch eval strategy
       UpperCAmelCase__						=state.global_step
       self.training_tracker.write_line(A_		)

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_=None,		**A_		)	->       str:
    if self.training_tracker is not None:
       UpperCAmelCase__						={"Training Loss": "No log", "Validation Loss": "No log"}
       for log in reversed(state.log_history		):
          if "loss" in log:
             UpperCAmelCase__						=log["loss"]
             break

       if self.first_column == "Epoch":
          UpperCAmelCase__						=int(state.epoch		)
       else:
          UpperCAmelCase__						=state.global_step
       UpperCAmelCase__						="eval"
       for k in metrics:
          if k.endswith("_loss"		):
             UpperCAmelCase__						=re.sub(R"\_loss$",		"",		A_		)
       UpperCAmelCase__						=metrics.pop("total_flos",		A_		)
       UpperCAmelCase__						=metrics.pop("epoch",		A_		)
       UpperCAmelCase__						=metrics.pop(f"""{metric_key_prefix}_runtime""",		A_		)
       UpperCAmelCase__						=metrics.pop(f"""{metric_key_prefix}_samples_per_second""",		A_		)
       UpperCAmelCase__						=metrics.pop(f"""{metric_key_prefix}_steps_per_second""",		A_		)
       UpperCAmelCase__						=metrics.pop(f"""{metric_key_prefix}_jit_compilation_time""",		A_		)
       for k, v in metrics.items():
          if k == f"""{metric_key_prefix}_loss""":
             UpperCAmelCase__						=v
          else:
             UpperCAmelCase__						=k.split("_"		)
             UpperCAmelCase__						=" ".join([part.capitalize() for part in splits[1:]]		)
             UpperCAmelCase__						=v
       self.training_tracker.write_line(A_		)
       self.training_tracker.remove_child()
       UpperCAmelCase__						=None
       # Evaluation takes a long time so we should force the next update.
       UpperCAmelCase__						=True






 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		**A_		)	->       List[str]:
    self.training_tracker.update(
        state.global_step,		comment=f"""Epoch {int(state.epoch		)}/{state.num_train_epochs}""",		force_update=A_		)
    UpperCAmelCase__						=None



