






"""simple docstring"""







import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import (
	    MODEL_MAPPING,
	    SegformerForImageClassification,
	    SegformerForSemanticSegmentation,
	    SegformerModel,
	)
	from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import SegformerImageProcessor

class 		UpperCamelCase      (   lowercase						):



				def  _lowercase					(self    :				Any)   ->     List[Any]:
					__snake_case      :							Any						=			self.config_class(**self.inputs_dict)
					self.parent.assertTrue(hasattr(_A     ,  'hidden_sizes'))
					self.parent.assertTrue(hasattr(_A     ,  'num_attention_heads'))
					self.parent.assertTrue(hasattr(_A     ,  'num_encoder_blocks'))







class 		UpperCamelCase      :



				def __init__(self    :				Optional[int]     ,  _A    :				Any     ,  _A    :				str=13     ,  _A    :				List[str]=64     ,  _A    :				List[Any]=3     ,  _A    :				Any=4     ,  _A    :				List[str]=[2, 2, 2, 2]     ,  _A    :				Tuple=[8, 4, 2, 1]     ,  _A    :				List[str]=[16, 32, 64, 1_28]     ,  _A    :				int=[1, 4, 8, 16]     ,  _A    :				List[str]=[1, 2, 4, 8]     ,  _A    :				Dict=True     ,  _A    :				Any=True     ,  _A    :				List[str]="gelu"     ,  _A    :				Optional[int]=0.1     ,  _A    :				Union[str, Any]=0.1     ,  _A    :				List[Any]=0.02     ,  _A    :				str=3     ,  _A    :				int=None     ,  )   ->     List[Any]:
					__snake_case      :							int						=			parent
					__snake_case      :							List[Any]						=			batch_size
					__snake_case      :							Optional[int]						=			image_size
					__snake_case      :							List[str]						=			num_channels
					__snake_case      :							Any						=			num_encoder_blocks
					__snake_case      :							Dict						=			sr_ratios
					__snake_case      :							Any						=			depths
					__snake_case      :							Tuple						=			hidden_sizes
					__snake_case      :							Tuple						=			downsampling_rates
					__snake_case      :							Union[str, Any]						=			num_attention_heads
					__snake_case      :							Optional[int]						=			is_training
					__snake_case      :							Any						=			use_labels
					__snake_case      :							List[Any]						=			hidden_act
					__snake_case      :							Union[str, Any]						=			hidden_dropout_prob
					__snake_case      :							Tuple						=			attention_probs_dropout_prob
					__snake_case      :							List[Any]						=			initializer_range
					__snake_case      :							Union[str, Any]						=			num_labels
					__snake_case      :							Dict						=			scope



				def  _lowercase					(self    :				List[Any])   ->     Tuple:
					__snake_case      :							Optional[Any]						=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

					__snake_case      :							str						=			None
					if self.use_labels:
						__snake_case      :							Optional[Any]						=			ids_tensor([self.batch_size, self.image_size, self.image_size]     ,  self.num_labels)

					__snake_case      :							Dict						=			self.get_config()
					return config, pixel_values, labels



				def  _lowercase					(self    :				Any)   ->     Optional[int]:
					return SegformerConfig(
					    image_size=self.image_size     ,  num_channels=self.num_channels     ,  num_encoder_blocks=self.num_encoder_blocks     ,  depths=self.depths     ,  hidden_sizes=self.hidden_sizes     ,  num_attention_heads=self.num_attention_heads     ,  hidden_act=self.hidden_act     ,  hidden_dropout_prob=self.hidden_dropout_prob     ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,  initializer_range=self.initializer_range     ,  )



				def  _lowercase					(self    :				List[str]     ,  _A    :				Union[str, Any]     ,  _A    :				List[Any]     ,  _A    :				Union[str, Any])   ->     int:
					__snake_case      :							Union[str, Any]						=			SegformerModel(config=_A)
					model.to(_A)
					model.eval()
					__snake_case      :							str						=			model(_A)
					__snake_case      :							List[Any]						=			self.image_size // (self.downsampling_rates[-1] * 2)
					self.parent.assertEqual(
					    result.last_hidden_state.shape     ,  (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width))



				def  _lowercase					(self    :				Tuple     ,  _A    :				Dict     ,  _A    :				Any     ,  _A    :				int)   ->     str:
					__snake_case      :							Any						=			self.num_labels
					__snake_case      :							List[str]						=			SegformerForSemanticSegmentation(_A)
					model.to(_A)
					model.eval()
					__snake_case      :							Dict						=			model(_A)
					self.parent.assertEqual(
					    result.logits.shape     ,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4))
					__snake_case      :							Dict						=			model(_A     ,  labels=_A)
					self.parent.assertEqual(
					    result.logits.shape     ,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4))
					self.parent.assertGreater(result.loss     ,  0.0)



				def  _lowercase					(self    :				Optional[Any]     ,  _A    :				Dict     ,  _A    :				Optional[int]     ,  _A    :				str)   ->     List[Any]:
					__snake_case      :							List[Any]						=			1
					__snake_case      :							str						=			SegformerForSemanticSegmentation(config=_A)
					model.to(_A)
					model.eval()
					__snake_case      :							Any						=			torch.randint(0     ,  1     ,  (self.batch_size, self.image_size, self.image_size)).to(_A)
					__snake_case      :							Any						=			model(_A     ,  labels=_A)
					self.parent.assertGreater(result.loss     ,  0.0)






				def  _lowercase					(self    :				Any)   ->     Optional[int]:
					__snake_case      :							Optional[Any]						=			self.prepare_config_and_inputs()
					__snake_case      :							str						=			config_and_inputs
					__snake_case      :							List[str]						=			{'pixel_values': pixel_values}
					return config, inputs_dict







