






'''simple docstring'''
import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


UpperCamelCase__ =			logging.getLogger(__name__)




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase							):


   """simple docstring"""




   return (preds == labels).mean()


@dataclass
class        _UpperCAmelCase						:
    __lowerCamelCase:   Optional[int]		       =    field(
        metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}			)
    __lowerCamelCase:   Any		       =    field(
        default=__SCREAMING_SNAKE_CASE				,					metadata={'help': 'Pretrained config name or path if not the same as model_name'}			)
    __lowerCamelCase:   Dict		       =    field(
        default=__SCREAMING_SNAKE_CASE				,					metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}			)
    __lowerCamelCase:   str		       =    field(
        default=__SCREAMING_SNAKE_CASE				,					metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}				,					)


@dataclass
class        _UpperCAmelCase						:
    __lowerCamelCase:   Optional[int]		       =    field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys()			)}			)
    __lowerCamelCase:   int		       =    field(metadata={'help': 'Should contain the data files for the task.'}			)
    __lowerCamelCase:   str		       =    field(
        default=128				,					metadata={
            'help': (
                'The maximum total input sequence length after tokenization. Sequences longer '
                'than this will be truncated, sequences shorter will be padded.'
            )
        }				,					)
    __lowerCamelCase:   List[Any]		       =    field(
        default=__SCREAMING_SNAKE_CASE				,					metadata={'help': 'Overwrite the cached training and evaluation sets'}			)




def 		__SCREAMING_SNAKE_CASE					(  ):


   """simple docstring"""




   lowercase_	:    Any           =     HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)
   lowercase_	:    Any           =     parser.parse_args_into_dataclasses()

   if (
       os.path.exists(training_args.output_dir							)
       and os.listdir(training_args.output_dir							)
       and training_args.do_train
       and not training_args.overwrite_output_dir
   ):
      raise ValueError(
          F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
          " --overwrite_output_dir to overcome."							)

   # Setup logging
   logging.basicConfig(
       format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"						,		datefmt="%m/%d/%Y %H:%M:%S"						,		level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN						,		)
   logger.warning(
       "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"						,		training_args.local_rank						,		training_args.device						,		training_args.n_gpu						,		bool(training_args.local_rank != -1							)						,		training_args.fpaa						,		)
   # Set the verbosity to info of the Transformers logger (on main process only):
   if is_main_process(training_args.local_rank							):
      transformers.utils.logging.set_verbosity_info()
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()
   logger.info("Training/evaluation parameters %s"						,		_UpperCamelCase							)

   # Set seed
   set_seed(training_args.seed							)

   try:
      lowercase_	:    List[str]           =     processors[data_args.task_name]()
      lowercase_	:    Optional[int]           =     processor.get_labels()
      lowercase_	:    List[str]           =     len(_UpperCamelCase							)
   except KeyError:
      raise ValueError("Task not found: %s" % (data_args.task_name)							)

   # Load pretrained model and tokenizer
   #
   # Distributed training:
   # The .from_pretrained methods guarantee that only one local process can concurrently
   # download model & vocab.

   lowercase_	:    Union[str, Any]           =     AutoConfig.from_pretrained(
       model_args.config_name if model_args.config_name else model_args.model_name_or_path						,		num_labels=_UpperCamelCase						,		finetuning_task=data_args.task_name						,		cache_dir=model_args.cache_dir						,		)
   lowercase_	:    Tuple           =     AutoTokenizer.from_pretrained(
       model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path						,		cache_dir=model_args.cache_dir						,		)
   lowercase_	:    Tuple           =     AutoModelForMultipleChoice.from_pretrained(
       model_args.model_name_or_path						,		from_tf=bool(".ckpt" in model_args.model_name_or_path							)						,		config=_UpperCamelCase						,		cache_dir=model_args.cache_dir						,		)

   # Get datasets
   lowercase_	:    Any           =     (
       MultipleChoiceDataset(
           data_dir=data_args.data_dir						,		tokenizer=_UpperCamelCase						,		task=data_args.task_name						,		max_seq_length=data_args.max_seq_length						,		overwrite_cache=data_args.overwrite_cache						,		mode=Split.train						,		)
       if training_args.do_train
       else None
   )
   lowercase_	:    List[Any]           =     (
       MultipleChoiceDataset(
           data_dir=data_args.data_dir						,		tokenizer=_UpperCamelCase						,		task=data_args.task_name						,		max_seq_length=data_args.max_seq_length						,		overwrite_cache=data_args.overwrite_cache						,		mode=Split.dev						,		)
       if training_args.do_eval
       else None
   )

   def compute_metrics(_UpperCamelCase							) -> Dict:
      lowercase_	:    Dict           =     np.argmax(p.predictions						,		axis=1							)
      return {"acc": simple_accuracy(_UpperCamelCase						,		p.label_ids							)}

   # Data collator
   lowercase_	:    str           =     DataCollatorWithPadding(_UpperCamelCase						,		pad_to_multiple_of=8							) if training_args.fpaa else None

   # Initialize our Trainer
   lowercase_	:    Optional[Any]           =     Trainer(
       model=_UpperCamelCase						,		args=_UpperCamelCase						,		train_dataset=_UpperCamelCase						,		eval_dataset=_UpperCamelCase						,		compute_metrics=_UpperCamelCase						,		data_collator=_UpperCamelCase						,		)

   # Training
   if training_args.do_train:
      trainer.train(
          model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path							) else None							)
      trainer.save_model()
      # For convenience, we also re-save the tokenizer to the same directory,
      # so that you can share your model easily on huggingface.co/models =)
      if trainer.is_world_master():
         tokenizer.save_pretrained(training_args.output_dir							)

    # Evaluation
   lowercase_	:    List[Any]           =     {}
   if training_args.do_eval:
      logger.info("*** Evaluate ***"							)

      lowercase_	:    List[str]           =     trainer.evaluate()

      lowercase_	:    Union[str, Any]           =     os.path.join(training_args.output_dir						,		"eval_results.txt"							)
      if trainer.is_world_master():
         with open(_UpperCamelCase						,		"w"							) as writer:
            logger.info("***** Eval results *****"							)
            for key, value in result.items():
               logger.info("  %s = %s"						,		_UpperCamelCase						,		_UpperCamelCase							)
               writer.write("%s = %s\n" % (key, value)							)

            results.update(_UpperCamelCase							)

   return results




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase							):


   """simple docstring"""




   main()


