

import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import YolosImageProcessor



class   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			def __init__( self  :     Tuple   ,						lowerCAmelCase__  :     Optional[int]   ,						lowerCAmelCase__  :     Optional[Any]=7   ,						lowerCAmelCase__  :     List[Any]=3   ,						lowerCAmelCase__  :     List[str]=30   ,						lowerCAmelCase__  :     int=400   ,						lowerCAmelCase__  :     Any=True   ,						lowerCAmelCase__  :     Union[str, Any]=None   ,						lowerCAmelCase__  :     Optional[Any]=True   ,						lowerCAmelCase__  :     Any=[0.5, 0.5, 0.5]   ,						lowerCAmelCase__  :     Optional[int]=[0.5, 0.5, 0.5]   ,						lowerCAmelCase__  :     Dict=True   ,						lowerCAmelCase__  :     int=1 / 255   ,						lowerCAmelCase__  :     Tuple=True   ,						):
									# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
									SCREAMING_SNAKE_CASE_: Tuple  		=       size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333}
									SCREAMING_SNAKE_CASE_: int  		=       parent
									SCREAMING_SNAKE_CASE_: Dict  		=       batch_size
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       num_channels
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       min_resolution
									SCREAMING_SNAKE_CASE_: Tuple  		=       max_resolution
									SCREAMING_SNAKE_CASE_: str  		=       do_resize
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       size
									SCREAMING_SNAKE_CASE_: int  		=       do_normalize
									SCREAMING_SNAKE_CASE_: int  		=       image_mean
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       image_std
									SCREAMING_SNAKE_CASE_: Tuple  		=       do_rescale
									SCREAMING_SNAKE_CASE_: List[str]  		=       rescale_factor
									SCREAMING_SNAKE_CASE_: Dict  		=       do_pad



			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									return {
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "do_normalize": self.do_normalize,
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_rescale": self.do_rescale,
									    "rescale_factor": self.rescale_factor,
									    "do_pad": self.do_pad,
									}




			def        _SCREAMING_SNAKE_CASE			( self  :     Any   ,						lowerCAmelCase__  :     str   ,						lowerCAmelCase__  :     int=False):
									if not batched:
															SCREAMING_SNAKE_CASE_: List[str]  		=       image_inputs[0]
															if isinstance(A__   ,						Image.Image):
																					SCREAMING_SNAKE_CASE_: int  		=       image.size
															else:
																					SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       image.shape[1], image.shape[2]
															if w < h:
																					SCREAMING_SNAKE_CASE_: Any  		=       int(self.size["shortest_edge"] * h / w)
																					SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.size["""shortest_edge"""]
															elif w > h:
																					SCREAMING_SNAKE_CASE_: List[str]  		=       self.size["""shortest_edge"""]
																					SCREAMING_SNAKE_CASE_: List[Any]  		=       int(self.size["shortest_edge"] * w / h)
															else:
																					SCREAMING_SNAKE_CASE_: str  		=       self.size["""shortest_edge"""]
																					SCREAMING_SNAKE_CASE_: Any  		=       self.size["""shortest_edge"""]

									else:
															SCREAMING_SNAKE_CASE_: Optional[Any]  		=       []
															for image in image_inputs:
																					SCREAMING_SNAKE_CASE_: int  		=       self.get_expected_values([image])
																					expected_values.append((expected_height, expected_width))
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       max(A__   ,						key=lambda lowerCAmelCase__: item[0])[0]
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       max(A__   ,						key=lambda lowerCAmelCase__: item[1])[1]

									return expected_height, expected_width