@require_torch
class 		UpperCamelCase      (   lowercase				,     lowercase				,     unittest.TestCase						):
				UpperCAmelCase    :				List[str]   =		(
				    (
				        SegformerModel,
				        SegformerForSemanticSegmentation,
				        SegformerForImageClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				UpperCAmelCase    :				Dict   =		(
				    {
				        """feature-extraction""": SegformerModel,
				        """image-classification""": SegformerForImageClassification,
				        """image-segmentation""": SegformerForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				UpperCAmelCase    :				Optional[int]   =		True
				UpperCAmelCase    :				Optional[int]   =		False
				UpperCAmelCase    :				List[Any]   =		False
				UpperCAmelCase    :				List[Any]   =		False



				def  _lowercase					(self    :				str)   ->     Union[str, Any]:
					__snake_case      :							Optional[int]						=			SegformerModelTester(self)
					__snake_case      :							Any						=			SegformerConfigTester(self     ,  config_class=_A)



				def  _lowercase					(self    :				List[str])   ->     Optional[int]:
					self.config_tester.run_common_tests()



				def  _lowercase					(self    :				List[Any])   ->     List[str]:
					__snake_case      :							int						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_A)



				def  _lowercase					(self    :				Optional[int])   ->     str:
					__snake_case      :							List[Any]						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_binary_image_segmentation(*_A)



				def  _lowercase					(self    :				int)   ->     Union[str, Any]:
					__snake_case      :							Union[str, Any]						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_segmentation(*_A)



				@unittest.skip('SegFormer does not use inputs_embeds')
				def  _lowercase					(self    :				Union[str, Any])   ->     str:
					pass



				@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods')
				def  _lowercase					(self    :				int)   ->     str:
					pass



				def  _lowercase					(self    :				List[str])   ->     Any:
					__snake_case      :							Dict						=			self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						__snake_case      :							str						=			model_class(_A)
						__snake_case      :							str						=			inspect.signature(model.forward)
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						__snake_case      :							List[str]						=			[*signature.parameters.keys()]

						__snake_case      :							Optional[int]						=			['pixel_values']
						self.assertListEqual(arg_names[:1]     ,  _A)



				def  _lowercase					(self    :				List[str])   ->     List[Any]:
					__snake_case      :							Union[str, Any]						=			self.model_tester.prepare_config_and_inputs_for_common()
					__snake_case      :							Optional[int]						=			True

					for model_class in self.all_model_classes:
						__snake_case      :							Union[str, Any]						=			True
						__snake_case      :							List[str]						=			False
						__snake_case      :							Tuple						=			True
						__snake_case      :							int						=			model_class(_A)
						model.to(_A)
						model.eval()
						with torch.no_grad():
							__snake_case      :							int						=			model(**self._prepare_for_class(_A     ,  _A))
						__snake_case      :							Union[str, Any]						=			outputs.attentions

						__snake_case      :							int						=			sum(self.model_tester.depths)
						self.assertEqual(len(_A)     ,  _A)

						# check that output_attentions also work using config
						del inputs_dict["output_attentions"]
						__snake_case      :							int						=			True
						__snake_case      :							Union[str, Any]						=			model_class(_A)
						model.to(_A)
						model.eval()
						with torch.no_grad():
							__snake_case      :							List[str]						=			model(**self._prepare_for_class(_A     ,  _A))
						__snake_case      :							Optional[int]						=			outputs.attentions

						self.assertEqual(len(_A)     ,  _A)

						# verify the first attentions (first block, first layer)
						__snake_case      :							Optional[int]						=			(self.model_tester.image_size // 4) ** 2
						__snake_case      :							Tuple						=			(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
						self.assertListEqual(
						    list(attentions[0].shape[-3:])     ,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]     ,  )

						# verify the last attentions (last block, last layer)
						__snake_case      :							int						=			(self.model_tester.image_size // 32) ** 2
						__snake_case      :							Any						=			(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
						self.assertListEqual(
						    list(attentions[-1].shape[-3:])     ,  [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]     ,  )
						__snake_case      :							int						=			len(_A)

						# Check attention is always last and order is fine
						__snake_case      :							Any						=			True
						__snake_case      :							Tuple						=			True
						__snake_case      :							Optional[Any]						=			model_class(_A)
						model.to(_A)
						model.eval()
						with torch.no_grad():
							__snake_case      :							Any						=			model(**self._prepare_for_class(_A     ,  _A))

						self.assertEqual(out_len + 1     ,  len(_A))

						__snake_case      :							List[Any]						=			outputs.attentions

						self.assertEqual(len(_A)     ,  _A)
						# verify the first attentions (first block, first layer)
						__snake_case      :							Any						=			(self.model_tester.image_size // 4) ** 2
						__snake_case      :							List[Any]						=			(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
						self.assertListEqual(
						    list(self_attentions[0].shape[-3:])     ,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]     ,  )



				def  _lowercase					(self    :				str)   ->     List[str]:
					def check_hidden_states_output(_A    :				Union[str, Any]     ,  _A    :				List[str]     ,  _A    :				Tuple):
						__snake_case      :							Tuple						=			model_class(_A)
						model.to(_A)
						model.eval()

						with torch.no_grad():
							__snake_case      :							Optional[int]						=			model(**self._prepare_for_class(_A     ,  _A))

						__snake_case      :							List[str]						=			outputs.hidden_states

						__snake_case      :							Tuple						=			self.model_tester.num_encoder_blocks
						self.assertEqual(len(_A)     ,  _A)

						# verify the first hidden states (first block)
						self.assertListEqual(
						    list(hidden_states[0].shape[-3:])     ,  [
						        self.model_tester.hidden_sizes[0],
						        self.model_tester.image_size // 4,
						        self.model_tester.image_size // 4,
						    ]     ,  )

					__snake_case      :							Optional[Any]						=			self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						__snake_case      :							List[str]						=			True
						check_hidden_states_output(_A     ,  _A     ,  _A)

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						__snake_case      :							Any						=			True

						check_hidden_states_output(_A     ,  _A     ,  _A)



				def  _lowercase					(self    :				Optional[int])   ->     int:
					if not self.model_tester.is_training:
						return

					__snake_case      :							Dict						=			self.model_tester.prepare_config_and_inputs_for_common()
					__snake_case      :							int						=			True

					for model_class in self.all_model_classes:
						if model_class in get_values(_A):
							continue

						__snake_case      :							Tuple						=			model_class(_A)
						model.to(_A)
						model.train()
						__snake_case      :							str						=			self._prepare_for_class(_A     ,  _A     ,  return_labels=_A)
						__snake_case      :							Dict						=			model(**_A).loss
						loss.backward()



				@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
				def  _lowercase					(self    :				Tuple)   ->     Dict:
					pass






				@slow
				def  _lowercase					(self    :				Any)   ->     List[str]:
					for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						__snake_case      :							List[Any]						=			SegformerModel.from_pretrained(_A)
						self.assertIsNotNone(_A)







def   __UpperCAmelCase    (   )							->      Union[str, Any]:

	'''simple docstring'''





	__snake_case      :							Tuple						=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
	return image

@require_torch
class 		UpperCamelCase      (   unittest.TestCase						):



				@slow
				def  _lowercase					(self    :				Union[str, Any])   ->     Any:
					# only resize + normalize
					__snake_case      :							List[str]						=			SegformerImageProcessor(
					    image_scale=(5_12, 5_12)     ,  keep_ratio=_A     ,  align=_A     ,  do_random_crop=_A)
					__snake_case      :							Tuple						=			SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512').to(
					    _A)

					__snake_case      :							Optional[Any]						=			prepare_img()
					__snake_case      :							Tuple						=			image_processor(images=_A     ,  return_tensors='pt')
					__snake_case      :							List[str]						=			encoded_inputs.pixel_values.to(_A)

					with torch.no_grad():
						__snake_case      :							Any						=			model(_A)

					__snake_case      :							Optional[int]						=			torch.Size((1, model.config.num_labels, 1_28, 1_28))
					self.assertEqual(outputs.logits.shape     ,  _A)

					__snake_case      :							Tuple						=			torch.tensor(
					    [
					        [[-4.6_310, -5.5_232, -6.2_356], [-5.1_921, -6.1_444, -6.5_996], [-5.4_424, -6.2_790, -6.7_574]],
					        [[-12.1_391, -13.3_122, -13.9_554], [-12.8_732, -13.9_352, -14.3_563], [-12.9_438, -13.8_226, -14.2_513]],
					        [[-12.5_134, -13.4_686, -14.4_915], [-12.8_669, -14.4_343, -14.7_758], [-13.2_523, -14.5_819, -15.0_694]],
					    ]).to(_A)
					self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]     ,  _A     ,  atol=1E-4))



				@slow
				def  _lowercase					(self    :				Any)   ->     Optional[int]:
					# only resize + normalize
					__snake_case      :							int						=			SegformerImageProcessor(
					    image_scale=(5_12, 5_12)     ,  keep_ratio=_A     ,  align=_A     ,  do_random_crop=_A)
					__snake_case      :							Tuple						=			SegformerForSemanticSegmentation.from_pretrained(
					    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024').to(_A)

					__snake_case      :							str						=			prepare_img()
					__snake_case      :							Union[str, Any]						=			image_processor(images=_A     ,  return_tensors='pt')
					__snake_case      :							str						=			encoded_inputs.pixel_values.to(_A)

					with torch.no_grad():
						__snake_case      :							Any						=			model(_A)

					__snake_case      :							Any						=			torch.Size((1, model.config.num_labels, 1_28, 1_28))
					self.assertEqual(outputs.logits.shape     ,  _A)

					__snake_case      :							List[Any]						=			torch.tensor(
					    [
					        [[-13.5_748, -13.9_111, -12.6_500], [-14.3_500, -15.3_683, -14.2_328], [-14.7_532, -16.0_424, -15.6_087]],
					        [[-17.1_651, -15.8_725, -12.9_653], [-17.2_580, -17.3_718, -14.8_223], [-16.6_058, -16.8_783, -16.7_452]],
					        [[-3.6_456, -3.0_209, -1.4_203], [-3.0_797, -3.1_959, -2.0_000], [-1.8_757, -1.9_217, -1.6_997]],
					    ]).to(_A)
					self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]     ,  _A     ,  atol=1E-1))






				@slow
				def  _lowercase					(self    :				Optional[int])   ->     Union[str, Any]:
					# only resize + normalize
					__snake_case      :							List[Any]						=			SegformerImageProcessor(
					    image_scale=(5_12, 5_12)     ,  keep_ratio=_A     ,  align=_A     ,  do_random_crop=_A)
					__snake_case      :							Optional[Any]						=			SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512').to(
					    _A)

					__snake_case      :							Optional[Any]						=			prepare_img()
					__snake_case      :							Optional[Any]						=			image_processor(images=_A     ,  return_tensors='pt')
					__snake_case      :							Union[str, Any]						=			encoded_inputs.pixel_values.to(_A)

					with torch.no_grad():
						__snake_case      :							Any						=			model(_A)

					__snake_case      :							Optional[Any]						=			outputs.logits.detach().cpu()

					__snake_case      :							Any						=			image_processor.post_process_semantic_segmentation(outputs=_A     ,  target_sizes=[(5_00, 3_00)])
					__snake_case      :							Any						=			torch.Size((5_00, 3_00))
					self.assertEqual(segmentation[0].shape     ,  _A)

					__snake_case      :							Any						=			image_processor.post_process_semantic_segmentation(outputs=_A)
					__snake_case      :							str						=			torch.Size((1_28, 1_28))
					self.assertEqual(segmentation[0].shape     ,  _A)






