


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 DetrImageProcessor




class A    (  unittest.TestCase	):






      def __init__(   self		:	int     ,  lowercase_		:	Dict     ,  lowercase_		:	Optional[Any]=7     ,  lowercase_		:	Any=3     ,  lowercase_		:	int=30     ,  lowercase_		:	Dict=400     ,  lowercase_		:	int=True     ,  lowercase_		:	str=None     ,  lowercase_		:	Optional[Any]=True     ,  lowercase_		:	Tuple=1 / 255     ,  lowercase_		:	int=True     ,  lowercase_		:	Dict=[0.5, 0.5, 0.5]     ,  lowercase_		:	Dict=[0.5, 0.5, 0.5]     ,  lowercase_		:	Dict=True     ,  )   ->		List[str]:
             """simple docstring"""




             _lowerCamelCase			:						Any            =size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333}
             _lowerCamelCase			:						List[Any]            =parent
             _lowerCamelCase			:						int            =batch_size
             _lowerCamelCase			:						Any            =num_channels
             _lowerCamelCase			:						str            =min_resolution
             _lowerCamelCase			:						Any            =max_resolution
             _lowerCamelCase			:						List[Any]            =do_resize
             _lowerCamelCase			:						Tuple            =size
             _lowerCamelCase			:						int            =do_rescale
             _lowerCamelCase			:						Tuple            =rescale_factor
             _lowerCamelCase			:						Optional[int]            =do_normalize
             _lowerCamelCase			:						Optional[Any]            =image_mean
             _lowerCamelCase			:						Union[str, Any]            =image_std
             _lowerCamelCase			:						List[str]            =do_pad






      def 			lowerCamelCase			(   self		:	Any					)   ->		Union[str, Any]:
             """simple docstring"""




             return {
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "do_rescale": self.do_rescale,
                 "rescale_factor": self.rescale_factor,
                 "do_normalize": self.do_normalize,
                 "image_mean": self.image_mean,
                 "image_std": self.image_std,
                 "do_pad": self.do_pad,
             }






      def 			lowerCamelCase			(   self		:	int     ,  lowercase_		:	int     ,  lowercase_		:	Tuple=False					)   ->		Optional[Any]:
             """simple docstring"""




             if not batched:
                    _lowerCamelCase			:						List[Any]            =image_inputs[0]
                    if isinstance(lowercase_     ,  Image.Image					):
                           _lowerCamelCase      ,	_lowerCamelCase			:						int            =image.size
                    else:
                           _lowerCamelCase      ,	_lowerCamelCase			:						Any            =image.shape[1], image.shape[2]
                    if w < h:
                           _lowerCamelCase			:						Optional[int]            =int(self.size['shortest_edge'] * h / w					)
                           _lowerCamelCase			:						Any            =self.size['shortest_edge']
                    elif w > h:
                           _lowerCamelCase			:						List[str]            =self.size['shortest_edge']
                           _lowerCamelCase			:						Optional[int]            =int(self.size['shortest_edge'] * w / h					)
                    else:
                           _lowerCamelCase			:						List[Any]            =self.size['shortest_edge']
                           _lowerCamelCase			:						Optional[int]            =self.size['shortest_edge']

             else:
                    _lowerCamelCase			:						Any            =[]
                    for image in image_inputs:
                           _lowerCamelCase      ,	_lowerCamelCase			:						Any            =self.get_expected_values([image]					)
                           expected_values.append((expected_height, expected_width)					)
                    _lowerCamelCase			:						List[Any]            =max(lowercase_     ,  key=lambda lowercase_					: item[0]					)[0]
                    _lowerCamelCase			:						Union[str, Any]            =max(lowercase_     ,  key=lambda lowercase_					: item[1]					)[1]

             return expected_height, expected_width




