



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_									=							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_									=							list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
UpperCAmelCase_									=							tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	str				)->str:






      with open(_lowercase     ,				'''rb'''				) as f:
            _lowerCAmelCase 			=  Image.open(_lowercase				)
            return im.convert('''RGB'''				)





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





   def 	__lowerCAmelCase							(	self			):
         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 		UpperCAmelCase						:
   SCREAMING_SNAKE_CASE__							=     field(
       default='''google/vit-base-patch16-224-in21k'''       ,metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}       ,)
   SCREAMING_SNAKE_CASE__							=     field(
       default=a__       ,metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(a__				)}       ,)
   SCREAMING_SNAKE_CASE__							=     field(
       default=a__       ,metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}				)
   SCREAMING_SNAKE_CASE__							=     field(
       default=a__       ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}				)
   SCREAMING_SNAKE_CASE__							=     field(
       default='''main'''       ,metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}       ,)
   SCREAMING_SNAKE_CASE__							=     field(default=a__       ,metadata={'''help''': '''Name or path of preprocessor config.'''}				)
   SCREAMING_SNAKE_CASE__							=     field(
       default=a__       ,metadata={
           '''help''': (
               '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
               '''with private models).'''
           )
       }       ,)
   SCREAMING_SNAKE_CASE__							=     field(
       default=a__       ,metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''}       ,)






def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Tuple				)->Dict:
      _lowerCAmelCase 			=  torch.stack([example['''pixel_values'''] for example in examples]				)
      _lowerCAmelCase 			=  torch.tensor([example['''labels'''] for example in examples]				)
      return {"pixel_values": pixel_values, "labels": labels}
