





"""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 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 def __init__(    self  ):



     '''simple docstring'''




     __A    :						str						 =     []

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_init_end'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_train_begin'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_train_end'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_epoch_begin'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_epoch_end'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_step_begin'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_step_end'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_evaluate'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_predict'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_save'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_log'''  )







 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase  ):



     '''simple docstring'''




     self.events.append('''on_prediction_step'''  )






@require_torch
class 		__snake_case					(		unittest.TestCase     ):





 """simple docstring"""


 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[str]						 =     tempfile.mkdtemp()

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     shutil.rmtree(self.output_dir  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase=0					,						__lowerCamelCase=0					,						__lowerCamelCase=64					,						__lowerCamelCase=64					,						__lowerCamelCase=None					,						__lowerCamelCase=False					,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Dict						 =     RegressionDataset(length=__lowerCamelCase  )
     __A    :						List[Any]						 =     RegressionDataset(length=__lowerCamelCase  )
     __A    :						List[str]						 =     RegressionModelConfig(a=__lowerCamelCase					,						b=__lowerCamelCase  )
     __A    :						Union[str, Any]						 =     RegressionPreTrainedModel(__lowerCamelCase  )

     __A    :						Union[str, Any]						 =     TrainingArguments(self.output_dir					,						disable_tqdm=__lowerCamelCase					,						report_to=[]					,						**__lowerCamelCase  )
     return Trainer(
         __lowerCamelCase					,						__lowerCamelCase					,						train_dataset=__lowerCamelCase					,						eval_dataset=__lowerCamelCase					,						callbacks=__lowerCamelCase					,						)

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     self.assertEqual(len(__lowerCamelCase  )					,						len(__lowerCamelCase  )  )

     # Order doesn't matter
     __A    :						List[Any]						 =     sorted(__lowerCamelCase					,						key=lambda __lowerCamelCase  : cb.__name__ if isinstance(__lowerCamelCase					,						__lowerCamelCase  ) else cb.__class__.__name__  )
     __A    :						List[str]						 =     sorted(__lowerCamelCase					,						key=lambda __lowerCamelCase  : cb.__name__ if isinstance(__lowerCamelCase					,						__lowerCamelCase  ) else cb.__class__.__name__  )

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						List[str]						 =     ['''on_init_end''', '''on_train_begin''']
     __A    :						Union[str, Any]						 =     0
     __A    :						str						 =     len(trainer.get_eval_dataloader()  )
     __A    :						Dict						 =     ['''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(__lowerCamelCase  ):
             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 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

     # Callbacks passed at init are added to the default callbacks
     __A    :						List[Any]						 =     self.get_trainer(callbacks=[MyTestTrainerCallback]  )
     expected_callbacks.append(__lowerCamelCase  )
     self.check_callbacks_equality(trainer.callback_handler.callbacks					,						__lowerCamelCase  )

     # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
     __A    :						Optional[int]						 =     self.get_trainer(disable_tqdm=__lowerCamelCase  )
     __A    :						Optional[Any]						 =     DEFAULT_CALLBACKS.copy() + [PrinterCallback]
     self.check_callbacks_equality(trainer.callback_handler.callbacks					,						__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Optional[Any]						 =     DEFAULT_CALLBACKS.copy() + [ProgressCallback]
     __A    :						Optional[Any]						 =     self.get_trainer()

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

     __A    :						Optional[int]						 =     self.get_trainer()
     __A    :						Any						 =     trainer.pop_callback(__lowerCamelCase  )
     self.assertEqual(cb.__class__					,						__lowerCamelCase  )
     self.check_callbacks_equality(trainer.callback_handler.callbacks					,						__lowerCamelCase  )

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

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

     __A    :						List[str]						 =     self.get_trainer()
     __A    :						Optional[int]						 =     trainer.callback_handler.callbacks[0]
     __A    :						List[Any]						 =     trainer.pop_callback(__lowerCamelCase  )
     self.assertEqual(__lowerCamelCase					,						__lowerCamelCase  )
     self.check_callbacks_equality(trainer.callback_handler.callbacks					,						__lowerCamelCase  )

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







 def 					UpperCamelCase__(    self  ):



     '''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=__lowerCamelCase  )

     __A    :						int						 =     self.get_trainer(callbacks=[MyTestTrainerCallback]  )
     trainer.train()
     __A    :						Tuple						 =     trainer.callback_handler.callbacks[-2].events
     self.assertEqual(__lowerCamelCase					,						self.get_expected_events(__lowerCamelCase  )  )

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

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

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

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

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

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











"""simple docstring"""



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool






class 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     """facebook/bart-large-mnli"""
 _lowerCamelCase        =     (
     """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """
     """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """
     """It returns the most likely label in the list of provided `labels` for the input text."""
 )
 _lowerCamelCase        =     """text_classifier"""
 _lowerCamelCase        =     AutoTokenizer
 _lowerCamelCase        =     AutoModelForSequenceClassification

 _lowerCamelCase        =     ["""text""", ["""text"""]]
 _lowerCamelCase        =     ["""text"""]

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     super().setup()
     __A    :						List[str]						 =     self.model.config
     __A    :						int						 =     -1
     for idx, label in config.idalabel.items():
         if label.lower().startswith('''entail'''  ):
             __A    :						List[str]						 =     int(__lowerCamelCase  )
     if self.entailment_id == -1:
         raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     labels
     return self.pre_processor(
         [text] * len(__lowerCamelCase  )					,						[F"""This example is {label}""" for label in labels]					,						return_tensors='''pt'''					,						padding='''max_length'''					,						)







 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     outputs.logits
     __A    :						List[str]						 =     torch.argmax(logits[:, 2]  ).item()
     return self._labels[label_id]




