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

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()
def 					lowerCamelCase__		(				_lowerCamelCase			,		_lowerCamelCase			,		_lowerCamelCase			,		_lowerCamelCase			,		_lowerCamelCase			,		_lowerCamelCase = None			,		)						->List[str]:
 _UpperCAmelCase 				={}

 if train_file is not None:
  _UpperCAmelCase 				=[train_file]
 if eval_file is not None:
  _UpperCAmelCase 				=[eval_file]
 if test_file is not None:
  _UpperCAmelCase 				=[test_file]

 _UpperCAmelCase 				=datasets.load_dataset("csv"			,		data_files=UpperCamelCase__  )
 _UpperCAmelCase 				=list(ds[list(files.keys()  )[0]].features.keys()  )
 _UpperCAmelCase 				=features_name.pop(UpperCamelCase__  )
 _UpperCAmelCase 				=list(set(ds[list(files.keys()  )[0]][label_name]  )  )
 _UpperCAmelCase 				={label: i for i, label in enumerate(UpperCamelCase__  )}
 _UpperCAmelCase 				=tokenizer.model_input_names
 _UpperCAmelCase 				={}

 if len(UpperCamelCase__  ) == 1:
  for k in files.keys():
   _UpperCAmelCase 				=ds[k].map(
       lambda _lowerCamelCase  : tokenizer.batch_encode_plus(
           example[features_name[0]]			,		truncation=UpperCamelCase__			,		max_length=UpperCamelCase__			,		padding="max_length"  )			,		batched=UpperCamelCase__			,		)
 elif len(UpperCamelCase__  ) == 2:
  for k in files.keys():
   _UpperCAmelCase 				=ds[k].map(
       lambda _lowerCamelCase  : tokenizer.batch_encode_plus(
           (example[features_name[0]], example[features_name[1]])			,		truncation=UpperCamelCase__			,		max_length=UpperCamelCase__			,		padding="max_length"			,		)			,		batched=UpperCamelCase__			,		)

 def gen_train():
  for ex in transformed_ds[datasets.Split.TRAIN]:
   _UpperCAmelCase 				={k: v for k, v in ex.items() if k in input_names}
   _UpperCAmelCase 				=labelaid[ex[label_name]]
   yield (d, label)

 def gen_val():
  for ex in transformed_ds[datasets.Split.VALIDATION]:
   _UpperCAmelCase 				={k: v for k, v in ex.items() if k in input_names}
   _UpperCAmelCase 				=labelaid[ex[label_name]]
   yield (d, label)

 def gen_test():
  for ex in transformed_ds[datasets.Split.TEST]:
   _UpperCAmelCase 				={k: v for k, v in ex.items() if k in input_names}
   _UpperCAmelCase 				=labelaid[ex[label_name]]
   yield (d, label)

 _UpperCAmelCase 				=(
     tf.data.Dataset.from_generator(
         UpperCamelCase__			,		({k: tf.intaa for k in input_names}, tf.intaa)			,		({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))			,		)
     if datasets.Split.TRAIN in transformed_ds
     else None
 )

 if train_ds is not None:
  _UpperCAmelCase 				=train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]  )  )  )

 _UpperCAmelCase 				=(
     tf.data.Dataset.from_generator(
         UpperCamelCase__			,		({k: tf.intaa for k in input_names}, tf.intaa)			,		({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))			,		)
     if datasets.Split.VALIDATION in transformed_ds
     else None
 )

 if val_ds is not None:
  _UpperCAmelCase 				=val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]  )  )  )

 _UpperCAmelCase 				=(
     tf.data.Dataset.from_generator(
         UpperCamelCase__			,		({k: tf.intaa for k in input_names}, tf.intaa)			,		({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))			,		)
     if datasets.Split.TEST in transformed_ds
     else None
 )

 if test_ds is not None:
  _UpperCAmelCase 				=test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]  )  )  )

 return train_ds, val_ds, test_ds, labelaid


