






"""simple docstring"""
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
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 MobileViTImageProcessor



class        UpperCamelCase__ (				unittest.TestCase):







    """simple docstring"""







    def __init__(		self :	Optional[int]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	List[Any]=7				,    UpperCamelCase_ :	Any=3				,    UpperCamelCase_ :	List[Any]=1_8				,    UpperCamelCase_ :	int=3_0				,    UpperCamelCase_ :	List[Any]=4_0_0				,    UpperCamelCase_ :	Optional[int]=True				,    UpperCamelCase_ :	Union[str, Any]=None				,    UpperCamelCase_ :	List[str]=True				,    UpperCamelCase_ :	List[str]=None				,    UpperCamelCase_ :	Any=True				,    ):





           '''simple docstring'''

           __magic_name__      				=    size if size is not None else {'shortest_edge': 2_0}
           __magic_name__      				=    crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
           __magic_name__      				=    parent
           __magic_name__      				=    batch_size
           __magic_name__      				=    num_channels
           __magic_name__      				=    image_size
           __magic_name__      				=    min_resolution
           __magic_name__      				=    max_resolution
           __magic_name__      				=    do_resize
           __magic_name__      				=    size
           __magic_name__      				=    do_center_crop
           __magic_name__      				=    crop_size
           __magic_name__      				=    do_flip_channel_order







    def 				a__			(		self :	Any ):





           '''simple docstring'''

           return {
               "do_resize": self.do_resize,
               "size": self.size,
               "do_center_crop": self.do_center_crop,
               "crop_size": self.crop_size,
               "do_flip_channel_order": self.do_flip_channel_order,
           }



@require_torch
@require_vision
class        UpperCamelCase__ (				a_							,	unittest.TestCase):







    """simple docstring"""
    __UpperCAmelCase           = MobileViTImageProcessor if is_vision_available() else None







    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           __magic_name__      				=    MobileViTImageProcessingTester(self )







    @property
    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           __magic_name__      				=    self.image_processing_class(**self.image_processor_dict )
           self.assertTrue(hasattr(UpperCamelCase_				,    'do_resize' ) )
           self.assertTrue(hasattr(UpperCamelCase_				,    'size' ) )
           self.assertTrue(hasattr(UpperCamelCase_				,    'do_center_crop' ) )
           self.assertTrue(hasattr(UpperCamelCase_				,    'center_crop' ) )
           self.assertTrue(hasattr(UpperCamelCase_				,    'do_flip_channel_order' ) )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           __magic_name__      				=    self.image_processing_class.from_dict(self.image_processor_dict )
           self.assertEqual(image_processor.size				,    {'shortest_edge': 2_0} )
           self.assertEqual(image_processor.crop_size				,    {'height': 1_8, 'width': 1_8} )

           __magic_name__      				=    self.image_processing_class.from_dict(self.image_processor_dict				,    size=4_2				,    crop_size=8_4 )
           self.assertEqual(image_processor.size				,    {'shortest_edge': 4_2} )
           self.assertEqual(image_processor.crop_size				,    {'height': 8_4, 'width': 8_4} )







    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

           pass







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

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

           # Test not batched input
           __magic_name__      				=    image_processing(image_inputs[0]				,    return_tensors='pt' ).pixel_values
           self.assertEqual(
               encoded_images.shape				,    (
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )				,    )

           # Test batched
           __magic_name__      				=    image_processing(UpperCamelCase_				,    return_tensors='pt' ).pixel_values
           self.assertEqual(
               encoded_images.shape				,    (
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )				,    )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           __magic_name__      				=    self.image_processing_class(**self.image_processor_dict )
           # create random numpy tensors
           __magic_name__      				=    prepare_image_inputs(self.image_processor_tester				,    equal_resolution=UpperCamelCase_				,    numpify=UpperCamelCase_ )
           for image in image_inputs:
                  self.assertIsInstance(UpperCamelCase_				,    np.ndarray )

           # Test not batched input
           __magic_name__      				=    image_processing(image_inputs[0]				,    return_tensors='pt' ).pixel_values
           self.assertEqual(
               encoded_images.shape				,    (
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )				,    )

           # Test batched
           __magic_name__      				=    image_processing(UpperCamelCase_				,    return_tensors='pt' ).pixel_values
           self.assertEqual(
               encoded_images.shape				,    (
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )				,    )







    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

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

           # Test not batched input
           __magic_name__      				=    image_processing(image_inputs[0]				,    return_tensors='pt' ).pixel_values
           self.assertEqual(
               encoded_images.shape				,    (
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )				,    )

           # Test batched
           __magic_name__      				=    image_processing(UpperCamelCase_				,    return_tensors='pt' ).pixel_values
           self.assertEqual(
               encoded_images.shape				,    (
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )				,    )