@require_torch
@require_vision
class   __lowercase				( UpperCAmelCase_		,       unittest.TestCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							List[Any]										=     YolosImageProcessor if is_vision_available() else None



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									SCREAMING_SNAKE_CASE_: List[str]  		=       YolosImageProcessingTester(self)



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									return self.image_processor_tester.prepare_image_processor_dict()



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.image_processing_class(**self.image_processor_dict)
									self.assertTrue(hasattr(A__   ,						"image_mean"))
									self.assertTrue(hasattr(A__   ,						"image_std"))
									self.assertTrue(hasattr(A__   ,						"do_normalize"))
									self.assertTrue(hasattr(A__   ,						"do_resize"))
									self.assertTrue(hasattr(A__   ,						"size"))



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.image_processing_class.from_dict(self.image_processor_dict)
									self.assertEqual(image_processor.size   ,						{"shortest_edge": 18, "longest_edge": 1333})
									self.assertEqual(image_processor.do_pad   ,						A__)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.image_processing_class.from_dict(
									    self.image_processor_dict   ,						size=42   ,						max_size=84   ,						pad_and_return_pixel_mask=A__)
									self.assertEqual(image_processor.size   ,						{"shortest_edge": 42, "longest_edge": 84})
									self.assertEqual(image_processor.do_pad   ,						A__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									pass



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									# Initialize image_processing
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.image_processing_class(**self.image_processor_dict)
									# create random PIL images
									SCREAMING_SNAKE_CASE_: Dict  		=       prepare_image_inputs(self.image_processor_tester   ,						equal_resolution=A__)
									for image in image_inputs:
															self.assertIsInstance(A__   ,						Image.Image)

									# Test not batched input
									SCREAMING_SNAKE_CASE_: int  		=       image_processing(image_inputs[0]   ,						return_tensors="pt").pixel_values

									SCREAMING_SNAKE_CASE_: str  		=       self.image_processor_tester.get_expected_values(A__)

									self.assertEqual(
									    encoded_images.shape   ,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)   ,						)

									# Test batched
									SCREAMING_SNAKE_CASE_: int  		=       self.image_processor_tester.get_expected_values(A__   ,						batched=A__)

									SCREAMING_SNAKE_CASE_: Tuple  		=       image_processing(A__   ,						return_tensors="pt").pixel_values
									self.assertEqual(
									    encoded_images.shape   ,						(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    )   ,						)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									# Initialize image_processing
									SCREAMING_SNAKE_CASE_: Any  		=       self.image_processing_class(**self.image_processor_dict)
									# create random numpy tensors
									SCREAMING_SNAKE_CASE_: int  		=       prepare_image_inputs(self.image_processor_tester   ,						equal_resolution=A__   ,						numpify=A__)
									for image in image_inputs:
															self.assertIsInstance(A__   ,						np.ndarray)

									# Test not batched input
									SCREAMING_SNAKE_CASE_: int  		=       image_processing(image_inputs[0]   ,						return_tensors="pt").pixel_values

									SCREAMING_SNAKE_CASE_: Tuple  		=       self.image_processor_tester.get_expected_values(A__)

									self.assertEqual(
									    encoded_images.shape   ,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)   ,						)

									# Test batched
									SCREAMING_SNAKE_CASE_: List[str]  		=       image_processing(A__   ,						return_tensors="pt").pixel_values

									SCREAMING_SNAKE_CASE_: int  		=       self.image_processor_tester.get_expected_values(A__   ,						batched=A__)

									self.assertEqual(
									    encoded_images.shape   ,						(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    )   ,						)



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									# Initialize image_processing
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self.image_processing_class(**self.image_processor_dict)
									# create random PyTorch tensors
									SCREAMING_SNAKE_CASE_: str  		=       prepare_image_inputs(self.image_processor_tester   ,						equal_resolution=A__   ,						torchify=A__)
									for image in image_inputs:
															self.assertIsInstance(A__   ,						torch.Tensor)

									# Test not batched input
									SCREAMING_SNAKE_CASE_: List[Any]  		=       image_processing(image_inputs[0]   ,						return_tensors="pt").pixel_values

									SCREAMING_SNAKE_CASE_: Any  		=       self.image_processor_tester.get_expected_values(A__)

									self.assertEqual(
									    encoded_images.shape   ,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)   ,						)

									# Test batched
									SCREAMING_SNAKE_CASE_: Dict  		=       image_processing(A__   ,						return_tensors="pt").pixel_values

									SCREAMING_SNAKE_CASE_: Dict  		=       self.image_processor_tester.get_expected_values(A__   ,						batched=A__)

									self.assertEqual(
									    encoded_images.shape   ,						(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    )   ,						)



			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									# Initialize image_processings
									SCREAMING_SNAKE_CASE_: int  		=       self.image_processing_class(**self.image_processor_dict)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self.image_processing_class(do_resize=A__   ,						do_normalize=A__   ,						do_rescale=A__)
									# create random PyTorch tensors
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       prepare_image_inputs(self.image_processor_tester   ,						equal_resolution=A__   ,						torchify=A__)
									for image in image_inputs:
															self.assertIsInstance(A__   ,						torch.Tensor)

									# Test whether the method "pad" and calling the image processor return the same tensors
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       image_processing_a.pad(A__   ,						return_tensors="pt")
									SCREAMING_SNAKE_CASE_: Dict  		=       image_processing_a(A__   ,						return_tensors="pt")

									self.assertTrue(
									    torch.allclose(encoded_images_with_method["pixel_values"]   ,						encoded_images["pixel_values"]   ,						atol=1E-4))



			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									# prepare image and target
									SCREAMING_SNAKE_CASE_: List[Any]  		=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
									with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt"   ,						"r") as f:
															SCREAMING_SNAKE_CASE_: List[str]  		=       json.loads(f.read())

									SCREAMING_SNAKE_CASE_: str  		=       {"""image_id""": 3_9769, """annotations""": target}

									# encode them
									SCREAMING_SNAKE_CASE_: Tuple  		=       YolosImageProcessor.from_pretrained("hustvl/yolos-small")
									SCREAMING_SNAKE_CASE_: List[str]  		=       image_processing(images=A__   ,						annotations=A__   ,						return_tensors="pt")

									# verify pixel values
									SCREAMING_SNAKE_CASE_: str  		=       torch.Size([1, 3, 800, 1066])
									self.assertEqual(encoding["pixel_values"].shape   ,						A__)

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.tensor([0.2796, 0.3138, 0.3481])
									self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]   ,						A__   ,						atol=1E-4))

									# verify area
									SCREAMING_SNAKE_CASE_: Any  		=       torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438])
									self.assertTrue(torch.allclose(encoding["labels"][0]["area"]   ,						A__))
									# verify boxes
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       torch.Size([6, 4])
									self.assertEqual(encoding["labels"][0]["boxes"].shape   ,						A__)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       torch.tensor([0.5503, 0.2765, 0.0604, 0.2215])
									self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]   ,						A__   ,						atol=1E-3))
									# verify image_id
									SCREAMING_SNAKE_CASE_: List[Any]  		=       torch.tensor([3_9769])
									self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]   ,						A__))
									# verify is_crowd
									SCREAMING_SNAKE_CASE_: str  		=       torch.tensor([0, 0, 0, 0, 0, 0])
									self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]   ,						A__))
									# verify class_labels
									SCREAMING_SNAKE_CASE_: Any  		=       torch.tensor([75, 75, 63, 65, 17, 17])
									self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]   ,						A__))
									# verify orig_size
									SCREAMING_SNAKE_CASE_: Tuple  		=       torch.tensor([480, 640])
									self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]   ,						A__))
									# verify size
									SCREAMING_SNAKE_CASE_: Dict  		=       torch.tensor([800, 1066])
									self.assertTrue(torch.allclose(encoding["labels"][0]["size"]   ,						A__))




			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									# prepare image, target and masks_path
									SCREAMING_SNAKE_CASE_: int  		=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
									with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"   ,						"r") as f:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       json.loads(f.read())

									SCREAMING_SNAKE_CASE_: Any  		=       {"""file_name""": """000000039769.png""", """image_id""": 3_9769, """segments_info""": target}

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")

									# encode them
									SCREAMING_SNAKE_CASE_: int  		=       YolosImageProcessor(format="coco_panoptic")
									SCREAMING_SNAKE_CASE_: List[str]  		=       image_processing(images=A__   ,						annotations=A__   ,						masks_path=A__   ,						return_tensors="pt")

									# verify pixel values
									SCREAMING_SNAKE_CASE_: Any  		=       torch.Size([1, 3, 800, 1066])
									self.assertEqual(encoding["pixel_values"].shape   ,						A__)

									SCREAMING_SNAKE_CASE_: Tuple  		=       torch.tensor([0.2796, 0.3138, 0.3481])
									self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]   ,						A__   ,						atol=1E-4))

									# verify area
									SCREAMING_SNAKE_CASE_: Dict  		=       torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147])
									self.assertTrue(torch.allclose(encoding["labels"][0]["area"]   ,						A__))
									# verify boxes
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       torch.Size([6, 4])
									self.assertEqual(encoding["labels"][0]["boxes"].shape   ,						A__)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       torch.tensor([0.2625, 0.5437, 0.4688, 0.8625])
									self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]   ,						A__   ,						atol=1E-3))
									# verify image_id
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.tensor([3_9769])
									self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]   ,						A__))
									# verify is_crowd
									SCREAMING_SNAKE_CASE_: Dict  		=       torch.tensor([0, 0, 0, 0, 0, 0])
									self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]   ,						A__))
									# verify class_labels
									SCREAMING_SNAKE_CASE_: Dict  		=       torch.tensor([17, 17, 63, 75, 75, 93])
									self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]   ,						A__))
									# verify masks
									SCREAMING_SNAKE_CASE_: Tuple  		=       82_2873
									self.assertEqual(encoding["labels"][0]["masks"].sum().item()   ,						A__)
									# verify orig_size
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       torch.tensor([480, 640])
									self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]   ,						A__))
									# verify size
									SCREAMING_SNAKE_CASE_: Dict  		=       torch.tensor([800, 1066])
									self.assertTrue(torch.allclose(encoding["labels"][0]["size"]   ,						A__))









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					(lowercase_: str					)     ->      Dict:
	A__							:    int        =		int(lowercase_					)
	A__   ,   A__   ,   A__							:    Tuple        =		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					(lowercase_: str    ,      lowercase_: Optional[Any]    ,      lowercase_: Union[str, Any]    ,      lowercase_: Tuple    ,      lowercase_: Any=300					)     ->      Optional[int]:
	# docstyle-ignore
	return f"""
    <div>
      {prefix}
      <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>
      {label}
    </div>
    """

