
"""simple docstring"""




import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
						from PIL import Image
else:





						class  snake_case     :

													@staticmethod
													def _lowercase					(*SCREAMING_SNAKE_CASE_       ,       **SCREAMING_SNAKE_CASE_    ):

															"""simple docstring"""







															pass





@is_pipeline_test
@require_vision
@require_torch
class  snake_case     (							unittest.TestCase   ):
							UpperCAmelCase__						     =      MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = pipeline(
									    '''zero-shot-object-detection'''       ,       model='''hf-internal-testing/tiny-random-owlvit-object-detection'''    )

									SCREAMING_SNAKE_CASE_						 = [
									    {
									        '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
									        '''candidate_labels''': ['''cat''', '''remote''', '''couch'''],
									    }
									]
									return object_detector, examples

							def _lowercase					(self       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = object_detector(examples[0]       ,       threshold=0.0    )

									SCREAMING_SNAKE_CASE_						 = len(SCREAMING_SNAKE_CASE_    )
									self.assertGreater(SCREAMING_SNAKE_CASE_       ,       0    )
									self.assertEqual(
									    SCREAMING_SNAKE_CASE_       ,       [
									        {
									            '''score''': ANY(SCREAMING_SNAKE_CASE_    ),
									            '''label''': ANY(SCREAMING_SNAKE_CASE_    ),
									            '''box''': {'''xmin''': ANY(SCREAMING_SNAKE_CASE_    ), '''ymin''': ANY(SCREAMING_SNAKE_CASE_    ), '''xmax''': ANY(SCREAMING_SNAKE_CASE_    ), '''ymax''': ANY(SCREAMING_SNAKE_CASE_    )},
									        }
									        for i in range(SCREAMING_SNAKE_CASE_    )
									    ]       ,       )

							@require_tf
							@unittest.skip('''Zero Shot Object Detection not implemented in TF'''    )
							def _lowercase					(self    ):

									"""simple docstring"""







									pass

							@require_torch
							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = pipeline(
									    '''zero-shot-object-detection'''       ,       model='''hf-internal-testing/tiny-random-owlvit-object-detection'''    )

									SCREAMING_SNAKE_CASE_						 = object_detector(
									    '''./tests/fixtures/tests_samples/COCO/000000039769.png'''       ,       candidate_labels=['''cat''', '''remote''', '''couch''']       ,       threshold=0.64       ,       )

									self.assertEqual(
									    nested_simplify(SCREAMING_SNAKE_CASE_       ,       decimals=4    )       ,       [
									        {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}},
									        {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}},
									        {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}},
									        {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}},
									        {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}},
									        {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}},
									        {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}},
									        {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 2_74, '''xmax''': 93, '''ymax''': 2_97}},
									        {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}},
									    ]       ,       )

									SCREAMING_SNAKE_CASE_						 = object_detector(
									    [
									        {
									            '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
									            '''candidate_labels''': ['''cat''', '''remote''', '''couch'''],
									        }
									    ]       ,       threshold=0.64       ,       )

									self.assertEqual(
									    nested_simplify(SCREAMING_SNAKE_CASE_       ,       decimals=4    )       ,       [
									        [
									            {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}},
									            {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}},
									            {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}},
									            {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}},
									            {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}},
									            {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}},
									            {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}},
									            {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 2_74, '''xmax''': 93, '''ymax''': 2_97}},
									            {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}},
									        ]
									    ]       ,       )

							@require_torch
							@slow
							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = pipeline('''zero-shot-object-detection'''    )

									SCREAMING_SNAKE_CASE_						 = object_detector(
									    '''http://images.cocodataset.org/val2017/000000039769.jpg'''       ,       candidate_labels=['''cat''', '''remote''', '''couch''']       ,       )
									self.assertEqual(
									    nested_simplify(SCREAMING_SNAKE_CASE_       ,       decimals=4    )       ,       [
									        {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}},
									        {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}},
									        {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}},
									        {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}},
									        {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}},
									    ]       ,       )

									SCREAMING_SNAKE_CASE_						 = object_detector(
									    [
									        {
									            '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''',
									            '''candidate_labels''': ['''cat''', '''remote''', '''couch'''],
									        },
									        {
									            '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''',
									            '''candidate_labels''': ['''cat''', '''remote''', '''couch'''],
									        },
									    ]       ,       )
									self.assertEqual(
									    nested_simplify(SCREAMING_SNAKE_CASE_       ,       decimals=4    )       ,       [
									        [
									            {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}},
									            {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}},
									            {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}},
									            {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}},
									            {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}},
									        ],
									        [
									            {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}},
									            {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}},
									            {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}},
									            {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}},
									            {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}},
									        ],
									    ]       ,       )

							@require_tf
							@unittest.skip('''Zero Shot Object Detection not implemented in TF'''    )
							def _lowercase					(self    ):

									"""simple docstring"""







									pass

							@require_torch
							@slow
							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = 0.2
									SCREAMING_SNAKE_CASE_						 = pipeline('''zero-shot-object-detection'''    )

									SCREAMING_SNAKE_CASE_						 = object_detector(
									    '''http://images.cocodataset.org/val2017/000000039769.jpg'''       ,       candidate_labels=['''cat''', '''remote''', '''couch''']       ,       threshold=SCREAMING_SNAKE_CASE_       ,       )
									self.assertEqual(
									    nested_simplify(SCREAMING_SNAKE_CASE_       ,       decimals=4    )       ,       [
									        {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}},
									        {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}},
									        {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}},
									    ]       ,       )







							@require_torch
							@slow
							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = 2
									SCREAMING_SNAKE_CASE_						 = pipeline('''zero-shot-object-detection'''    )

									SCREAMING_SNAKE_CASE_						 = object_detector(
									    '''http://images.cocodataset.org/val2017/000000039769.jpg'''       ,       candidate_labels=['''cat''', '''remote''', '''couch''']       ,       top_k=SCREAMING_SNAKE_CASE_       ,       )
									self.assertEqual(
									    nested_simplify(SCREAMING_SNAKE_CASE_       ,       decimals=4    )       ,       [
									        {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}},
									        {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}},
									    ]       ,       )

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