"""simple docstring"""







import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints

import yaml


_a					:					int=			NewType("DataClass", Any)
_a					:					Dict=			NewType("DataClassType", Any)
def   __UpperCAmelCase    (   UpperCAmelCase_   :    Any  )							->      Optional[Any]:

	'''simple docstring'''





	if isinstance(UpperCAmelCase_      ,							UpperCAmelCase_  ):
		return v
	if v.lower() in ("yes", "true", "t", "y", "1"):
		return True
	elif v.lower() in ("no", "false", "f", "n", "0"):
		return False
	else:
		raise ArgumentTypeError(
		    F"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."  )
def   __UpperCAmelCase    (   UpperCAmelCase_   :    list  )							->      Callable[[str], Any]:

	'''simple docstring'''





	__snake_case      :							str						=			{str(UpperCAmelCase_  ): choice for choice in choices}
	return lambda UpperCAmelCase_  : str_to_choice.get(UpperCAmelCase_      ,							UpperCAmelCase_  )
def   __UpperCAmelCase    (   *,
    UpperCAmelCase_   :    Union[str, List[str]] = None      ,							UpperCAmelCase_   :    str = None      ,							UpperCAmelCase_   :    Any = dataclasses.MISSING      ,							UpperCAmelCase_   :    Callable[[], Any] = dataclasses.MISSING      ,							UpperCAmelCase_   :    dict = None      ,							**UpperCAmelCase_   :    str      ,							)							->      dataclasses.Field:

	'''simple docstring'''





	if metadata is None:
		# Important, don't use as default param in function signature because dict is mutable and shared across function calls
		__snake_case      :							Optional[Any]						=			{}
	if aliases is not None:
		__snake_case      :							Optional[int]						=			aliases
	if help is not None:
		__snake_case      :							Optional[int]						=			help

	return dataclasses.field(metadata=UpperCAmelCase_      ,							default=UpperCAmelCase_      ,							default_factory=UpperCAmelCase_      ,							**UpperCAmelCase_  )

