
'''simple docstring'''






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							(  UpperCAmelCase__							:							Any):
				lowerCamelCase					:			Optional[int]									= int(__snake_case)
				lowerCamelCase			, lowerCamelCase			, lowerCamelCase					:			int									= t // 36_00, (t // 60) % 60, t % 60
				return F'''{h}:{m:02d}:{s:02d}''' if h != 0 else F'''{m:02d}:{s:02d}'''





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[str]       ,							UpperCAmelCase__							:							Tuple       ,							UpperCAmelCase__							:							List[str]       ,							UpperCAmelCase__							:							str       ,							UpperCAmelCase__							:							List[Any]=3_00):
				return F'''\n    <div>\n      {prefix}\n      <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>\n      {label}\n    </div>\n    '''





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[str]):
				lowerCamelCase					:			List[Any]									= '<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:
												lowerCamelCase					:			List[str]									= F'''{elt:.6f}''' if isinstance(__snake_case       ,							__snake_case) else str(__snake_case)
												html_code += F'''      <td>{elt}</td>\n'''
								html_code += "    </tr>\n"
				html_code += "  </tbody>\n</table><p>"
				return html_code




class     __snake_case		:
					_lowerCAmelCase			     =	5
					_lowerCAmelCase			     =	0.2
					def __init__(     self,    A,    A = None,    A = True,    A = None,    A = 300,    ):

									"""simple docstring"""


									lowerCamelCase					:			Tuple									= total
									lowerCamelCase					:			Tuple									= '' if prefix is None else prefix
									lowerCamelCase					:			Tuple									= leave
									lowerCamelCase					:			Dict									= parent
									lowerCamelCase					:			List[Any]									= width
									lowerCamelCase					:			List[Any]									= None
									lowerCamelCase					:			Union[str, Any]									= None
									lowerCamelCase					:			Optional[int]									= None
					def     UpperCAmelCase_							(     self,    A,    A = False,    A = None      ):

									"""simple docstring"""


									lowerCamelCase					:			int									= value
									if comment is not None:
													lowerCamelCase					:			int									= comment
									if self.last_value is None:
													lowerCamelCase					:			List[str]									= time.time()
													lowerCamelCase					:			int									= value
													lowerCamelCase					:			str									= None
													lowerCamelCase					:			Optional[Any]									= self.warmup
													lowerCamelCase					:			int									= 1
													self.update_bar(__lowerCAmelCase      )
									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
													lowerCamelCase					:			Union[str, Any]									= time.time()
													lowerCamelCase					:			List[str]									= 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:
																	lowerCamelCase					:			Any									= self.elapsed_time / (value - self.start_value)
													else:
																	lowerCamelCase					:			List[str]									= None
													if value >= self.total:
																	lowerCamelCase					:			int									= self.total
																	lowerCamelCase					:			int									= None
																	if not self.leave:
																					self.close()
													elif self.average_time_per_item is not None:
																	lowerCamelCase					:			Tuple									= self.average_time_per_item * (self.total - value)
													self.update_bar(__lowerCAmelCase      )
													lowerCamelCase					:			Any									= value
													lowerCamelCase					:			Optional[Any]									= current_time
													if self.average_time_per_item is None:
																	lowerCamelCase					:			Dict									= 1
													else:
																	lowerCamelCase					:			List[Any]									= max(int(self.update_every / self.average_time_per_item      ),    1      )
					def     UpperCAmelCase_							(     self,    A,    A=None      ):

									"""simple docstring"""


									lowerCamelCase					:			str									= ' ' * (len(str(self.total      )      ) - len(str(__lowerCAmelCase      )      )) + str(__lowerCAmelCase      )
									if self.elapsed_time is None:
													lowerCamelCase					:			int									= F'''[{spaced_value}/{self.total} : < :'''
									elif self.predicted_remaining is None:
													lowerCamelCase					:			int									= F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time      )}'''
									else:
													lowerCamelCase					:			Any									= (
													    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      ):

									"""simple docstring"""


									lowerCamelCase					:			Union[str, Any]									= 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:
													lowerCamelCase					:			int									= disp.display(disp.HTML(self.html_code      ),    display_id=__lowerCAmelCase      )
									else:
													self.output.update(disp.HTML(self.html_code      )      )




					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									if self.parent is None and self.output is not None:
													self.output.update(disp.HTML(''      )      )





class     __snake_case		(   a__):
					def __init__(     self,    A,    A=None      ):

									"""simple docstring"""


									super().__init__(__lowerCAmelCase      )
									lowerCamelCase					:			Optional[Any]									= None if column_names is None else [column_names]
									lowerCamelCase					:			Tuple									= None
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			int									= 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:
													lowerCamelCase					:			Tuple									= disp.display(disp.HTML(self.html_code      ),    display_id=__lowerCAmelCase      )
									else:
													self.output.update(disp.HTML(self.html_code      )      )
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									if self.inner_table is None:
													lowerCamelCase					:			Optional[int]									= [list(values.keys()      ), list(values.values()      )]
									else:
													lowerCamelCase					:			Tuple									= 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(__lowerCAmelCase      )
																	lowerCamelCase					:			Tuple									= columns
													self.inner_table.append([values[c] for c in columns]      )
					def     UpperCAmelCase_							(     self,    A,    A=None,    A=300      ):

									"""simple docstring"""


									lowerCamelCase					:			Any									= NotebookProgressBar(__lowerCAmelCase,    prefix=__lowerCAmelCase,    parent=self,    width=__lowerCAmelCase      )
									return self.child_bar




					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Union[str, Any]									= None
									self.display()





class     __snake_case		(   a__):
					def __init__(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			List[str]									= None
									lowerCamelCase					:			Dict									= None
									lowerCamelCase					:			Any									= False
					def     UpperCAmelCase_							(     self,    A,    A,    A,    **A      ):

									"""simple docstring"""


									lowerCamelCase					:			Dict									= 'Epoch' if args.evaluation_strategy == IntervalStrategy.EPOCH else 'Step'
									lowerCamelCase					:			int									= 0
									lowerCamelCase					:			List[str]									= 0
									lowerCamelCase					:			Dict									= [self.first_column] + ['Training Loss']
									if args.evaluation_strategy != IntervalStrategy.NO:
													column_names.append('Validation Loss'      )
									lowerCamelCase					:			Dict									= NotebookTrainingTracker(state.max_steps,    __lowerCAmelCase      )
					def     UpperCAmelCase_							(     self,    A,    A,    A,    **A      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[Any]									= 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,    )
									lowerCamelCase					:			List[str]									= False
					def     UpperCAmelCase_							(     self,    A,    A,    A,    A=None,    **A      ):

									"""simple docstring"""


									if not has_length(__lowerCAmelCase      ):
													return
									if self.prediction_bar is None:
													if self.training_tracker is not None:
																	lowerCamelCase					:			List[str]									= self.training_tracker.add_child(len(__lowerCAmelCase      )      )
													else:
																	lowerCamelCase					:			Optional[int]									= NotebookProgressBar(len(__lowerCAmelCase      )      )
													self.prediction_bar.update(1      )
									else:
													self.prediction_bar.update(self.prediction_bar.value + 1      )
					def     UpperCAmelCase_							(     self,    A,    A,    A,    **A      ):

									"""simple docstring"""


									if self.prediction_bar is not None:
													self.prediction_bar.close()
									lowerCamelCase					:			Dict									= None
					def     UpperCAmelCase_							(     self,    A,    A,    A,    A=None,    **A      ):

									"""simple docstring"""


									if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
													lowerCamelCase					:			Dict									= {'Training Loss': logs['loss']}
													# First column is necessarily Step sine we're not in epoch eval strategy
													lowerCamelCase					:			List[Any]									= state.global_step
													self.training_tracker.write_line(__lowerCAmelCase      )
					def     UpperCAmelCase_							(     self,    A,    A,    A,    A=None,    **A      ):

									"""simple docstring"""


									if self.training_tracker is not None:
													lowerCamelCase					:			Optional[int]									= {'Training Loss': 'No log', 'Validation Loss': 'No log'}
													for log in reversed(state.log_history      ):
																	if "loss" in log:
																					lowerCamelCase					:			List[str]									= log['loss']
																					break

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




					def     UpperCAmelCase_							(     self,    A,    A,    A,    **A      ):

									"""simple docstring"""


									self.training_tracker.update(
									    state.global_step,    comment=F'''Epoch {int(state.epoch      )}/{state.num_train_epochs}''',    force_update=__lowerCAmelCase      )
									lowerCamelCase					:			Union[str, Any]									= None





'''simple docstring'''






import importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


A			      =      {
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>=': operator.ge,
    '>': operator.gt,
}





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[Any]       ,							UpperCAmelCase__							:							Optional[Any]       ,							UpperCAmelCase__							:							Union[str, Any]       ,							UpperCAmelCase__							:							List[Any]       ,							UpperCAmelCase__							:							Dict       ,							UpperCAmelCase__							:							Optional[int]):
				if got_ver is None or want_ver is None:
								raise ValueError(
								    F'''Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider'''
								    F''' reinstalling {pkg}.''')
				if not ops[op](version.parse(UpperCAmelCase__)       ,							version.parse(UpperCAmelCase__)):
								raise ImportError(
								    F'''{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}''')





def    UpperCAmelCase							(  UpperCAmelCase__							:							str       ,							UpperCAmelCase__							:							Optional[str] = None):
				lowerCamelCase					:			List[Any]									= F'''\n{hint}''' if hint is not None else ''

				# non-versioned check
				if re.match(R'^[\w_\-\d]+$'       ,							UpperCAmelCase__):
								lowerCamelCase			, lowerCamelCase			, lowerCamelCase					:			Optional[Any]									= requirement, None, None
				else:
								lowerCamelCase					:			Optional[Any]									= re.findall(R'^([^!=<>\s]+)([\s!=<>]{1,2}.+)'       ,							UpperCAmelCase__)
								if not match:
												raise ValueError(
												    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'
												    F''' got {requirement}''')
								lowerCamelCase			, lowerCamelCase					:			Dict									= match[0]
								lowerCamelCase					:			Dict									= want_full.split(',')  # there could be multiple requirements
								lowerCamelCase					:			Union[str, Any]									= {}
								for w in want_range:
												lowerCamelCase					:			int									= re.findall(R'^([\s!=<>]{1,2})(.+)'       ,							UpperCAmelCase__)
												if not match:
																raise ValueError(
																    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'
																    F''' but got {requirement}''')
												lowerCamelCase			, lowerCamelCase					:			List[Any]									= match[0]
												lowerCamelCase					:			Optional[int]									= want_ver
												if op not in ops:
																raise ValueError(F'''{requirement}: need one of {list(ops.keys())}, but got {op}''')

    # special case
				if pkg == "python":
								lowerCamelCase					:			Optional[int]									= '.'.join([str(UpperCAmelCase__) for x in sys.version_info[:3]])
								for op, want_ver in wanted.items():
												_compare_versions(UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__)
								return

				# check if any version is installed
				try:
								lowerCamelCase					:			Any									= importlib.metadata.version(UpperCAmelCase__)
				except importlib.metadata.PackageNotFoundError:
								raise importlib.metadata.PackageNotFoundError(
								    F'''The \'{requirement}\' distribution was not found and is required by this application. {hint}''')

				# check that the right version is installed if version number or a range was provided
				if want_ver is not None:
								for op, want_ver in wanted.items():
												_compare_versions(UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__       ,							UpperCAmelCase__)





def    UpperCAmelCase							(  UpperCAmelCase__							:							str):
				lowerCamelCase					:			List[str]									= 'Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'
				return require_version(UpperCAmelCase__       ,							UpperCAmelCase__)
