


'''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


a_   :      int				    =      logging.getLogger(__name__)






def 		_A			(lowerCAmelCase__					:int			,  lowerCAmelCase__					:Dict						)				->					Optional[int]:




     '''simple docstring'''



     return (preds == labels).mean()




@dataclass
class 	a       :
 _lowerCAmelCase	   =		field(
     metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}    )
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}    )
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}    )
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}					,			)





@dataclass
class 	a       :
 _lowerCAmelCase	   =		field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(processors.keys()    )}    )
 _lowerCAmelCase	   =		field(metadata={"""help""": """Should contain the data files for the task."""}    )
 _lowerCAmelCase	   =		field(
     default=1_2_8					,			metadata={
         """help""": (
             """The maximum total input sequence length after tokenization. Sequences longer """
             """than this will be truncated, sequences shorter will be padded."""
         )
     }					,			)
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Overwrite the cached training and evaluation sets"""}    )






def 		_A			()				->					Optional[int]:




     '''simple docstring'''



     _a      =							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
     _a ,				_a ,				_a      =							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'			,  lowerCAmelCase__						)

     # Set seed
     set_seed(training_args.seed						)

     try:
          _a      =							processors[data_args.task_name]()
          _a      =							processor.get_labels()
          _a      =							len(lowerCAmelCase__						)
     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.

     _a      =							AutoConfig.from_pretrained(
         model_args.config_name if model_args.config_name else model_args.model_name_or_path			,  num_labels=lowerCAmelCase__			,  finetuning_task=data_args.task_name			,  cache_dir=model_args.cache_dir			,  )
     _a      =							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			,  )
     _a      =							AutoModelForMultipleChoice.from_pretrained(
         model_args.model_name_or_path			,  from_tf=bool('.ckpt' in model_args.model_name_or_path						)			,  config=lowerCAmelCase__			,  cache_dir=model_args.cache_dir			,  )

     # Get datasets
     _a      =							(
         MultipleChoiceDataset(
             data_dir=data_args.data_dir			,  tokenizer=lowerCAmelCase__			,  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
     )
     _a      =							(
         MultipleChoiceDataset(
             data_dir=data_args.data_dir			,  tokenizer=lowerCAmelCase__			,  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(lowerCAmelCase__					:EvalPrediction						) -> Dict:
          _a      =							np.argmax(p.predictions			,  axis=1						)
          return {"acc": simple_accuracy(lowerCAmelCase__			,  p.label_ids						)}

     # Data collator
     _a      =							DataCollatorWithPadding(lowerCAmelCase__			,  pad_to_multiple_of=8						) if training_args.fpaa else None

     # Initialize our Trainer
     _a      =							Trainer(
         model=lowerCAmelCase__			,  args=lowerCAmelCase__			,  train_dataset=lowerCAmelCase__			,  eval_dataset=lowerCAmelCase__			,  compute_metrics=lowerCAmelCase__			,  data_collator=lowerCAmelCase__			,  )

     # 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
     _a      =							{}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'						)

          _a      =							trainer.evaluate()

          _a      =							os.path.join(training_args.output_dir			,  'eval_results.txt'						)
          if trainer.is_world_master():
               with open(lowerCAmelCase__			,  'w'						) as writer:
                    logger.info('***** Eval results *****'						)
                    for key, value in result.items():
                         logger.info('  %s = %s'			,  lowerCAmelCase__			,  lowerCAmelCase__						)
                         writer.write('%s = %s\n' % (key, value)						)

                    results.update(lowerCAmelCase__						)

     return results






def 		_A			(lowerCAmelCase__					:List[str]						)				->					List[Any]:




     '''simple docstring'''



     main()


if __name__ == "__main__":
 main()





'''simple docstring'''






import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


a_   :      Tuple				    =      get_tests_dir("fixtures")




class 	a       (       unittest.TestCase    ):
 def 							__UpperCAmelCase						(	self  )   ->							str:
      # A mock response for an HTTP head request to emulate server down
      _a      =							mock.Mock()
      _a      =							5_00
      _a      =							{}
      _a      =							HTTPError
      _a      =							{}

      # Download this model to make sure it's in the cache.
      _a      =							ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'  )
      # Under the mock environment we get a 500 error when trying to reach the model.
      with mock.patch('requests.Session.request' ,			return_value=__magic_name__  ) as mock_head:
           _a      =							ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'  )
           # This check we did call the fake head request
           mock_head.assert_called()
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      # This test is for deprecated behavior and can be removed in v5
      _a      =							ViTImageProcessor.from_pretrained(
          'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'  )




 def 							__UpperCAmelCase						(	self  )   ->							Dict:
      with self.assertRaises(__magic_name__  ):
           # config is in subfolder, the following should not work without specifying the subfolder
           _a      =							AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants'  )

      _a      =							AutoImageProcessor.from_pretrained(
          'hf-internal-testing/stable-diffusion-all-variants' ,			subfolder='feature_extractor'  )

      self.assertIsNotNone(__magic_name__  )





@is_staging_test
class 	a       (       unittest.TestCase    ):
 @classmethod
 def 							__UpperCAmelCase						(	cls  )   ->							Dict:
      _a      =							TOKEN
      HfFolder.save_token(__magic_name__  )
 @classmethod
 def 							__UpperCAmelCase						(	cls  )   ->							List[Any]:
      try:
           delete_repo(token=cls._token ,			repo_id='test-image-processor'  )
      except HTTPError:
           pass

      try:
           delete_repo(token=cls._token ,			repo_id='valid_org/test-image-processor-org'  )
      except HTTPError:
           pass

      try:
           delete_repo(token=cls._token ,			repo_id='test-dynamic-image-processor'  )
      except HTTPError:
           pass
 def 							__UpperCAmelCase						(	self  )   ->							str:
      _a      =							ViTImageProcessor.from_pretrained(__magic_name__  )
      image_processor.push_to_hub('test-image-processor' ,			use_auth_token=self._token  )

      _a      =							ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor'  )
      for k, v in image_processor.__dict__.items():
           self.assertEqual(__magic_name__ ,			getattr(__magic_name__ ,			__magic_name__  )  )

      # Reset repo
      delete_repo(token=self._token ,			repo_id='test-image-processor'  )

      # Push to hub via save_pretrained
      with tempfile.TemporaryDirectory() as tmp_dir:
           image_processor.save_pretrained(
               __magic_name__ ,			repo_id='test-image-processor' ,			push_to_hub=__magic_name__ ,			use_auth_token=self._token  )

      _a      =							ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor'  )
      for k, v in image_processor.__dict__.items():
           self.assertEqual(__magic_name__ ,			getattr(__magic_name__ ,			__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      _a      =							ViTImageProcessor.from_pretrained(__magic_name__  )
      image_processor.push_to_hub('valid_org/test-image-processor' ,			use_auth_token=self._token  )

      _a      =							ViTImageProcessor.from_pretrained('valid_org/test-image-processor'  )
      for k, v in image_processor.__dict__.items():
           self.assertEqual(__magic_name__ ,			getattr(__magic_name__ ,			__magic_name__  )  )

      # Reset repo
      delete_repo(token=self._token ,			repo_id='valid_org/test-image-processor'  )

      # Push to hub via save_pretrained
      with tempfile.TemporaryDirectory() as tmp_dir:
           image_processor.save_pretrained(
               __magic_name__ ,			repo_id='valid_org/test-image-processor-org' ,			push_to_hub=__magic_name__ ,			use_auth_token=self._token  )

      _a      =							ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org'  )
      for k, v in image_processor.__dict__.items():
           self.assertEqual(__magic_name__ ,			getattr(__magic_name__ ,			__magic_name__  )  )




 def 							__UpperCAmelCase						(	self  )   ->							Any:
      CustomImageProcessor.register_for_auto_class()
      _a      =							CustomImageProcessor.from_pretrained(__magic_name__  )

      image_processor.push_to_hub('test-dynamic-image-processor' ,			use_auth_token=self._token  )

      # This has added the proper auto_map field to the config
      self.assertDictEqual(
          image_processor.auto_map ,			{'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'} ,			)

      _a      =							AutoImageProcessor.from_pretrained(
          f'{USER}/test-dynamic-image-processor' ,			trust_remote_code=__magic_name__  )
      # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
      self.assertEqual(new_image_processor.__class__.__name__ ,			'CustomImageProcessor'  )