def 							UpperCAmelCase__		(				)->Any:
      _lowerCAmelCase 			=  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.
            _lowerCAmelCase 			=  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
      else:
            _lowerCAmelCase 			=  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'''     ,				_lowercase     ,				_lowercase				)

      # 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()

      _lowerCAmelCase 			=  training_args.get_process_log_level()
      logger.setLevel(_lowercase				)
      transformers.utils.logging.set_verbosity(_lowercase				)
      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.
      _lowerCAmelCase 			=  None
      if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
            _lowerCAmelCase 			=  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:
            _lowerCAmelCase 			=  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:
            _lowerCAmelCase 			=  {}
            if data_args.train_dir is not None:
                  _lowerCAmelCase 			=  os.path.join(data_args.train_dir     ,				'''**'''				)
            if data_args.validation_dir is not None:
                  _lowerCAmelCase 			=  os.path.join(data_args.validation_dir     ,				'''**'''				)
            _lowerCAmelCase 			=  load_dataset(
                '''imagefolder'''     ,				data_files=_lowercase     ,				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.
      _lowerCAmelCase 			=  None if "validation" in dataset.keys() else data_args.train_val_split
      if isinstance(data_args.train_val_split     ,				_lowercase				) and data_args.train_val_split > 0.0:
            _lowerCAmelCase 			=  dataset["train"].train_test_split(data_args.train_val_split				)
            _lowerCAmelCase 			=  split["train"]
            _lowerCAmelCase 			=  split["test"]

      # Prepare label mappings.
      # We'll include these in the model's config to get human readable labels in the Inference API.
      _lowerCAmelCase 			=  dataset["train"].features["labels"].names
      _lowerCAmelCase 			=  {}, {}
      for i, label in enumerate(_lowercase				):
            _lowerCAmelCase 			=  str(_lowercase				)
            _lowerCAmelCase 			=  label

      # Load the accuracy metric from the datasets package
      _lowerCAmelCase 			=  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(_SCREAMING_SNAKE_CASE   :	Optional[int]				):
            return metric.compute(predictions=np.argmax(p.predictions     ,				axis=1				)     ,				references=p.label_ids				)

      _lowerCAmelCase 			=  AutoConfig.from_pretrained(
          model_args.config_name or model_args.model_name_or_path     ,				num_labels=len(_lowercase				)     ,				labelaid=_lowercase     ,				idalabel=_lowercase     ,				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     ,				)
      _lowerCAmelCase 			=  AutoModelForImageClassification.from_pretrained(
          model_args.model_name_or_path     ,				from_tf=bool('''.ckpt''' in model_args.model_name_or_path				)     ,				config=_lowercase     ,				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     ,				)
      _lowerCAmelCase 			=  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:
            _lowerCAmelCase 			=  image_processor.size["shortest_edge"]
      else:
            _lowerCAmelCase 			=  (image_processor.size["height"], image_processor.size["width"])
      _lowerCAmelCase 			=  Normalize(mean=image_processor.image_mean     ,				std=image_processor.image_std				)
      _lowerCAmelCase 			=  Compose(
          [
              RandomResizedCrop(_lowercase				),
              RandomHorizontalFlip(),
              ToTensor(),
              normalize,
          ]				)
      _lowerCAmelCase 			=  Compose(
          [
              Resize(_lowercase				),
              CenterCrop(_lowercase				),
              ToTensor(),
              normalize,
          ]				)

      def train_transforms(_SCREAMING_SNAKE_CASE   :	List[str]				):
            _lowerCAmelCase 			=  [
                _train_transforms(pil_img.convert('''RGB'''				)				) for pil_img in example_batch["image"]
            ]
            return example_batch

      def val_transforms(_SCREAMING_SNAKE_CASE   :	List[Any]				):
            _lowerCAmelCase 			=  [_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:
                  _lowerCAmelCase 			=  (
                      dataset["train"].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
                  )
            # Set the training transforms
            dataset["train"].set_transform(_lowercase				)

      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:
                  _lowerCAmelCase 			=  (
                      dataset["validation"].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
                  )
            # Set the validation transforms
            dataset["validation"].set_transform(_lowercase				)

      # Initalize our trainer
      _lowerCAmelCase 			=  Trainer(
          model=_lowercase     ,				args=_lowercase     ,				train_dataset=dataset['''train'''] if training_args.do_train else None     ,				eval_dataset=dataset['''validation'''] if training_args.do_eval else None     ,				compute_metrics=_lowercase     ,				tokenizer=_lowercase     ,				data_collator=_lowercase     ,				)

      # Training
      if training_args.do_train:
            _lowerCAmelCase 			=  None
            if training_args.resume_from_checkpoint is not None:
                  _lowerCAmelCase 			=  training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  _lowerCAmelCase 			=  last_checkpoint
            _lowerCAmelCase 			=  trainer.train(resume_from_checkpoint=_lowercase				)
            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:
            _lowerCAmelCase 			=  trainer.evaluate()
            trainer.log_metrics('''eval'''     ,				_lowercase				)
            trainer.save_metrics('''eval'''     ,				_lowercase				)

      # Write model card and (optionally) push to hub
      _lowerCAmelCase 			=  {
          "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(**_lowercase				)
      else:
            trainer.create_model_card(**_lowercase				)


if __name__ == "__main__":
    main()




import numpy as np
import torch
from torch.utils.data import Dataset, IterableDataset

from ..utils.generic import ModelOutput





class 		UpperCAmelCase						(						snake_case_				):





   def __init__(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  dataset
         _lowerCAmelCase 			=  process
         _lowerCAmelCase 			=  params





   def __len__(	self			):
         return len(self.dataset			)





   def __getitem__(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  self.dataset[i]
         _lowerCAmelCase 			=  self.process(_lowerCAmelCase       ,     **self.params			)
         return processed






class 		UpperCAmelCase						(						snake_case_				):





   def __init__(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase=None			):
         _lowerCAmelCase 			=  loader
         _lowerCAmelCase 			=  infer
         _lowerCAmelCase 			=  params
         if loader_batch_size == 1:
               # Let's spare some time by deactivating altogether
               _lowerCAmelCase 			=  None
         _lowerCAmelCase 			=  loader_batch_size

         # Internal bookkeeping
         _lowerCAmelCase 			=  None
         _lowerCAmelCase 			=  None





   def __len__(	self			):
         return len(self.loader			)





   def __iter__(	self			):
         _lowerCAmelCase 			=  iter(self.loader			)
         return self





   def 	__lowerCAmelCase							(	self			):
         if isinstance(self._loader_batch_data       ,     torch.Tensor			):
               # Batch data is simple tensor, just fetch the slice
               _lowerCAmelCase 			=  self._loader_batch_data[self._loader_batch_index]
         else:
               # Batch data is assumed to be BaseModelOutput (or dict)
               _lowerCAmelCase 			=  {}
               for k, element in self._loader_batch_data.items():
                     if isinstance(_lowerCAmelCase       ,     _lowerCAmelCase			):
                           # Convert ModelOutput to tuple first
                           _lowerCAmelCase 			=  element.to_tuple()
                           if isinstance(element[0]       ,     torch.Tensor			):
                                 _lowerCAmelCase 			=  tuple(el[self._loader_batch_index].unsqueeze(0			) for el in element			)
                           elif isinstance(element[0]       ,     np.ndarray			):
                                 _lowerCAmelCase 			=  tuple(np.expand_dims(el[self._loader_batch_index]       ,     0			) for el in element			)
                           continue
                     if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_lowerCAmelCase       ,     _lowerCAmelCase			):
                           # Those are stored as lists of tensors so need specific unbatching.
                           if isinstance(element[0]       ,     torch.Tensor			):
                                 _lowerCAmelCase 			=  tuple(el[self._loader_batch_index].unsqueeze(0			) for el in element			)
                           elif isinstance(element[0]       ,     np.ndarray			):
                                 _lowerCAmelCase 			=  tuple(np.expand_dims(el[self._loader_batch_index]       ,     0			) for el in element			)
                           continue
                     if element is None:
                           # This can happen for optional data that get passed around
                           _lowerCAmelCase 			=  None
                     elif isinstance(element[self._loader_batch_index]       ,     torch.Tensor			):
                           # Take correct batch data, but make it looked like batch_size=1
                           # For compatibility with other methods within transformers

                           _lowerCAmelCase 			=  element[self._loader_batch_index].unsqueeze(0			)
                     elif isinstance(element[self._loader_batch_index]       ,     np.ndarray			):
                           # Take correct batch data, but make it looked like batch_size=1
                           # For compatibility with other methods within transformers
                           _lowerCAmelCase 			=  np.expand_dims(element[self._loader_batch_index]       ,     0			)
                     else:
                           # This is typically a list, so no need to `unsqueeze`.
                           _lowerCAmelCase 			=  element[self._loader_batch_index]
            # Recreate the element by reusing the original class to make it look
            # batch_size=1
               _lowerCAmelCase 			=  self._loader_batch_data.__class__(_lowerCAmelCase			)
         self._loader_batch_index += 1
         return result





   def 	__lowerCAmelCase							(	self			):
         if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
               # We are currently unrolling a batch so we just need to return
               # the current item within a batch
               return self.loader_batch_item()

         # We're out of items within a batch
         _lowerCAmelCase 			=  next(self.iterator			)
         _lowerCAmelCase 			=  self.infer(_lowerCAmelCase       ,     **self.params			)
         # We now have a batch of "inferred things".
         if self.loader_batch_size is not None:
               # Try to infer the size of the batch
               if isinstance(_lowerCAmelCase       ,     torch.Tensor			):
                     _lowerCAmelCase 			=  processed
               else:
                     _lowerCAmelCase 			=  list(processed.keys()			)[0]
                     _lowerCAmelCase 			=  processed[key]
               if isinstance(_lowerCAmelCase       ,     _lowerCAmelCase			):
                     _lowerCAmelCase 			=  len(_lowerCAmelCase			)
               else:
                     _lowerCAmelCase 			=  first_tensor.shape[0]
               if 0 < observed_batch_size < self.loader_batch_size:
                     # could be last batch so we can't unroll as many
                     # elements.
                     _lowerCAmelCase 			=  observed_batch_size
               # Setting internal index to unwrap the batch
               _lowerCAmelCase 			=  processed
               _lowerCAmelCase 			=  0
               return self.loader_batch_item()
         else:
               # We're not unrolling batches
               return processed






class 		UpperCAmelCase						(						snake_case_				):





   def __init__(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase=None			):
         super().__init__(_lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			)





   def __iter__(	self			):
         _lowerCAmelCase 			=  iter(self.loader			)
         _lowerCAmelCase 			=  None
         return self





   def 	__lowerCAmelCase							(	self			):
         if self.subiterator is None:
               _lowerCAmelCase 			=  self.infer(next(self.iterator			)       ,     **self.params			)
         try:
               # Try to return next item
               _lowerCAmelCase 			=  next(self.subiterator			)
         except StopIteration:
               # When a preprocess iterator ends, we can start lookig at the next item
               # ChunkIterator will keep feeding until ALL elements of iterator
               # all have created their subiterator and have been iterating against.
               #
               # Another way to look at it, is we're basically flattening lists of lists
               # into a single list, but with generators
               _lowerCAmelCase 			=  self.infer(next(self.iterator			)       ,     **self.params			)
               _lowerCAmelCase 			=  next(self.subiterator			)
         return processed






class 		UpperCAmelCase						(						snake_case_				):





   def __iter__(	self			):
         _lowerCAmelCase 			=  iter(self.loader			)
         return self





   def 	__lowerCAmelCase							(	self			):
         # Extremely similar to PipelineIterator in its unpacking mechanism
         # BUT, we have an extra required item which is the presence of `is_last`
         # That is because everything is flattened by `PipelineChunkIterator` we
         # need to keep track of how to regroup here in the original `process`
         # boundaries so that `process` and `postprocess` see the same data.

         # This iterator accumulates items (possibly while unbatching) until it
         # its a `is_last` and then just passes it on to the caller.
         _lowerCAmelCase 			=  False
         _lowerCAmelCase 			=  []
         if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
               while self._loader_batch_index < self.loader_batch_size:
                     _lowerCAmelCase 			=  self.loader_batch_item()
                     _lowerCAmelCase 			=  item.pop('''is_last'''			)
                     accumulator.append(_lowerCAmelCase			)
                     if is_last:
                           return accumulator

         while not is_last:
               _lowerCAmelCase 			=  self.infer(next(self.iterator			)       ,     **self.params			)
               if self.loader_batch_size is not None:
                     if isinstance(_lowerCAmelCase       ,     torch.Tensor			):
                           _lowerCAmelCase 			=  processed
                     else:
                           _lowerCAmelCase 			=  list(processed.keys()			)[0]
                           _lowerCAmelCase 			=  processed[key]
                     if isinstance(_lowerCAmelCase       ,     _lowerCAmelCase			):
                           _lowerCAmelCase 			=  len(_lowerCAmelCase			)
                     else:
                           _lowerCAmelCase 			=  first_tensor.shape[0]
                     if 0 < observed_batch_size < self.loader_batch_size:
                           # could be last batch so we can't unroll as many
                           # elements.
                           _lowerCAmelCase 			=  observed_batch_size
                     _lowerCAmelCase 			=  processed
                     _lowerCAmelCase 			=  0
                     while self._loader_batch_index < self.loader_batch_size:
                           _lowerCAmelCase 			=  self.loader_batch_item()
                           _lowerCAmelCase 			=  item.pop('''is_last'''			)
                           accumulator.append(_lowerCAmelCase			)
                           if is_last:
                                 return accumulator
               else:
                     _lowerCAmelCase 			=  processed
                     _lowerCAmelCase 			=  item.pop('''is_last'''			)
                     accumulator.append(_lowerCAmelCase			)
         return accumulator






class 		UpperCAmelCase						(						snake_case_				):





   def __init__(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  dataset
         _lowerCAmelCase 			=  key





   def __len__(	self			):
         return len(self.dataset			)





   def __getitem__(	self       ,     _lowerCAmelCase			):
         return self.dataset[i][self.key]






class 		UpperCAmelCase						(						snake_case_				):





   def __init__(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  dataset
         _lowerCAmelCase 			=  keya
         _lowerCAmelCase 			=  keya





   def __len__(	self			):
         return len(self.dataset			)





   def __getitem__(	self       ,     _lowerCAmelCase			):
         return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}