



import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import 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 SegformerImageProcessor


class    _lowercase (unittest.TestCase   ):
				'''simple docstring'''







				def __init__(			self  ,			snake_case__  ,			snake_case__=7  ,			snake_case__=3  ,			snake_case__=30  ,			snake_case__=400  ,			snake_case__=True  ,			snake_case__=None  ,			snake_case__=True  ,			snake_case__=[0.5, 0.5, 0.5]  ,			snake_case__=[0.5, 0.5, 0.5]  ,			snake_case__=False  ,			):

									'''simple docstring'''


									UpperCamelCase_			= size if size is not None else {"height": 30, "width": 30}
									UpperCamelCase_			= parent
									UpperCamelCase_			= batch_size
									UpperCamelCase_			= num_channels
									UpperCamelCase_			= min_resolution
									UpperCamelCase_			= max_resolution
									UpperCamelCase_			= do_resize
									UpperCamelCase_			= size
									UpperCamelCase_			= do_normalize
									UpperCamelCase_			= image_mean
									UpperCamelCase_			= image_std
									UpperCamelCase_			= do_reduce_labels

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									return {
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "do_normalize": self.do_normalize,
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_reduce_labels": self.do_reduce_labels,
									}




def  _lowerCAmelCase     ():
					UpperCamelCase_			= load_dataset("hf-internal-testing/fixtures_ade20k" ,						split="test")

					UpperCamelCase_			= Image.open(dataset[0]["file"])
					UpperCamelCase_			= Image.open(dataset[1]["file"])

					return image, map



def  _lowerCAmelCase     ():
					UpperCamelCase_			= load_dataset("hf-internal-testing/fixtures_ade20k" ,						split="test")

					UpperCamelCase_			= Image.open(dataset[0]["file"])
					UpperCamelCase_			= Image.open(dataset[1]["file"])
					UpperCamelCase_			= Image.open(dataset[2]["file"])
					UpperCamelCase_			= Image.open(dataset[3]["file"])

					return [imagea, imagea], [mapa, mapa]