lowerCAmelCase__							=				logging.getLogger(__name__)



def        _lowerCamelCase ( __a,							__a    ):
		return (preds == labels).mean()





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







@dataclass
class  snake_case     :
							UpperCAmelCase__						     =      field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys()   )}   )
							UpperCAmelCase__						     =      field(metadata={'''help''': '''Should contain the data files for the task.'''}   )
							UpperCAmelCase__						     =      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.'''
							        )
							    }       ,			)
							UpperCAmelCase__						     =      field(
							    default=__lowercase       ,			metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}   )







def        _lowerCamelCase ( ):
		# 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.

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

		# Set seed
		set_seed(training_args.seed    )

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

		SCREAMING_SNAKE_CASE_						 = AutoConfig.from_pretrained(
		    model_args.config_name if model_args.config_name else model_args.model_name_or_path,							num_labels=__a,							finetuning_task=data_args.task_name,							cache_dir=model_args.cache_dir,							)
		SCREAMING_SNAKE_CASE_						 = 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,							)
		SCREAMING_SNAKE_CASE_						 = AutoModelForMultipleChoice.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,							)

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

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

		# Initialize our Trainer
		SCREAMING_SNAKE_CASE_						 = Trainer(
		    model=__a,							args=__a,							train_dataset=__a,							eval_dataset=__a,							compute_metrics=__a,							data_collator=__a,							)

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

				SCREAMING_SNAKE_CASE_						 = trainer.evaluate()

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

								results.update(__a    )

		return results



def        _lowerCamelCase ( __a    ):
		# For xla_spawn (TPUs)
		main()


if __name__ == "__main__":
						main()