






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   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:List[str]   =   int(snake_case			)
				__magic_name__  ,					__magic_name__  ,					__magic_name__		:Optional[Any]   =   t // 3_6_0_0, (t // 6_0) % 6_0, t % 6_0
				return f'''{h}:{m:02d}:{s:02d}''' if h != 0 else f'''{m:02d}:{s:02d}'''

def   __lowercase       (			snake_case,	snake_case,	snake_case,	snake_case,	snake_case=3_0_0			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Union[str, 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:
												__magic_name__		: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     lowerCamelCase_					:
				a__       							=	5
				a__       							=	0.2







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase = None							,       __lowerCAmelCase = True							,       __lowerCAmelCase = None							,       __lowerCAmelCase = 3_0_0							,       ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   total
								__magic_name__		:int   =   '''''' if prefix is None else prefix
								__magic_name__		:str   =   leave
								__magic_name__		:List[str]   =   parent
								__magic_name__		:List[str]   =   width
								__magic_name__		:Any   =   None
								__magic_name__		:Optional[int]   =   None
								__magic_name__		:Tuple   =   None







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







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								__magic_name__		:str   =   ''' ''' * (len(str(self.total  )  ) - len(str(__lowerCAmelCase  )  )) + str(__lowerCAmelCase  )
								if self.elapsed_time is None:
												__magic_name__		:Union[str, Any]   =   F'''[{spaced_value}/{self.total} : < :'''
								elif self.predicted_remaining is None:
												__magic_name__		:int   =   F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time  )}'''
								else:
												__magic_name__		:Tuple   =   (
												    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       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:List[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:
												__magic_name__		:Optional[Any]   =   disp.display(disp.HTML(self.html_code  )							,       display_id=__lowerCAmelCase  )
								else:
												self.output.update(disp.HTML(self.html_code  )  )







				def       A						(    self  ):
								"""simple docstring"""
								if self.parent is None and self.output is not None:
												self.output.update(disp.HTML(''''''  )  )







class     lowerCamelCase_					(   lowerCamelCase			):







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								super().__init__(__lowerCAmelCase  )
								__magic_name__		:Any   =   None if column_names is None else [column_names]
								__magic_name__		:str   =   None







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:str   =   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:
												__magic_name__		:Optional[Any]   =   disp.display(disp.HTML(self.html_code  )							,       display_id=__lowerCAmelCase  )
								else:
												self.output.update(disp.HTML(self.html_code  )  )







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								if self.inner_table is None:
												__magic_name__		:Any   =   [list(values.keys()  ), list(values.values()  )]
								else:
												__magic_name__		:Dict   =   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  )
																__magic_name__		:int   =   columns
												self.inner_table.append([values[c] for c in columns]  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase=None							,       __lowerCAmelCase=3_0_0  ):
								"""simple docstring"""
								__magic_name__		:int   =   NotebookProgressBar(__lowerCAmelCase							,       prefix=__lowerCAmelCase							,       parent=self							,       width=__lowerCAmelCase  )
								return self.child_bar







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:str   =   None
								self.display()







class     lowerCamelCase_					(   lowerCamelCase			):







				def __init__(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   None
								__magic_name__		:List[Any]   =   None
								__magic_name__		:int   =   False







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:str   =   '''Epoch''' if args.evaluation_strategy == IntervalStrategy.EPOCH else '''Step'''
								__magic_name__		:Union[str, Any]   =   0
								__magic_name__		:int   =   0
								__magic_name__		:str   =   [self.first_column] + ['''Training Loss''']
								if args.evaluation_strategy != IntervalStrategy.NO:
												column_names.append('''Validation Loss'''  )
								__magic_name__		:Optional[int]   =   NotebookTrainingTracker(state.max_steps							,       __lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   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							,       )
								__magic_name__		:Union[str, Any]   =   False







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase=None							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								if not has_length(__lowerCAmelCase  ):
												return
								if self.prediction_bar is None:
												if self.training_tracker is not None:
																__magic_name__		:Tuple   =   self.training_tracker.add_child(len(__lowerCAmelCase  )  )
												else:
																__magic_name__		:Union[str, Any]   =   NotebookProgressBar(len(__lowerCAmelCase  )  )
												self.prediction_bar.update(1  )
								else:
												self.prediction_bar.update(self.prediction_bar.value + 1  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								if self.prediction_bar is not None:
												self.prediction_bar.close()
								__magic_name__		:str   =   None







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







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase=None							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								if self.training_tracker is not None:
												__magic_name__		:int   =   {'''Training Loss''': '''No log''', '''Validation Loss''': '''No log'''}
												for log in reversed(state.log_history  ):
																if "loss" in log:
																				__magic_name__		:List[str]   =   log['''loss''']
																				break

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







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								self.training_tracker.update(
								    state.global_step							,       comment=F'''Epoch {int(state.epoch  )}/{state.num_train_epochs}'''							,       force_update=__lowerCAmelCase  )
								__magic_name__		:Optional[int]   =   None














from sklearn.metrics import matthews_corrcoef

import datasets


SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		"""
Compute the Matthews correlation coefficient (MCC)

The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary and multiclass classifications. It takes
into account true and false positives and negatives and is generally
regarded as a balanced measure which can be used even if the classes are of
very different sizes. The MCC is in essence a correlation coefficient value
between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
an average random prediction and -1 an inverse prediction.  The statistic
is also known as the phi coefficient. [source: Wikipedia]
"""

SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		"""
Args:
    predictions (list of int): Predicted labels, as returned by a model.
    references (list of int): Ground truth labels.
    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.
Returns:
    matthews_correlation (dict containing float): Matthews correlation.
Examples:
    Example 1, a basic example with only predictions and references as inputs:
        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3])
        >>> print(round(results['matthews_correlation'], 2))
        0.54

    Example 2, the same example as above, but also including sample weights:
        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3],
        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])
        >>> print(round(results['matthews_correlation'], 2))
        0.1

    Example 3, the same example as above, but with sample weights that cause a negative correlation:
        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")
        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],
        ...                                     predictions=[1, 2, 2, 0, 3, 3],
        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])
        >>> print(round(results['matthews_correlation'], 2))
        -0.25
"""

SCREAMING_SNAKE_CASE__   :      int				=		"""\
@article{scikit-learn,
  title={Scikit-learn: Machine Learning in {P}ython},
  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
  journal={Journal of Machine Learning Research},
  volume={12},
  pages={2825--2830},
  year={2011}
}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,					_KWARGS_DESCRIPTION			)
class     lowerCamelCase_					(   datasets.Metric			):







				def       A						(    self  ):
								"""simple docstring"""
								return datasets.MetricInfo(
								    description=_DESCRIPTION							,       citation=_CITATION							,       inputs_description=_KWARGS_DESCRIPTION							,       features=datasets.Features(
								        {
								            '''predictions''': datasets.Value('''int32'''  ),
								            '''references''': datasets.Value('''int32'''  ),
								        }  )							,       reference_urls=[
								        '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html'''
								    ]							,       )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								return {
								    "matthews_correlation": float(matthews_corrcoef(__lowerCAmelCase							,       __lowerCAmelCase							,       sample_weight=__lowerCAmelCase  )  ),
								}