@require_torch
@require_vision
class    _lowercase (a_   , unittest.TestCase   ):
				'''simple docstring'''







				lowercase__     =    SegformerImageProcessor if is_vision_available() else None

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= SegformerImageProcessingTester(self     )

				@property
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									return self.image_processor_tester.prepare_image_processor_dict()

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.image_processing_class(**self.image_processor_dict     )
									self.assertTrue(hasattr(snake_case__  ,			"do_resize"     )     )
									self.assertTrue(hasattr(snake_case__  ,			"size"     )     )
									self.assertTrue(hasattr(snake_case__  ,			"do_normalize"     )     )
									self.assertTrue(hasattr(snake_case__  ,			"image_mean"     )     )
									self.assertTrue(hasattr(snake_case__  ,			"image_std"     )     )
									self.assertTrue(hasattr(snake_case__  ,			"do_reduce_labels"     )     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.image_processing_class.from_dict(self.image_processor_dict     )
									self.assertEqual(image_processor.size  ,			{"height": 30, "width": 30}     )
									self.assertEqual(image_processor.do_reduce_labels  ,			snake_case__     )

									UpperCamelCase_			= self.image_processing_class.from_dict(self.image_processor_dict  ,			size=42  ,			reduce_labels=snake_case__     )
									self.assertEqual(image_processor.size  ,			{"height": 42, "width": 42}     )
									self.assertEqual(image_processor.do_reduce_labels  ,			snake_case__     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									pass

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.image_processing_class(**self.image_processor_dict     )
									# create random PIL images
									UpperCamelCase_			= prepare_image_inputs(self.image_processor_tester  ,			equal_resolution=snake_case__     )
									for image in image_inputs:
														self.assertIsInstance(snake_case__  ,			Image.Image     )

									# Test not batched input
									UpperCamelCase_			= 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
									UpperCamelCase_			= image_processing(snake_case__  ,			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"],
									    )  ,			)

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.image_processing_class(**self.image_processor_dict     )
									# create random numpy tensors
									UpperCamelCase_			= prepare_image_inputs(self.image_processor_tester  ,			equal_resolution=snake_case__  ,			numpify=snake_case__     )
									for image in image_inputs:
														self.assertIsInstance(snake_case__  ,			np.ndarray     )

									# Test not batched input
									UpperCamelCase_			= 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
									UpperCamelCase_			= image_processing(snake_case__  ,			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"],
									    )  ,			)

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


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

									# Test not batched input
									UpperCamelCase_			= 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
									UpperCamelCase_			= image_processing(snake_case__  ,			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"],
									    )  ,			)

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.image_processing_class(**self.image_processor_dict     )
									# create random PyTorch tensors
									UpperCamelCase_			= prepare_image_inputs(self.image_processor_tester  ,			equal_resolution=snake_case__  ,			torchify=snake_case__     )
									UpperCamelCase_			= []
									for image in image_inputs:
														self.assertIsInstance(snake_case__  ,			torch.Tensor     )
														maps.append(torch.zeros(image.shape[-2:]     ).long()     )

									# Test not batched input
									UpperCamelCase_			= image_processing(image_inputs[0]  ,			maps[0]  ,			return_tensors="pt"     )
									self.assertEqual(
									    encoding["pixel_values"].shape  ,			(
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.size["height"],
									        self.image_processor_tester.size["width"],
									    )  ,			)
									self.assertEqual(
									    encoding["labels"].shape  ,			(
									        1,
									        self.image_processor_tester.size["height"],
									        self.image_processor_tester.size["width"],
									    )  ,			)
									self.assertEqual(encoding["labels"].dtype  ,			torch.long     )
									self.assertTrue(encoding["labels"].min().item() >= 0     )
									self.assertTrue(encoding["labels"].max().item() <= 255     )

									# Test batched
									UpperCamelCase_			= image_processing(snake_case__  ,			snake_case__  ,			return_tensors="pt"     )
									self.assertEqual(
									    encoding["pixel_values"].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"],
									    )  ,			)
									self.assertEqual(
									    encoding["labels"].shape  ,			(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.size["height"],
									        self.image_processor_tester.size["width"],
									    )  ,			)
									self.assertEqual(encoding["labels"].dtype  ,			torch.long     )
									self.assertTrue(encoding["labels"].min().item() >= 0     )
									self.assertTrue(encoding["labels"].max().item() <= 255     )

									# Test not batched input (PIL images)
									UpperCamelCase_	,     UpperCamelCase_			= prepare_semantic_single_inputs()

									UpperCamelCase_			= image_processing(snake_case__  ,			snake_case__  ,			return_tensors="pt"     )
									self.assertEqual(
									    encoding["pixel_values"].shape  ,			(
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.size["height"],
									        self.image_processor_tester.size["width"],
									    )  ,			)
									self.assertEqual(
									    encoding["labels"].shape  ,			(
									        1,
									        self.image_processor_tester.size["height"],
									        self.image_processor_tester.size["width"],
									    )  ,			)
									self.assertEqual(encoding["labels"].dtype  ,			torch.long     )
									self.assertTrue(encoding["labels"].min().item() >= 0     )
									self.assertTrue(encoding["labels"].max().item() <= 255     )

									# Test batched input (PIL images)
									UpperCamelCase_	,     UpperCamelCase_			= prepare_semantic_batch_inputs()

									UpperCamelCase_			= image_processing(snake_case__  ,			snake_case__  ,			return_tensors="pt"     )
									self.assertEqual(
									    encoding["pixel_values"].shape  ,			(
									        2,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.size["height"],
									        self.image_processor_tester.size["width"],
									    )  ,			)
									self.assertEqual(
									    encoding["labels"].shape  ,			(
									        2,
									        self.image_processor_tester.size["height"],
									        self.image_processor_tester.size["width"],
									    )  ,			)
									self.assertEqual(encoding["labels"].dtype  ,			torch.long     )
									self.assertTrue(encoding["labels"].min().item() >= 0     )
									self.assertTrue(encoding["labels"].max().item() <= 255     )

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= self.image_processing_class(**self.image_processor_dict     )

									# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
									UpperCamelCase_	,     UpperCamelCase_			= prepare_semantic_single_inputs()
									UpperCamelCase_			= image_processing(snake_case__  ,			snake_case__  ,			return_tensors="pt"     )
									self.assertTrue(encoding["labels"].min().item() >= 0     )
									self.assertTrue(encoding["labels"].max().item() <= 150     )

									UpperCamelCase_			= True
									UpperCamelCase_			= image_processing(snake_case__  ,			snake_case__  ,			return_tensors="pt"     )
									self.assertTrue(encoding["labels"].min().item() >= 0     )
									self.assertTrue(encoding["labels"].max().item() <= 255     )


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

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


_A       =					logging.getLogger(__name__)







@dataclass
class 	lowerCamelCase						:
     UpperCAmelCase__							:				str 	=						field(
         metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}    )
     UpperCAmelCase__							:				Optional[str] 	=						field(
         default=A_				,					metadata={"help": "Pretrained config name or path if not the same as model_name"}    )
     UpperCAmelCase__							:				Optional[str] 	=						field(
         default=A_				,					metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}    )
     UpperCAmelCase__							:				bool 	=						field(default=A_				,					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.
     UpperCAmelCase__							:				Optional[str] 	=						field(
         default=A_				,					metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}				,					)



def 		lowercase_     (  )				->				int:
    """simple docstring"""

    snake_case						=   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						=   parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
    else:
        snake_case	,				snake_case	,				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__						)

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

    snake_case						=   AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path					,						cache_dir=model_args.cache_dir					,						)
    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					,						use_fast=A__					,						)
    snake_case						=   AutoModelForQuestionAnswering.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
    snake_case						=   hasattr(model.config					,						"lang2id"						)
    snake_case						=   (
        SquadDataset(
            A__					,						tokenizer=A__					,						is_language_sensitive=A__					,						cache_dir=model_args.cache_dir						)
        if training_args.do_train
        else None
    )
    snake_case						=   (
        SquadDataset(
            A__					,						tokenizer=A__					,						mode="dev"					,						is_language_sensitive=A__					,						cache_dir=model_args.cache_dir					,						)
        if training_args.do_eval
        else None
    )

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

    # Initialize our Trainer
    snake_case						=   Trainer(
        model=A__					,						args=A__					,						train_dataset=A__					,						eval_dataset=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						)



def 		lowercase_     (  A__						)				->				Optional[Any]:
    """simple docstring"""

    main()


if __name__ == "__main__":
   main()