snake_case__      :		List[str]				=       logging.getLogger(__name__)





@dataclass
class 						_a   :

       """simple docstring"""





       snake_case				=field(metadata={"""help""": """Which column contains the label"""}       )
       snake_case				=field(default=UpperCamelCase__ ,      metadata={"""help""": """The path of the training file"""}       )
       snake_case				=field(default=UpperCamelCase__ ,      metadata={"""help""": """The path of the development file"""}       )
       snake_case				=field(default=UpperCamelCase__ ,      metadata={"""help""": """The path of the test file"""}       )
       snake_case				=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."""
               )
           } ,      )
       snake_case				=field(
           default=UpperCamelCase__ ,      metadata={"""help""": """Overwrite the cached training and evaluation sets"""}       )







@dataclass
class 						_a   :

       """simple docstring"""





       snake_case				=field(
           metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}       )
       snake_case				=field(
           default=UpperCamelCase__ ,      metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}       )
       snake_case				=field(
           default=UpperCamelCase__ ,      metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}       )
       snake_case				=field(default=UpperCamelCase__ ,      metadata={"""help""": """Set this flag to use fast tokenization."""}       )
       # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
       # or just modify its tokenizer_config.json.
       snake_case				=field(
           default=UpperCamelCase__ ,      metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} ,      )







def 					lowerCamelCase__		(				)						->Optional[int]:
 # 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.
 _UpperCAmelCase 				=HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)  )
 _UpperCAmelCase				,      _UpperCAmelCase				,      _UpperCAmelCase 				=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			,		)
 logger.info(
     F"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1  )}, "
     F"16-bits training: {training_args.fpaa}"  )
 logger.info(F"Training/evaluation parameters {training_args}"  )

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

 _UpperCAmelCase 				=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			,		)

 _UpperCAmelCase				,      _UpperCAmelCase				,      _UpperCAmelCase				,      _UpperCAmelCase 				=get_tfds(
     train_file=data_args.train_file			,		eval_file=data_args.dev_file			,		test_file=data_args.test_file			,		tokenizer=UpperCamelCase__			,		label_column_id=data_args.label_column_id			,		max_seq_length=data_args.max_seq_length			,		)

 _UpperCAmelCase 				=AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path			,		num_labels=len(UpperCamelCase__  )			,		labelaid=UpperCamelCase__			,		idalabel={id: label for label, id in labelaid.items()}			,		finetuning_task="text-classification"			,		cache_dir=model_args.cache_dir			,		)

 with training_args.strategy.scope():
  _UpperCAmelCase 				=TFAutoModelForSequenceClassification.from_pretrained(
      model_args.model_name_or_path			,		from_pt=bool(".bin" in model_args.model_name_or_path  )			,		config=UpperCamelCase__			,		cache_dir=model_args.cache_dir			,		)

 def compute_metrics(_lowerCamelCase  ) -> Dict:
  _UpperCAmelCase 				=np.argmax(p.predictions			,		axis=1  )

  return {"acc": (preds == p.label_ids).mean()}

 # Initialize our Trainer
 _UpperCAmelCase 				=TFTrainer(
     model=UpperCamelCase__			,		args=UpperCamelCase__			,		train_dataset=UpperCamelCase__			,		eval_dataset=UpperCamelCase__			,		compute_metrics=UpperCamelCase__			,		)

 # Training
 if training_args.do_train:
  trainer.train()
  trainer.save_model()
  tokenizer.save_pretrained(training_args.output_dir  )

 # Evaluation
 _UpperCAmelCase 				={}
 if training_args.do_eval:
  logger.info("*** Evaluate ***"  )
  _UpperCAmelCase 				=trainer.evaluate()
  _UpperCAmelCase 				=os.path.join(training_args.output_dir			,		"eval_results.txt"  )

  with open(UpperCamelCase__			,		"w"  ) as writer:
   logger.info("***** Eval results *****"  )

   for key, value in result.items():
    logger.info(F"  {key} = {value}"  )
    writer.write(F"{key} = {value}\n"  )

   results.update(UpperCamelCase__  )

 return results


if __name__ == "__main__":
       main()












import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
       import torch

if is_tf_available():
       import tensorflow as tf




@require_vision
@require_torchvision
class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def 							UpperCamelCase     (				self					):
        A__		   =		tempfile.mkdtemp()
        A__		   =		SamImageProcessor()
        A__		   =		SamProcessor(__lowerCamelCase					)
        processor.save_pretrained(self.tmpdirname					)



 def 							UpperCamelCase     (				self,**__lowerCamelCase					):
        return AutoProcessor.from_pretrained(self.tmpdirname,**__lowerCamelCase					).image_processor



 def 							UpperCamelCase     (				self					):
        shutil.rmtree(self.tmpdirname					)



 def 							UpperCamelCase     (				self					):
        A__		   =		[np.random.randint(255,size=(3, 30, 400),dtype=np.uinta					)]

        A__		   =		[Image.fromarray(np.moveaxis(__lowerCamelCase,0,-1					)					) for x in image_inputs]

        return image_inputs



 def 							UpperCamelCase     (				self					):
        A__		   =		SamProcessor(image_processor=self.get_image_processor()					)
        processor.save_pretrained(self.tmpdirname					)

        A__		   =		self.get_image_processor(do_normalize=__lowerCamelCase,padding_value=1.0					)

        A__		   =		SamProcessor.from_pretrained(self.tmpdirname,do_normalize=__lowerCamelCase,padding_value=1.0					)

        self.assertEqual(processor.image_processor.to_json_string(),image_processor_add_kwargs.to_json_string()					)
        self.assertIsInstance(processor.image_processor,__lowerCamelCase					)



 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)

        A__		   =		self.prepare_image_inputs()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''np'''					)
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''np'''					)

        input_feat_extract.pop('''original_sizes'''					)  # pop original_sizes as it is popped in the processor
        input_feat_extract.pop('''reshaped_input_sizes'''					)  # pop original_sizes as it is popped in the processor

        for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum(),input_processor[key].sum(),delta=1E-2					)




 @require_torch
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)
        A__		   =		[torch.ones((1, 3, 5, 5)					)]

        A__		   =		[[1764, 2646]]

        A__		   =		[[683, 1024]]
        A__		   =		processor.post_process_masks(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase					)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		processor.post_process_masks(
            __lowerCamelCase,torch.tensor(__lowerCamelCase					),torch.tensor(__lowerCamelCase					)					)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        # should also work with np
        A__		   =		[np.ones((1, 3, 5, 5)					)]
        A__		   =		processor.post_process_masks(__lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					)					)

        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		[[1, 0], [0, 1]]
        with self.assertRaises(__lowerCamelCase					):
               A__		   =		processor.post_process_masks(__lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					)					)




@require_vision
@require_tf
class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def 							UpperCamelCase     (				self					):
        A__		   =		tempfile.mkdtemp()
        A__		   =		SamImageProcessor()
        A__		   =		SamProcessor(__lowerCamelCase					)
        processor.save_pretrained(self.tmpdirname					)



 def 							UpperCamelCase     (				self,**__lowerCamelCase					):
        return AutoProcessor.from_pretrained(self.tmpdirname,**__lowerCamelCase					).image_processor



 def 							UpperCamelCase     (				self					):
        shutil.rmtree(self.tmpdirname					)



 def 							UpperCamelCase     (				self					):
        A__		   =		[np.random.randint(255,size=(3, 30, 400),dtype=np.uinta					)]

        A__		   =		[Image.fromarray(np.moveaxis(__lowerCamelCase,0,-1					)					) for x in image_inputs]

        return image_inputs



 def 							UpperCamelCase     (				self					):
        A__		   =		SamProcessor(image_processor=self.get_image_processor()					)
        processor.save_pretrained(self.tmpdirname					)

        A__		   =		self.get_image_processor(do_normalize=__lowerCamelCase,padding_value=1.0					)

        A__		   =		SamProcessor.from_pretrained(self.tmpdirname,do_normalize=__lowerCamelCase,padding_value=1.0					)

        self.assertEqual(processor.image_processor.to_json_string(),image_processor_add_kwargs.to_json_string()					)
        self.assertIsInstance(processor.image_processor,__lowerCamelCase					)



 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)

        A__		   =		self.prepare_image_inputs()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''np'''					)
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''np'''					)

        input_feat_extract.pop('''original_sizes'''					)  # pop original_sizes as it is popped in the processor
        input_feat_extract.pop('''reshaped_input_sizes'''					)  # pop reshaped_input_sizes as it is popped in the processor

        for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum(),input_processor[key].sum(),delta=1E-2					)




 @require_tf
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)
        A__		   =		[tf.ones((1, 3, 5, 5)					)]

        A__		   =		[[1764, 2646]]

        A__		   =		[[683, 1024]]
        A__		   =		processor.post_process_masks(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,return_tensors='''tf'''					)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		processor.post_process_masks(
            __lowerCamelCase,tf.convert_to_tensor(__lowerCamelCase					),tf.convert_to_tensor(__lowerCamelCase					),return_tensors='''tf''',)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        # should also work with np
        A__		   =		[np.ones((1, 3, 5, 5)					)]
        A__		   =		processor.post_process_masks(
            __lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					),return_tensors='''tf'''					)

        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		[[1, 0], [0, 1]]
        with self.assertRaises(tf.errors.InvalidArgumentError					):
               A__		   =		processor.post_process_masks(
                   __lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					),return_tensors='''tf'''					)




@require_vision
@require_torchvision
class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def 							UpperCamelCase     (				self					):
        A__		   =		tempfile.mkdtemp()
        A__		   =		SamImageProcessor()
        A__		   =		SamProcessor(__lowerCamelCase					)
        processor.save_pretrained(self.tmpdirname					)



 def 							UpperCamelCase     (				self,**__lowerCamelCase					):
        return AutoProcessor.from_pretrained(self.tmpdirname,**__lowerCamelCase					).image_processor



 def 							UpperCamelCase     (				self					):
        shutil.rmtree(self.tmpdirname					)



 def 							UpperCamelCase     (				self					):
        A__		   =		[np.random.randint(255,size=(3, 30, 400),dtype=np.uinta					)]

        A__		   =		[Image.fromarray(np.moveaxis(__lowerCamelCase,0,-1					)					) for x in image_inputs]

        return image_inputs



 @is_pt_tf_cross_test
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)
        A__		   =		np.random.randint(0,2,size=(1, 3, 5, 5)					).astype(np.floataa					)
        A__		   =		[tf.convert_to_tensor(__lowerCamelCase					)]
        A__		   =		[torch.tensor(__lowerCamelCase					)]

        A__		   =		[[1764, 2646]]

        A__		   =		[[683, 1024]]
        A__		   =		processor.post_process_masks(
            __lowerCamelCase,__lowerCamelCase,__lowerCamelCase,return_tensors='''tf'''					)
        A__		   =		processor.post_process_masks(
            __lowerCamelCase,__lowerCamelCase,__lowerCamelCase,return_tensors='''pt'''					)

        self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()					)					)




 @is_pt_tf_cross_test
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)

        A__		   =		self.prepare_image_inputs()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''pt'''					)['''pixel_values'''].numpy()
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''pt'''					)['''pixel_values'''].numpy()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''tf'''					)['''pixel_values'''].numpy()
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''tf'''					)['''pixel_values'''].numpy()

        self.assertTrue(np.allclose(__lowerCamelCase,__lowerCamelCase					)					)
        self.assertTrue(np.allclose(__lowerCamelCase,__lowerCamelCase					)					)
        self.assertTrue(np.allclose(__lowerCamelCase,__lowerCamelCase					)					)