@require_torch
@require_vision
class A    (  UpperCamelCase_       ,				unittest.TestCase	):
      UpperCamelCase__				:    List[Any] =DetrImageProcessor if is_vision_available() else None






      def 			lowerCamelCase			(   self		:	Optional[Any]					)   ->		List[Any]:
             """simple docstring"""




             _lowerCamelCase			:						Any            =DetrImageProcessingTester(self					)






      @property
      def 			lowerCamelCase			(   self		:	Optional[Any]					)   ->		Optional[int]:
             """simple docstring"""




             return self.image_processor_tester.prepare_image_processor_dict()






      def 			lowerCamelCase			(   self		:	List[str]					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase			:						Dict            =self.image_processing_class(**self.image_processor_dict					)
             self.assertTrue(hasattr(lowercase_     ,  'image_mean'					)					)
             self.assertTrue(hasattr(lowercase_     ,  'image_std'					)					)
             self.assertTrue(hasattr(lowercase_     ,  'do_normalize'					)					)
             self.assertTrue(hasattr(lowercase_     ,  'do_rescale'					)					)
             self.assertTrue(hasattr(lowercase_     ,  'rescale_factor'					)					)
             self.assertTrue(hasattr(lowercase_     ,  'do_resize'					)					)
             self.assertTrue(hasattr(lowercase_     ,  'size'					)					)
             self.assertTrue(hasattr(lowercase_     ,  'do_pad'					)					)






      def 			lowerCamelCase			(   self		:	List[str]					)   ->		List[str]:
             """simple docstring"""




             _lowerCamelCase			:						str            =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     ,  lowercase_					)

             _lowerCamelCase			:						List[str]            =self.image_processing_class.from_dict(
                 self.image_processor_dict     ,  size=42     ,  max_size=84     ,  pad_and_return_pixel_mask=lowercase_					)
             self.assertEqual(image_processor.size     ,  {'shortest_edge': 42, 'longest_edge': 84}					)
             self.assertEqual(image_processor.do_pad     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	List[Any]					)   ->		Union[str, Any]:
             """simple docstring"""




             pass






      def 			lowerCamelCase			(   self		:	int					)   ->		int:
             """simple docstring"""




             _lowerCamelCase			:						str            =self.image_processing_class(**self.image_processor_dict					)
             # create random PIL images
             _lowerCamelCase			:						Any            =prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=lowercase_					)
             for image in image_inputs:
                    self.assertIsInstance(lowercase_     ,  Image.Image					)

             # Test not batched input
             _lowerCamelCase			:						Optional[Any]            =image_processing(image_inputs[0]     ,  return_tensors='pt'					).pixel_values

             _lowerCamelCase      ,	_lowerCamelCase			:						Optional[Any]            =self.image_processor_tester.get_expected_values(lowercase_					)

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

             # Test batched
             _lowerCamelCase      ,	_lowerCamelCase			:						str            =self.image_processor_tester.get_expected_values(lowercase_     ,  batched=lowercase_					)

             _lowerCamelCase			:						Optional[Any]            =image_processing(lowercase_     ,  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 			lowerCamelCase			(   self		:	Tuple					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase			:						Optional[Any]            =self.image_processing_class(**self.image_processor_dict					)
             # create random numpy tensors
             _lowerCamelCase			:						List[str]            =prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=lowercase_     ,  numpify=lowercase_					)
             for image in image_inputs:
                    self.assertIsInstance(lowercase_     ,  np.ndarray					)

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

             _lowerCamelCase      ,	_lowerCamelCase			:						Tuple            =self.image_processor_tester.get_expected_values(lowercase_					)

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

             # Test batched
             _lowerCamelCase			:						Dict            =image_processing(lowercase_     ,  return_tensors='pt'					).pixel_values

             _lowerCamelCase      ,	_lowerCamelCase			:						Dict            =self.image_processor_tester.get_expected_values(lowercase_     ,  batched=lowercase_					)

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






      def 			lowerCamelCase			(   self		:	List[str]					)   ->		int:
             """simple docstring"""




             _lowerCamelCase			:						Tuple            =self.image_processing_class(**self.image_processor_dict					)
             # create random PyTorch tensors
             _lowerCamelCase			:						int            =prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=lowercase_     ,  torchify=lowercase_					)
             for image in image_inputs:
                    self.assertIsInstance(lowercase_     ,  torch.Tensor					)

             # Test not batched input
             _lowerCamelCase			:						Optional[Any]            =image_processing(image_inputs[0]     ,  return_tensors='pt'					).pixel_values

             _lowerCamelCase      ,	_lowerCamelCase			:						List[str]            =self.image_processor_tester.get_expected_values(lowercase_					)

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

             # Test batched
             _lowerCamelCase			:						str            =image_processing(lowercase_     ,  return_tensors='pt'					).pixel_values

             _lowerCamelCase      ,	_lowerCamelCase			:						List[str]            =self.image_processor_tester.get_expected_values(lowercase_     ,  batched=lowercase_					)

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






      @slow
      def 			lowerCamelCase			(   self		:	List[Any]					)   ->		Tuple:
             """simple docstring"""




             _lowerCamelCase			:						Tuple            =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
             with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'     ,  'r'					) as f:
                    _lowerCamelCase			:						List[str]            =json.loads(f.read()					)

             _lowerCamelCase			:						Dict            ={'image_id': 3_9769, 'annotations': target}

             # encode them
             _lowerCamelCase			:						Optional[int]            =DetrImageProcessor.from_pretrained('facebook/detr-resnet-50'					)
             _lowerCamelCase			:						Dict            =image_processing(images=lowercase_     ,  annotations=lowercase_     ,  return_tensors='pt'					)

             # verify pixel values
             _lowerCamelCase			:						List[str]            =torch.Size([1, 3, 800, 1066]					)
             self.assertEqual(encoding['pixel_values'].shape     ,  lowercase_					)

             _lowerCamelCase			:						Optional[int]            =torch.tensor([0.2796, 0.3138, 0.3481]					)
             self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]     ,  lowercase_     ,  atol=1E-4					)					)

             # verify area
             _lowerCamelCase			:						str            =torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['area']     ,  lowercase_					)					)
             # verify boxes
             _lowerCamelCase			:						Optional[Any]            =torch.Size([6, 4]					)
             self.assertEqual(encoding['labels'][0]['boxes'].shape     ,  lowercase_					)
             _lowerCamelCase			:						Any            =torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]     ,  lowercase_     ,  atol=1E-3					)					)
             # verify image_id
             _lowerCamelCase			:						str            =torch.tensor([3_9769]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']     ,  lowercase_					)					)
             # verify is_crowd
             _lowerCamelCase			:						Any            =torch.tensor([0, 0, 0, 0, 0, 0]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']     ,  lowercase_					)					)
             # verify class_labels
             _lowerCamelCase			:						Union[str, Any]            =torch.tensor([75, 75, 63, 65, 17, 17]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']     ,  lowercase_					)					)
             # verify orig_size
             _lowerCamelCase			:						int            =torch.tensor([480, 640]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']     ,  lowercase_					)					)
             # verify size
             _lowerCamelCase			:						Tuple            =torch.tensor([800, 1066]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['size']     ,  lowercase_					)					)






      @slow
      def 			lowerCamelCase			(   self		:	Dict					)   ->		Tuple:
             """simple docstring"""




             _lowerCamelCase			:						Union[str, Any]            =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
             with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'     ,  'r'					) as f:
                    _lowerCamelCase			:						Optional[int]            =json.loads(f.read()					)

             _lowerCamelCase			:						Tuple            ={'file_name': '000000039769.png', 'image_id': 3_9769, 'segments_info': target}

             _lowerCamelCase			:						str            =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'					)

             # encode them
             _lowerCamelCase			:						str            =DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic'					)
             _lowerCamelCase			:						int            =image_processing(images=lowercase_     ,  annotations=lowercase_     ,  masks_path=lowercase_     ,  return_tensors='pt'					)

             # verify pixel values
             _lowerCamelCase			:						Optional[Any]            =torch.Size([1, 3, 800, 1066]					)
             self.assertEqual(encoding['pixel_values'].shape     ,  lowercase_					)

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

             # verify area
             _lowerCamelCase			:						Union[str, Any]            =torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['area']     ,  lowercase_					)					)
             # verify boxes
             _lowerCamelCase			:						int            =torch.Size([6, 4]					)
             self.assertEqual(encoding['labels'][0]['boxes'].shape     ,  lowercase_					)
             _lowerCamelCase			:						Union[str, Any]            =torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]     ,  lowercase_     ,  atol=1E-3					)					)
             # verify image_id
             _lowerCamelCase			:						Dict            =torch.tensor([3_9769]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']     ,  lowercase_					)					)
             # verify is_crowd
             _lowerCamelCase			:						Tuple            =torch.tensor([0, 0, 0, 0, 0, 0]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']     ,  lowercase_					)					)
             # verify class_labels
             _lowerCamelCase			:						Optional[int]            =torch.tensor([17, 17, 63, 75, 75, 93]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']     ,  lowercase_					)					)
             # verify masks
             _lowerCamelCase			:						List[str]            =82_2873
             self.assertEqual(encoding['labels'][0]['masks'].sum().item()     ,  lowercase_					)
             # verify orig_size
             _lowerCamelCase			:						Dict            =torch.tensor([480, 640]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']     ,  lowercase_					)					)
             # verify size
             _lowerCamelCase			:						int            =torch.tensor([800, 1066]					)
             self.assertTrue(torch.allclose(encoding['labels'][0]['size']     ,  lowercase_					)					)






import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
 from transformers.trainer import DEFAULT_CALLBACKS

 from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel




class A    (  UpperCamelCase_	):






      def __init__(   self		:	str					)   ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase			:						Optional[Any]            =[]






      def 			lowerCamelCase			(   self		:	Dict     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	Optional[int]     ,  **lowercase_		:	List[Any]					)   ->		List[Any]:
             """simple docstring"""




             self.events.append('on_init_end'					)






      def 			lowerCamelCase			(   self		:	int     ,  lowercase_		:	Tuple     ,  lowercase_		:	Any     ,  lowercase_		:	Optional[Any]     ,  **lowercase_		:	Any					)   ->		Union[str, Any]:
             """simple docstring"""




             self.events.append('on_train_begin'					)






      def 			lowerCamelCase			(   self		:	Optional[int]     ,  lowercase_		:	Dict     ,  lowercase_		:	Dict     ,  lowercase_		:	Tuple     ,  **lowercase_		:	str					)   ->		Optional[Any]:
             """simple docstring"""




             self.events.append('on_train_end'					)






      def 			lowerCamelCase			(   self		:	Optional[Any]     ,  lowercase_		:	str     ,  lowercase_		:	Dict     ,  lowercase_		:	int     ,  **lowercase_		:	List[str]					)   ->		Dict:
             """simple docstring"""




             self.events.append('on_epoch_begin'					)






      def 			lowerCamelCase			(   self		:	Dict     ,  lowercase_		:	Any     ,  lowercase_		:	Dict     ,  lowercase_		:	List[Any]     ,  **lowercase_		:	Dict					)   ->		Optional[Any]:
             """simple docstring"""




             self.events.append('on_epoch_end'					)






      def 			lowerCamelCase			(   self		:	List[str]     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	Any     ,  **lowercase_		:	Dict					)   ->		Tuple:
             """simple docstring"""




             self.events.append('on_step_begin'					)






      def 			lowerCamelCase			(   self		:	List[str]     ,  lowercase_		:	Dict     ,  lowercase_		:	str     ,  lowercase_		:	Optional[Any]     ,  **lowercase_		:	Optional[int]					)   ->		Tuple:
             """simple docstring"""




             self.events.append('on_step_end'					)






      def 			lowerCamelCase			(   self		:	Tuple     ,  lowercase_		:	int     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Union[str, Any]     ,  **lowercase_		:	List[Any]					)   ->		Any:
             """simple docstring"""




             self.events.append('on_evaluate'					)






      def 			lowerCamelCase			(   self		:	Tuple     ,  lowercase_		:	Union[str, Any]     ,  lowercase_		:	Dict     ,  lowercase_		:	List[str]     ,  **lowercase_		:	Dict					)   ->		Dict:
             """simple docstring"""




             self.events.append('on_predict'					)






      def 			lowerCamelCase			(   self		:	Union[str, Any]     ,  lowercase_		:	List[str]     ,  lowercase_		:	Optional[int]     ,  lowercase_		:	List[Any]     ,  **lowercase_		:	Optional[int]					)   ->		Any:
             """simple docstring"""




             self.events.append('on_save'					)






      def 			lowerCamelCase			(   self		:	str     ,  lowercase_		:	List[Any]     ,  lowercase_		:	Any     ,  lowercase_		:	Optional[int]     ,  **lowercase_		:	Optional[int]					)   ->		List[str]:
             """simple docstring"""




             self.events.append('on_log'					)






      def 			lowerCamelCase			(   self		:	Any     ,  lowercase_		:	List[Any]     ,  lowercase_		:	int     ,  lowercase_		:	List[Any]     ,  **lowercase_		:	str					)   ->		List[Any]:
             """simple docstring"""




             self.events.append('on_prediction_step'					)




@require_torch
class A    (  unittest.TestCase	):






      def 			lowerCamelCase			(   self		:	List[Any]					)   ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase			:						Dict            =tempfile.mkdtemp()






      def 			lowerCamelCase			(   self		:	Union[str, Any]					)   ->		int:
             """simple docstring"""




             shutil.rmtree(self.output_dir					)






      def 			lowerCamelCase			(   self		:	Optional[Any]     ,  lowercase_		:	Optional[int]=0     ,  lowercase_		:	int=0     ,  lowercase_		:	Dict=64     ,  lowercase_		:	List[str]=64     ,  lowercase_		:	int=None     ,  lowercase_		:	Tuple=False     ,  **lowercase_		:	Dict					)   ->		Optional[int]:
             """simple docstring"""




             _lowerCamelCase			:						int            =RegressionDataset(length=lowercase_					)
             _lowerCamelCase			:						Optional[Any]            =RegressionDataset(length=lowercase_					)
             _lowerCamelCase			:						str            =RegressionModelConfig(a=lowercase_     ,  b=lowercase_					)
             _lowerCamelCase			:						Optional[Any]            =RegressionPreTrainedModel(lowercase_					)

             _lowerCamelCase			:						str            =TrainingArguments(self.output_dir     ,  disable_tqdm=lowercase_     ,  report_to=[]     ,  **lowercase_					)
             return Trainer(
                 lowercase_     ,  lowercase_     ,  train_dataset=lowercase_     ,  eval_dataset=lowercase_     ,  callbacks=lowercase_     ,  )






      def 			lowerCamelCase			(   self		:	List[str]     ,  lowercase_		:	int     ,  lowercase_		:	int					)   ->		str:
             """simple docstring"""




             self.assertEqual(len(lowercase_					)     ,  len(lowercase_					)					)

             # Order doesn't matter
             _lowerCamelCase			:						Any            =sorted(lowercase_     ,  key=lambda lowercase_					: cb.__name__ if isinstance(lowercase_     ,  lowercase_					) else cb.__class__.__name__					)
             _lowerCamelCase			:						Any            =sorted(lowercase_     ,  key=lambda lowercase_					: cb.__name__ if isinstance(lowercase_     ,  lowercase_					) else cb.__class__.__name__					)

             for cba, cba in zip(lowercase_     ,  lowercase_					):
                    if isinstance(lowercase_     ,  lowercase_					) and isinstance(lowercase_     ,  lowercase_					):
                           self.assertEqual(lowercase_     ,  lowercase_					)
                    elif isinstance(lowercase_     ,  lowercase_					) and not isinstance(lowercase_     ,  lowercase_					):
                           self.assertEqual(lowercase_     ,  cba.__class__					)
                    elif not isinstance(lowercase_     ,  lowercase_					) and isinstance(lowercase_     ,  lowercase_					):
                           self.assertEqual(cba.__class__     ,  lowercase_					)
                    else:
                           self.assertEqual(lowercase_     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	Dict     ,  lowercase_		:	List[str]					)   ->		str:
             """simple docstring"""




             _lowerCamelCase			:						List[Any]            =['on_init_end', 'on_train_begin']
             _lowerCamelCase			:						Dict            =0
             _lowerCamelCase			:						str            =len(trainer.get_eval_dataloader()					)
             _lowerCamelCase			:						List[Any]            =['on_prediction_step'] * len(trainer.get_eval_dataloader()					) + ['on_log', 'on_evaluate']
             for _ in range(trainer.state.num_train_epochs					):
                    expected_events.append('on_epoch_begin'					)
                    for _ in range(lowercase_					):
                           step += 1
                           expected_events += ["on_step_begin", "on_step_end"]
                           if step % trainer.args.logging_steps == 0:
                                  expected_events.append('on_log'					)
                           if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
                                  expected_events += evaluation_events.copy()
                           if step % trainer.args.save_steps == 0:
                                  expected_events.append('on_save'					)
                    expected_events.append('on_epoch_end'					)
                    if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
                           expected_events += evaluation_events.copy()
             expected_events += ["on_log", "on_train_end"]
             return expected_events






      def 			lowerCamelCase			(   self		:	Optional[Any]					)   ->		List[str]:
             """simple docstring"""




             _lowerCamelCase			:						Any            =self.get_trainer()
             _lowerCamelCase			:						Optional[Any]            =DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             # Callbacks passed at init are added to the default callbacks
             _lowerCamelCase			:						Dict            =self.get_trainer(callbacks=[MyTestTrainerCallback]					)
             expected_callbacks.append(lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
             _lowerCamelCase			:						List[str]            =self.get_trainer(disable_tqdm=lowercase_					)
             _lowerCamelCase			:						Tuple            =DEFAULT_CALLBACKS.copy() + [PrinterCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	str					)   ->		Optional[Any]:
             """simple docstring"""




             _lowerCamelCase			:						int            =DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             _lowerCamelCase			:						List[str]            =self.get_trainer()

             # We can add, pop, or remove by class name
             trainer.remove_callback(lowercase_					)
             expected_callbacks.remove(lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             _lowerCamelCase			:						Tuple            =self.get_trainer()
             _lowerCamelCase			:						Dict            =trainer.pop_callback(lowercase_					)
             self.assertEqual(cb.__class__     ,  lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             trainer.add_callback(lowercase_					)
             expected_callbacks.insert(0     ,  lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             # We can also add, pop, or remove by instance
             _lowerCamelCase			:						Optional[int]            =self.get_trainer()
             _lowerCamelCase			:						Any            =trainer.callback_handler.callbacks[0]
             trainer.remove_callback(lowercase_					)
             expected_callbacks.remove(lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             _lowerCamelCase			:						Any            =self.get_trainer()
             _lowerCamelCase			:						Optional[int]            =trainer.callback_handler.callbacks[0]
             _lowerCamelCase			:						Dict            =trainer.pop_callback(lowercase_					)
             self.assertEqual(lowercase_     ,  lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)

             trainer.add_callback(lowercase_					)
             expected_callbacks.insert(0     ,  lowercase_					)
             self.check_callbacks_equality(trainer.callback_handler.callbacks     ,  lowercase_					)






      def 			lowerCamelCase			(   self		:	Tuple					)   ->		Union[str, Any]:
             """simple docstring"""




             import warnings

             # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
             warnings.simplefilter(action='ignore'     ,  category=lowercase_					)

             _lowerCamelCase			:						str            =self.get_trainer(callbacks=[MyTestTrainerCallback]					)
             trainer.train()
             _lowerCamelCase			:						List[Any]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             # Independent log/save/eval
             _lowerCamelCase			:						str            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  logging_steps=5					)
             trainer.train()
             _lowerCamelCase			:						Union[str, Any]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             _lowerCamelCase			:						int            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  save_steps=5					)
             trainer.train()
             _lowerCamelCase			:						Optional[Any]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             _lowerCamelCase			:						str            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  eval_steps=5     ,  evaluation_strategy='steps'					)
             trainer.train()
             _lowerCamelCase			:						Any            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             _lowerCamelCase			:						Optional[int]            =self.get_trainer(callbacks=[MyTestTrainerCallback]     ,  evaluation_strategy='epoch'					)
             trainer.train()
             _lowerCamelCase			:						Optional[int]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             # A bit of everything
             _lowerCamelCase			:						Optional[Any]            =self.get_trainer(
                 callbacks=[MyTestTrainerCallback]     ,  logging_steps=3     ,  save_steps=10     ,  eval_steps=5     ,  evaluation_strategy='steps'     ,  )
             trainer.train()
             _lowerCamelCase			:						List[str]            =trainer.callback_handler.callbacks[-2].events
             self.assertEqual(lowercase_     ,  self.get_expected_events(lowercase_					)					)

             # warning should be emitted for duplicated callbacks
             with patch('transformers.trainer_callback.logger.warning'					) as warn_mock:
                    _lowerCamelCase			:						Union[str, Any]            =self.get_trainer(
                        callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]     ,  )
                    assert str(lowercase_					) in warn_mock.call_args[0][0]