if __name__ == "__main__":
 main()








'''simple docstring'''
from pathlib import Path
from typing import List

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image


UpperCamelCase__ =			['text', 'image', 'audio']




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase							):


   """simple docstring"""




   lowercase_	:    List[Any]           =     []

   for input_type in input_types:
      if input_type == "text":
         inputs.append("Text input"							)
      elif input_type == "image":
         inputs.append(
             Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO"							)							) / "000000039769.png"							).resize((512, 512)							)							)
      elif input_type == "audio":
         inputs.append(torch.ones(3000							)							)
      elif isinstance(_UpperCamelCase						,		_UpperCamelCase							):
         inputs.append(create_inputs(_UpperCamelCase							)							)
      else:
         raise ValueError(F"""Invalid type requested: {input_type}"""							)

   return inputs




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase							):


   """simple docstring"""




   lowercase_	:    Optional[int]           =     []

   for output in outputs:
      if isinstance(_UpperCamelCase						,		(str, AgentText)							):
         output_types.append("text"							)
      elif isinstance(_UpperCamelCase						,		(Image.Image, AgentImage)							):
         output_types.append("image"							)
      elif isinstance(_UpperCamelCase						,		(torch.Tensor, AgentAudio)							):
         output_types.append("audio"							)
      else:
         raise ValueError(F"""Invalid output: {output}"""							)

   return output_types





@is_tool_test
class        _UpperCAmelCase						:




    def 				lowerCAmelCase__				(			self  :       List[Any]			):






       '''simple docstring'''






       self.assertTrue(hasattr(self.tool  ,     "inputs"			)			)
       self.assertTrue(hasattr(self.tool  ,     "outputs"			)			)

       lowercase_	:    Optional[Any]           =     self.tool.inputs
       for _input in inputs:
          if isinstance(_input  ,     a			):
             for __input in _input:
                self.assertTrue(__input in authorized_types			)
          else:
             self.assertTrue(_input in authorized_types			)

       lowercase_	:    Any           =     self.tool.outputs
       for _output in outputs:
          self.assertTrue(_output in authorized_types			)




    def 				lowerCAmelCase__				(			self  :       Any			):






       '''simple docstring'''






       lowercase_	:    List[str]           =     create_inputs(self.tool.inputs			)
       lowercase_	:    List[str]           =     self.tool(*a			)

       # There is a single output
       if len(self.tool.outputs			) == 1:
          lowercase_	:    Union[str, Any]           =     [outputs]

       self.assertListEqual(output_types(a			)  ,     self.tool.outputs			)




    def 				lowerCAmelCase__				(			self  :       List[str]			):






       '''simple docstring'''






       self.assertTrue(hasattr(self.tool  ,     "description"			)			)
       self.assertTrue(hasattr(self.tool  ,     "default_checkpoint"			)			)
       self.assertTrue(self.tool.description.startswith("This is a tool that"			)			)




    def 				lowerCAmelCase__				(			self  :       Any			):






       '''simple docstring'''






       lowercase_	:    Any           =     create_inputs(self.tool.inputs			)
       lowercase_	:    str           =     self.tool(*a			)

       if not isinstance(a  ,     a			):
          lowercase_	:    List[Any]           =     [outputs]

       self.assertEqual(len(a			)  ,     len(self.tool.outputs			)			)

       for output, output_type in zip(a  ,     self.tool.outputs			):
          lowercase_	:    int           =     AGENT_TYPE_MAPPING[output_type]
          self.assertTrue(isinstance(a  ,     a			)			)





    def 				lowerCAmelCase__				(			self  :       Tuple			):






       '''simple docstring'''






       lowercase_	:    Dict           =     create_inputs(self.tool.inputs			)

       lowercase_	:    Optional[int]           =     []

       for _input, input_type in zip(a  ,     self.tool.inputs			):
          if isinstance(a  ,     a			):
             _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input			) for _input_type in input_type]			)
          else:
             _inputs.append(AGENT_TYPE_MAPPING[input_type](_input			)			)

        # Should not raise an error
       lowercase_	:    Any           =     self.tool(*a			)

       if not isinstance(a  ,     a			):
          lowercase_	:    Any           =     [outputs]

       self.assertEqual(len(a			)  ,     len(self.tool.outputs			)			)