"""simple docstring"""
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        UpperCamelCase__ (				a_):







    """simple docstring"""







    def __init__(		self :	Union[str, Any] ):





           '''simple docstring'''

           __magic_name__      				=    []







    def 				a__			(		self :	Tuple				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	int				,    **UpperCamelCase_ :	int ):





           '''simple docstring'''

           self.events.append('on_init_end' )







    def 				a__			(		self :	Any				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	List[str]				,    **UpperCamelCase_ :	str ):





           '''simple docstring'''

           self.events.append('on_train_begin' )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    **UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           self.events.append('on_train_end' )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Tuple				,    **UpperCamelCase_ :	Optional[Any] ):





           '''simple docstring'''

           self.events.append('on_epoch_begin' )







    def 				a__			(		self :	Optional[int]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Tuple				,    **UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           self.events.append('on_epoch_end' )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Union[str, Any]				,    **UpperCamelCase_ :	Optional[Any] ):





           '''simple docstring'''

           self.events.append('on_step_begin' )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Any				,    **UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           self.events.append('on_step_end' )







    def 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Tuple				,    **UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           self.events.append('on_evaluate' )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Dict				,    **UpperCamelCase_ :	Any ):





           '''simple docstring'''

           self.events.append('on_predict' )







    def 				a__			(		self :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	str				,    **UpperCamelCase_ :	Optional[int] ):





           '''simple docstring'''

           self.events.append('on_save' )







    def 				a__			(		self :	Optional[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Union[str, Any]				,    **UpperCamelCase_ :	Optional[int] ):





           '''simple docstring'''

           self.events.append('on_log' )







    def 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	str				,    **UpperCamelCase_ :	List[Any] ):





           '''simple docstring'''

           self.events.append('on_prediction_step' )



@require_torch
class        UpperCamelCase__ (				unittest.TestCase):







    """simple docstring"""







    def 				a__			(		self :	Optional[Any] ):





           '''simple docstring'''

           __magic_name__      				=    tempfile.mkdtemp()







    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

           shutil.rmtree(self.output_dir )







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Optional[int]=0				,    UpperCamelCase_ :	List[Any]=0				,    UpperCamelCase_ :	Optional[int]=6_4				,    UpperCamelCase_ :	Optional[int]=6_4				,    UpperCamelCase_ :	List[Any]=None				,    UpperCamelCase_ :	Optional[Any]=False				,    **UpperCamelCase_ :	str ):





           '''simple docstring'''

           __magic_name__      				=    RegressionDataset(length=UpperCamelCase_ )
           __magic_name__      				=    RegressionDataset(length=UpperCamelCase_ )
           __magic_name__      				=    RegressionModelConfig(a=UpperCamelCase_				,    b=UpperCamelCase_ )
           __magic_name__      				=    RegressionPreTrainedModel(UpperCamelCase_ )

           __magic_name__      				=    TrainingArguments(self.output_dir				,    disable_tqdm=UpperCamelCase_				,    report_to=[]				,    **UpperCamelCase_ )
           return Trainer(
               UpperCamelCase_				,    UpperCamelCase_				,    train_dataset=UpperCamelCase_				,    eval_dataset=UpperCamelCase_				,    callbacks=UpperCamelCase_				,    )







    def 				a__			(		self :	Optional[int]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           self.assertEqual(len(UpperCamelCase_ )				,    len(UpperCamelCase_ ) )

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

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







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	Any ):





           '''simple docstring'''

           __magic_name__      				=    ['on_init_end', 'on_train_begin']
           __magic_name__      				=    0
           __magic_name__      				=    len(trainer.get_eval_dataloader() )
           __magic_name__      				=    ['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(UpperCamelCase_ ):
                         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 				a__			(		self :	List[Any] ):





           '''simple docstring'''

           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

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

           # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
           __magic_name__      				=    self.get_trainer(disable_tqdm=UpperCamelCase_ )
           __magic_name__      				=    DEFAULT_CALLBACKS.copy() + [PrinterCallback]
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
           __magic_name__      				=    self.get_trainer()

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

           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    trainer.pop_callback(UpperCamelCase_ )
           self.assertEqual(cb.__class__				,    UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

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

           # We can also add, pop, or remove by instance
           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    trainer.callback_handler.callbacks[0]
           trainer.remove_callback(UpperCamelCase_ )
           expected_callbacks.remove(UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

           __magic_name__      				=    self.get_trainer()
           __magic_name__      				=    trainer.callback_handler.callbacks[0]
           __magic_name__      				=    trainer.pop_callback(UpperCamelCase_ )
           self.assertEqual(UpperCamelCase_				,    UpperCamelCase_ )
           self.check_callbacks_equality(trainer.callback_handler.callbacks				,    UpperCamelCase_ )

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







    def 				a__			(		self :	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=UpperCamelCase_ )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback] )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           # Independent log/save/eval
           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    logging_steps=5 )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    save_steps=5 )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    eval_steps=5				,    evaluation_strategy='steps' )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           __magic_name__      				=    self.get_trainer(callbacks=[MyTestTrainerCallback]				,    evaluation_strategy='epoch' )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

           # A bit of everything
           __magic_name__      				=    self.get_trainer(
               callbacks=[MyTestTrainerCallback]				,    logging_steps=3				,    save_steps=1_0				,    eval_steps=5				,    evaluation_strategy='steps'				,    )
           trainer.train()
           __magic_name__      				=    trainer.callback_handler.callbacks[-2].events
           self.assertEqual(UpperCamelCase_				,    self.get_expected_events(UpperCamelCase_ ) )

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