






"""simple docstring"""





import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

import transformers
from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForImageClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
UpperCamelCase_	:				Any										= logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-classification/requirements.txt""")

UpperCamelCase_	:				int										= list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
UpperCamelCase_	:				List[Any]										= tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



def     __lowercase					(    a :				str )					->					Optional[Any]:
      with open(a       ,		'''rb''' ) as f:
            __snake_case      :    Optional[Any]  			=Image.open(a )
            return im.convert('''RGB''' )


@dataclass
class      _lowercase :
      _a   :     Optional[str]								=   field(
          default=lowerCAmelCase		,  metadata={
              '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'''
          }		,  )
      _a   :     Optional[str]								=   field(
          default=lowerCAmelCase		,  metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}						)
      _a   :     Optional[str]								=   field(default=lowerCAmelCase		,  metadata={'''help''': '''A folder containing the training data.'''}						)
      _a   :     Optional[str]								=   field(default=lowerCAmelCase		,  metadata={'''help''': '''A folder containing the validation data.'''}						)
      _a   :     Optional[float]								=   field(
          default=0.15		,  metadata={'''help''': '''Percent to split off of train for validation.'''}						)
      _a   :     Optional[int]								=   field(
          default=lowerCAmelCase		,  metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                  '''value if set.'''
              )
          }		,  )
      _a   :     Optional[int]								=   field(
          default=lowerCAmelCase		,  metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
                  '''value if set.'''
              )
          }		,  )


      def _UpperCamelCase						(    self				:	List[Any]						):





            """simple docstring"""







            if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
                  raise ValueError(
                      '''You must specify either a dataset name from the hub or a train and/or validation directory.'''						)



@dataclass
class      _lowercase :
      _a   :     str								=   field(
          default='''google/vit-base-patch16-224-in21k'''		,  metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}		,  )
      _a   :     Optional[str]								=   field(
          default=lowerCAmelCase		,  metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(lowerCAmelCase						)}		,  )
      _a   :     Optional[str]								=   field(
          default=lowerCAmelCase		,  metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}						)
      _a   :     Optional[str]								=   field(
          default=lowerCAmelCase		,  metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}						)
      _a   :     str								=   field(
          default='''main'''		,  metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}		,  )
      _a   :     str								=   field(default=lowerCAmelCase		,  metadata={'''help''': '''Name or path of preprocessor config.'''}						)
      _a   :     bool								=   field(
          default=lowerCAmelCase		,  metadata={
              '''help''': (
                  '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
                  '''with private models).'''
              )
          }		,  )
      _a   :     bool								=   field(
          default=lowerCAmelCase		,  metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''}		,  )



def     __lowercase					(    a :				List[str] )					->					Optional[int]:
      __snake_case      :    Any  			=torch.stack([example['''pixel_values'''] for example in examples] )
      __snake_case      :    Tuple  			=torch.tensor([example['''labels'''] for example in examples] )
      return {"pixel_values": pixel_values, "labels": labels}



def     __lowercase					(    )					->					str:
      # See all possible arguments in src/transformers/training_args.py
      # or by passing the --help flag to this script.
      # We now keep distinct sets of args, for a cleaner separation of concerns.

      __snake_case      :    Any  			=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
      if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ):
            # If we pass only one argument to the script and it's the path to a json file,
            # let's parse it to get our arguments.
            __snake_case			,				__snake_case			,				__snake_case      :    Optional[int]  			=parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
      else:
            __snake_case			,				__snake_case			,				__snake_case      :    Optional[int]  			=parser.parse_args_into_dataclasses()

      # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
      # information sent is the one passed as arguments along with your Python/PyTorch versions.
      send_example_telemetry('''run_image_classification'''       ,		a       ,		a )

      # Setup logging
      logging.basicConfig(
          format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''       ,		datefmt='''%m/%d/%Y %H:%M:%S'''       ,		handlers=[logging.StreamHandler(sys.stdout )]       ,		)

      if training_args.should_log:
            # The default of training_args.log_level is passive, so we set log level at info here to have that default.
            transformers.utils.logging.set_verbosity_info()

      __snake_case      :    Union[str, Any]  			=training_args.get_process_log_level()
      logger.setLevel(a )
      transformers.utils.logging.set_verbosity(a )
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()

      # Log on each process the small summary:
      logger.warning(
          f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
          + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' )
      logger.info(f'''Training/evaluation parameters {training_args}''' )

      # Detecting last checkpoint.
      __snake_case      :    Dict  			=None
      if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
            __snake_case      :    str  			=get_last_checkpoint(training_args.output_dir )
            if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
                  raise ValueError(
                      f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                      '''Use --overwrite_output_dir to overcome.''' )
            elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
                  logger.info(
                      f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                      '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' )

    # Set seed before initializing model.
      set_seed(training_args.seed )

      # Initialize our dataset and prepare it for the 'image-classification' task.
      if data_args.dataset_name is not None:
            __snake_case      :    Dict  			=load_dataset(
                data_args.dataset_name       ,		data_args.dataset_config_name       ,		cache_dir=model_args.cache_dir       ,		task='''image-classification'''       ,		use_auth_token=True if model_args.use_auth_token else None       ,		)
      else:
            __snake_case      :    str  			={}
            if data_args.train_dir is not None:
                  __snake_case      :    str  			=os.path.join(data_args.train_dir       ,		'''**''' )
            if data_args.validation_dir is not None:
                  __snake_case      :    Optional[Any]  			=os.path.join(data_args.validation_dir       ,		'''**''' )
            __snake_case      :    Any  			=load_dataset(
                '''imagefolder'''       ,		data_files=a       ,		cache_dir=model_args.cache_dir       ,		task='''image-classification'''       ,		)

      # If we don't have a validation split, split off a percentage of train as validation.
      __snake_case      :    Dict  			=None if '''validation''' in dataset.keys() else data_args.train_val_split
      if isinstance(data_args.train_val_split       ,		a ) and data_args.train_val_split > 0.0:
            __snake_case      :    Tuple  			=dataset['''train'''].train_test_split(data_args.train_val_split )
            __snake_case      :    Any  			=split['''train''']
            __snake_case      :    List[Any]  			=split['''test''']

      # Prepare label mappings.
      # We'll include these in the model's config to get human readable labels in the Inference API.
      __snake_case      :    List[str]  			=dataset['''train'''].features['''labels'''].names
      __snake_case			,				__snake_case      :    Optional[int]  			={}, {}
      for i, label in enumerate(a ):
            __snake_case      :    Dict  			=str(a )
            __snake_case      :    Any  			=label

      # Load the accuracy metric from the datasets package
      __snake_case      :    Tuple  			=evaluate.load('''accuracy''' )

      # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
      # predictions and label_ids field) and has to return a dictionary string to float.
      def compute_metrics(a :				Optional[int] ):
            return metric.compute(predictions=np.argmax(p.predictions       ,		axis=1 )       ,		references=p.label_ids )

      __snake_case      :    Tuple  			=AutoConfig.from_pretrained(
          model_args.config_name or model_args.model_name_or_path       ,		num_labels=len(a )       ,		labelaid=a       ,		idalabel=a       ,		finetuning_task='''image-classification'''       ,		cache_dir=model_args.cache_dir       ,		revision=model_args.model_revision       ,		use_auth_token=True if model_args.use_auth_token else None       ,		)
      __snake_case      :    Union[str, Any]  			=AutoModelForImageClassification.from_pretrained(
          model_args.model_name_or_path       ,		from_tf=bool('''.ckpt''' in model_args.model_name_or_path )       ,		config=a       ,		cache_dir=model_args.cache_dir       ,		revision=model_args.model_revision       ,		use_auth_token=True if model_args.use_auth_token else None       ,		ignore_mismatched_sizes=model_args.ignore_mismatched_sizes       ,		)
      __snake_case      :    List[str]  			=AutoImageProcessor.from_pretrained(
          model_args.image_processor_name or model_args.model_name_or_path       ,		cache_dir=model_args.cache_dir       ,		revision=model_args.model_revision       ,		use_auth_token=True if model_args.use_auth_token else None       ,		)

      # Define torchvision transforms to be applied to each image.
      if "shortest_edge" in image_processor.size:
            __snake_case      :    Any  			=image_processor.size['''shortest_edge''']
      else:
            __snake_case      :    Tuple  			=(image_processor.size['''height'''], image_processor.size['''width'''])
      __snake_case      :    str  			=Normalize(mean=image_processor.image_mean       ,		std=image_processor.image_std )
      __snake_case      :    Optional[Any]  			=Compose(
          [
              RandomResizedCrop(a ),
              RandomHorizontalFlip(),
              ToTensor(),
              normalize,
          ] )
      __snake_case      :    List[str]  			=Compose(
          [
              Resize(a ),
              CenterCrop(a ),
              ToTensor(),
              normalize,
          ] )

      def train_transforms(a :				Tuple ):
            __snake_case      :    List[str]  			=[
                _train_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image''']
            ]
            return example_batch

      def val_transforms(a :				Tuple ):
            __snake_case      :    int  			=[_val_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image''']]
            return example_batch

      if training_args.do_train:
            if "train" not in dataset:
                  raise ValueError('''--do_train requires a train dataset''' )
            if data_args.max_train_samples is not None:
                  __snake_case      :    Union[str, Any]  			=(
                      dataset['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) )
                  )
            # Set the training transforms
            dataset["train"].set_transform(a )

      if training_args.do_eval:
            if "validation" not in dataset:
                  raise ValueError('''--do_eval requires a validation dataset''' )
            if data_args.max_eval_samples is not None:
                  __snake_case      :    Optional[Any]  			=(
                      dataset['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) )
                  )
            # Set the validation transforms
            dataset["validation"].set_transform(a )

      # Initalize our trainer
      __snake_case      :    Union[str, Any]  			=Trainer(
          model=a       ,		args=a       ,		train_dataset=dataset['''train'''] if training_args.do_train else None       ,		eval_dataset=dataset['''validation'''] if training_args.do_eval else None       ,		compute_metrics=a       ,		tokenizer=a       ,		data_collator=a       ,		)

      # Training
      if training_args.do_train:
            __snake_case      :    Optional[int]  			=None
            if training_args.resume_from_checkpoint is not None:
                  __snake_case      :    Union[str, Any]  			=training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  __snake_case      :    Union[str, Any]  			=last_checkpoint
            __snake_case      :    Optional[Any]  			=trainer.train(resume_from_checkpoint=a )
            trainer.save_model()
            trainer.log_metrics('''train'''       ,		train_result.metrics )
            trainer.save_metrics('''train'''       ,		train_result.metrics )
            trainer.save_state()

      # Evaluation
      if training_args.do_eval:
            __snake_case      :    Any  			=trainer.evaluate()
            trainer.log_metrics('''eval'''       ,		a )
            trainer.save_metrics('''eval'''       ,		a )

      # Write model card and (optionally) push to hub
      __snake_case      :    Optional[int]  			={
          '''finetuned_from''': model_args.model_name_or_path,
          '''tasks''': '''image-classification''',
          '''dataset''': data_args.dataset_name,
          '''tags''': ['''image-classification''', '''vision'''],
      }
      if training_args.push_to_hub:
            trainer.push_to_hub(**a )
      else:
            trainer.create_model_card(**a )


if __name__ == "__main__":
    main()










"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import is_flaky, 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 DonutImageProcessor


class      _lowercase (     unittest.TestCase						):


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





            """simple docstring"""







            __snake_case      :    List[Any]  			=parent
            __snake_case      :    List[Any]  			=batch_size
            __snake_case      :    str  			=num_channels
            __snake_case      :    Dict  			=image_size
            __snake_case      :    str  			=min_resolution
            __snake_case      :    Tuple  			=max_resolution
            __snake_case      :    str  			=do_resize
            __snake_case      :    Any  			=size if size is not None else {'''height''': 1_8, '''width''': 2_0}
            __snake_case      :    List[Any]  			=do_thumbnail
            __snake_case      :    Tuple  			=do_align_axis
            __snake_case      :    Any  			=do_pad
            __snake_case      :    Dict  			=do_normalize
            __snake_case      :    List[Any]  			=image_mean
            __snake_case      :    Any  			=image_std







      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            return {
                "do_resize": self.do_resize,
                "size": self.size,
                "do_thumbnail": self.do_thumbnail,
                "do_align_long_axis": self.do_align_axis,
                "do_pad": self.do_pad,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
            }



@require_torch
@require_vision
class      _lowercase (     lowerCAmelCase		,  unittest.TestCase						):
      _a   :     str								=   DonutImageProcessor if is_vision_available() else None


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=DonutImageProcessingTester(self						)


      @property
      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            return self.image_processor_tester.prepare_image_processor_dict()


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            self.assertTrue(hasattr(a							,   '''do_resize'''						)						)
            self.assertTrue(hasattr(a							,   '''size'''						)						)
            self.assertTrue(hasattr(a							,   '''do_thumbnail'''						)						)
            self.assertTrue(hasattr(a							,   '''do_align_long_axis'''						)						)
            self.assertTrue(hasattr(a							,   '''do_pad'''						)						)
            self.assertTrue(hasattr(a							,   '''do_normalize'''						)						)
            self.assertTrue(hasattr(a							,   '''image_mean'''						)						)
            self.assertTrue(hasattr(a							,   '''image_std'''						)						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







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

            __snake_case      :    List[Any]  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=4_2						)
            self.assertEqual(image_processor.size							,   {'''height''': 4_2, '''width''': 4_2}						)

            # Previous config had dimensions in (width, height) order
            __snake_case      :    Tuple  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=(4_2, 8_4)						)
            self.assertEqual(image_processor.size							,   {'''height''': 8_4, '''width''': 4_2}						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            pass


      @is_flaky()
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PIL images
            __snake_case      :    List[Any]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   Image.Image						)

            # Test not batched input
            __snake_case      :    str  			=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.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   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.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


      @is_flaky()
      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Tuple  			=self.image_processing_class(**self.image_processor_dict						)
            # create random numpy tensors
            __snake_case      :    Optional[int]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   numpify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   np.ndarray						)

            # Test not batched input
            __snake_case      :    List[Any]  			=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.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    int  			=image_processing(a							,   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.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )







      @is_flaky()
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







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

            # Test not batched input
            __snake_case      :    Dict  			=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.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   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.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