class 		UpperCamelCase      (   lowercase						):
				UpperCAmelCase    :				Iterable[DataClassType]



				def __init__(self    :				Tuple     ,  _A    :				Union[DataClassType, Iterable[DataClassType]]     ,  **_A    :				int)   ->     int:
					# To make the default appear when using --help
					if "formatter_class" not in kwargs:
						__snake_case      :							Union[str, Any]						=			ArgumentDefaultsHelpFormatter
					super().__init__(**_A)
					if dataclasses.is_dataclass(_A):
						__snake_case      :							Optional[int]						=			[dataclass_types]
					__snake_case      :							Dict						=			list(_A)
					for dtype in self.dataclass_types:
						self._add_dataclass_arguments(_A)



				@staticmethod
				def  _lowercase					(_A    :				ArgumentParser     ,  _A    :				dataclasses.Field)   ->     Tuple:
					__snake_case      :							Union[str, Any]						=			f"--{field.name}"
					__snake_case      :							Optional[int]						=			field.metadata.copy()
					# field.metadata is not used at all by Data Classes,
					# it is provided as a third-party extension mechanism.
					if isinstance(field.type     ,  _A):
						raise RuntimeError(
						    'Unresolved type detected, which should have been done with the help of '
						    '`typing.get_type_hints` method by default')

					__snake_case      :							Any						=			kwargs.pop('aliases'     ,  [])
					if isinstance(_A     ,  _A):
						__snake_case      :							Optional[Any]						=			[aliases]

					__snake_case      :							Tuple						=			getattr(field.type     ,  '__origin__'     ,  field.type)
					if origin_type is Union or (hasattr(_A     ,  'UnionType') and isinstance(_A     ,  types.UnionType)):
						if str not in field.type.__args__ and (
						    len(field.type.__args__) != 2 or type(_A) not in field.type.__args__
						):
							raise ValueError(
							    'Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'
							    ' the argument parser only supports one type per argument.'
							    f" Problem encountered in field '{field.name}'.")
						if type(_A) not in field.type.__args__:
							# filter `str` in Union
							__snake_case      :							Tuple						=			field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
							__snake_case      :							Optional[int]						=			getattr(field.type     ,  '__origin__'     ,  field.type)
						elif bool not in field.type.__args__:
							# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
							__snake_case      :							Optional[Any]						=			(
							    field.type.__args__[0] if isinstance(_A     ,  field.type.__args__[1]) else field.type.__args__[1]
							)
							__snake_case      :							Tuple						=			getattr(field.type     ,  '__origin__'     ,  field.type)

        # A variable to store kwargs for a boolean field, if needed
        # so that we can init a `no_*` complement argument (see below)
					__snake_case      :							Optional[int]						=			{}
					if origin_type is Literal or (isinstance(field.type     ,  _A) and issubclass(field.type     ,  _A)):
						if origin_type is Literal:
							__snake_case      :							Tuple						=			field.type.__args__
						else:
							__snake_case      :							Dict						=			[x.value for x in field.type]

						__snake_case      :							Dict						=			make_choice_type_function(kwargs['choices'])

						if field.default is not dataclasses.MISSING:
							__snake_case      :							Dict						=			field.default
						else:
							__snake_case      :							Union[str, Any]						=			True
					elif field.type is bool or field.type == Optional[bool]:
						# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
						# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
						__snake_case      :							Tuple						=			copy(_A)

						# Hack because type=bool in argparse does not behave as we want.
						__snake_case      :							Dict						=			string_to_bool
						if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
							# Default value is False if we have no default when of type bool.
							__snake_case      :							str						=			False if field.default is dataclasses.MISSING else field.default
							# This is the value that will get picked if we don't include --field_name in any way
							__snake_case      :							Any						=			default
							# This tells argparse we accept 0 or 1 value after --field_name
							__snake_case      :							Dict						=			'?'
							# This is the value that will get picked if we do --field_name (without value)
							__snake_case      :							List[str]						=			True
					elif isclass(_A) and issubclass(_A     ,  _A):
						__snake_case      :							str						=			field.type.__args__[0]
						__snake_case      :							Any						=			'+'
						if field.default_factory is not dataclasses.MISSING:
							__snake_case      :							List[str]						=			field.default_factory()
						elif field.default is dataclasses.MISSING:
							__snake_case      :							Any						=			True
					else:
						__snake_case      :							Tuple						=			field.type
						if field.default is not dataclasses.MISSING:
							__snake_case      :							Optional[int]						=			field.default
						elif field.default_factory is not dataclasses.MISSING:
							__snake_case      :							List[Any]						=			field.default_factory()
						else:
							__snake_case      :							Union[str, Any]						=			True
					parser.add_argument(_A     ,  *_A     ,  **_A)

					# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
					# Order is important for arguments with the same destination!
					# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
					# here and we do not need those changes/additional keys.
					if field.default is True and (field.type is bool or field.type == Optional[bool]):
						__snake_case      :							List[str]						=			False
						parser.add_argument(f"--no_{field.name}"     ,  action='store_false'     ,  dest=field.name     ,  **_A)



				def  _lowercase					(self    :				List[Any]     ,  _A    :				DataClassType)   ->     Optional[int]:
					if hasattr(_A     ,  '_argument_group_name'):
						__snake_case      :							Union[str, Any]						=			self.add_argument_group(dtype._argument_group_name)
					else:
						__snake_case      :							int						=			self

					try:
						__snake_case      :							Dict[str, type]						=			get_type_hints(_A)
					except NameError:
						raise RuntimeError(
						    f"Type resolution failed for {dtype}. Try declaring the class in global scope or "
						    'removing line of `from __future__ import annotations` which opts in Postponed '
						    'Evaluation of Annotations (PEP 563)')
					except TypeError as ex:
						# Remove this block when we drop Python 3.9 support
						if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(_A):
							__snake_case      :							Union[str, Any]						=			'.'.join(map(_A     ,  sys.version_info[:3]))
							raise RuntimeError(
							    f"Type resolution failed for {dtype} on Python {python_version}. Try removing "
							    'line of `from __future__ import annotations` which opts in union types as '
							    '`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '
							    'support Python versions that lower than 3.10, you need to use '
							    '`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '
							    '`X | None`.') from ex
						raise

					for field in dataclasses.fields(_A):
						if not field.init:
							continue
						__snake_case      :							Optional[Any]						=			type_hints[field.name]
						self._parse_dataclass_field(_A     ,  _A)



				def  _lowercase					(self    :				Union[str, Any]     ,  _A    :				List[Any]=None     ,  _A    :				Optional[Any]=False     ,  _A    :				int=True     ,  _A    :				List[Any]=None     ,  _A    :				str=None     ,  )   ->     Tuple[DataClass, ...]:

					if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)):
						__snake_case      :							Any						=			[]

						if args_filename:
							args_files.append(Path(_A))
						elif look_for_args_file and len(sys.argv):
							args_files.append(Path(sys.argv[0]).with_suffix('.args'))

						# args files specified via command line flag should overwrite default args files so we add them last
						if args_file_flag:
							# Create special parser just to extract the args_file_flag values
							__snake_case      :							int						=			ArgumentParser()
							args_file_parser.add_argument(_A     ,  type=_A     ,  action='append')

							# Use only remaining args for further parsing (remove the args_file_flag)
							__snake_case		,    __snake_case      :							int						=			args_file_parser.parse_known_args(args=_A)
							__snake_case      :							int						=			vars(_A).get(args_file_flag.lstrip('-')     ,  _A)

							if cmd_args_file_paths:
								args_files.extend([Path(_A) for p in cmd_args_file_paths])

						__snake_case      :							Optional[int]						=			[]
						for args_file in args_files:
							if args_file.exists():
								file_args += args_file.read_text().split()

            # in case of duplicate arguments the last one has precedence
            # args specified via the command line should overwrite args from files, so we add them last
						__snake_case      :							List[str]						=			file_args + args if args is not None else file_args + sys.argv[1:]
					__snake_case		,    __snake_case      :							Tuple						=			self.parse_known_args(args=_A)
					__snake_case      :							Dict						=			[]
					for dtype in self.dataclass_types:
						__snake_case      :							List[Any]						=			{f.name for f in dataclasses.fields(_A) if f.init}
						__snake_case      :							List[str]						=			{k: v for k, v in vars(_A).items() if k in keys}
						for k in keys:
							delattr(_A     ,  _A)
						__snake_case      :							List[str]						=			dtype(**_A)
						outputs.append(_A)
					if len(namespace.__dict__) > 0:
						# additional namespace.
						outputs.append(_A)
					if return_remaining_strings:
						return (*outputs, remaining_args)
					else:
						if remaining_args:
							raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}")

						return (*outputs,)



				def  _lowercase					(self    :				Tuple     ,  _A    :				Dict[str, Any]     ,  _A    :				bool = False)   ->     Tuple[DataClass, ...]:
					__snake_case      :							List[Any]						=			set(args.keys())
					__snake_case      :							Dict						=			[]
					for dtype in self.dataclass_types:
						__snake_case      :							List[str]						=			{f.name for f in dataclasses.fields(_A) if f.init}
						__snake_case      :							Union[str, Any]						=			{k: v for k, v in args.items() if k in keys}
						unused_keys.difference_update(inputs.keys())
						__snake_case      :							List[str]						=			dtype(**_A)
						outputs.append(_A)
					if not allow_extra_keys and unused_keys:
						raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(_A)}")
					return tuple(_A)



				def  _lowercase					(self    :				int     ,  _A    :				str     ,  _A    :				bool = False)   ->     Tuple[DataClass, ...]:
					with open(Path(_A)     ,  encoding='utf-8') as open_json_file:
						__snake_case      :							int						=			json.loads(open_json_file.read())
					__snake_case      :							Optional[int]						=			self.parse_dict(_A     ,  allow_extra_keys=_A)
					return tuple(_A)






				def  _lowercase					(self    :				List[str]     ,  _A    :				str     ,  _A    :				bool = False)   ->     Tuple[DataClass, ...]:
					__snake_case      :							Dict						=			self.parse_dict(yaml.safe_load(Path(_A).read_text())     ,  allow_extra_keys=_A)
					return tuple(_A)