def 						UpperCamelCase					(lowercase_: Tuple					)     ->      Optional[int]:
	A__							:    Tuple        =		"""<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:
			A__							:    str        =		f"""{elt:.6f}""" if isinstance(lowercase_    ,      lowercase_					) else str(lowercase_					)
			html_code += f"""      <td>{elt}</td>\n"""
		html_code += "    </tr>\n"
	html_code += "  </tbody>\n</table><p>"
	return html_code



class     _a						:


					'''simple docstring'''






					UpperCAmelCase__:   str  							=       5
					UpperCAmelCase__:   int  							=       0.2






					def __init__( self    ,       A__    ,       A__ = None    ,       A__ = True    ,       A__ = None    ,       A__ = 300    ,       ):
						A__							:    Optional[int]        =		total
						A__							:    Tuple        =		"""""" if prefix is None else prefix
						A__							:    str        =		leave
						A__							:    str        =		parent
						A__							:    int        =		width
						A__							:    Dict        =		None
						A__							:    List[str]        =		None
						A__							:    Optional[int]        =		None






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






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






					def   __A			( self			):
						if self.parent is None and self.output is not None:
							self.output.update(disp.HTML(""""""			)			)



class     _a						(__magic_name__				):


					'''simple docstring'''






					def __init__( self    ,       A__    ,       A__=None			):
						super().__init__(A__			)
						A__							:    Optional[Any]        =		None if column_names is None else [column_names]
						A__							:    Optional[Any]        =		None






					def   __A			( self			):
						A__							:    List[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:
							A__							:    Optional[int]        =		disp.display(disp.HTML(self.html_code			)    ,       display_id=A__			)
						else:
							self.output.update(disp.HTML(self.html_code			)			)






					def   __A			( self    ,       A__			):
						if self.inner_table is None:
							A__							:    List[str]        =		[list(values.keys()			), list(values.values()			)]
						else:
							A__							:    Optional[Any]        =		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__			)
								A__							:    Any        =		columns
							self.inner_table.append([values[c] for c in columns]			)






					def   __A			( self    ,       A__    ,       A__=None    ,       A__=300			):
						A__							:    Optional[Any]        =		NotebookProgressBar(A__    ,       prefix=A__    ,       parent=self    ,       width=A__			)
						return self.child_bar






					def   __A			( self			):
						A__							:    List[str]        =		None
						self.display()



class     _a						(__magic_name__				):


					'''simple docstring'''






					def __init__( self			):
						A__							:    int        =		None
						A__							:    List[str]        =		None
						A__							:    Union[str, Any]        =		False






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						A__							:    List[str]        =		"""Epoch""" if args.evaluation_strategy == IntervalStrategy.EPOCH else """Step"""
						A__							:    Dict        =		0
						A__							:    Tuple        =		0
						A__							:    Optional[int]        =		[self.first_column] + ["""Training Loss"""]
						if args.evaluation_strategy != IntervalStrategy.NO:
							column_names.append("""Validation Loss"""			)
						A__							:    Union[str, Any]        =		NotebookTrainingTracker(state.max_steps    ,       A__			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						A__							:    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    ,       )
						A__							:    str        =		False






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						if not has_length(A__			):
							return
						if self.prediction_bar is None:
							if self.training_tracker is not None:
								A__							:    Union[str, Any]        =		self.training_tracker.add_child(len(A__			)			)
							else:
								A__							:    Tuple        =		NotebookProgressBar(len(A__			)			)
							self.prediction_bar.update(1			)
						else:
							self.prediction_bar.update(self.prediction_bar.value + 1			)






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						if self.prediction_bar is not None:
							self.prediction_bar.close()
						A__							:    List[str]        =		None






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






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       A__=None    ,       **A__			):
						if self.training_tracker is not None:
							A__							:    Tuple        =		{"""Training Loss""": """No log""", """Validation Loss""": """No log"""}
							for log in reversed(state.log_history			):
								if "loss" in log:
									A__							:    Dict        =		log["""loss"""]
									break

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






					def   __A			( self    ,       A__    ,       A__    ,       A__    ,       **A__			):
						self.training_tracker.update(
						    state.global_step    ,       comment=F"""Epoch {int(state.epoch			)}/{state.num_train_epochs}"""    ,       force_update=A__			)
						A__							:    Optional[int]        =		None



